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