clang  3.7.0
CGDecl.cpp
Go to the documentation of this file.
1 //===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This contains code to emit Decl nodes as LLVM code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenFunction.h"
15 #include "CGCleanup.h"
16 #include "CGDebugInfo.h"
17 #include "CGOpenCLRuntime.h"
18 #include "CodeGenModule.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclObjC.h"
24 #include "clang/Basic/TargetInfo.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/GlobalVariable.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Type.h"
31 using namespace clang;
32 using namespace CodeGen;
33 
34 
36  switch (D.getKind()) {
37  case Decl::TranslationUnit:
38  case Decl::ExternCContext:
39  case Decl::Namespace:
40  case Decl::UnresolvedUsingTypename:
41  case Decl::ClassTemplateSpecialization:
42  case Decl::ClassTemplatePartialSpecialization:
43  case Decl::VarTemplateSpecialization:
44  case Decl::VarTemplatePartialSpecialization:
45  case Decl::TemplateTypeParm:
46  case Decl::UnresolvedUsingValue:
47  case Decl::NonTypeTemplateParm:
48  case Decl::CXXMethod:
49  case Decl::CXXConstructor:
50  case Decl::CXXDestructor:
51  case Decl::CXXConversion:
52  case Decl::Field:
53  case Decl::MSProperty:
54  case Decl::IndirectField:
55  case Decl::ObjCIvar:
56  case Decl::ObjCAtDefsField:
57  case Decl::ParmVar:
58  case Decl::ImplicitParam:
59  case Decl::ClassTemplate:
60  case Decl::VarTemplate:
61  case Decl::FunctionTemplate:
62  case Decl::TypeAliasTemplate:
63  case Decl::TemplateTemplateParm:
64  case Decl::ObjCMethod:
65  case Decl::ObjCCategory:
66  case Decl::ObjCProtocol:
67  case Decl::ObjCInterface:
68  case Decl::ObjCCategoryImpl:
69  case Decl::ObjCImplementation:
70  case Decl::ObjCProperty:
71  case Decl::ObjCCompatibleAlias:
72  case Decl::AccessSpec:
73  case Decl::LinkageSpec:
74  case Decl::ObjCPropertyImpl:
75  case Decl::FileScopeAsm:
76  case Decl::Friend:
77  case Decl::FriendTemplate:
78  case Decl::Block:
79  case Decl::Captured:
80  case Decl::ClassScopeFunctionSpecialization:
81  case Decl::UsingShadow:
82  case Decl::ObjCTypeParam:
83  llvm_unreachable("Declaration should not be in declstmts!");
84  case Decl::Function: // void X();
85  case Decl::Record: // struct/union/class X;
86  case Decl::Enum: // enum X;
87  case Decl::EnumConstant: // enum ? { X = ? }
88  case Decl::CXXRecord: // struct/union/class X; [C++]
89  case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
90  case Decl::Label: // __label__ x;
91  case Decl::Import:
92  case Decl::OMPThreadPrivate:
93  case Decl::Empty:
94  // None of these decls require codegen support.
95  return;
96 
97  case Decl::NamespaceAlias:
98  if (CGDebugInfo *DI = getDebugInfo())
99  DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
100  return;
101  case Decl::Using: // using X; [C++]
102  if (CGDebugInfo *DI = getDebugInfo())
103  DI->EmitUsingDecl(cast<UsingDecl>(D));
104  return;
105  case Decl::UsingDirective: // using namespace X; [C++]
106  if (CGDebugInfo *DI = getDebugInfo())
107  DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
108  return;
109  case Decl::Var: {
110  const VarDecl &VD = cast<VarDecl>(D);
111  assert(VD.isLocalVarDecl() &&
112  "Should not see file-scope variables inside a function!");
113  return EmitVarDecl(VD);
114  }
115 
116  case Decl::Typedef: // typedef int X;
117  case Decl::TypeAlias: { // using X = int; [C++0x]
118  const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
119  QualType Ty = TD.getUnderlyingType();
120 
121  if (Ty->isVariablyModifiedType())
123  }
124  }
125 }
126 
127 /// EmitVarDecl - This method handles emission of any variable declaration
128 /// inside a function, including static vars etc.
130  if (D.isStaticLocal()) {
131  llvm::GlobalValue::LinkageTypes Linkage =
132  CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
133 
134  // FIXME: We need to force the emission/use of a guard variable for
135  // some variables even if we can constant-evaluate them because
136  // we can't guarantee every translation unit will constant-evaluate them.
137 
138  return EmitStaticVarDecl(D, Linkage);
139  }
140 
141  if (D.hasExternalStorage())
142  // Don't emit it now, allow it to be emitted lazily on its first use.
143  return;
144 
147 
148  assert(D.hasLocalStorage());
149  return EmitAutoVarDecl(D);
150 }
151 
152 static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
153  if (CGM.getLangOpts().CPlusPlus)
154  return CGM.getMangledName(&D).str();
155 
156  // If this isn't C++, we don't need a mangled name, just a pretty one.
157  assert(!D.isExternallyVisible() && "name shouldn't matter");
158  std::string ContextName;
159  const DeclContext *DC = D.getDeclContext();
160  if (auto *CD = dyn_cast<CapturedDecl>(DC))
161  DC = cast<DeclContext>(CD->getNonClosureContext());
162  if (const auto *FD = dyn_cast<FunctionDecl>(DC))
163  ContextName = CGM.getMangledName(FD);
164  else if (const auto *BD = dyn_cast<BlockDecl>(DC))
165  ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
166  else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
167  ContextName = OMD->getSelector().getAsString();
168  else
169  llvm_unreachable("Unknown context for static var decl");
170 
171  ContextName += "." + D.getNameAsString();
172  return ContextName;
173 }
174 
176  const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
177  // In general, we don't always emit static var decls once before we reference
178  // them. It is possible to reference them before emitting the function that
179  // contains them, and it is possible to emit the containing function multiple
180  // times.
181  if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
182  return ExistingGV;
183 
184  QualType Ty = D.getType();
185  assert(Ty->isConstantSizeType() && "VLAs can't be static");
186 
187  // Use the label if the variable is renamed with the asm-label extension.
188  std::string Name;
189  if (D.hasAttr<AsmLabelAttr>())
190  Name = getMangledName(&D);
191  else
192  Name = getStaticDeclName(*this, D);
193 
194  llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
195  unsigned AddrSpace =
196  GetGlobalVarAddressSpace(&D, getContext().getTargetAddressSpace(Ty));
197 
198  // Local address space cannot have an initializer.
199  llvm::Constant *Init = nullptr;
201  Init = EmitNullConstant(Ty);
202  else
203  Init = llvm::UndefValue::get(LTy);
204 
205  llvm::GlobalVariable *GV =
206  new llvm::GlobalVariable(getModule(), LTy,
208  Init, Name, nullptr,
209  llvm::GlobalVariable::NotThreadLocal,
210  AddrSpace);
211  GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
212  setGlobalVisibility(GV, &D);
213 
214  if (supportsCOMDAT() && GV->isWeakForLinker())
215  GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
216 
217  if (D.getTLSKind())
218  setTLSMode(GV, D);
219 
220  if (D.isExternallyVisible()) {
221  if (D.hasAttr<DLLImportAttr>())
222  GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
223  else if (D.hasAttr<DLLExportAttr>())
224  GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
225  }
226 
227  // Make sure the result is of the correct type.
228  unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(Ty);
229  llvm::Constant *Addr = GV;
230  if (AddrSpace != ExpectedAddrSpace) {
231  llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
232  Addr = llvm::ConstantExpr::getAddrSpaceCast(GV, PTy);
233  }
234 
235  setStaticLocalDeclAddress(&D, Addr);
236 
237  // Ensure that the static local gets initialized by making sure the parent
238  // function gets emitted eventually.
239  const Decl *DC = cast<Decl>(D.getDeclContext());
240 
241  // We can't name blocks or captured statements directly, so try to emit their
242  // parents.
243  if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
244  DC = DC->getNonClosureContext();
245  // FIXME: Ensure that global blocks get emitted.
246  if (!DC)
247  return Addr;
248  }
249 
250  GlobalDecl GD;
251  if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
252  GD = GlobalDecl(CD, Ctor_Base);
253  else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
254  GD = GlobalDecl(DD, Dtor_Base);
255  else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
256  GD = GlobalDecl(FD);
257  else {
258  // Don't do anything for Obj-C method decls or global closures. We should
259  // never defer them.
260  assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
261  }
262  if (GD.getDecl())
263  (void)GetAddrOfGlobal(GD);
264 
265  return Addr;
266 }
267 
268 /// hasNontrivialDestruction - Determine whether a type's destruction is
269 /// non-trivial. If so, and the variable uses static initialization, we must
270 /// register its destructor to run on exit.
273  return RD && !RD->hasTrivialDestructor();
274 }
275 
276 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
277 /// global variable that has already been created for it. If the initializer
278 /// has a different type than GV does, this may free GV and return a different
279 /// one. Otherwise it just returns GV.
280 llvm::GlobalVariable *
282  llvm::GlobalVariable *GV) {
283  llvm::Constant *Init = CGM.EmitConstantInit(D, this);
284 
285  // If constant emission failed, then this should be a C++ static
286  // initializer.
287  if (!Init) {
288  if (!getLangOpts().CPlusPlus)
289  CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
290  else if (Builder.GetInsertBlock()) {
291  // Since we have a static initializer, this global variable can't
292  // be constant.
293  GV->setConstant(false);
294 
295  EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
296  }
297  return GV;
298  }
299 
300  // The initializer may differ in type from the global. Rewrite
301  // the global to match the initializer. (We have to do this
302  // because some types, like unions, can't be completely represented
303  // in the LLVM type system.)
304  if (GV->getType()->getElementType() != Init->getType()) {
305  llvm::GlobalVariable *OldGV = GV;
306 
307  GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
308  OldGV->isConstant(),
309  OldGV->getLinkage(), Init, "",
310  /*InsertBefore*/ OldGV,
311  OldGV->getThreadLocalMode(),
313  GV->setVisibility(OldGV->getVisibility());
314 
315  // Steal the name of the old global
316  GV->takeName(OldGV);
317 
318  // Replace all uses of the old global with the new global
319  llvm::Constant *NewPtrForOldDecl =
320  llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
321  OldGV->replaceAllUsesWith(NewPtrForOldDecl);
322 
323  // Erase the old global, since it is no longer used.
324  OldGV->eraseFromParent();
325  }
326 
327  GV->setConstant(CGM.isTypeConstant(D.getType(), true));
328  GV->setInitializer(Init);
329 
331  // We have a constant initializer, but a nontrivial destructor. We still
332  // need to perform a guarded "initialization" in order to register the
333  // destructor.
334  EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
335  }
336 
337  return GV;
338 }
339 
341  llvm::GlobalValue::LinkageTypes Linkage) {
342  llvm::Value *&DMEntry = LocalDeclMap[&D];
343  assert(!DMEntry && "Decl already exists in localdeclmap!");
344 
345  // Check to see if we already have a global variable for this
346  // declaration. This can happen when double-emitting function
347  // bodies, e.g. with complete and base constructors.
348  llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
349 
350  // Store into LocalDeclMap before generating initializer to handle
351  // circular references.
352  DMEntry = addr;
353 
354  // We can't have a VLA here, but we can have a pointer to a VLA,
355  // even though that doesn't really make any sense.
356  // Make sure to evaluate VLA bounds now so that we have them for later.
357  if (D.getType()->isVariablyModifiedType())
359 
360  // Save the type in case adding the initializer forces a type change.
361  llvm::Type *expectedType = addr->getType();
362 
363  llvm::GlobalVariable *var =
364  cast<llvm::GlobalVariable>(addr->stripPointerCasts());
365  // If this value has an initializer, emit it.
366  if (D.getInit())
367  var = AddInitializerToStaticVarDecl(D, var);
368 
369  var->setAlignment(getContext().getDeclAlign(&D).getQuantity());
370 
371  if (D.hasAttr<AnnotateAttr>())
372  CGM.AddGlobalAnnotations(&D, var);
373 
374  if (const SectionAttr *SA = D.getAttr<SectionAttr>())
375  var->setSection(SA->getName());
376 
377  if (D.hasAttr<UsedAttr>())
378  CGM.addUsedGlobal(var);
379 
380  // We may have to cast the constant because of the initializer
381  // mismatch above.
382  //
383  // FIXME: It is really dangerous to store this in the map; if anyone
384  // RAUW's the GV uses of this constant will be invalid.
385  llvm::Constant *castedAddr =
386  llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
387  DMEntry = castedAddr;
388  CGM.setStaticLocalDeclAddress(&D, castedAddr);
389 
391 
392  // Emit global variable debug descriptor for static vars.
393  CGDebugInfo *DI = getDebugInfo();
394  if (DI &&
396  DI->setLocation(D.getLocation());
397  DI->EmitGlobalVariable(var, &D);
398  }
399 }
400 
401 namespace {
402  struct DestroyObject : EHScopeStack::Cleanup {
403  DestroyObject(llvm::Value *addr, QualType type,
404  CodeGenFunction::Destroyer *destroyer,
405  bool useEHCleanupForArray)
406  : addr(addr), type(type), destroyer(destroyer),
407  useEHCleanupForArray(useEHCleanupForArray) {}
408 
409  llvm::Value *addr;
410  QualType type;
411  CodeGenFunction::Destroyer *destroyer;
412  bool useEHCleanupForArray;
413 
414  void Emit(CodeGenFunction &CGF, Flags flags) override {
415  // Don't use an EH cleanup recursively from an EH cleanup.
416  bool useEHCleanupForArray =
417  flags.isForNormalCleanup() && this->useEHCleanupForArray;
418 
419  CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
420  }
421  };
422 
423  struct DestroyNRVOVariable : EHScopeStack::Cleanup {
424  DestroyNRVOVariable(llvm::Value *addr,
425  const CXXDestructorDecl *Dtor,
426  llvm::Value *NRVOFlag)
427  : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
428 
429  const CXXDestructorDecl *Dtor;
430  llvm::Value *NRVOFlag;
431  llvm::Value *Loc;
432 
433  void Emit(CodeGenFunction &CGF, Flags flags) override {
434  // Along the exceptions path we always execute the dtor.
435  bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
436 
437  llvm::BasicBlock *SkipDtorBB = nullptr;
438  if (NRVO) {
439  // If we exited via NRVO, we skip the destructor call.
440  llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
441  SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
442  llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
443  CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
444  CGF.EmitBlock(RunDtorBB);
445  }
446 
448  /*ForVirtualBase=*/false,
449  /*Delegating=*/false,
450  Loc);
451 
452  if (NRVO) CGF.EmitBlock(SkipDtorBB);
453  }
454  };
455 
456  struct CallStackRestore : EHScopeStack::Cleanup {
458  CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
459  void Emit(CodeGenFunction &CGF, Flags flags) override {
460  llvm::Value *V = CGF.Builder.CreateLoad(Stack);
461  llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
462  CGF.Builder.CreateCall(F, V);
463  }
464  };
465 
466  struct ExtendGCLifetime : EHScopeStack::Cleanup {
467  const VarDecl &Var;
468  ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
469 
470  void Emit(CodeGenFunction &CGF, Flags flags) override {
471  // Compute the address of the local variable, in case it's a
472  // byref or something.
473  DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
474  Var.getType(), VK_LValue, SourceLocation());
475  llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
476  SourceLocation());
477  CGF.EmitExtendGCLifetime(value);
478  }
479  };
480 
481  struct CallCleanupFunction : EHScopeStack::Cleanup {
482  llvm::Constant *CleanupFn;
483  const CGFunctionInfo &FnInfo;
484  const VarDecl &Var;
485 
486  CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
487  const VarDecl *Var)
488  : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
489 
490  void Emit(CodeGenFunction &CGF, Flags flags) override {
491  DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
492  Var.getType(), VK_LValue, SourceLocation());
493  // Compute the address of the local variable, in case it's a byref
494  // or something.
495  llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
496 
497  // In some cases, the type of the function argument will be different from
498  // the type of the pointer. An example of this is
499  // void f(void* arg);
500  // __attribute__((cleanup(f))) void *g;
501  //
502  // To fix this we insert a bitcast here.
503  QualType ArgTy = FnInfo.arg_begin()->type;
504  llvm::Value *Arg =
505  CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
506 
507  CallArgList Args;
508  Args.add(RValue::get(Arg),
509  CGF.getContext().getPointerType(Var.getType()));
510  CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
511  }
512  };
513 
514  /// A cleanup to call @llvm.lifetime.end.
515  class CallLifetimeEnd : public EHScopeStack::Cleanup {
516  llvm::Value *Addr;
517  llvm::Value *Size;
518  public:
519  CallLifetimeEnd(llvm::Value *addr, llvm::Value *size)
520  : Addr(addr), Size(size) {}
521 
522  void Emit(CodeGenFunction &CGF, Flags flags) override {
523  CGF.EmitLifetimeEnd(Size, Addr);
524  }
525  };
526 }
527 
528 /// EmitAutoVarWithLifetime - Does the setup required for an automatic
529 /// variable with lifetime.
530 static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
531  llvm::Value *addr,
532  Qualifiers::ObjCLifetime lifetime) {
533  switch (lifetime) {
535  llvm_unreachable("present but none");
536 
538  // nothing to do
539  break;
540 
541  case Qualifiers::OCL_Strong: {
542  CodeGenFunction::Destroyer *destroyer =
543  (var.hasAttr<ObjCPreciseLifetimeAttr>()
546 
547  CleanupKind cleanupKind = CGF.getARCCleanupKind();
548  CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
549  cleanupKind & EHCleanup);
550  break;
551  }
553  // nothing to do
554  break;
555 
557  // __weak objects always get EH cleanups; otherwise, exceptions
558  // could cause really nasty crashes instead of mere leaks.
559  CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
561  /*useEHCleanup*/ true);
562  break;
563  }
564 }
565 
566 static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
567  if (const Expr *e = dyn_cast<Expr>(s)) {
568  // Skip the most common kinds of expressions that make
569  // hierarchy-walking expensive.
570  s = e = e->IgnoreParenCasts();
571 
572  if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
573  return (ref->getDecl() == &var);
574  if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
575  const BlockDecl *block = be->getBlockDecl();
576  for (const auto &I : block->captures()) {
577  if (I.getVariable() == &var)
578  return true;
579  }
580  }
581  }
582 
583  for (const Stmt *SubStmt : s->children())
584  // SubStmt might be null; as in missing decl or conditional of an if-stmt.
585  if (SubStmt && isAccessedBy(var, SubStmt))
586  return true;
587 
588  return false;
589 }
590 
591 static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
592  if (!decl) return false;
593  if (!isa<VarDecl>(decl)) return false;
594  const VarDecl *var = cast<VarDecl>(decl);
595  return isAccessedBy(*var, e);
596 }
597 
599  LValue &lvalue,
600  const VarDecl *var) {
601  lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
602 }
603 
604 void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
605  LValue lvalue, bool capturedByInit) {
606  Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
607  if (!lifetime) {
608  llvm::Value *value = EmitScalarExpr(init);
609  if (capturedByInit)
610  drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
611  EmitStoreThroughLValue(RValue::get(value), lvalue, true);
612  return;
613  }
614 
615  if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
616  init = DIE->getExpr();
617 
618  // If we're emitting a value with lifetime, we have to do the
619  // initialization *before* we leave the cleanup scopes.
620  if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
621  enterFullExpression(ewc);
622  init = ewc->getSubExpr();
623  }
625 
626  // We have to maintain the illusion that the variable is
627  // zero-initialized. If the variable might be accessed in its
628  // initializer, zero-initialize before running the initializer, then
629  // actually perform the initialization with an assign.
630  bool accessedByInit = false;
631  if (lifetime != Qualifiers::OCL_ExplicitNone)
632  accessedByInit = (capturedByInit || isAccessedBy(D, init));
633  if (accessedByInit) {
634  LValue tempLV = lvalue;
635  // Drill down to the __block object if necessary.
636  if (capturedByInit) {
637  // We can use a simple GEP for this because it can't have been
638  // moved yet.
639  tempLV.setAddress(Builder.CreateStructGEP(
640  nullptr, tempLV.getAddress(),
641  getByRefValueLLVMField(cast<VarDecl>(D)).second));
642  }
643 
644  llvm::PointerType *ty
645  = cast<llvm::PointerType>(tempLV.getAddress()->getType());
646  ty = cast<llvm::PointerType>(ty->getElementType());
647 
648  llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
649 
650  // If __weak, we want to use a barrier under certain conditions.
651  if (lifetime == Qualifiers::OCL_Weak)
652  EmitARCInitWeak(tempLV.getAddress(), zero);
653 
654  // Otherwise just do a simple store.
655  else
656  EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
657  }
658 
659  // Emit the initializer.
660  llvm::Value *value = nullptr;
661 
662  switch (lifetime) {
664  llvm_unreachable("present but none");
665 
667  // nothing to do
668  value = EmitScalarExpr(init);
669  break;
670 
671  case Qualifiers::OCL_Strong: {
672  value = EmitARCRetainScalarExpr(init);
673  break;
674  }
675 
676  case Qualifiers::OCL_Weak: {
677  // No way to optimize a producing initializer into this. It's not
678  // worth optimizing for, because the value will immediately
679  // disappear in the common case.
680  value = EmitScalarExpr(init);
681 
682  if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
683  if (accessedByInit)
684  EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
685  else
686  EmitARCInitWeak(lvalue.getAddress(), value);
687  return;
688  }
689 
692  break;
693  }
694 
695  if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
696 
697  // If the variable might have been accessed by its initializer, we
698  // might have to initialize with a barrier. We have to do this for
699  // both __weak and __strong, but __weak got filtered out above.
700  if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
701  llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
702  EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
704  return;
705  }
706 
707  EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
708 }
709 
710 /// EmitScalarInit - Initialize the given lvalue with the given object.
712  Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
713  if (!lifetime)
714  return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
715 
716  switch (lifetime) {
718  llvm_unreachable("present but none");
719 
721  // nothing to do
722  break;
723 
725  init = EmitARCRetain(lvalue.getType(), init);
726  break;
727 
729  // Initialize and then skip the primitive store.
730  EmitARCInitWeak(lvalue.getAddress(), init);
731  return;
732 
734  init = EmitARCRetainAutorelease(lvalue.getType(), init);
735  break;
736  }
737 
738  EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
739 }
740 
741 /// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
742 /// non-zero parts of the specified initializer with equal or fewer than
743 /// NumStores scalar stores.
744 static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
745  unsigned &NumStores) {
746  // Zero and Undef never requires any extra stores.
747  if (isa<llvm::ConstantAggregateZero>(Init) ||
748  isa<llvm::ConstantPointerNull>(Init) ||
749  isa<llvm::UndefValue>(Init))
750  return true;
751  if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
752  isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
753  isa<llvm::ConstantExpr>(Init))
754  return Init->isNullValue() || NumStores--;
755 
756  // See if we can emit each element.
757  if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
758  for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
759  llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
760  if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
761  return false;
762  }
763  return true;
764  }
765 
766  if (llvm::ConstantDataSequential *CDS =
767  dyn_cast<llvm::ConstantDataSequential>(Init)) {
768  for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
769  llvm::Constant *Elt = CDS->getElementAsConstant(i);
770  if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
771  return false;
772  }
773  return true;
774  }
775 
776  // Anything else is hard and scary.
777  return false;
778 }
779 
780 /// emitStoresForInitAfterMemset - For inits that
781 /// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
782 /// stores that would be required.
783 static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
784  bool isVolatile, CGBuilderTy &Builder) {
785  assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
786  "called emitStoresForInitAfterMemset for zero or undef value.");
787 
788  if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
789  isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
790  isa<llvm::ConstantExpr>(Init)) {
791  Builder.CreateStore(Init, Loc, isVolatile);
792  return;
793  }
794 
795  if (llvm::ConstantDataSequential *CDS =
796  dyn_cast<llvm::ConstantDataSequential>(Init)) {
797  for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
798  llvm::Constant *Elt = CDS->getElementAsConstant(i);
799 
800  // If necessary, get a pointer to the element and emit it.
801  if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
803  Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
804  isVolatile, Builder);
805  }
806  return;
807  }
808 
809  assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
810  "Unknown value type!");
811 
812  for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
813  llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
814 
815  // If necessary, get a pointer to the element and emit it.
816  if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
818  Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
819  isVolatile, Builder);
820  }
821 }
822 
823 
824 /// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
825 /// plus some stores to initialize a local variable instead of using a memcpy
826 /// from a constant global. It is beneficial to use memset if the global is all
827 /// zeros, or mostly zeros and large.
828 static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
829  uint64_t GlobalSize) {
830  // If a global is all zeros, always use a memset.
831  if (isa<llvm::ConstantAggregateZero>(Init)) return true;
832 
833  // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
834  // do it if it will require 6 or fewer scalar stores.
835  // TODO: Should budget depends on the size? Avoiding a large global warrants
836  // plopping in more stores.
837  unsigned StoreBudget = 6;
838  uint64_t SizeLimit = 32;
839 
840  return GlobalSize > SizeLimit &&
841  canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
842 }
843 
844 /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
845 /// variable declaration with auto, register, or no storage class specifier.
846 /// These turn into simple stack objects, or GlobalValues depending on target.
848  AutoVarEmission emission = EmitAutoVarAlloca(D);
849  EmitAutoVarInit(emission);
850  EmitAutoVarCleanups(emission);
851 }
852 
853 /// Emit a lifetime.begin marker if some criteria are satisfied.
854 /// \return a pointer to the temporary size Value if a marker was emitted, null
855 /// otherwise
857  llvm::Value *Addr) {
858  // For now, only in optimized builds.
859  if (CGM.getCodeGenOpts().OptimizationLevel == 0)
860  return nullptr;
861 
862  // Disable lifetime markers in msan builds.
863  // FIXME: Remove this when msan works with lifetime markers.
864  if (getLangOpts().Sanitize.has(SanitizerKind::Memory))
865  return nullptr;
866 
867  llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
868  Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
869  llvm::CallInst *C =
870  Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
871  C->setDoesNotThrow();
872  return SizeV;
873 }
874 
876  Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
877  llvm::CallInst *C =
878  Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
879  C->setDoesNotThrow();
880 }
881 
882 /// EmitAutoVarAlloca - Emit the alloca and debug information for a
883 /// local variable. Does not emit initialization or destruction.
886  QualType Ty = D.getType();
887 
888  AutoVarEmission emission(D);
889 
890  bool isByRef = D.hasAttr<BlocksAttr>();
891  emission.IsByRef = isByRef;
892 
893  CharUnits alignment = getContext().getDeclAlign(&D);
894  emission.Alignment = alignment;
895 
896  // If the type is variably-modified, emit all the VLA sizes for it.
897  if (Ty->isVariablyModifiedType())
899 
900  llvm::Value *DeclPtr;
901  if (Ty->isConstantSizeType()) {
902  bool NRVO = getLangOpts().ElideConstructors &&
903  D.isNRVOVariable();
904 
905  // If this value is an array or struct with a statically determinable
906  // constant initializer, there are optimizations we can do.
907  //
908  // TODO: We should constant-evaluate the initializer of any variable,
909  // as long as it is initialized by a constant expression. Currently,
910  // isConstantInitializer produces wrong answers for structs with
911  // reference or bitfield members, and a few other cases, and checking
912  // for POD-ness protects us from some of these.
913  if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
914  (D.isConstexpr() ||
915  ((Ty.isPODType(getContext()) ||
917  D.getInit()->isConstantInitializer(getContext(), false)))) {
918 
919  // If the variable's a const type, and it's neither an NRVO
920  // candidate nor a __block variable and has no mutable members,
921  // emit it as a global instead.
922  if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
923  CGM.isTypeConstant(Ty, true)) {
925 
926  emission.Address = nullptr; // signal this condition to later callbacks
927  assert(emission.wasEmittedAsGlobal());
928  return emission;
929  }
930 
931  // Otherwise, tell the initialization code that we're in this case.
932  emission.IsConstantAggregate = true;
933  }
934 
935  // A normal fixed sized variable becomes an alloca in the entry block,
936  // unless it's an NRVO variable.
937  llvm::Type *LTy = ConvertTypeForMem(Ty);
938 
939  if (NRVO) {
940  // The named return value optimization: allocate this variable in the
941  // return slot, so that we can elide the copy when returning this
942  // variable (C++0x [class.copy]p34).
943  DeclPtr = ReturnValue;
944 
945  if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
946  if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
947  // Create a flag that is used to indicate when the NRVO was applied
948  // to this variable. Set it to zero to indicate that NRVO was not
949  // applied.
950  llvm::Value *Zero = Builder.getFalse();
951  llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
953  Builder.CreateStore(Zero, NRVOFlag);
954 
955  // Record the NRVO flag for this variable.
956  NRVOFlags[&D] = NRVOFlag;
957  emission.NRVOFlag = NRVOFlag;
958  }
959  }
960  } else {
961  if (isByRef)
962  LTy = BuildByRefType(&D);
963 
964  llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
965  Alloc->setName(D.getName());
966 
967  CharUnits allocaAlignment = alignment;
968  if (isByRef)
969  allocaAlignment = std::max(allocaAlignment,
970  getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0)));
971  Alloc->setAlignment(allocaAlignment.getQuantity());
972  DeclPtr = Alloc;
973 
974  // Emit a lifetime intrinsic if meaningful. There's no point
975  // in doing this if we don't have a valid insertion point (?).
976  uint64_t size = CGM.getDataLayout().getTypeAllocSize(LTy);
977  if (HaveInsertPoint()) {
978  emission.SizeForLifetimeMarkers = EmitLifetimeStart(size, Alloc);
979  } else {
980  assert(!emission.useLifetimeMarkers());
981  }
982  }
983  } else {
985 
986  if (!DidCallStackSave) {
987  // Save the stack.
988  llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
989 
990  llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
991  llvm::Value *V = Builder.CreateCall(F);
992 
993  Builder.CreateStore(V, Stack);
994 
995  DidCallStackSave = true;
996 
997  // Push a cleanup block and restore the stack there.
998  // FIXME: in general circumstances, this should be an EH cleanup.
1000  }
1001 
1002  llvm::Value *elementCount;
1003  QualType elementType;
1004  std::tie(elementCount, elementType) = getVLASize(Ty);
1005 
1006  llvm::Type *llvmTy = ConvertTypeForMem(elementType);
1007 
1008  // Allocate memory for the array.
1009  llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
1010  vla->setAlignment(alignment.getQuantity());
1011 
1012  DeclPtr = vla;
1013  }
1014 
1015  llvm::Value *&DMEntry = LocalDeclMap[&D];
1016  assert(!DMEntry && "Decl already exists in localdeclmap!");
1017  DMEntry = DeclPtr;
1018  emission.Address = DeclPtr;
1019 
1020  // Emit debug info for local var declaration.
1021  if (HaveInsertPoint())
1022  if (CGDebugInfo *DI = getDebugInfo()) {
1023  if (CGM.getCodeGenOpts().getDebugInfo()
1025  DI->setLocation(D.getLocation());
1026  DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
1027  }
1028  }
1029 
1030  if (D.hasAttr<AnnotateAttr>())
1031  EmitVarAnnotations(&D, emission.Address);
1032 
1033  return emission;
1034 }
1035 
1036 /// Determines whether the given __block variable is potentially
1037 /// captured by the given expression.
1038 static bool isCapturedBy(const VarDecl &var, const Expr *e) {
1039  // Skip the most common kinds of expressions that make
1040  // hierarchy-walking expensive.
1041  e = e->IgnoreParenCasts();
1042 
1043  if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
1044  const BlockDecl *block = be->getBlockDecl();
1045  for (const auto &I : block->captures()) {
1046  if (I.getVariable() == &var)
1047  return true;
1048  }
1049 
1050  // No need to walk into the subexpressions.
1051  return false;
1052  }
1053 
1054  if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1055  const CompoundStmt *CS = SE->getSubStmt();
1056  for (const auto *BI : CS->body())
1057  if (const auto *E = dyn_cast<Expr>(BI)) {
1058  if (isCapturedBy(var, E))
1059  return true;
1060  }
1061  else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
1062  // special case declarations
1063  for (const auto *I : DS->decls()) {
1064  if (const auto *VD = dyn_cast<VarDecl>((I))) {
1065  const Expr *Init = VD->getInit();
1066  if (Init && isCapturedBy(var, Init))
1067  return true;
1068  }
1069  }
1070  }
1071  else
1072  // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1073  // Later, provide code to poke into statements for capture analysis.
1074  return true;
1075  return false;
1076  }
1077 
1078  for (const Stmt *SubStmt : e->children())
1079  if (isCapturedBy(var, cast<Expr>(SubStmt)))
1080  return true;
1081 
1082  return false;
1083 }
1084 
1085 /// \brief Determine whether the given initializer is trivial in the sense
1086 /// that it requires no code to be generated.
1088  if (!Init)
1089  return true;
1090 
1091  if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1092  if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1093  if (Constructor->isTrivial() &&
1094  Constructor->isDefaultConstructor() &&
1095  !Construct->requiresZeroInitialization())
1096  return true;
1097 
1098  return false;
1099 }
1101  assert(emission.Variable && "emission was not valid!");
1102 
1103  // If this was emitted as a global constant, we're done.
1104  if (emission.wasEmittedAsGlobal()) return;
1105 
1106  const VarDecl &D = *emission.Variable;
1108  QualType type = D.getType();
1109 
1110  // If this local has an initializer, emit it now.
1111  const Expr *Init = D.getInit();
1112 
1113  // If we are at an unreachable point, we don't need to emit the initializer
1114  // unless it contains a label.
1115  if (!HaveInsertPoint()) {
1116  if (!Init || !ContainsLabel(Init)) return;
1118  }
1119 
1120  // Initialize the structure of a __block variable.
1121  if (emission.IsByRef)
1122  emitByrefStructureInit(emission);
1123 
1124  if (isTrivialInitializer(Init))
1125  return;
1126 
1127  CharUnits alignment = emission.Alignment;
1128 
1129  // Check whether this is a byref variable that's potentially
1130  // captured and moved by its own initializer. If so, we'll need to
1131  // emit the initializer first, then copy into the variable.
1132  bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1133 
1134  llvm::Value *Loc =
1135  capturedByInit ? emission.Address : emission.getObjectAddress(*this);
1136 
1137  llvm::Constant *constant = nullptr;
1138  if (emission.IsConstantAggregate || D.isConstexpr()) {
1139  assert(!capturedByInit && "constant init contains a capturing block?");
1140  constant = CGM.EmitConstantInit(D, this);
1141  }
1142 
1143  if (!constant) {
1144  LValue lv = MakeAddrLValue(Loc, type, alignment);
1145  lv.setNonGC(true);
1146  return EmitExprAsInit(Init, &D, lv, capturedByInit);
1147  }
1148 
1149  if (!emission.IsConstantAggregate) {
1150  // For simple scalar/complex initialization, store the value directly.
1151  LValue lv = MakeAddrLValue(Loc, type, alignment);
1152  lv.setNonGC(true);
1153  return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1154  }
1155 
1156  // If this is a simple aggregate initialization, we can optimize it
1157  // in various ways.
1158  bool isVolatile = type.isVolatileQualified();
1159 
1160  llvm::Value *SizeVal =
1161  llvm::ConstantInt::get(IntPtrTy,
1162  getContext().getTypeSizeInChars(type).getQuantity());
1163 
1164  llvm::Type *BP = Int8PtrTy;
1165  if (Loc->getType() != BP)
1166  Loc = Builder.CreateBitCast(Loc, BP);
1167 
1168  // If the initializer is all or mostly zeros, codegen with memset then do
1169  // a few stores afterward.
1171  CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
1172  Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1173  alignment.getQuantity(), isVolatile);
1174  // Zero and undef don't require a stores.
1175  if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
1176  Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1177  emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
1178  }
1179  } else {
1180  // Otherwise, create a temporary global with the initializer then
1181  // memcpy from the global to the alloca.
1182  std::string Name = getStaticDeclName(CGM, D);
1183  llvm::GlobalVariable *GV =
1184  new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
1185  llvm::GlobalValue::PrivateLinkage,
1186  constant, Name);
1187  GV->setAlignment(alignment.getQuantity());
1188  GV->setUnnamedAddr(true);
1189 
1190  llvm::Value *SrcPtr = GV;
1191  if (SrcPtr->getType() != BP)
1192  SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
1193 
1194  Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
1195  isVolatile);
1196  }
1197 }
1198 
1199 /// Emit an expression as an initializer for a variable at the given
1200 /// location. The expression is not necessarily the normal
1201 /// initializer for the variable, and the address is not necessarily
1202 /// its normal location.
1203 ///
1204 /// \param init the initializing expression
1205 /// \param var the variable to act as if we're initializing
1206 /// \param loc the address to initialize; its type is a pointer
1207 /// to the LLVM mapping of the variable's type
1208 /// \param alignment the alignment of the address
1209 /// \param capturedByInit true if the variable is a __block variable
1210 /// whose address is potentially changed by the initializer
1212  LValue lvalue, bool capturedByInit) {
1213  QualType type = D->getType();
1214 
1215  if (type->isReferenceType()) {
1216  RValue rvalue = EmitReferenceBindingToExpr(init);
1217  if (capturedByInit)
1218  drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1219  EmitStoreThroughLValue(rvalue, lvalue, true);
1220  return;
1221  }
1222  switch (getEvaluationKind(type)) {
1223  case TEK_Scalar:
1224  EmitScalarInit(init, D, lvalue, capturedByInit);
1225  return;
1226  case TEK_Complex: {
1227  ComplexPairTy complex = EmitComplexExpr(init);
1228  if (capturedByInit)
1229  drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1230  EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1231  return;
1232  }
1233  case TEK_Aggregate:
1234  if (type->isAtomicType()) {
1235  EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1236  } else {
1237  // TODO: how can we delay here if D is captured by its initializer?
1238  EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
1242  }
1243  return;
1244  }
1245  llvm_unreachable("bad evaluation kind");
1246 }
1247 
1248 /// Enter a destroy cleanup for the given local variable.
1250  const CodeGenFunction::AutoVarEmission &emission,
1251  QualType::DestructionKind dtorKind) {
1252  assert(dtorKind != QualType::DK_none);
1253 
1254  // Note that for __block variables, we want to destroy the
1255  // original stack object, not the possibly forwarded object.
1256  llvm::Value *addr = emission.getObjectAddress(*this);
1257 
1258  const VarDecl *var = emission.Variable;
1259  QualType type = var->getType();
1260 
1261  CleanupKind cleanupKind = NormalAndEHCleanup;
1262  CodeGenFunction::Destroyer *destroyer = nullptr;
1263 
1264  switch (dtorKind) {
1265  case QualType::DK_none:
1266  llvm_unreachable("no cleanup for trivially-destructible variable");
1267 
1269  // If there's an NRVO flag on the emission, we need a different
1270  // cleanup.
1271  if (emission.NRVOFlag) {
1272  assert(!type->isArrayType());
1274  EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
1275  emission.NRVOFlag);
1276  return;
1277  }
1278  break;
1279 
1281  // Suppress cleanups for pseudo-strong variables.
1282  if (var->isARCPseudoStrong()) return;
1283 
1284  // Otherwise, consider whether to use an EH cleanup or not.
1285  cleanupKind = getARCCleanupKind();
1286 
1287  // Use the imprecise destroyer by default.
1288  if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1290  break;
1291 
1293  break;
1294  }
1295 
1296  // If we haven't chosen a more specific destroyer, use the default.
1297  if (!destroyer) destroyer = getDestroyer(dtorKind);
1298 
1299  // Use an EH cleanup in array destructors iff the destructor itself
1300  // is being pushed as an EH cleanup.
1301  bool useEHCleanup = (cleanupKind & EHCleanup);
1302  EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1303  useEHCleanup);
1304 }
1305 
1307  assert(emission.Variable && "emission was not valid!");
1308 
1309  // If this was emitted as a global constant, we're done.
1310  if (emission.wasEmittedAsGlobal()) return;
1311 
1312  // If we don't have an insertion point, we're done. Sema prevents
1313  // us from jumping into any of these scopes anyway.
1314  if (!HaveInsertPoint()) return;
1315 
1316  const VarDecl &D = *emission.Variable;
1317 
1318  // Make sure we call @llvm.lifetime.end. This needs to happen
1319  // *last*, so the cleanup needs to be pushed *first*.
1320  if (emission.useLifetimeMarkers()) {
1321  EHStack.pushCleanup<CallLifetimeEnd>(NormalCleanup,
1322  emission.getAllocatedAddress(),
1323  emission.getSizeForLifetimeMarkers());
1324  EHCleanupScope &cleanup = cast<EHCleanupScope>(*EHStack.begin());
1325  cleanup.setLifetimeMarker();
1326  }
1327 
1328  // Check the type for a cleanup.
1329  if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1330  emitAutoVarTypeCleanup(emission, dtorKind);
1331 
1332  // In GC mode, honor objc_precise_lifetime.
1333  if (getLangOpts().getGC() != LangOptions::NonGC &&
1334  D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1335  EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1336  }
1337 
1338  // Handle the cleanup attribute.
1339  if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
1340  const FunctionDecl *FD = CA->getFunctionDecl();
1341 
1342  llvm::Constant *F = CGM.GetAddrOfFunction(FD);
1343  assert(F && "Could not find function!");
1344 
1346  EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
1347  }
1348 
1349  // If this is a block variable, call _Block_object_destroy
1350  // (on the unforwarded address).
1351  if (emission.IsByRef)
1352  enterByrefCleanup(emission);
1353 }
1354 
1357  switch (kind) {
1358  case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
1360  return destroyCXXObject;
1362  return destroyARCStrongPrecise;
1364  return destroyARCWeak;
1365  }
1366  llvm_unreachable("Unknown DestructionKind");
1367 }
1368 
1369 /// pushEHDestroy - Push the standard destructor for the given type as
1370 /// an EH-only cleanup.
1372  llvm::Value *addr, QualType type) {
1373  assert(dtorKind && "cannot push destructor for trivial type");
1374  assert(needsEHCleanup(dtorKind));
1375 
1376  pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1377 }
1378 
1379 /// pushDestroy - Push the standard destructor for the given type as
1380 /// at least a normal cleanup.
1382  llvm::Value *addr, QualType type) {
1383  assert(dtorKind && "cannot push destructor for trivial type");
1384 
1385  CleanupKind cleanupKind = getCleanupKind(dtorKind);
1386  pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1387  cleanupKind & EHCleanup);
1388 }
1389 
1391  QualType type, Destroyer *destroyer,
1392  bool useEHCleanupForArray) {
1393  pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1394  destroyer, useEHCleanupForArray);
1395 }
1396 
1398  EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1399 }
1400 
1402  CleanupKind cleanupKind, llvm::Value *addr, QualType type,
1403  Destroyer *destroyer, bool useEHCleanupForArray) {
1404  assert(!isInConditionalBranch() &&
1405  "performing lifetime extension from within conditional");
1406 
1407  // Push an EH-only cleanup for the object now.
1408  // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1409  // around in case a temporary's destructor throws an exception.
1410  if (cleanupKind & EHCleanup)
1411  EHStack.pushCleanup<DestroyObject>(
1412  static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1413  destroyer, useEHCleanupForArray);
1414 
1415  // Remember that we need to push a full cleanup for the object at the
1416  // end of the full-expression.
1417  pushCleanupAfterFullExpr<DestroyObject>(
1418  cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1419 }
1420 
1421 /// emitDestroy - Immediately perform the destruction of the given
1422 /// object.
1423 ///
1424 /// \param addr - the address of the object; a type*
1425 /// \param type - the type of the object; if an array type, all
1426 /// objects are destroyed in reverse order
1427 /// \param destroyer - the function to call to destroy individual
1428 /// elements
1429 /// \param useEHCleanupForArray - whether an EH cleanup should be
1430 /// used when destroying array elements, in case one of the
1431 /// destructions throws an exception
1433  Destroyer *destroyer,
1434  bool useEHCleanupForArray) {
1435  const ArrayType *arrayType = getContext().getAsArrayType(type);
1436  if (!arrayType)
1437  return destroyer(*this, addr, type);
1438 
1439  llvm::Value *begin = addr;
1440  llvm::Value *length = emitArrayLength(arrayType, type, begin);
1441 
1442  // Normally we have to check whether the array is zero-length.
1443  bool checkZeroLength = true;
1444 
1445  // But if the array length is constant, we can suppress that.
1446  if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1447  // ...and if it's constant zero, we can just skip the entire thing.
1448  if (constLength->isZero()) return;
1449  checkZeroLength = false;
1450  }
1451 
1452  llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
1453  emitArrayDestroy(begin, end, type, destroyer,
1454  checkZeroLength, useEHCleanupForArray);
1455 }
1456 
1457 /// emitArrayDestroy - Destroys all the elements of the given array,
1458 /// beginning from last to first. The array cannot be zero-length.
1459 ///
1460 /// \param begin - a type* denoting the first element of the array
1461 /// \param end - a type* denoting one past the end of the array
1462 /// \param type - the element type of the array
1463 /// \param destroyer - the function to call to destroy elements
1464 /// \param useEHCleanup - whether to push an EH cleanup to destroy
1465 /// the remaining elements in case the destruction of a single
1466 /// element throws
1468  llvm::Value *end,
1469  QualType type,
1470  Destroyer *destroyer,
1471  bool checkZeroLength,
1472  bool useEHCleanup) {
1473  assert(!type->isArrayType());
1474 
1475  // The basic structure here is a do-while loop, because we don't
1476  // need to check for the zero-element case.
1477  llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1478  llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1479 
1480  if (checkZeroLength) {
1481  llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1482  "arraydestroy.isempty");
1483  Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1484  }
1485 
1486  // Enter the loop body, making that address the current address.
1487  llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1488  EmitBlock(bodyBB);
1489  llvm::PHINode *elementPast =
1490  Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1491  elementPast->addIncoming(end, entryBB);
1492 
1493  // Shift the address back by one element.
1494  llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1495  llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1496  "arraydestroy.element");
1497 
1498  if (useEHCleanup)
1499  pushRegularPartialArrayCleanup(begin, element, type, destroyer);
1500 
1501  // Perform the actual destruction there.
1502  destroyer(*this, element, type);
1503 
1504  if (useEHCleanup)
1505  PopCleanupBlock();
1506 
1507  // Check whether we've reached the end.
1508  llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1509  Builder.CreateCondBr(done, doneBB, bodyBB);
1510  elementPast->addIncoming(element, Builder.GetInsertBlock());
1511 
1512  // Done.
1513  EmitBlock(doneBB);
1514 }
1515 
1516 /// Perform partial array destruction as if in an EH cleanup. Unlike
1517 /// emitArrayDestroy, the element type here may still be an array type.
1519  llvm::Value *begin, llvm::Value *end,
1520  QualType type,
1521  CodeGenFunction::Destroyer *destroyer) {
1522  // If the element type is itself an array, drill down.
1523  unsigned arrayDepth = 0;
1524  while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1525  // VLAs don't require a GEP index to walk into.
1526  if (!isa<VariableArrayType>(arrayType))
1527  arrayDepth++;
1528  type = arrayType->getElementType();
1529  }
1530 
1531  if (arrayDepth) {
1532  llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
1533 
1534  SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
1535  begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1536  end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
1537  }
1538 
1539  // Destroy the array. We don't ever need an EH cleanup because we
1540  // assume that we're in an EH cleanup ourselves, so a throwing
1541  // destructor causes an immediate terminate.
1542  CGF.emitArrayDestroy(begin, end, type, destroyer,
1543  /*checkZeroLength*/ true, /*useEHCleanup*/ false);
1544 }
1545 
1546 namespace {
1547  /// RegularPartialArrayDestroy - a cleanup which performs a partial
1548  /// array destroy where the end pointer is regularly determined and
1549  /// does not need to be loaded from a local.
1550  class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
1551  llvm::Value *ArrayBegin;
1552  llvm::Value *ArrayEnd;
1553  QualType ElementType;
1554  CodeGenFunction::Destroyer *Destroyer;
1555  public:
1556  RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1557  QualType elementType,
1558  CodeGenFunction::Destroyer *destroyer)
1559  : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
1560  ElementType(elementType), Destroyer(destroyer) {}
1561 
1562  void Emit(CodeGenFunction &CGF, Flags flags) override {
1563  emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1564  ElementType, Destroyer);
1565  }
1566  };
1567 
1568  /// IrregularPartialArrayDestroy - a cleanup which performs a
1569  /// partial array destroy where the end pointer is irregularly
1570  /// determined and must be loaded from a local.
1571  class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
1572  llvm::Value *ArrayBegin;
1573  llvm::Value *ArrayEndPointer;
1574  QualType ElementType;
1575  CodeGenFunction::Destroyer *Destroyer;
1576  public:
1577  IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1578  llvm::Value *arrayEndPointer,
1579  QualType elementType,
1580  CodeGenFunction::Destroyer *destroyer)
1581  : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
1582  ElementType(elementType), Destroyer(destroyer) {}
1583 
1584  void Emit(CodeGenFunction &CGF, Flags flags) override {
1585  llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
1586  emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1587  ElementType, Destroyer);
1588  }
1589  };
1590 }
1591 
1592 /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
1593 /// already-constructed elements of the given array. The cleanup
1594 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1595 ///
1596 /// \param elementType - the immediate element type of the array;
1597 /// possibly still an array type
1599  llvm::Value *arrayEndPointer,
1600  QualType elementType,
1601  Destroyer *destroyer) {
1602  pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1603  arrayBegin, arrayEndPointer,
1604  elementType, destroyer);
1605 }
1606 
1607 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1608 /// already-constructed elements of the given array. The cleanup
1609 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1610 ///
1611 /// \param elementType - the immediate element type of the array;
1612 /// possibly still an array type
1614  llvm::Value *arrayEnd,
1615  QualType elementType,
1616  Destroyer *destroyer) {
1617  pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
1618  arrayBegin, arrayEnd,
1619  elementType, destroyer);
1620 }
1621 
1622 /// Lazily declare the @llvm.lifetime.start intrinsic.
1624  if (LifetimeStartFn) return LifetimeStartFn;
1625  LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1626  llvm::Intrinsic::lifetime_start);
1627  return LifetimeStartFn;
1628 }
1629 
1630 /// Lazily declare the @llvm.lifetime.end intrinsic.
1632  if (LifetimeEndFn) return LifetimeEndFn;
1633  LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1634  llvm::Intrinsic::lifetime_end);
1635  return LifetimeEndFn;
1636 }
1637 
1638 namespace {
1639  /// A cleanup to perform a release of an object at the end of a
1640  /// function. This is used to balance out the incoming +1 of a
1641  /// ns_consumed argument when we can't reasonably do that just by
1642  /// not doing the initial retain for a __block argument.
1643  struct ConsumeARCParameter : EHScopeStack::Cleanup {
1644  ConsumeARCParameter(llvm::Value *param,
1645  ARCPreciseLifetime_t precise)
1646  : Param(param), Precise(precise) {}
1647 
1648  llvm::Value *Param;
1649  ARCPreciseLifetime_t Precise;
1650 
1651  void Emit(CodeGenFunction &CGF, Flags flags) override {
1652  CGF.EmitARCRelease(Param, Precise);
1653  }
1654  };
1655 }
1656 
1657 /// Emit an alloca (or GlobalValue depending on target)
1658 /// for the specified parameter and set up LocalDeclMap.
1660  bool ArgIsPointer, unsigned ArgNo) {
1661  // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
1662  assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
1663  "Invalid argument to EmitParmDecl");
1664 
1665  Arg->setName(D.getName());
1666 
1667  QualType Ty = D.getType();
1668 
1669  // Use better IR generation for certain implicit parameters.
1670  if (isa<ImplicitParamDecl>(D)) {
1671  // The only implicit argument a block has is its literal.
1672  if (BlockInfo) {
1673  LocalDeclMap[&D] = Arg;
1674  llvm::Value *LocalAddr = nullptr;
1675  if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1676  // Allocate a stack slot to let the debug info survive the RA.
1677  llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1678  D.getName() + ".addr");
1679  Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
1680  LValue lv = MakeAddrLValue(Alloc, Ty, getContext().getDeclAlign(&D));
1681  EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1682  LocalAddr = Builder.CreateLoad(Alloc);
1683  }
1684 
1685  if (CGDebugInfo *DI = getDebugInfo()) {
1686  if (CGM.getCodeGenOpts().getDebugInfo()
1688  DI->setLocation(D.getLocation());
1689  DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, ArgNo,
1690  LocalAddr, Builder);
1691  }
1692  }
1693 
1694  return;
1695  }
1696  }
1697 
1698  llvm::Value *DeclPtr;
1699  bool DoStore = false;
1700  bool IsScalar = hasScalarEvaluationKind(Ty);
1701  CharUnits Align = getContext().getDeclAlign(&D);
1702  // If we already have a pointer to the argument, reuse the input pointer.
1703  if (ArgIsPointer) {
1704  // If we have a prettier pointer type at this point, bitcast to that.
1705  unsigned AS = cast<llvm::PointerType>(Arg->getType())->getAddressSpace();
1706  llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
1707  DeclPtr = Arg->getType() == IRTy ? Arg : Builder.CreateBitCast(Arg, IRTy,
1708  D.getName());
1709  // Push a destructor cleanup for this parameter if the ABI requires it.
1710  // Don't push a cleanup in a thunk for a method that will also emit a
1711  // cleanup.
1712  if (!IsScalar && !CurFuncIsThunk &&
1714  const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1715  if (RD && RD->hasNonTrivialDestructor())
1717  }
1718  } else {
1719  // Otherwise, create a temporary to hold the value.
1720  llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1721  D.getName() + ".addr");
1722  Alloc->setAlignment(Align.getQuantity());
1723  DeclPtr = Alloc;
1724  DoStore = true;
1725  }
1726 
1727  LValue lv = MakeAddrLValue(DeclPtr, Ty, Align);
1728  if (IsScalar) {
1729  Qualifiers qs = Ty.getQualifiers();
1730  if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1731  // We honor __attribute__((ns_consumed)) for types with lifetime.
1732  // For __strong, it's handled by just skipping the initial retain;
1733  // otherwise we have to balance out the initial +1 with an extra
1734  // cleanup to do the release at the end of the function.
1735  bool isConsumed = D.hasAttr<NSConsumedAttr>();
1736 
1737  // 'self' is always formally __strong, but if this is not an
1738  // init method then we don't want to retain it.
1739  if (D.isARCPseudoStrong()) {
1740  const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1741  assert(&D == method->getSelfDecl());
1742  assert(lt == Qualifiers::OCL_Strong);
1743  assert(qs.hasConst());
1744  assert(method->getMethodFamily() != OMF_init);
1745  (void) method;
1747  }
1748 
1749  if (lt == Qualifiers::OCL_Strong) {
1750  if (!isConsumed) {
1751  if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1752  // use objc_storeStrong(&dest, value) for retaining the
1753  // object. But first, store a null into 'dest' because
1754  // objc_storeStrong attempts to release its old value.
1755  llvm::Value *Null = CGM.EmitNullConstant(D.getType());
1756  EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
1757  EmitARCStoreStrongCall(lv.getAddress(), Arg, true);
1758  DoStore = false;
1759  }
1760  else
1761  // Don't use objc_retainBlock for block pointers, because we
1762  // don't want to Block_copy something just because we got it
1763  // as a parameter.
1764  Arg = EmitARCRetainNonBlock(Arg);
1765  }
1766  } else {
1767  // Push the cleanup for a consumed parameter.
1768  if (isConsumed) {
1769  ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1771  EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg,
1772  precise);
1773  }
1774 
1775  if (lt == Qualifiers::OCL_Weak) {
1776  EmitARCInitWeak(DeclPtr, Arg);
1777  DoStore = false; // The weak init is a store, no need to do two.
1778  }
1779  }
1780 
1781  // Enter the cleanup scope.
1782  EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1783  }
1784  }
1785 
1786  // Store the initial value into the alloca.
1787  if (DoStore)
1788  EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1789 
1790  llvm::Value *&DMEntry = LocalDeclMap[&D];
1791  assert(!DMEntry && "Decl already exists in localdeclmap!");
1792  DMEntry = DeclPtr;
1793 
1794  // Emit debug info for param declaration.
1795  if (CGDebugInfo *DI = getDebugInfo()) {
1796  if (CGM.getCodeGenOpts().getDebugInfo()
1798  DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
1799  }
1800  }
1801 
1802  if (D.hasAttr<AnnotateAttr>())
1803  EmitVarAnnotations(&D, DeclPtr);
1804 }
unsigned getAddressSpace() const
getAddressSpace - Return the address space of this type.
Definition: Type.h:5131
CGOpenCLRuntime & getOpenCLRuntime()
Return a reference to the configured OpenCL runtime.
Defines the clang::ASTContext interface.
StringRef getName() const
Definition: Decl.h:168
void EmitStaticVarDecl(const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage)
Definition: CGDecl.cpp:340
llvm::Value * EmitARCRetainAutoreleaseScalarExpr(const Expr *expr)
Definition: CGObjC.cpp:2747
Destroyer * getDestroyer(QualType::DestructionKind destructionKind)
Definition: CGDecl.cpp:1356
void EmitExtendGCLifetime(llvm::Value *object)
Definition: CGObjC.cpp:2867
llvm::Type * ConvertTypeForMem(QualType T)
void EmitVarDecl(const VarDecl &D)
Definition: CGDecl.cpp:129
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1263
DestructionKind isDestructedType() const
Definition: Type.h:999
llvm::Module & getModule() const
static AggValueSlot forLValue(const LValue &LV, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, IsZeroed_t isZeroed=IsNotZeroed)
Definition: CGValue.h:441
const TargetInfo & getTarget() const
SanitizerSet Sanitize
Set of enabled sanitizers.
Definition: LangOptions.h:79
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp")
Definition: CGExpr.cpp:57
Defines the SourceManager interface.
static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init, unsigned &NumStores)
Definition: CGDecl.cpp:744
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:163
bool isRecordType() const
Definition: Type.h:5289
void emitAutoVarTypeCleanup(const AutoVarEmission &emission, QualType::DestructionKind dtorKind)
Enter a destroy cleanup for the given local variable.
Definition: CGDecl.cpp:1249
QualType getUnderlyingType() const
Definition: Decl.h:2616
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
bool hasNonTrivialDestructor() const
Determine whether this class has a non-trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1269
void EmitAutoVarDecl(const VarDecl &D)
Definition: CGDecl.cpp:847
const llvm::DataLayout & getDataLayout() const
static Destroyer destroyARCStrongPrecise
void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false)
Definition: CGExpr.cpp:1469
const Expr * getInit() const
Definition: Decl.h:1068
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1075
const LangOptions & getLangOpts() const
llvm::Value * EmitARCRetainNonBlock(llvm::Value *value)
Definition: CGObjC.cpp:1933
void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, bool ForVirtualBase, bool Delegating, llvm::Value *This)
Definition: CGClass.cpp:1950
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2147
llvm::Value * getAddress() const
Definition: CGValue.h:265
void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin, llvm::Value *arrayEndPointer, QualType elementType, Destroyer *destroyer)
Definition: CGDecl.cpp:1598
bool areArgsDestroyedLeftToRightInCallee() const
Definition: TargetCXXABI.h:163
ObjCLifetime getObjCLifetime() const
Definition: Type.h:287
void EmitVariablyModifiedType(QualType Ty)
capture_range captures()
Definition: Decl.h:3563
llvm::Type * ConvertTypeForMem(QualType T)
void setAddress(llvm::Value *address)
Definition: CGValue.h:266
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have...
Definition: Linkage.h:25
void emitByrefStructureInit(const AutoVarEmission &emission)
Definition: CGBlocks.cpp:2127
bool hasAttr() const
Definition: DeclBase.h:487
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:1742
void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue, bool capturedByInit)
Definition: CGDecl.cpp:1211
RValue EmitReferenceBindingToExpr(const Expr *E)
Emits a reference binding to the passed in expression.
Definition: CGExpr.cpp:442
bool isReferenceType() const
Definition: Type.h:5241
void EmitARCInitWeak(llvm::Value *value, llvm::Value *addr)
Definition: CGObjC.cpp:2214
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
Definition: ASTMatchers.h:258
void reportGlobalToASan(llvm::GlobalVariable *GV, const VarDecl &D, bool IsDynInit=false)
CleanupKind getCleanupKind(QualType::DestructionKind kind)
const Decl * getDecl() const
Definition: GlobalDecl.h:60
StorageClass getStorageClass() const
Returns the storage class as written in the source. For the computed linkage of symbol, see getLinkage.
Definition: Decl.h:871
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:913
void setNonGC(bool Value)
Definition: CGValue.h:218
T * getAttr() const
Definition: DeclBase.h:484
LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment=CharUnits())
llvm::Constant * getLLVMLifetimeStartFn()
Lazily declare the .lifetime.start intrinsic.
Definition: CGDecl.cpp:1623
static bool hasScalarEvaluationKind(QualType T)
void Destroyer(CodeGenFunction &CGF, llvm::Value *addr, QualType ty)
iterator begin() const
Returns an iterator pointing to the innermost EH scope.
Definition: CGCleanup.h:518
static void drillIntoBlockVariable(CodeGenFunction &CGF, LValue &lvalue, const VarDecl *var)
Definition: CGDecl.cpp:598
RValue EmitCall(const CGFunctionInfo &FnInfo, llvm::Value *Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, const Decl *TargetDecl=nullptr, llvm::Instruction **callOrInvoke=nullptr)
Definition: CGCall.cpp:3106
Base object ctor.
Definition: ABI.h:27
static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init, uint64_t GlobalSize)
Definition: CGDecl.cpp:828
Qualifiers::ObjCLifetime getObjCLifetime() const
Definition: CGValue.h:207
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
Definition: DeclObjC.cpp:856
void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin, llvm::Value *arrayEnd, QualType elementType, Destroyer *destroyer)
Definition: CGDecl.cpp:1613
void EmitGlobalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl)
Emit information about a global variable.
void setStaticLocalDeclAddress(const VarDecl *D, llvm::Constant *C)
const ArrayType * getAsArrayType(QualType T) const
bool needsEHCleanup(QualType::DestructionKind kind)
void pushDestroy(QualType::DestructionKind dtorKind, llvm::Value *addr, QualType type)
Definition: CGDecl.cpp:1381
llvm::Value * getObjectAddress(CodeGenFunction &CGF) const
std::string getNameAsString() const
Definition: Decl.h:183
Expr * IgnoreParenCasts() LLVM_READONLY
Definition: Expr.cpp:2439
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
llvm::Value * EmitARCRetainScalarExpr(const Expr *expr)
Definition: CGObjC.cpp:2731
void EmitAtomicInit(Expr *E, LValue lvalue)
Definition: CGAtomic.cpp:1750
bool hasConst() const
Definition: Type.h:226
bool isStaticLocal() const
Definition: Decl.h:904
static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts=false)
llvm::Type * BuildByRefType(const VarDecl *var)
Definition: CGBlocks.cpp:2036
void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const
Set the visibility for the given LLVM GlobalValue.
QualType getType() const
Definition: Decl.h:538
bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor)
std::pair< llvm::Value *, llvm::Value * > ComplexPairTy
AutoVarEmission EmitAutoVarAlloca(const VarDecl &var)
Definition: CGDecl.cpp:885
void emitDestroy(llvm::Value *addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray)
Definition: CGDecl.cpp:1432
const CodeGen::CGBlockInfo * BlockInfo
StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD)
std::vector< bool > & Stack
void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr, bool PerformInit)
Definition: CGDeclCXX.cpp:237
static TypeEvaluationKind getEvaluationKind(QualType T)
llvm::Value * EmitARCStoreWeak(llvm::Value *value, llvm::Value *addr, bool ignored)
Definition: CGObjC.cpp:2202
void EmitAutoVarInit(const AutoVarEmission &emission)
Definition: CGDecl.cpp:1100
static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var, llvm::Value *addr, Qualifiers::ObjCLifetime lifetime)
Definition: CGDecl.cpp:530
void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV)
Enters a new scope for capturing cleanups, all of which will be executed once the scope is exited...
bool isAtomicType() const
Definition: Type.h:5314
virtual void EmitWorkGroupLocalVarDecl(CodeGenFunction &CGF, const VarDecl &D)
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2358
llvm::Value * emitArrayLength(const ArrayType *arrayType, QualType &baseType, llvm::Value *&addr)
Kind getKind() const
Definition: DeclBase.h:375
DeclContext * getDeclContext()
Definition: DeclBase.h:381
ASTContext & getContext() const
ImplicitParamDecl * getSelfDecl() const
Definition: DeclObjC.h:411
void add(RValue rvalue, QualType type, bool needscopy=false)
Definition: CGCall.h:81
std::pair< llvm::Type *, unsigned > getByRefValueLLVMField(const ValueDecl *VD) const
Definition: CGBlocks.cpp:2005
Base object dtor.
Definition: ABI.h:37
llvm::GlobalValue::LinkageTypes getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant)
Returns LLVM linkage for a declarator.
bool isExternallyVisible() const
Definition: Decl.h:279
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys=None)
static bool hasNontrivialDestruction(QualType T)
Definition: CGDecl.cpp:271
static bool isCapturedBy(const VarDecl &var, const Expr *e)
Definition: CGDecl.cpp:1038
llvm::IRBuilder< PreserveNames, llvm::ConstantFolder, CGBuilderInserterTy > CGBuilderTy
Definition: CGBuilder.h:49
void EmitParmDecl(const VarDecl &D, llvm::Value *Arg, bool ArgIsPointer, unsigned ArgNo)
EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
Definition: CGDecl.cpp:1659
void enterByrefCleanup(const AutoVarEmission &emission)
Definition: CGBlocks.cpp:2258
llvm::Constant * getOrCreateStaticVarDecl(const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage)
Definition: CGDecl.cpp:175
There is no lifetime qualification on this type.
Definition: Type.h:130
llvm::GlobalVariable * AddInitializerToStaticVarDecl(const VarDecl &D, llvm::GlobalVariable *GV)
Definition: CGDecl.cpp:281
Kind
ASTContext & getContext() const
Encodes a location in the source. The SourceManager can decode this to get at the full include stack...
body_range body()
Definition: Stmt.h:585
void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise)
Definition: CGObjC.cpp:2021
LValue EmitDeclRefLValue(const DeclRefExpr *E)
Definition: CGExpr.cpp:1928
static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D)
Definition: CGDecl.cpp:152
bool isConstant(ASTContext &Ctx) const
Definition: Type.h:703
bool isConstantSizeType() const
Definition: Type.cpp:1859
bool isLocalVarDecl() const
Definition: Decl.h:951
llvm::Value * EmitLifetimeStart(uint64_t Size, llvm::Value *Addr)
Definition: CGDecl.cpp:856
static bool isAccessedBy(const VarDecl &var, const Stmt *s)
Definition: CGDecl.cpp:566
void pushEHDestroy(QualType::DestructionKind dtorKind, llvm::Value *addr, QualType type)
Definition: CGDecl.cpp:1371
bool isTrivialInitializer(const Expr *Init)
Determine whether the given initializer is trivial in the sense that it requires no code to be genera...
Definition: CGDecl.cpp:1087
const CodeGenOptions & getCodeGenOpts() const
const Type * getBaseElementTypeUnsafe() const
Definition: Type.h:5520
const LangOptions & getLangOpts() const
Complete object dtor.
Definition: ABI.h:36
Assigning into this object requires a lifetime extension.
Definition: Type.h:147
llvm::Value * EmitARCRetain(QualType type, llvm::Value *value)
Definition: CGObjC.cpp:1924
llvm::Constant * getLLVMLifetimeEndFn()
Lazily declare the .lifetime.end intrinsic.
Definition: CGDecl.cpp:1631
void enterFullExpression(const ExprWithCleanups *E)
void EmitDecl(const Decl &D)
Definition: CGDecl.cpp:35
static Destroyer destroyARCStrongImprecise
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.cpp:193
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
void addUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.used metadata.
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:2576
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn't support the specified stmt yet.
static ApplyDebugLocation CreateDefaultArtificial(CodeGenFunction &CGF, SourceLocation TemporaryLocation)
Apply TemporaryLocation if it is valid. Otherwise switch to an artificial debug location that has a v...
Definition: CGDebugInfo.h:532
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=0, bool ForVTable=false, bool DontDefer=false)
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:1302
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
Definition: ASTMatchers.h:1639
const CGFunctionInfo & arrangeFunctionDeclaration(const FunctionDecl *FD)
Definition: CGCall.cpp:257
void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
void emitArrayDestroy(llvm::Value *begin, llvm::Value *end, QualType type, Destroyer *destroyer, bool checkZeroLength, bool useEHCleanup)
Definition: CGDecl.cpp:1467
static void emitPartialArrayDestroy(CodeGenFunction &CGF, llvm::Value *begin, llvm::Value *end, QualType type, CodeGenFunction::Destroyer *destroyer)
Definition: CGDecl.cpp:1518
Decl * getNonClosureContext()
Definition: DeclBase.cpp:782
llvm::Constant * EmitNullConstant(QualType T)
unsigned GetGlobalVarAddressSpace(const VarDecl *D, unsigned AddrSpace)
void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr, bool Volatile, unsigned Alignment, QualType Ty, llvm::MDNode *TBAAInfo=nullptr, bool isInit=false, QualType TBAABaseTy=QualType(), uint64_t TBAAOffset=0)
Definition: CGExpr.cpp:1244
void EmitAggExpr(const Expr *E, AggValueSlot AS)
Definition: CGExprAgg.cpp:1403
bool isConstantInitializer(ASTContext &Ctx, bool ForRef, const Expr **Culprit=nullptr) const
Definition: Expr.cpp:2727
void EmitAutoVarCleanups(const AutoVarEmission &emission)
Definition: CGDecl.cpp:1306
const T * getAs() const
Definition: Type.h:5555
void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit)
EmitStoreOfComplex - Store a complex number into the specified l-value.
llvm::Value * BuildBlockByrefAddress(llvm::Value *BaseAddr, const VarDecl *V)
Definition: CGBlocks.cpp:2011
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition: Sanitizers.h:52
void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue, bool capturedByInit)
Definition: CGDecl.cpp:604
bool isNRVOVariable() const
Determine whether this local variable can be used with the named return value optimization (NRVO)...
Definition: Decl.h:1202
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1505
llvm::Value * EmitARCRetainAutorelease(QualType type, llvm::Value *value)
Definition: CGObjC.cpp:2162
StringRef getMangledName(GlobalDecl GD)
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition: Linkage.h:33
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
Definition: CGStmt.cpp:348
ARCPreciseLifetime_t
Does an ARC strong l-value have precise lifetime?
Definition: CGValue.h:102
ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal=false, bool IgnoreImag=false)
llvm::Constant * EmitConstantInit(const VarDecl &D, CodeGenFunction *CGF=nullptr)
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:952
Reading or writing from this object requires a barrier call.
Definition: Type.h:144
bool isPODType(ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:1922
llvm::DenseMap< const VarDecl *, llvm::Value * > NRVOFlags
A mapping from NRVO variables to the flags used to indicate when the NRVO has been applied to this va...
static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc, bool isVolatile, CGBuilderTy &Builder)
Definition: CGDecl.cpp:783
bool isARCPseudoStrong() const
Determine whether this variable is an ARC pseudo-__strong variable. A pseudo-__strong variable has a ...
Definition: Decl.h:1224
Represents a C++ struct/union/class.
Definition: DeclCXX.h:285
BoundNodesTreeBuilder *const Builder
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
bool isObjCObjectPointerType() const
Definition: Type.h:5304
llvm::Type * ConvertType(QualType T)
llvm::Constant * GetAddrOfGlobal(GlobalDecl GD)
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1233
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Definition: DiagnosticIDs.h:43
A cleanup scope which generates the cleanup blocks lazily.
Definition: CGCleanup.h:219
bool isArrayType() const
Definition: Type.h:5271
llvm::Value * EmitARCStoreStrongCall(llvm::Value *addr, llvm::Value *value, bool resultIgnored)
Definition: CGObjC.cpp:2069
std::pair< llvm::Value *, QualType > getVLASize(const VariableArrayType *vla)
Defines the clang::TargetInfo interface.
QualType getType() const
Definition: CGValue.h:205
void setLocation(SourceLocation Loc)
void pushStackRestore(CleanupKind kind, llvm::Value *SPMem)
Definition: CGDecl.cpp:1397
unsigned getTargetAddressSpace(QualType T) const
Definition: ASTContext.h:2089
A reference to a declared variable, function, enum, etc. [C99 6.5.1p2].
Definition: Expr.h:899
static RValue get(llvm::Value *V)
Definition: CGValue.h:71
llvm::Value * EmitLoadOfScalar(llvm::Value *Addr, bool Volatile, unsigned Alignment, QualType Ty, SourceLocation Loc, llvm::MDNode *TBAAInfo=nullptr, QualType TBAABaseTy=QualType(), uint64_t TBAAOffset=0)
Definition: CGExpr.cpp:1120
void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr)
Definition: CGDecl.cpp:875
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:99
void pushLifetimeExtendedDestroy(CleanupKind kind, llvm::Value *addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray)
Definition: CGDecl.cpp:1401
SourceLocation getLocation() const
Definition: DeclBase.h:372
void EmitVarAnnotations(const VarDecl *D, llvm::Value *V)
Emit local annotations for the local variable V, declared by D.
SanitizerMetadata * getSanitizerMetadata()
void PopCleanupBlock(bool FallThroughIsBranchThrough=false)
Definition: CGCleanup.cpp:583
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
bool hasLocalStorage() const
Definition: Decl.h:887
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:5043