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