clang  8.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/Analysis/ValueTracking.h"
34 #include "llvm/IR/DataLayout.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/IR/Type.h"
38 
39 using namespace clang;
40 using namespace CodeGen;
41 
43  switch (D.getKind()) {
44  case Decl::BuiltinTemplate:
45  case Decl::TranslationUnit:
46  case Decl::ExternCContext:
47  case Decl::Namespace:
48  case Decl::UnresolvedUsingTypename:
49  case Decl::ClassTemplateSpecialization:
50  case Decl::ClassTemplatePartialSpecialization:
51  case Decl::VarTemplateSpecialization:
52  case Decl::VarTemplatePartialSpecialization:
53  case Decl::TemplateTypeParm:
54  case Decl::UnresolvedUsingValue:
55  case Decl::NonTypeTemplateParm:
56  case Decl::CXXDeductionGuide:
57  case Decl::CXXMethod:
58  case Decl::CXXConstructor:
59  case Decl::CXXDestructor:
60  case Decl::CXXConversion:
61  case Decl::Field:
62  case Decl::MSProperty:
63  case Decl::IndirectField:
64  case Decl::ObjCIvar:
65  case Decl::ObjCAtDefsField:
66  case Decl::ParmVar:
67  case Decl::ImplicitParam:
68  case Decl::ClassTemplate:
69  case Decl::VarTemplate:
70  case Decl::FunctionTemplate:
71  case Decl::TypeAliasTemplate:
72  case Decl::TemplateTemplateParm:
73  case Decl::ObjCMethod:
74  case Decl::ObjCCategory:
75  case Decl::ObjCProtocol:
76  case Decl::ObjCInterface:
77  case Decl::ObjCCategoryImpl:
78  case Decl::ObjCImplementation:
79  case Decl::ObjCProperty:
80  case Decl::ObjCCompatibleAlias:
81  case Decl::PragmaComment:
82  case Decl::PragmaDetectMismatch:
83  case Decl::AccessSpec:
84  case Decl::LinkageSpec:
85  case Decl::Export:
86  case Decl::ObjCPropertyImpl:
87  case Decl::FileScopeAsm:
88  case Decl::Friend:
89  case Decl::FriendTemplate:
90  case Decl::Block:
91  case Decl::Captured:
92  case Decl::ClassScopeFunctionSpecialization:
93  case Decl::UsingShadow:
94  case Decl::ConstructorUsingShadow:
95  case Decl::ObjCTypeParam:
96  case Decl::Binding:
97  llvm_unreachable("Declaration should not be in declstmts!");
98  case Decl::Function: // void X();
99  case Decl::Record: // struct/union/class X;
100  case Decl::Enum: // enum X;
101  case Decl::EnumConstant: // enum ? { X = ? }
102  case Decl::CXXRecord: // struct/union/class X; [C++]
103  case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
104  case Decl::Label: // __label__ x;
105  case Decl::Import:
106  case Decl::OMPThreadPrivate:
107  case Decl::OMPCapturedExpr:
108  case Decl::OMPRequires:
109  case Decl::Empty:
110  // None of these decls require codegen support.
111  return;
112 
113  case Decl::NamespaceAlias:
114  if (CGDebugInfo *DI = getDebugInfo())
115  DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
116  return;
117  case Decl::Using: // using X; [C++]
118  if (CGDebugInfo *DI = getDebugInfo())
119  DI->EmitUsingDecl(cast<UsingDecl>(D));
120  return;
121  case Decl::UsingPack:
122  for (auto *Using : cast<UsingPackDecl>(D).expansions())
123  EmitDecl(*Using);
124  return;
125  case Decl::UsingDirective: // using namespace X; [C++]
126  if (CGDebugInfo *DI = getDebugInfo())
127  DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
128  return;
129  case Decl::Var:
130  case Decl::Decomposition: {
131  const VarDecl &VD = cast<VarDecl>(D);
132  assert(VD.isLocalVarDecl() &&
133  "Should not see file-scope variables inside a function!");
134  EmitVarDecl(VD);
135  if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
136  for (auto *B : DD->bindings())
137  if (auto *HD = B->getHoldingVar())
138  EmitVarDecl(*HD);
139  return;
140  }
141 
142  case Decl::OMPDeclareReduction:
143  return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
144 
145  case Decl::Typedef: // typedef int X;
146  case Decl::TypeAlias: { // using X = int; [C++0x]
147  const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
148  QualType Ty = TD.getUnderlyingType();
149 
150  if (Ty->isVariablyModifiedType())
152  }
153  }
154 }
155 
156 /// EmitVarDecl - This method handles emission of any variable declaration
157 /// inside a function, including static vars etc.
159  if (D.hasExternalStorage())
160  // Don't emit it now, allow it to be emitted lazily on its first use.
161  return;
162 
163  // Some function-scope variable does not have static storage but still
164  // needs to be emitted like a static variable, e.g. a function-scope
165  // variable in constant address space in OpenCL.
166  if (D.getStorageDuration() != SD_Automatic) {
167  // Static sampler variables translated to function calls.
168  if (D.getType()->isSamplerT())
169  return;
170 
171  llvm::GlobalValue::LinkageTypes Linkage =
172  CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
173 
174  // FIXME: We need to force the emission/use of a guard variable for
175  // some variables even if we can constant-evaluate them because
176  // we can't guarantee every translation unit will constant-evaluate them.
177 
178  return EmitStaticVarDecl(D, Linkage);
179  }
180 
183 
184  assert(D.hasLocalStorage());
185  return EmitAutoVarDecl(D);
186 }
187 
188 static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
189  if (CGM.getLangOpts().CPlusPlus)
190  return CGM.getMangledName(&D).str();
191 
192  // If this isn't C++, we don't need a mangled name, just a pretty one.
193  assert(!D.isExternallyVisible() && "name shouldn't matter");
194  std::string ContextName;
195  const DeclContext *DC = D.getDeclContext();
196  if (auto *CD = dyn_cast<CapturedDecl>(DC))
197  DC = cast<DeclContext>(CD->getNonClosureContext());
198  if (const auto *FD = dyn_cast<FunctionDecl>(DC))
199  ContextName = CGM.getMangledName(FD);
200  else if (const auto *BD = dyn_cast<BlockDecl>(DC))
201  ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
202  else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
203  ContextName = OMD->getSelector().getAsString();
204  else
205  llvm_unreachable("Unknown context for static var decl");
206 
207  ContextName += "." + D.getNameAsString();
208  return ContextName;
209 }
210 
212  const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
213  // In general, we don't always emit static var decls once before we reference
214  // them. It is possible to reference them before emitting the function that
215  // contains them, and it is possible to emit the containing function multiple
216  // times.
217  if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
218  return ExistingGV;
219 
220  QualType Ty = D.getType();
221  assert(Ty->isConstantSizeType() && "VLAs can't be static");
222 
223  // Use the label if the variable is renamed with the asm-label extension.
224  std::string Name;
225  if (D.hasAttr<AsmLabelAttr>())
226  Name = getMangledName(&D);
227  else
228  Name = getStaticDeclName(*this, D);
229 
231  LangAS AS = GetGlobalVarAddressSpace(&D);
232  unsigned TargetAS = getContext().getTargetAddressSpace(AS);
233 
234  // OpenCL variables in local address space and CUDA shared
235  // variables cannot have an initializer.
236  llvm::Constant *Init = nullptr;
238  D.hasAttr<CUDASharedAttr>())
239  Init = llvm::UndefValue::get(LTy);
240  else
241  Init = EmitNullConstant(Ty);
242 
243  llvm::GlobalVariable *GV = new llvm::GlobalVariable(
244  getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name,
245  nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
246  GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
247 
248  if (supportsCOMDAT() && GV->isWeakForLinker())
249  GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
250 
251  if (D.getTLSKind())
252  setTLSMode(GV, D);
253 
254  setGVProperties(GV, &D);
255 
256  // Make sure the result is of the correct type.
257  LangAS ExpectedAS = Ty.getAddressSpace();
258  llvm::Constant *Addr = GV;
259  if (AS != ExpectedAS) {
260  Addr = getTargetCodeGenInfo().performAddrSpaceCast(
261  *this, GV, AS, ExpectedAS,
262  LTy->getPointerTo(getContext().getTargetAddressSpace(ExpectedAS)));
263  }
264 
265  setStaticLocalDeclAddress(&D, Addr);
266 
267  // Ensure that the static local gets initialized by making sure the parent
268  // function gets emitted eventually.
269  const Decl *DC = cast<Decl>(D.getDeclContext());
270 
271  // We can't name blocks or captured statements directly, so try to emit their
272  // parents.
273  if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
274  DC = DC->getNonClosureContext();
275  // FIXME: Ensure that global blocks get emitted.
276  if (!DC)
277  return Addr;
278  }
279 
280  GlobalDecl GD;
281  if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
282  GD = GlobalDecl(CD, Ctor_Base);
283  else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
284  GD = GlobalDecl(DD, Dtor_Base);
285  else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
286  GD = GlobalDecl(FD);
287  else {
288  // Don't do anything for Obj-C method decls or global closures. We should
289  // never defer them.
290  assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
291  }
292  if (GD.getDecl()) {
293  // Disable emission of the parent function for the OpenMP device codegen.
295  (void)GetAddrOfGlobal(GD);
296  }
297 
298  return Addr;
299 }
300 
301 /// hasNontrivialDestruction - Determine whether a type's destruction is
302 /// non-trivial. If so, and the variable uses static initialization, we must
303 /// register its destructor to run on exit.
306  return RD && !RD->hasTrivialDestructor();
307 }
308 
309 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
310 /// global variable that has already been created for it. If the initializer
311 /// has a different type than GV does, this may free GV and return a different
312 /// one. Otherwise it just returns GV.
313 llvm::GlobalVariable *
315  llvm::GlobalVariable *GV) {
316  ConstantEmitter emitter(*this);
317  llvm::Constant *Init = emitter.tryEmitForInitializer(D);
318 
319  // If constant emission failed, then this should be a C++ static
320  // initializer.
321  if (!Init) {
322  if (!getLangOpts().CPlusPlus)
323  CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
324  else if (HaveInsertPoint()) {
325  // Since we have a static initializer, this global variable can't
326  // be constant.
327  GV->setConstant(false);
328 
329  EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
330  }
331  return GV;
332  }
333 
334  // The initializer may differ in type from the global. Rewrite
335  // the global to match the initializer. (We have to do this
336  // because some types, like unions, can't be completely represented
337  // in the LLVM type system.)
338  if (GV->getType()->getElementType() != Init->getType()) {
339  llvm::GlobalVariable *OldGV = GV;
340 
341  GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
342  OldGV->isConstant(),
343  OldGV->getLinkage(), Init, "",
344  /*InsertBefore*/ OldGV,
345  OldGV->getThreadLocalMode(),
347  GV->setVisibility(OldGV->getVisibility());
348  GV->setDSOLocal(OldGV->isDSOLocal());
349  GV->setComdat(OldGV->getComdat());
350 
351  // Steal the name of the old global
352  GV->takeName(OldGV);
353 
354  // Replace all uses of the old global with the new global
355  llvm::Constant *NewPtrForOldDecl =
356  llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
357  OldGV->replaceAllUsesWith(NewPtrForOldDecl);
358 
359  // Erase the old global, since it is no longer used.
360  OldGV->eraseFromParent();
361  }
362 
363  GV->setConstant(CGM.isTypeConstant(D.getType(), true));
364  GV->setInitializer(Init);
365 
366  emitter.finalize(GV);
367 
369  // We have a constant initializer, but a nontrivial destructor. We still
370  // need to perform a guarded "initialization" in order to register the
371  // destructor.
372  EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
373  }
374 
375  return GV;
376 }
377 
379  llvm::GlobalValue::LinkageTypes Linkage) {
380  // Check to see if we already have a global variable for this
381  // declaration. This can happen when double-emitting function
382  // bodies, e.g. with complete and base constructors.
383  llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
384  CharUnits alignment = getContext().getDeclAlign(&D);
385 
386  // Store into LocalDeclMap before generating initializer to handle
387  // circular references.
388  setAddrOfLocalVar(&D, Address(addr, alignment));
389 
390  // We can't have a VLA here, but we can have a pointer to a VLA,
391  // even though that doesn't really make any sense.
392  // Make sure to evaluate VLA bounds now so that we have them for later.
393  if (D.getType()->isVariablyModifiedType())
395 
396  // Save the type in case adding the initializer forces a type change.
397  llvm::Type *expectedType = addr->getType();
398 
399  llvm::GlobalVariable *var =
400  cast<llvm::GlobalVariable>(addr->stripPointerCasts());
401 
402  // CUDA's local and local static __shared__ variables should not
403  // have any non-empty initializers. This is ensured by Sema.
404  // Whatever initializer such variable may have when it gets here is
405  // a no-op and should not be emitted.
406  bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
407  D.hasAttr<CUDASharedAttr>();
408  // If this value has an initializer, emit it.
409  if (D.getInit() && !isCudaSharedVar)
410  var = AddInitializerToStaticVarDecl(D, var);
411 
412  var->setAlignment(alignment.getQuantity());
413 
414  if (D.hasAttr<AnnotateAttr>())
415  CGM.AddGlobalAnnotations(&D, var);
416 
417  if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())
418  var->addAttribute("bss-section", SA->getName());
419  if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())
420  var->addAttribute("data-section", SA->getName());
421  if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())
422  var->addAttribute("rodata-section", SA->getName());
423 
424  if (const SectionAttr *SA = D.getAttr<SectionAttr>())
425  var->setSection(SA->getName());
426 
427  if (D.hasAttr<UsedAttr>())
428  CGM.addUsedGlobal(var);
429 
430  // We may have to cast the constant because of the initializer
431  // mismatch above.
432  //
433  // FIXME: It is really dangerous to store this in the map; if anyone
434  // RAUW's the GV uses of this constant will be invalid.
435  llvm::Constant *castedAddr =
436  llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
437  if (var != castedAddr)
438  LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
439  CGM.setStaticLocalDeclAddress(&D, castedAddr);
440 
442 
443  // Emit global variable debug descriptor for static vars.
444  CGDebugInfo *DI = getDebugInfo();
445  if (DI &&
447  DI->setLocation(D.getLocation());
448  DI->EmitGlobalVariable(var, &D);
449  }
450 }
451 
452 namespace {
453  struct DestroyObject final : EHScopeStack::Cleanup {
454  DestroyObject(Address addr, QualType type,
455  CodeGenFunction::Destroyer *destroyer,
456  bool useEHCleanupForArray)
457  : addr(addr), type(type), destroyer(destroyer),
458  useEHCleanupForArray(useEHCleanupForArray) {}
459 
460  Address addr;
461  QualType type;
462  CodeGenFunction::Destroyer *destroyer;
463  bool useEHCleanupForArray;
464 
465  void Emit(CodeGenFunction &CGF, Flags flags) override {
466  // Don't use an EH cleanup recursively from an EH cleanup.
467  bool useEHCleanupForArray =
468  flags.isForNormalCleanup() && this->useEHCleanupForArray;
469 
470  CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
471  }
472  };
473 
474  template <class Derived>
475  struct DestroyNRVOVariable : EHScopeStack::Cleanup {
476  DestroyNRVOVariable(Address addr, llvm::Value *NRVOFlag)
477  : NRVOFlag(NRVOFlag), Loc(addr) {}
478 
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 
497  static_cast<Derived *>(this)->emitDestructorCall(CGF);
498 
499  if (NRVO) CGF.EmitBlock(SkipDtorBB);
500  }
501 
502  virtual ~DestroyNRVOVariable() = default;
503  };
504 
505  struct DestroyNRVOVariableCXX final
506  : DestroyNRVOVariable<DestroyNRVOVariableCXX> {
507  DestroyNRVOVariableCXX(Address addr, const CXXDestructorDecl *Dtor,
508  llvm::Value *NRVOFlag)
509  : DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, NRVOFlag),
510  Dtor(Dtor) {}
511 
512  const CXXDestructorDecl *Dtor;
513 
514  void emitDestructorCall(CodeGenFunction &CGF) {
516  /*ForVirtualBase=*/false,
517  /*Delegating=*/false, Loc);
518  }
519  };
520 
521  struct DestroyNRVOVariableC final
522  : DestroyNRVOVariable<DestroyNRVOVariableC> {
523  DestroyNRVOVariableC(Address addr, llvm::Value *NRVOFlag, QualType Ty)
524  : DestroyNRVOVariable<DestroyNRVOVariableC>(addr, NRVOFlag), Ty(Ty) {}
525 
526  QualType Ty;
527 
528  void emitDestructorCall(CodeGenFunction &CGF) {
529  CGF.destroyNonTrivialCStruct(CGF, Loc, Ty);
530  }
531  };
532 
533  struct CallStackRestore final : EHScopeStack::Cleanup {
534  Address Stack;
535  CallStackRestore(Address Stack) : Stack(Stack) {}
536  void Emit(CodeGenFunction &CGF, Flags flags) override {
537  llvm::Value *V = CGF.Builder.CreateLoad(Stack);
538  llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
539  CGF.Builder.CreateCall(F, V);
540  }
541  };
542 
543  struct ExtendGCLifetime final : EHScopeStack::Cleanup {
544  const VarDecl &Var;
545  ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
546 
547  void Emit(CodeGenFunction &CGF, Flags flags) override {
548  // Compute the address of the local variable, in case it's a
549  // byref or something.
550  DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
551  Var.getType(), VK_LValue, SourceLocation());
552  llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
553  SourceLocation());
554  CGF.EmitExtendGCLifetime(value);
555  }
556  };
557 
558  struct CallCleanupFunction final : EHScopeStack::Cleanup {
559  llvm::Constant *CleanupFn;
560  const CGFunctionInfo &FnInfo;
561  const VarDecl &Var;
562 
563  CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
564  const VarDecl *Var)
565  : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
566 
567  void Emit(CodeGenFunction &CGF, Flags flags) override {
568  DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
569  Var.getType(), VK_LValue, SourceLocation());
570  // Compute the address of the local variable, in case it's a byref
571  // or something.
572  llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
573 
574  // In some cases, the type of the function argument will be different from
575  // the type of the pointer. An example of this is
576  // void f(void* arg);
577  // __attribute__((cleanup(f))) void *g;
578  //
579  // To fix this we insert a bitcast here.
580  QualType ArgTy = FnInfo.arg_begin()->type;
581  llvm::Value *Arg =
582  CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
583 
584  CallArgList Args;
585  Args.add(RValue::get(Arg),
586  CGF.getContext().getPointerType(Var.getType()));
587  auto Callee = CGCallee::forDirect(CleanupFn);
588  CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
589  }
590  };
591 } // end anonymous namespace
592 
593 /// EmitAutoVarWithLifetime - Does the setup required for an automatic
594 /// variable with lifetime.
595 static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
596  Address addr,
597  Qualifiers::ObjCLifetime lifetime) {
598  switch (lifetime) {
600  llvm_unreachable("present but none");
601 
603  // nothing to do
604  break;
605 
606  case Qualifiers::OCL_Strong: {
607  CodeGenFunction::Destroyer *destroyer =
608  (var.hasAttr<ObjCPreciseLifetimeAttr>()
611 
612  CleanupKind cleanupKind = CGF.getARCCleanupKind();
613  CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
614  cleanupKind & EHCleanup);
615  break;
616  }
618  // nothing to do
619  break;
620 
622  // __weak objects always get EH cleanups; otherwise, exceptions
623  // could cause really nasty crashes instead of mere leaks.
624  CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
626  /*useEHCleanup*/ true);
627  break;
628  }
629 }
630 
631 static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
632  if (const Expr *e = dyn_cast<Expr>(s)) {
633  // Skip the most common kinds of expressions that make
634  // hierarchy-walking expensive.
635  s = e = e->IgnoreParenCasts();
636 
637  if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
638  return (ref->getDecl() == &var);
639  if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
640  const BlockDecl *block = be->getBlockDecl();
641  for (const auto &I : block->captures()) {
642  if (I.getVariable() == &var)
643  return true;
644  }
645  }
646  }
647 
648  for (const Stmt *SubStmt : s->children())
649  // SubStmt might be null; as in missing decl or conditional of an if-stmt.
650  if (SubStmt && isAccessedBy(var, SubStmt))
651  return true;
652 
653  return false;
654 }
655 
656 static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
657  if (!decl) return false;
658  if (!isa<VarDecl>(decl)) return false;
659  const VarDecl *var = cast<VarDecl>(decl);
660  return isAccessedBy(*var, e);
661 }
662 
664  const LValue &destLV, const Expr *init) {
665  bool needsCast = false;
666 
667  while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
668  switch (castExpr->getCastKind()) {
669  // Look through casts that don't require representation changes.
670  case CK_NoOp:
671  case CK_BitCast:
672  case CK_BlockPointerToObjCPointerCast:
673  needsCast = true;
674  break;
675 
676  // If we find an l-value to r-value cast from a __weak variable,
677  // emit this operation as a copy or move.
678  case CK_LValueToRValue: {
679  const Expr *srcExpr = castExpr->getSubExpr();
680  if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
681  return false;
682 
683  // Emit the source l-value.
684  LValue srcLV = CGF.EmitLValue(srcExpr);
685 
686  // Handle a formal type change to avoid asserting.
687  auto srcAddr = srcLV.getAddress();
688  if (needsCast) {
689  srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
690  destLV.getAddress().getElementType());
691  }
692 
693  // If it was an l-value, use objc_copyWeak.
694  if (srcExpr->getValueKind() == VK_LValue) {
695  CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
696  } else {
697  assert(srcExpr->getValueKind() == VK_XValue);
698  CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
699  }
700  return true;
701  }
702 
703  // Stop at anything else.
704  default:
705  return false;
706  }
707 
708  init = castExpr->getSubExpr();
709  }
710  return false;
711 }
712 
714  LValue &lvalue,
715  const VarDecl *var) {
716  lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
717 }
718 
720  SourceLocation Loc) {
721  if (!SanOpts.has(SanitizerKind::NullabilityAssign))
722  return;
723 
724  auto Nullability = LHS.getType()->getNullability(getContext());
726  return;
727 
728  // Check if the right hand side of the assignment is nonnull, if the left
729  // hand side must be nonnull.
730  SanitizerScope SanScope(this);
731  llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
732  llvm::Constant *StaticData[] = {
734  llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.
735  llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
736  EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},
737  SanitizerHandler::TypeMismatch, StaticData, RHS);
738 }
739 
740 void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
741  LValue lvalue, bool capturedByInit) {
742  Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
743  if (!lifetime) {
744  llvm::Value *value = EmitScalarExpr(init);
745  if (capturedByInit)
746  drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
747  EmitNullabilityCheck(lvalue, value, init->getExprLoc());
748  EmitStoreThroughLValue(RValue::get(value), lvalue, true);
749  return;
750  }
751 
752  if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
753  init = DIE->getExpr();
754 
755  // If we're emitting a value with lifetime, we have to do the
756  // initialization *before* we leave the cleanup scopes.
757  if (const FullExpr *fe = dyn_cast<FullExpr>(init)) {
759  init = fe->getSubExpr();
760  }
762 
763  // We have to maintain the illusion that the variable is
764  // zero-initialized. If the variable might be accessed in its
765  // initializer, zero-initialize before running the initializer, then
766  // actually perform the initialization with an assign.
767  bool accessedByInit = false;
768  if (lifetime != Qualifiers::OCL_ExplicitNone)
769  accessedByInit = (capturedByInit || isAccessedBy(D, init));
770  if (accessedByInit) {
771  LValue tempLV = lvalue;
772  // Drill down to the __block object if necessary.
773  if (capturedByInit) {
774  // We can use a simple GEP for this because it can't have been
775  // moved yet.
777  cast<VarDecl>(D),
778  /*follow*/ false));
779  }
780 
781  auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
782  llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
783 
784  // If __weak, we want to use a barrier under certain conditions.
785  if (lifetime == Qualifiers::OCL_Weak)
786  EmitARCInitWeak(tempLV.getAddress(), zero);
787 
788  // Otherwise just do a simple store.
789  else
790  EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
791  }
792 
793  // Emit the initializer.
794  llvm::Value *value = nullptr;
795 
796  switch (lifetime) {
798  llvm_unreachable("present but none");
799 
801  value = EmitARCUnsafeUnretainedScalarExpr(init);
802  break;
803 
804  case Qualifiers::OCL_Strong: {
805  value = EmitARCRetainScalarExpr(init);
806  break;
807  }
808 
809  case Qualifiers::OCL_Weak: {
810  // If it's not accessed by the initializer, try to emit the
811  // initialization with a copy or move.
812  if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
813  return;
814  }
815 
816  // No way to optimize a producing initializer into this. It's not
817  // worth optimizing for, because the value will immediately
818  // disappear in the common case.
819  value = EmitScalarExpr(init);
820 
821  if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
822  if (accessedByInit)
823  EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
824  else
825  EmitARCInitWeak(lvalue.getAddress(), value);
826  return;
827  }
828 
831  break;
832  }
833 
834  if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
835 
836  EmitNullabilityCheck(lvalue, value, init->getExprLoc());
837 
838  // If the variable might have been accessed by its initializer, we
839  // might have to initialize with a barrier. We have to do this for
840  // both __weak and __strong, but __weak got filtered out above.
841  if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
842  llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
843  EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
845  return;
846  }
847 
848  EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
849 }
850 
851 /// Decide whether we can emit the non-zero parts of the specified initializer
852 /// with equal or fewer than NumStores scalar stores.
853 static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init,
854  unsigned &NumStores) {
855  // Zero and Undef never requires any extra stores.
856  if (isa<llvm::ConstantAggregateZero>(Init) ||
857  isa<llvm::ConstantPointerNull>(Init) ||
858  isa<llvm::UndefValue>(Init))
859  return true;
860  if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
861  isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
862  isa<llvm::ConstantExpr>(Init))
863  return Init->isNullValue() || NumStores--;
864 
865  // See if we can emit each element.
866  if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
867  for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
868  llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
869  if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
870  return false;
871  }
872  return true;
873  }
874 
875  if (llvm::ConstantDataSequential *CDS =
876  dyn_cast<llvm::ConstantDataSequential>(Init)) {
877  for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
878  llvm::Constant *Elt = CDS->getElementAsConstant(i);
879  if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
880  return false;
881  }
882  return true;
883  }
884 
885  // Anything else is hard and scary.
886  return false;
887 }
888 
889 /// For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit
890 /// the scalar stores that would be required.
892  llvm::Constant *Init, Address Loc,
893  bool isVolatile, CGBuilderTy &Builder) {
894  assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
895  "called emitStoresForInitAfterBZero for zero or undef value.");
896 
897  if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
898  isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
899  isa<llvm::ConstantExpr>(Init)) {
900  Builder.CreateStore(Init, Loc, isVolatile);
901  return;
902  }
903 
904  if (llvm::ConstantDataSequential *CDS =
905  dyn_cast<llvm::ConstantDataSequential>(Init)) {
906  for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
907  llvm::Constant *Elt = CDS->getElementAsConstant(i);
908 
909  // If necessary, get a pointer to the element and emit it.
910  if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
912  CGM, Elt,
913  Builder.CreateConstInBoundsGEP2_32(Loc, 0, i, CGM.getDataLayout()),
914  isVolatile, Builder);
915  }
916  return;
917  }
918 
919  assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
920  "Unknown value type!");
921 
922  for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
923  llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
924 
925  // If necessary, get a pointer to the element and emit it.
926  if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
928  CGM, Elt,
929  Builder.CreateConstInBoundsGEP2_32(Loc, 0, i, CGM.getDataLayout()),
930  isVolatile, Builder);
931  }
932 }
933 
934 /// Decide whether we should use bzero plus some stores to initialize a local
935 /// variable instead of using a memcpy from a constant global. It is beneficial
936 /// to use bzero if the global is all zeros, or mostly zeros and large.
937 static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init,
938  uint64_t GlobalSize) {
939  // If a global is all zeros, always use a bzero.
940  if (isa<llvm::ConstantAggregateZero>(Init)) return true;
941 
942  // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
943  // do it if it will require 6 or fewer scalar stores.
944  // TODO: Should budget depends on the size? Avoiding a large global warrants
945  // plopping in more stores.
946  unsigned StoreBudget = 6;
947  uint64_t SizeLimit = 32;
948 
949  return GlobalSize > SizeLimit &&
950  canEmitInitWithFewStoresAfterBZero(Init, StoreBudget);
951 }
952 
953 /// Decide whether we should use memset to initialize a local variable instead
954 /// of using a memcpy from a constant global. Assumes we've already decided to
955 /// not user bzero.
956 /// FIXME We could be more clever, as we are for bzero above, and generate
957 /// memset followed by stores. It's unclear that's worth the effort.
958 static llvm::Value *shouldUseMemSetToInitialize(llvm::Constant *Init,
959  uint64_t GlobalSize) {
960  uint64_t SizeLimit = 32;
961  if (GlobalSize <= SizeLimit)
962  return nullptr;
963  return llvm::isBytewiseValue(Init);
964 }
965 
968  llvm::Constant *Constant,
969  CharUnits Align) {
970  auto FunctionName = [&](const DeclContext *DC) -> std::string {
971  if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
972  if (const auto *CC = dyn_cast<CXXConstructorDecl>(FD))
973  return CC->getNameAsString();
974  if (const auto *CD = dyn_cast<CXXDestructorDecl>(FD))
975  return CD->getNameAsString();
976  return CGM.getMangledName(FD);
977  } else if (const auto *OM = dyn_cast<ObjCMethodDecl>(DC)) {
978  return OM->getNameAsString();
979  } else if (isa<BlockDecl>(DC)) {
980  return "<block>";
981  } else if (isa<CapturedDecl>(DC)) {
982  return "<captured>";
983  } else {
984  llvm::llvm_unreachable_internal("expected a function or method");
985  }
986  };
987 
988  auto *Ty = Constant->getType();
989  bool isConstant = true;
990  llvm::GlobalVariable *InsertBefore = nullptr;
991  unsigned AS = CGM.getContext().getTargetAddressSpace(
993  llvm::GlobalVariable *GV = new llvm::GlobalVariable(
994  CGM.getModule(), Ty, isConstant, llvm::GlobalValue::PrivateLinkage,
995  Constant,
996  "__const." + FunctionName(D.getParentFunctionOrMethod()) + "." +
997  D.getName(),
998  InsertBefore, llvm::GlobalValue::NotThreadLocal, AS);
999  GV->setAlignment(Align.getQuantity());
1000  GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1001 
1002  Address SrcPtr = Address(GV, Align);
1003  llvm::Type *BP = llvm::PointerType::getInt8PtrTy(CGM.getLLVMContext(), AS);
1004  if (SrcPtr.getType() != BP)
1005  SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
1006  return SrcPtr;
1007 }
1008 
1010  Address Loc, bool isVolatile,
1012  llvm::Constant *constant) {
1013  auto *Int8Ty = llvm::IntegerType::getInt8Ty(CGM.getLLVMContext());
1014  auto *IntPtrTy = CGM.getDataLayout().getIntPtrType(CGM.getLLVMContext());
1015 
1016  // If the initializer is all or mostly the same, codegen with bzero / memset
1017  // then do a few stores afterward.
1018  uint64_t ConstantSize =
1019  CGM.getDataLayout().getTypeAllocSize(constant->getType());
1020  auto *SizeVal = llvm::ConstantInt::get(IntPtrTy, ConstantSize);
1021  if (shouldUseBZeroPlusStoresToInitialize(constant, ConstantSize)) {
1022  Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1023  isVolatile);
1024 
1025  bool valueAlreadyCorrect =
1026  constant->isNullValue() || isa<llvm::UndefValue>(constant);
1027  if (!valueAlreadyCorrect) {
1028  Loc = Builder.CreateBitCast(
1029  Loc, constant->getType()->getPointerTo(Loc.getAddressSpace()));
1030  emitStoresForInitAfterBZero(CGM, constant, Loc, isVolatile, Builder);
1031  }
1032  return;
1033  }
1034 
1035  llvm::Value *Pattern = shouldUseMemSetToInitialize(constant, ConstantSize);
1036  if (Pattern) {
1037  uint64_t Value = 0x00;
1038  if (!isa<llvm::UndefValue>(Pattern)) {
1039  const llvm::APInt &AP = cast<llvm::ConstantInt>(Pattern)->getValue();
1040  assert(AP.getBitWidth() <= 8);
1041  Value = AP.getLimitedValue();
1042  }
1043  Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, Value), SizeVal,
1044  isVolatile);
1045  return;
1046  }
1047 
1048  Builder.CreateMemCpy(
1049  Loc,
1050  createUnnamedGlobalFrom(CGM, D, Builder, constant, Loc.getAlignment()),
1051  SizeVal, isVolatile);
1052 }
1053 
1054 /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
1055 /// variable declaration with auto, register, or no storage class specifier.
1056 /// These turn into simple stack objects, or GlobalValues depending on target.
1058  AutoVarEmission emission = EmitAutoVarAlloca(D);
1059  EmitAutoVarInit(emission);
1060  EmitAutoVarCleanups(emission);
1061 }
1062 
1063 /// Emit a lifetime.begin marker if some criteria are satisfied.
1064 /// \return a pointer to the temporary size Value if a marker was emitted, null
1065 /// otherwise
1067  llvm::Value *Addr) {
1068  if (!ShouldEmitLifetimeMarkers)
1069  return nullptr;
1070 
1071  assert(Addr->getType()->getPointerAddressSpace() ==
1072  CGM.getDataLayout().getAllocaAddrSpace() &&
1073  "Pointer should be in alloca address space");
1074  llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
1075  Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
1076  llvm::CallInst *C =
1077  Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
1078  C->setDoesNotThrow();
1079  return SizeV;
1080 }
1081 
1083  assert(Addr->getType()->getPointerAddressSpace() ==
1084  CGM.getDataLayout().getAllocaAddrSpace() &&
1085  "Pointer should be in alloca address space");
1086  Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
1087  llvm::CallInst *C =
1088  Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
1089  C->setDoesNotThrow();
1090 }
1091 
1093  CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) {
1094  // For each dimension stores its QualType and corresponding
1095  // size-expression Value.
1097  SmallVector<IdentifierInfo *, 4> VLAExprNames;
1098 
1099  // Break down the array into individual dimensions.
1100  QualType Type1D = D.getType();
1101  while (getContext().getAsVariableArrayType(Type1D)) {
1102  auto VlaSize = getVLAElements1D(Type1D);
1103  if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1104  Dimensions.emplace_back(C, Type1D.getUnqualifiedType());
1105  else {
1106  // Generate a locally unique name for the size expression.
1107  Twine Name = Twine("__vla_expr") + Twine(VLAExprCounter++);
1108  SmallString<12> Buffer;
1109  StringRef NameRef = Name.toStringRef(Buffer);
1110  auto &Ident = getContext().Idents.getOwn(NameRef);
1111  VLAExprNames.push_back(&Ident);
1112  auto SizeExprAddr =
1113  CreateDefaultAlignTempAlloca(VlaSize.NumElts->getType(), NameRef);
1114  Builder.CreateStore(VlaSize.NumElts, SizeExprAddr);
1115  Dimensions.emplace_back(SizeExprAddr.getPointer(),
1116  Type1D.getUnqualifiedType());
1117  }
1118  Type1D = VlaSize.Type;
1119  }
1120 
1121  if (!EmitDebugInfo)
1122  return;
1123 
1124  // Register each dimension's size-expression with a DILocalVariable,
1125  // so that it can be used by CGDebugInfo when instantiating a DISubrange
1126  // to describe this array.
1127  unsigned NameIdx = 0;
1128  for (auto &VlaSize : Dimensions) {
1129  llvm::Metadata *MD;
1130  if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1131  MD = llvm::ConstantAsMetadata::get(C);
1132  else {
1133  // Create an artificial VarDecl to generate debug info for.
1134  IdentifierInfo *NameIdent = VLAExprNames[NameIdx++];
1135  auto VlaExprTy = VlaSize.NumElts->getType()->getPointerElementType();
1136  auto QT = getContext().getIntTypeForBitwidth(
1137  VlaExprTy->getScalarSizeInBits(), false);
1138  auto *ArtificialDecl = VarDecl::Create(
1139  getContext(), const_cast<DeclContext *>(D.getDeclContext()),
1140  D.getLocation(), D.getLocation(), NameIdent, QT,
1142  ArtificialDecl->setImplicit();
1143 
1144  MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts,
1145  Builder);
1146  }
1147  assert(MD && "No Size expression debug node created");
1148  DI->registerVLASizeExpression(VlaSize.Type, MD);
1149  }
1150 }
1151 
1152 /// EmitAutoVarAlloca - Emit the alloca and debug information for a
1153 /// local variable. Does not emit initialization or destruction.
1156  QualType Ty = D.getType();
1157  assert(
1158  Ty.getAddressSpace() == LangAS::Default ||
1159  (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL));
1160 
1161  AutoVarEmission emission(D);
1162 
1163  bool isEscapingByRef = D.isEscapingByref();
1164  emission.IsEscapingByRef = isEscapingByRef;
1165 
1166  CharUnits alignment = getContext().getDeclAlign(&D);
1167 
1168  // If the type is variably-modified, emit all the VLA sizes for it.
1169  if (Ty->isVariablyModifiedType())
1171 
1172  auto *DI = getDebugInfo();
1173  bool EmitDebugInfo = DI && CGM.getCodeGenOpts().getDebugInfo() >=
1175 
1176  Address address = Address::invalid();
1177  Address AllocaAddr = Address::invalid();
1178  if (Ty->isConstantSizeType()) {
1179  bool NRVO = getLangOpts().ElideConstructors &&
1180  D.isNRVOVariable();
1181 
1182  // If this value is an array or struct with a statically determinable
1183  // constant initializer, there are optimizations we can do.
1184  //
1185  // TODO: We should constant-evaluate the initializer of any variable,
1186  // as long as it is initialized by a constant expression. Currently,
1187  // isConstantInitializer produces wrong answers for structs with
1188  // reference or bitfield members, and a few other cases, and checking
1189  // for POD-ness protects us from some of these.
1190  if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
1191  (D.isConstexpr() ||
1192  ((Ty.isPODType(getContext()) ||
1194  D.getInit()->isConstantInitializer(getContext(), false)))) {
1195 
1196  // If the variable's a const type, and it's neither an NRVO
1197  // candidate nor a __block variable and has no mutable members,
1198  // emit it as a global instead.
1199  // Exception is if a variable is located in non-constant address space
1200  // in OpenCL.
1201  if ((!getLangOpts().OpenCL ||
1203  (CGM.getCodeGenOpts().MergeAllConstants && !NRVO &&
1204  !isEscapingByRef && CGM.isTypeConstant(Ty, true))) {
1206 
1207  // Signal this condition to later callbacks.
1208  emission.Addr = Address::invalid();
1209  assert(emission.wasEmittedAsGlobal());
1210  return emission;
1211  }
1212 
1213  // Otherwise, tell the initialization code that we're in this case.
1214  emission.IsConstantAggregate = true;
1215  }
1216 
1217  // A normal fixed sized variable becomes an alloca in the entry block,
1218  // unless:
1219  // - it's an NRVO variable.
1220  // - we are compiling OpenMP and it's an OpenMP local variable.
1221 
1222  Address OpenMPLocalAddr =
1223  getLangOpts().OpenMP
1224  ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
1225  : Address::invalid();
1226  if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
1227  address = OpenMPLocalAddr;
1228  } else if (NRVO) {
1229  // The named return value optimization: allocate this variable in the
1230  // return slot, so that we can elide the copy when returning this
1231  // variable (C++0x [class.copy]p34).
1232  address = ReturnValue;
1233 
1234  if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1235  const auto *RD = RecordTy->getDecl();
1236  const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1237  if ((CXXRD && !CXXRD->hasTrivialDestructor()) ||
1238  RD->isNonTrivialToPrimitiveDestroy()) {
1239  // Create a flag that is used to indicate when the NRVO was applied
1240  // to this variable. Set it to zero to indicate that NRVO was not
1241  // applied.
1242  llvm::Value *Zero = Builder.getFalse();
1243  Address NRVOFlag =
1244  CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
1246  Builder.CreateStore(Zero, NRVOFlag);
1247 
1248  // Record the NRVO flag for this variable.
1249  NRVOFlags[&D] = NRVOFlag.getPointer();
1250  emission.NRVOFlag = NRVOFlag.getPointer();
1251  }
1252  }
1253  } else {
1254  CharUnits allocaAlignment;
1255  llvm::Type *allocaTy;
1256  if (isEscapingByRef) {
1257  auto &byrefInfo = getBlockByrefInfo(&D);
1258  allocaTy = byrefInfo.Type;
1259  allocaAlignment = byrefInfo.ByrefAlignment;
1260  } else {
1261  allocaTy = ConvertTypeForMem(Ty);
1262  allocaAlignment = alignment;
1263  }
1264 
1265  // Create the alloca. Note that we set the name separately from
1266  // building the instruction so that it's there even in no-asserts
1267  // builds.
1268  address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName(),
1269  /*ArraySize=*/nullptr, &AllocaAddr);
1270 
1271  // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1272  // the catch parameter starts in the catchpad instruction, and we can't
1273  // insert code in those basic blocks.
1274  bool IsMSCatchParam =
1276 
1277  // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1278  // if we don't have a valid insertion point (?).
1279  if (HaveInsertPoint() && !IsMSCatchParam) {
1280  // If there's a jump into the lifetime of this variable, its lifetime
1281  // gets broken up into several regions in IR, which requires more work
1282  // to handle correctly. For now, just omit the intrinsics; this is a
1283  // rare case, and it's better to just be conservatively correct.
1284  // PR28267.
1285  //
1286  // We have to do this in all language modes if there's a jump past the
1287  // declaration. We also have to do it in C if there's a jump to an
1288  // earlier point in the current block because non-VLA lifetimes begin as
1289  // soon as the containing block is entered, not when its variables
1290  // actually come into scope; suppressing the lifetime annotations
1291  // completely in this case is unnecessarily pessimistic, but again, this
1292  // is rare.
1293  if (!Bypasses.IsBypassed(&D) &&
1294  !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
1295  uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1296  emission.SizeForLifetimeMarkers =
1297  EmitLifetimeStart(size, AllocaAddr.getPointer());
1298  }
1299  } else {
1300  assert(!emission.useLifetimeMarkers());
1301  }
1302  }
1303  } else {
1305 
1306  if (!DidCallStackSave) {
1307  // Save the stack.
1308  Address Stack =
1309  CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
1310 
1311  llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
1312  llvm::Value *V = Builder.CreateCall(F);
1313  Builder.CreateStore(V, Stack);
1314 
1315  DidCallStackSave = true;
1316 
1317  // Push a cleanup block and restore the stack there.
1318  // FIXME: in general circumstances, this should be an EH cleanup.
1320  }
1321 
1322  auto VlaSize = getVLASize(Ty);
1323  llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type);
1324 
1325  // Allocate memory for the array.
1326  address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts,
1327  &AllocaAddr);
1328 
1329  // If we have debug info enabled, properly describe the VLA dimensions for
1330  // this type by registering the vla size expression for each of the
1331  // dimensions.
1332  EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo);
1333  }
1334 
1335  setAddrOfLocalVar(&D, address);
1336  emission.Addr = address;
1337  emission.AllocaAddr = AllocaAddr;
1338 
1339  // Emit debug info for local var declaration.
1340  if (EmitDebugInfo && HaveInsertPoint()) {
1341  DI->setLocation(D.getLocation());
1342  (void)DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
1343  }
1344 
1345  if (D.hasAttr<AnnotateAttr>())
1346  EmitVarAnnotations(&D, address.getPointer());
1347 
1348  // Make sure we call @llvm.lifetime.end.
1349  if (emission.useLifetimeMarkers())
1351  emission.getOriginalAllocatedAddress(),
1352  emission.getSizeForLifetimeMarkers());
1353 
1354  return emission;
1355 }
1356 
1357 static bool isCapturedBy(const VarDecl &, const Expr *);
1358 
1359 /// Determines whether the given __block variable is potentially
1360 /// captured by the given statement.
1361 static bool isCapturedBy(const VarDecl &Var, const Stmt *S) {
1362  if (const Expr *E = dyn_cast<Expr>(S))
1363  return isCapturedBy(Var, E);
1364  for (const Stmt *SubStmt : S->children())
1365  if (isCapturedBy(Var, SubStmt))
1366  return true;
1367  return false;
1368 }
1369 
1370 /// Determines whether the given __block variable is potentially
1371 /// captured by the given expression.
1372 static bool isCapturedBy(const VarDecl &Var, const Expr *E) {
1373  // Skip the most common kinds of expressions that make
1374  // hierarchy-walking expensive.
1375  E = E->IgnoreParenCasts();
1376 
1377  if (const BlockExpr *BE = dyn_cast<BlockExpr>(E)) {
1378  const BlockDecl *Block = BE->getBlockDecl();
1379  for (const auto &I : Block->captures()) {
1380  if (I.getVariable() == &Var)
1381  return true;
1382  }
1383 
1384  // No need to walk into the subexpressions.
1385  return false;
1386  }
1387 
1388  if (const StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
1389  const CompoundStmt *CS = SE->getSubStmt();
1390  for (const auto *BI : CS->body())
1391  if (const auto *BIE = dyn_cast<Expr>(BI)) {
1392  if (isCapturedBy(Var, BIE))
1393  return true;
1394  }
1395  else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
1396  // special case declarations
1397  for (const auto *I : DS->decls()) {
1398  if (const auto *VD = dyn_cast<VarDecl>((I))) {
1399  const Expr *Init = VD->getInit();
1400  if (Init && isCapturedBy(Var, Init))
1401  return true;
1402  }
1403  }
1404  }
1405  else
1406  // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1407  // Later, provide code to poke into statements for capture analysis.
1408  return true;
1409  return false;
1410  }
1411 
1412  for (const Stmt *SubStmt : E->children())
1413  if (isCapturedBy(Var, SubStmt))
1414  return true;
1415 
1416  return false;
1417 }
1418 
1419 /// Determine whether the given initializer is trivial in the sense
1420 /// that it requires no code to be generated.
1422  if (!Init)
1423  return true;
1424 
1425  if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1426  if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1427  if (Constructor->isTrivial() &&
1428  Constructor->isDefaultConstructor() &&
1429  !Construct->requiresZeroInitialization())
1430  return true;
1431 
1432  return false;
1433 }
1434 
1436  assert(emission.Variable && "emission was not valid!");
1437 
1438  // If this was emitted as a global constant, we're done.
1439  if (emission.wasEmittedAsGlobal()) return;
1440 
1441  const VarDecl &D = *emission.Variable;
1443  QualType type = D.getType();
1444 
1445  // If this local has an initializer, emit it now.
1446  const Expr *Init = D.getInit();
1447 
1448  // If we are at an unreachable point, we don't need to emit the initializer
1449  // unless it contains a label.
1450  if (!HaveInsertPoint()) {
1451  if (!Init || !ContainsLabel(Init)) return;
1453  }
1454 
1455  // Initialize the structure of a __block variable.
1456  if (emission.IsEscapingByRef)
1457  emitByrefStructureInit(emission);
1458 
1459  // Initialize the variable here if it doesn't have a initializer and it is a
1460  // C struct that is non-trivial to initialize or an array containing such a
1461  // struct.
1462  if (!Init &&
1463  type.isNonTrivialToPrimitiveDefaultInitialize() ==
1465  LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type);
1466  if (emission.IsEscapingByRef)
1467  drillIntoBlockVariable(*this, Dst, &D);
1469  return;
1470  }
1471 
1472  if (isTrivialInitializer(Init))
1473  return;
1474 
1475  // Check whether this is a byref variable that's potentially
1476  // captured and moved by its own initializer. If so, we'll need to
1477  // emit the initializer first, then copy into the variable.
1478  bool capturedByInit = emission.IsEscapingByRef && isCapturedBy(D, Init);
1479 
1480  Address Loc =
1481  capturedByInit ? emission.Addr : emission.getObjectAddress(*this);
1482 
1483  llvm::Constant *constant = nullptr;
1484  if (emission.IsConstantAggregate || D.isConstexpr()) {
1485  assert(!capturedByInit && "constant init contains a capturing block?");
1486  constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
1487  }
1488 
1489  if (!constant) {
1490  LValue lv = MakeAddrLValue(Loc, type);
1491  lv.setNonGC(true);
1492  return EmitExprAsInit(Init, &D, lv, capturedByInit);
1493  }
1494 
1495  if (!emission.IsConstantAggregate) {
1496  // For simple scalar/complex initialization, store the value directly.
1497  LValue lv = MakeAddrLValue(Loc, type);
1498  lv.setNonGC(true);
1499  return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1500  }
1501 
1502  // If this is a simple aggregate initialization, we can optimize it
1503  // in various ways.
1504  bool isVolatile = type.isVolatileQualified();
1505 
1506  llvm::Type *BP = CGM.Int8Ty->getPointerTo(Loc.getAddressSpace());
1507  if (Loc.getType() != BP)
1508  Loc = Builder.CreateBitCast(Loc, BP);
1509 
1510  emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant);
1511 }
1512 
1513 /// Emit an expression as an initializer for an object (variable, field, etc.)
1514 /// at the given location. The expression is not necessarily the normal
1515 /// initializer for the object, and the address is not necessarily
1516 /// its normal location.
1517 ///
1518 /// \param init the initializing expression
1519 /// \param D the object to act as if we're initializing
1520 /// \param loc the address to initialize; its type is a pointer
1521 /// to the LLVM mapping of the object's type
1522 /// \param alignment the alignment of the address
1523 /// \param capturedByInit true if \p D is a __block variable
1524 /// whose address is potentially changed by the initializer
1526  LValue lvalue, bool capturedByInit) {
1527  QualType type = D->getType();
1528 
1529  if (type->isReferenceType()) {
1530  RValue rvalue = EmitReferenceBindingToExpr(init);
1531  if (capturedByInit)
1532  drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1533  EmitStoreThroughLValue(rvalue, lvalue, true);
1534  return;
1535  }
1536  switch (getEvaluationKind(type)) {
1537  case TEK_Scalar:
1538  EmitScalarInit(init, D, lvalue, capturedByInit);
1539  return;
1540  case TEK_Complex: {
1541  ComplexPairTy complex = EmitComplexExpr(init);
1542  if (capturedByInit)
1543  drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1544  EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1545  return;
1546  }
1547  case TEK_Aggregate:
1548  if (type->isAtomicType()) {
1549  EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1550  } else {
1552  if (isa<VarDecl>(D))
1553  Overlap = AggValueSlot::DoesNotOverlap;
1554  else if (auto *FD = dyn_cast<FieldDecl>(D))
1555  Overlap = overlapForFieldInit(FD);
1556  // TODO: how can we delay here if D is captured by its initializer?
1557  EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
1561  Overlap));
1562  }
1563  return;
1564  }
1565  llvm_unreachable("bad evaluation kind");
1566 }
1567 
1568 /// Enter a destroy cleanup for the given local variable.
1570  const CodeGenFunction::AutoVarEmission &emission,
1571  QualType::DestructionKind dtorKind) {
1572  assert(dtorKind != QualType::DK_none);
1573 
1574  // Note that for __block variables, we want to destroy the
1575  // original stack object, not the possibly forwarded object.
1576  Address addr = emission.getObjectAddress(*this);
1577 
1578  const VarDecl *var = emission.Variable;
1579  QualType type = var->getType();
1580 
1581  CleanupKind cleanupKind = NormalAndEHCleanup;
1582  CodeGenFunction::Destroyer *destroyer = nullptr;
1583 
1584  switch (dtorKind) {
1585  case QualType::DK_none:
1586  llvm_unreachable("no cleanup for trivially-destructible variable");
1587 
1589  // If there's an NRVO flag on the emission, we need a different
1590  // cleanup.
1591  if (emission.NRVOFlag) {
1592  assert(!type->isArrayType());
1594  EHStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, dtor,
1595  emission.NRVOFlag);
1596  return;
1597  }
1598  break;
1599 
1601  // Suppress cleanups for pseudo-strong variables.
1602  if (var->isARCPseudoStrong()) return;
1603 
1604  // Otherwise, consider whether to use an EH cleanup or not.
1605  cleanupKind = getARCCleanupKind();
1606 
1607  // Use the imprecise destroyer by default.
1608  if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1610  break;
1611 
1613  break;
1614 
1617  if (emission.NRVOFlag) {
1618  assert(!type->isArrayType());
1619  EHStack.pushCleanup<DestroyNRVOVariableC>(cleanupKind, addr,
1620  emission.NRVOFlag, type);
1621  return;
1622  }
1623  break;
1624  }
1625 
1626  // If we haven't chosen a more specific destroyer, use the default.
1627  if (!destroyer) destroyer = getDestroyer(dtorKind);
1628 
1629  // Use an EH cleanup in array destructors iff the destructor itself
1630  // is being pushed as an EH cleanup.
1631  bool useEHCleanup = (cleanupKind & EHCleanup);
1632  EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1633  useEHCleanup);
1634 }
1635 
1637  assert(emission.Variable && "emission was not valid!");
1638 
1639  // If this was emitted as a global constant, we're done.
1640  if (emission.wasEmittedAsGlobal()) return;
1641 
1642  // If we don't have an insertion point, we're done. Sema prevents
1643  // us from jumping into any of these scopes anyway.
1644  if (!HaveInsertPoint()) return;
1645 
1646  const VarDecl &D = *emission.Variable;
1647 
1648  // Check the type for a cleanup.
1649  if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1650  emitAutoVarTypeCleanup(emission, dtorKind);
1651 
1652  // In GC mode, honor objc_precise_lifetime.
1653  if (getLangOpts().getGC() != LangOptions::NonGC &&
1654  D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1655  EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1656  }
1657 
1658  // Handle the cleanup attribute.
1659  if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
1660  const FunctionDecl *FD = CA->getFunctionDecl();
1661 
1662  llvm::Constant *F = CGM.GetAddrOfFunction(FD);
1663  assert(F && "Could not find function!");
1664 
1666  EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
1667  }
1668 
1669  // If this is a block variable, call _Block_object_destroy
1670  // (on the unforwarded address). Don't enter this cleanup if we're in pure-GC
1671  // mode.
1672  if (emission.IsEscapingByRef &&
1673  CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
1675  if (emission.Variable->getType().isObjCGCWeak())
1676  Flags |= BLOCK_FIELD_IS_WEAK;
1677  enterByrefCleanup(NormalAndEHCleanup, emission.Addr, Flags,
1678  /*LoadBlockVarAddr*/ false,
1679  cxxDestructorCanThrow(emission.Variable->getType()));
1680  }
1681 }
1682 
1685  switch (kind) {
1686  case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
1688  return destroyCXXObject;
1690  return destroyARCStrongPrecise;
1692  return destroyARCWeak;
1694  return destroyNonTrivialCStruct;
1695  }
1696  llvm_unreachable("Unknown DestructionKind");
1697 }
1698 
1699 /// pushEHDestroy - Push the standard destructor for the given type as
1700 /// an EH-only cleanup.
1702  Address addr, QualType type) {
1703  assert(dtorKind && "cannot push destructor for trivial type");
1704  assert(needsEHCleanup(dtorKind));
1705 
1706  pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1707 }
1708 
1709 /// pushDestroy - Push the standard destructor for the given type as
1710 /// at least a normal cleanup.
1712  Address addr, QualType type) {
1713  assert(dtorKind && "cannot push destructor for trivial type");
1714 
1715  CleanupKind cleanupKind = getCleanupKind(dtorKind);
1716  pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1717  cleanupKind & EHCleanup);
1718 }
1719 
1721  QualType type, Destroyer *destroyer,
1722  bool useEHCleanupForArray) {
1723  pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1724  destroyer, useEHCleanupForArray);
1725 }
1726 
1728  EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1729 }
1730 
1732  CleanupKind cleanupKind, Address addr, QualType type,
1733  Destroyer *destroyer, bool useEHCleanupForArray) {
1734  // Push an EH-only cleanup for the object now.
1735  // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1736  // around in case a temporary's destructor throws an exception.
1737  if (cleanupKind & EHCleanup)
1738  EHStack.pushCleanup<DestroyObject>(
1739  static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1740  destroyer, useEHCleanupForArray);
1741 
1742  // Remember that we need to push a full cleanup for the object at the
1743  // end of the full-expression.
1744  pushCleanupAfterFullExpr<DestroyObject>(
1745  cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1746 }
1747 
1748 /// emitDestroy - Immediately perform the destruction of the given
1749 /// object.
1750 ///
1751 /// \param addr - the address of the object; a type*
1752 /// \param type - the type of the object; if an array type, all
1753 /// objects are destroyed in reverse order
1754 /// \param destroyer - the function to call to destroy individual
1755 /// elements
1756 /// \param useEHCleanupForArray - whether an EH cleanup should be
1757 /// used when destroying array elements, in case one of the
1758 /// destructions throws an exception
1760  Destroyer *destroyer,
1761  bool useEHCleanupForArray) {
1762  const ArrayType *arrayType = getContext().getAsArrayType(type);
1763  if (!arrayType)
1764  return destroyer(*this, addr, type);
1765 
1766  llvm::Value *length = emitArrayLength(arrayType, type, addr);
1767 
1768  CharUnits elementAlign =
1769  addr.getAlignment()
1770  .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
1771 
1772  // Normally we have to check whether the array is zero-length.
1773  bool checkZeroLength = true;
1774 
1775  // But if the array length is constant, we can suppress that.
1776  if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1777  // ...and if it's constant zero, we can just skip the entire thing.
1778  if (constLength->isZero()) return;
1779  checkZeroLength = false;
1780  }
1781 
1782  llvm::Value *begin = addr.getPointer();
1783  llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
1784  emitArrayDestroy(begin, end, type, elementAlign, destroyer,
1785  checkZeroLength, useEHCleanupForArray);
1786 }
1787 
1788 /// emitArrayDestroy - Destroys all the elements of the given array,
1789 /// beginning from last to first. The array cannot be zero-length.
1790 ///
1791 /// \param begin - a type* denoting the first element of the array
1792 /// \param end - a type* denoting one past the end of the array
1793 /// \param elementType - the element type of the array
1794 /// \param destroyer - the function to call to destroy elements
1795 /// \param useEHCleanup - whether to push an EH cleanup to destroy
1796 /// the remaining elements in case the destruction of a single
1797 /// element throws
1799  llvm::Value *end,
1800  QualType elementType,
1801  CharUnits elementAlign,
1802  Destroyer *destroyer,
1803  bool checkZeroLength,
1804  bool useEHCleanup) {
1805  assert(!elementType->isArrayType());
1806 
1807  // The basic structure here is a do-while loop, because we don't
1808  // need to check for the zero-element case.
1809  llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1810  llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1811 
1812  if (checkZeroLength) {
1813  llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1814  "arraydestroy.isempty");
1815  Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1816  }
1817 
1818  // Enter the loop body, making that address the current address.
1819  llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1820  EmitBlock(bodyBB);
1821  llvm::PHINode *elementPast =
1822  Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1823  elementPast->addIncoming(end, entryBB);
1824 
1825  // Shift the address back by one element.
1826  llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1827  llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1828  "arraydestroy.element");
1829 
1830  if (useEHCleanup)
1831  pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
1832  destroyer);
1833 
1834  // Perform the actual destruction there.
1835  destroyer(*this, Address(element, elementAlign), elementType);
1836 
1837  if (useEHCleanup)
1838  PopCleanupBlock();
1839 
1840  // Check whether we've reached the end.
1841  llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1842  Builder.CreateCondBr(done, doneBB, bodyBB);
1843  elementPast->addIncoming(element, Builder.GetInsertBlock());
1844 
1845  // Done.
1846  EmitBlock(doneBB);
1847 }
1848 
1849 /// Perform partial array destruction as if in an EH cleanup. Unlike
1850 /// emitArrayDestroy, the element type here may still be an array type.
1852  llvm::Value *begin, llvm::Value *end,
1853  QualType type, CharUnits elementAlign,
1854  CodeGenFunction::Destroyer *destroyer) {
1855  // If the element type is itself an array, drill down.
1856  unsigned arrayDepth = 0;
1857  while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1858  // VLAs don't require a GEP index to walk into.
1859  if (!isa<VariableArrayType>(arrayType))
1860  arrayDepth++;
1861  type = arrayType->getElementType();
1862  }
1863 
1864  if (arrayDepth) {
1865  llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
1866 
1867  SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
1868  begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1869  end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
1870  }
1871 
1872  // Destroy the array. We don't ever need an EH cleanup because we
1873  // assume that we're in an EH cleanup ourselves, so a throwing
1874  // destructor causes an immediate terminate.
1875  CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
1876  /*checkZeroLength*/ true, /*useEHCleanup*/ false);
1877 }
1878 
1879 namespace {
1880  /// RegularPartialArrayDestroy - a cleanup which performs a partial
1881  /// array destroy where the end pointer is regularly determined and
1882  /// does not need to be loaded from a local.
1883  class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
1884  llvm::Value *ArrayBegin;
1885  llvm::Value *ArrayEnd;
1886  QualType ElementType;
1888  CharUnits ElementAlign;
1889  public:
1890  RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1891  QualType elementType, CharUnits elementAlign,
1892  CodeGenFunction::Destroyer *destroyer)
1893  : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
1894  ElementType(elementType), Destroyer(destroyer),
1895  ElementAlign(elementAlign) {}
1896 
1897  void Emit(CodeGenFunction &CGF, Flags flags) override {
1898  emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1899  ElementType, ElementAlign, Destroyer);
1900  }
1901  };
1902 
1903  /// IrregularPartialArrayDestroy - a cleanup which performs a
1904  /// partial array destroy where the end pointer is irregularly
1905  /// determined and must be loaded from a local.
1906  class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
1907  llvm::Value *ArrayBegin;
1908  Address ArrayEndPointer;
1909  QualType ElementType;
1911  CharUnits ElementAlign;
1912  public:
1913  IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1914  Address arrayEndPointer,
1915  QualType elementType,
1916  CharUnits elementAlign,
1917  CodeGenFunction::Destroyer *destroyer)
1918  : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
1919  ElementType(elementType), Destroyer(destroyer),
1920  ElementAlign(elementAlign) {}
1921 
1922  void Emit(CodeGenFunction &CGF, Flags flags) override {
1923  llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
1924  emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1925  ElementType, ElementAlign, Destroyer);
1926  }
1927  };
1928 } // end anonymous namespace
1929 
1930 /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
1931 /// already-constructed elements of the given array. The cleanup
1932 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1933 ///
1934 /// \param elementType - the immediate element type of the array;
1935 /// possibly still an array type
1937  Address arrayEndPointer,
1938  QualType elementType,
1939  CharUnits elementAlign,
1940  Destroyer *destroyer) {
1941  pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1942  arrayBegin, arrayEndPointer,
1943  elementType, elementAlign,
1944  destroyer);
1945 }
1946 
1947 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1948 /// already-constructed elements of the given array. The cleanup
1949 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1950 ///
1951 /// \param elementType - the immediate element type of the array;
1952 /// possibly still an array type
1954  llvm::Value *arrayEnd,
1955  QualType elementType,
1956  CharUnits elementAlign,
1957  Destroyer *destroyer) {
1958  pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
1959  arrayBegin, arrayEnd,
1960  elementType, elementAlign,
1961  destroyer);
1962 }
1963 
1964 /// Lazily declare the @llvm.lifetime.start intrinsic.
1966  if (LifetimeStartFn)
1967  return LifetimeStartFn;
1968  LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1969  llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
1970  return LifetimeStartFn;
1971 }
1972 
1973 /// Lazily declare the @llvm.lifetime.end intrinsic.
1975  if (LifetimeEndFn)
1976  return LifetimeEndFn;
1977  LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1978  llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
1979  return LifetimeEndFn;
1980 }
1981 
1982 namespace {
1983  /// A cleanup to perform a release of an object at the end of a
1984  /// function. This is used to balance out the incoming +1 of a
1985  /// ns_consumed argument when we can't reasonably do that just by
1986  /// not doing the initial retain for a __block argument.
1987  struct ConsumeARCParameter final : EHScopeStack::Cleanup {
1988  ConsumeARCParameter(llvm::Value *param,
1989  ARCPreciseLifetime_t precise)
1990  : Param(param), Precise(precise) {}
1991 
1992  llvm::Value *Param;
1993  ARCPreciseLifetime_t Precise;
1994 
1995  void Emit(CodeGenFunction &CGF, Flags flags) override {
1996  CGF.EmitARCRelease(Param, Precise);
1997  }
1998  };
1999 } // end anonymous namespace
2000 
2001 /// Emit an alloca (or GlobalValue depending on target)
2002 /// for the specified parameter and set up LocalDeclMap.
2004  unsigned ArgNo) {
2005  // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
2006  assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
2007  "Invalid argument to EmitParmDecl");
2008 
2009  Arg.getAnyValue()->setName(D.getName());
2010 
2011  QualType Ty = D.getType();
2012 
2013  // Use better IR generation for certain implicit parameters.
2014  if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
2015  // The only implicit argument a block has is its literal.
2016  // This may be passed as an inalloca'ed value on Windows x86.
2017  if (BlockInfo) {
2018  llvm::Value *V = Arg.isIndirect()
2020  : Arg.getDirectValue();
2021  setBlockContextParameter(IPD, ArgNo, V);
2022  return;
2023  }
2024  }
2025 
2026  Address DeclPtr = Address::invalid();
2027  bool DoStore = false;
2028  bool IsScalar = hasScalarEvaluationKind(Ty);
2029  // If we already have a pointer to the argument, reuse the input pointer.
2030  if (Arg.isIndirect()) {
2031  DeclPtr = Arg.getIndirectAddress();
2032  // If we have a prettier pointer type at this point, bitcast to that.
2033  unsigned AS = DeclPtr.getType()->getAddressSpace();
2034  llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
2035  if (DeclPtr.getType() != IRTy)
2036  DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
2037  // Indirect argument is in alloca address space, which may be different
2038  // from the default address space.
2039  auto AllocaAS = CGM.getASTAllocaAddressSpace();
2040  auto *V = DeclPtr.getPointer();
2041  auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS;
2042  auto DestLangAS =
2044  if (SrcLangAS != DestLangAS) {
2045  assert(getContext().getTargetAddressSpace(SrcLangAS) ==
2046  CGM.getDataLayout().getAllocaAddrSpace());
2047  auto DestAS = getContext().getTargetAddressSpace(DestLangAS);
2048  auto *T = V->getType()->getPointerElementType()->getPointerTo(DestAS);
2049  DeclPtr = Address(getTargetHooks().performAddrSpaceCast(
2050  *this, V, SrcLangAS, DestLangAS, T, true),
2051  DeclPtr.getAlignment());
2052  }
2053 
2054  // Push a destructor cleanup for this parameter if the ABI requires it.
2055  // Don't push a cleanup in a thunk for a method that will also emit a
2056  // cleanup.
2058  Ty->getAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
2059  if (QualType::DestructionKind DtorKind = Ty.isDestructedType()) {
2060  assert((DtorKind == QualType::DK_cxx_destructor ||
2061  DtorKind == QualType::DK_nontrivial_c_struct) &&
2062  "unexpected destructor type");
2063  pushDestroy(DtorKind, DeclPtr, Ty);
2064  CalleeDestructedParamCleanups[cast<ParmVarDecl>(&D)] =
2066  }
2067  }
2068  } else {
2069  // Check if the parameter address is controlled by OpenMP runtime.
2070  Address OpenMPLocalAddr =
2071  getLangOpts().OpenMP
2072  ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
2073  : Address::invalid();
2074  if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
2075  DeclPtr = OpenMPLocalAddr;
2076  } else {
2077  // Otherwise, create a temporary to hold the value.
2078  DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
2079  D.getName() + ".addr");
2080  }
2081  DoStore = true;
2082  }
2083 
2084  llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
2085 
2086  LValue lv = MakeAddrLValue(DeclPtr, Ty);
2087  if (IsScalar) {
2088  Qualifiers qs = Ty.getQualifiers();
2089  if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
2090  // We honor __attribute__((ns_consumed)) for types with lifetime.
2091  // For __strong, it's handled by just skipping the initial retain;
2092  // otherwise we have to balance out the initial +1 with an extra
2093  // cleanup to do the release at the end of the function.
2094  bool isConsumed = D.hasAttr<NSConsumedAttr>();
2095 
2096  // 'self' is always formally __strong, but if this is not an
2097  // init method then we don't want to retain it.
2098  if (D.isARCPseudoStrong()) {
2099  const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
2100  assert(&D == method->getSelfDecl());
2101  assert(lt == Qualifiers::OCL_Strong);
2102  assert(qs.hasConst());
2103  assert(method->getMethodFamily() != OMF_init);
2104  (void) method;
2106  }
2107 
2108  // Load objects passed indirectly.
2109  if (Arg.isIndirect() && !ArgVal)
2110  ArgVal = Builder.CreateLoad(DeclPtr);
2111 
2112  if (lt == Qualifiers::OCL_Strong) {
2113  if (!isConsumed) {
2114  if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2115  // use objc_storeStrong(&dest, value) for retaining the
2116  // object. But first, store a null into 'dest' because
2117  // objc_storeStrong attempts to release its old value.
2118  llvm::Value *Null = CGM.EmitNullConstant(D.getType());
2119  EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
2120  EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
2121  DoStore = false;
2122  }
2123  else
2124  // Don't use objc_retainBlock for block pointers, because we
2125  // don't want to Block_copy something just because we got it
2126  // as a parameter.
2127  ArgVal = EmitARCRetainNonBlock(ArgVal);
2128  }
2129  } else {
2130  // Push the cleanup for a consumed parameter.
2131  if (isConsumed) {
2132  ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
2134  EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
2135  precise);
2136  }
2137 
2138  if (lt == Qualifiers::OCL_Weak) {
2139  EmitARCInitWeak(DeclPtr, ArgVal);
2140  DoStore = false; // The weak init is a store, no need to do two.
2141  }
2142  }
2143 
2144  // Enter the cleanup scope.
2145  EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
2146  }
2147  }
2148 
2149  // Store the initial value into the alloca.
2150  if (DoStore)
2151  EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
2152 
2153  setAddrOfLocalVar(&D, DeclPtr);
2154 
2155  // Emit debug info for param declaration.
2156  if (CGDebugInfo *DI = getDebugInfo()) {
2157  if (CGM.getCodeGenOpts().getDebugInfo() >=
2159  DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
2160  }
2161  }
2162 
2163  if (D.hasAttr<AnnotateAttr>())
2164  EmitVarAnnotations(&D, DeclPtr.getPointer());
2165 
2166  // We can only check return value nullability if all arguments to the
2167  // function satisfy their nullability preconditions. This makes it necessary
2168  // to emit null checks for args in the function body itself.
2169  if (requiresReturnValueNullabilityCheck()) {
2170  auto Nullability = Ty->getNullability(getContext());
2172  SanitizerScope SanScope(this);
2173  RetValNullabilityPrecondition =
2174  Builder.CreateAnd(RetValNullabilityPrecondition,
2175  Builder.CreateIsNotNull(Arg.getAnyValue()));
2176  }
2177  }
2178 }
2179 
2181  CodeGenFunction *CGF) {
2182  if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
2183  return;
2184  getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
2185 }
2186 
2188  //Do nothing - here to avoid build errors
2189 }
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:361
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
Defines the clang::ASTContext interface.
static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init, unsigned &NumStores)
Decide whether we can emit the non-zero parts of the specified initializer with equal or fewer than N...
Definition: CGDecl.cpp:853
void setImplicit(bool I=true)
Definition: DeclBase.h:548
Represents a function declaration or definition.
Definition: Decl.h:1732
void EmitStaticVarDecl(const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage)
Definition: CGDecl.cpp:378
llvm::Value * EmitARCRetainAutoreleaseScalarExpr(const Expr *expr)
Definition: CGObjC.cpp:3002
Destroyer * getDestroyer(QualType::DestructionKind destructionKind)
Definition: CGDecl.cpp:1684
A (possibly-)qualified type.
Definition: Type.h:642
Allows to disable automatic handling of functions used in target regions as those marked as omp decla...
void EmitExtendGCLifetime(llvm::Value *object)
EmitExtendGCLifetime - Given a pointer to an Objective-C object, make sure it survives garbage collec...
Definition: CGObjC.cpp:3212
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2093
bool isArrayType() const
Definition: Type.h:6331
llvm::Type * ConvertTypeForMem(QualType T)
const CodeGenOptions & getCodeGenOpts() const
void EmitVarDecl(const VarDecl &D)
EmitVarDecl - Emit a local variable declaration.
Definition: CGDecl.cpp:158
Address CreateMemTemp(QualType T, const Twine &Name="tmp", Address *Alloca=nullptr)
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen and cas...
Definition: CGExpr.cpp:139
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:2706
void enterFullExpression(const FullExpr *E)
bool HaveInsertPoint() const
HaveInsertPoint - True if an insertion point is defined.
llvm::LLVMContext & getLLVMContext()
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.
bool isRecordType() const
Definition: Type.h:6355
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:1569
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:87
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:2918
void EmitAutoVarDecl(const VarDecl &D)
EmitAutoVarDecl - Emit an auto variable declaration.
Definition: CGDecl.cpp:1057
static Destroyer destroyARCStrongPrecise
void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray)
Definition: CGDecl.cpp:1731
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:1910
static void emitStoresForInitAfterBZero(CodeGenModule &CGM, llvm::Constant *Init, Address Loc, bool isVolatile, CGBuilderTy &Builder)
For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit the scalar stores that woul...
Definition: CGDecl.cpp:891
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2818
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1262
stable_iterator stable_begin() const
Create a stable reference to the top of the EH stack.
Definition: EHScopeStack.h:379
void EmitARCCopyWeak(Address dst, Address src)
void @objc_copyWeak(i8** dest, i8** src) Disregards the current value in dest.
Definition: CGObjC.cpp:2307
constexpr XRayInstrMask Function
Definition: XRayInstr.h:39
llvm::Value * EmitARCRetainNonBlock(llvm::Value *value)
Retain the given object, with normal retain semantics.
Definition: CGObjC.cpp:1966
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2478
const DeclContext * getParentFunctionOrMethod() const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext...
Definition: DeclBase.cpp:254
The type is a struct containing a field whose type is not PCK_Trivial.
Definition: Type.h:1096
static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init, uint64_t GlobalSize)
Decide whether we should use bzero plus some stores to initialize a local variable instead of using a...
Definition: CGDecl.cpp:937
static llvm::Value * shouldUseMemSetToInitialize(llvm::Constant *Init, uint64_t GlobalSize)
Decide whether we should use memset to initialize a local variable instead of using a memcpy from a c...
Definition: CGDecl.cpp:958
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::Instruction **callOrInvoke, SourceLocation Loc)
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:3787
Represents a variable declaration or definition.
Definition: Decl.h:812
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:6716
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:54
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.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have...
Definition: Linkage.h:24
unsigned getAddressSpace() const
Return the address space that this address resides in.
Definition: Address.h:57
The collection of all-type qualifiers we support.
Definition: Type.h:141
void add(RValue rvalue, QualType type)
Definition: CGCall.h:285
bool isARCPseudoStrong() const
Determine whether this variable is an ARC pseudo-__strong variable.
Definition: Decl.h:1356
const TargetInfo & getTarget() const
One of these records is kept for each identifier that is lexed.
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1018
void emitDestroy(Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray)
emitDestroy - Immediately perform the destruction of the given object.
Definition: CGDecl.cpp:1759
void emitByrefStructureInit(const AutoVarEmission &emission)
Initialize the structural components of a __block variable, i.e.
Definition: CGBlocks.cpp:2824
VlaSizePair getVLAElements1D(const VariableArrayType *vla)
Return the number of elements for a single dimension for the given array type.
Address getAddress() const
Definition: CGValue.h:327
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:1525
RValue EmitReferenceBindingToExpr(const Expr *E)
Emits a reference binding to the passed in expression.
Definition: CGExpr.cpp:589
FullExpr - Represents a "full-expression" node.
Definition: Expr.h:876
Qualifiers::ObjCLifetime getObjCLifetime() const
Definition: CGValue.h:266
bool isReferenceType() const
Definition: Type.h:6294
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:1701
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)
IdentifierTable & Idents
Definition: ASTContext.h:565
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:277
llvm::Constant * getLLVMLifetimeStartFn()
Lazily declare the .lifetime.start intrinsic.
Definition: CGDecl.cpp:1965
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
Definition: DeclObjC.cpp:986
llvm::Value * EmitARCStoreStrongCall(Address addr, llvm::Value *value, bool resultIgnored)
Store into a strong object.
Definition: CGObjC.cpp:2119
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:1953
static bool hasScalarEvaluationKind(QualType T)
static void drillIntoBlockVariable(CodeGenFunction &CGF, LValue &lvalue, const VarDecl *var)
Definition: CGDecl.cpp:713
Base object ctor.
Definition: ABI.h:27
void defaultInitNonTrivialCStructVar(LValue Dst)
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
void EmitOMPRequiresDecl(const OMPRequiresDecl *D)
Emit a code for requires directive.
Definition: CGDecl.cpp:2187
void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D, CodeGenFunction *CGF=nullptr)
Emit a code for declare reduction construct.
Definition: CGDecl.cpp:2180
An x-value expression is a reference to an object with independent storage but which can be "moved"...
Definition: Specifiers.h:119
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:229
static void emitStoresForConstant(CodeGenModule &CGM, const VarDecl &D, Address Loc, bool isVolatile, CGBuilderTy &Builder, llvm::Constant *constant)
Definition: CGDecl.cpp:1009
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:3113
llvm::CallInst * CreateMemCpy(Address Dest, Address Src, llvm::Value *Size, bool IsVolatile=false)
Definition: CGBuilder.h:274
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1383
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:2574
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:40
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:2986
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:2004
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:1478
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:1918
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:1697
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:106
bool hasConst() const
Definition: Type.h:258
static bool isCapturedBy(const VarDecl &, const Expr *)
Determines whether the given __block variable is potentially captured by the given expression...
Definition: CGDecl.cpp:1372
void registerVLASizeExpression(QualType Ty, llvm::Metadata *SizeExpr)
Register VLA size expression debug node with the qualified type.
Definition: CGDebugInfo.h:345
This object can be modified without requiring retains or releases.
Definition: Type.h:162
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:1080
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:531
bool isValid() const
Definition: Address.h:36
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:903
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:1155
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1605
const CodeGen::CGBlockInfo * BlockInfo
IdentifierInfo & getOwn(StringRef Name)
Gets an IdentifierInfo for the given name without consulting external sources.
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:328
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
AggValueSlot::Overlap_t overlapForFieldInit(const FieldDecl *FD)
Determine whether a field initialization may overlap some other object.
Address CreateDefaultAlignTempAlloca(llvm::Type *Ty, const Twine &Name="tmp")
CreateDefaultAlignedTempAlloca - This creates an alloca with the default ABI alignment of the given L...
Definition: CGExpr.cpp:119
This represents &#39;#pragma omp requires...&#39; directive.
Definition: DeclOpenMP.h:250
llvm::Value * EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored)
i8* @objc_storeWeak(i8** addr, i8* value) Returns value.
Definition: CGObjC.cpp:2251
void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr, bool PerformInit)
Emit code in this function to perform a guarded variable initialization.
Definition: CGDeclCXX.cpp:270
llvm::DILocalVariable * EmitDeclareOfAutoVariable(const VarDecl *Decl, llvm::Value *AI, CGBuilderTy &Builder)
Emit call to llvm.dbg.declare for an automatic variable declaration.
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
Pepresents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:3854
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:636
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:2298
Emit only debug info necessary for generating line number tables (-gline-tables-only).
Address getOriginalAllocatedAddress() const
Returns the address for the original alloca instruction.
void EmitAutoVarInit(const AutoVarEmission &emission)
Definition: CGDecl.cpp:1435
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
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1035
Enters a new scope for capturing cleanups, all of which will be executed once the scope is exited...
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition: CGCall.h:134
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:5096
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2700
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:1306
VlaSizePair getVLASize(const VariableArrayType *vla)
Returns an LLVM value that corresponds to the size, in non-variably-sized elements, of a variable length array type, plus that largest non-variably-sized element type.
llvm::PointerType * getType() const
Return the type of the pointer value.
Definition: Address.h:44
ObjCLifetime getObjCLifetime() const
Definition: Type.h:330
DeclContext * getDeclContext()
Definition: DeclBase.h:427
static SVal getValue(SVal val, SValBuilder &svalBuilder)
const AstTypeMatcher< ArrayType > arrayType
Matches all kinds of arrays.
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:719
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.
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:296
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:1798
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:6674
static bool hasNontrivialDestruction(QualType T)
hasNontrivialDestruction - Determine whether a type&#39;s destruction is non-trivial. ...
Definition: CGDecl.cpp:304
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:406
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:1481
llvm::Constant * getOrCreateStaticVarDecl(const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage)
Definition: CGDecl.cpp:211
There is no lifetime qualification on this type.
Definition: Type.h:158
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:169
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:314
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:1711
Encodes a location in the source.
void EmitAndRegisterVariableArrayDimensions(CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo)
Emits the alloca and debug information for the size expressions for each dimension of an array...
Definition: CGDecl.cpp:1092
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:936
void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise)
Release the given object.
Definition: CGObjC.cpp:2073
LValue EmitDeclRefLValue(const DeclRefExpr *E)
Definition: CGExpr.cpp:2439
This represents &#39;#pragma omp declare reduction ...&#39; directive.
Definition: DeclOpenMP.h:103
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:6174
static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D)
Definition: CGDecl.cpp:188
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2101
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition: Decl.h:291
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
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:1851
const Decl * getDecl() const
Definition: GlobalDecl.h:69
const BlockByrefInfo & getBlockByrefInfo(const VarDecl *var)
BuildByrefInfo - This routine changes a __block variable declared as T x into:
Definition: CGBlocks.cpp:2736
llvm::Value * EmitLifetimeStart(uint64_t Size, llvm::Value *Addr)
Emit a lifetime.begin marker if some criteria are satisfied.
Definition: CGDecl.cpp:1066
LangAS getStringLiteralAddressSpace() const
Return the AST address space of string literal, which is used to emit the string literal as global va...
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
static bool cxxDestructorCanThrow(QualType T)
Check if T is a C++ class that has a destructor that can throw.
Definition: CGBlocks.cpp:1808
static bool isAccessedBy(const VarDecl &var, const Stmt *s)
Definition: CGDecl.cpp:631
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:1421
bool isObjCObjectPointerType() const
Definition: Type.h:6379
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:1160
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:595
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required...
Definition: DeclBase.cpp:397
void enterByrefCleanup(CleanupKind Kind, Address Addr, BlockFieldFlags Flags, bool LoadBlockVarAddr, bool CanThrow)
Enter a cleanup to destroy a __block variable.
Definition: CGBlocks.cpp:2945
Complete object dtor.
Definition: ABI.h:36
Address CreateConstInBoundsGEP2_32(Address Addr, unsigned Idx0, unsigned Idx1, const llvm::DataLayout &DL, const llvm::Twine &Name="")
Definition: CGBuilder.h:248
void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo)
EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
Definition: CGDecl.cpp:2003
Assigning into this object requires a lifetime extension.
Definition: Type.h:175
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:3733
QualType getType() const
Definition: CGValue.h:264
llvm::Constant * getLLVMLifetimeEndFn()
Lazily declare the .lifetime.end intrinsic.
Definition: CGDecl.cpp:1974
void EmitDecl(const Decl &D)
EmitDecl - Emit a declaration.
Definition: CGDecl.cpp:42
const TargetCodeGenInfo & getTargetHooks() const
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.
bool isObjCGCWeak() const
true when Type is objc&#39;s weak.
Definition: Type.h:1056
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:2912
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.
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
Dataflow Directional Tag Classes.
static ApplyDebugLocation CreateDefaultArtificial(CodeGenFunction &CGF, SourceLocation TemporaryLocation)
Apply TemporaryLocation if it is valid.
Definition: CGDebugInfo.h:718
void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, bool ForVirtualBase, bool Delegating, Address This)
Definition: CGClass.cpp:2376
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1261
ArrayRef< Capture > captures() const
Definition: Decl.h:3981
const CGFunctionInfo & arrangeFunctionDeclaration(const FunctionDecl *FD)
Free functions are functions that are compatible with an ordinary C function pointer type...
Definition: CGCall.cpp:431
QualType getUnderlyingType() const
Definition: Decl.h:2967
const Expr * getInit() const
Definition: Decl.h:1219
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition: CGBuilder.h:70
Kind getKind() const
Definition: DeclBase.h:421
Decl * getNonClosureContext()
Find the innermost non-closure ancestor of this declaration, walking up through blocks, lambdas, etc.
Definition: DeclBase.cpp:1002
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
static AggValueSlot forLValue(const LValue &LV, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed, IsSanitizerChecked_t isChecked=IsNotSanitizerChecked)
Definition: CGValue.h:540
bool isEscapingByref() const
Indicates the capture is a __block variable that is captured by a block that can potentially escape (...
Definition: Decl.cpp:2374
llvm::Module & getModule() const
static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF, const LValue &destLV, const Expr *init)
Definition: CGDecl.cpp:663
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:1777
static bool hasAggregateEvaluationKind(QualType T)
void EmitAutoVarCleanups(const AutoVarEmission &emission)
Definition: CGDecl.cpp:1636
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4356
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:2013
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:2877
T * getAttr() const
Definition: DeclBase.h:527
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition: Address.h:52
bool isAtomicType() const
Definition: Type.h:6392
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:740
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:32
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition: CGStmt.cpp:445
void EmitARCInitWeak(Address addr, llvm::Value *value)
i8* @objc_initWeak(i8** addr, i8* value) Returns value.
Definition: CGObjC.cpp:2263
Optional< NullabilityKind > getNullability(const ASTContext &context) const
Determine the nullability of the given type.
Definition: Type.cpp:3671
static Destroyer destroyNonTrivialCStruct
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:1134
static llvm::Constant * EmitNullConstant(CodeGenModule &CGM, const RecordDecl *record, bool asCompleteObject)
Reading or writing from this object requires a barrier call.
Definition: Type.h:172
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...
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6138
Represents a C++ struct/union/class.
Definition: DeclCXX.h:300
bool isNRVOVariable() const
Determine whether this local variable can be used with the named return value optimization (NRVO)...
Definition: Decl.h:1324
llvm::Type * ConvertType(QualType T)
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6085
static Address createUnnamedGlobalFrom(CodeGenModule &CGM, const VarDecl &D, CGBuilderTy &Builder, llvm::Constant *Constant, CharUnits Align)
Definition: CGDecl.cpp:966
LValue EmitLValue(const Expr *E)
EmitLValue - Emit code to compute a designator that specifies the location of the expression...
Definition: CGExpr.cpp:1232
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
bool isSamplerT() const
Definition: Type.h:6436
void pushStackRestore(CleanupKind kind, Address SPMem)
Definition: CGDecl.cpp:1727
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:1068
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition: Sanitizers.h:52
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
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:275
void setLocation(SourceLocation Loc)
Update the current source location.
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1036
static RValue get(llvm::Value *V)
Definition: CGValue.h:86
void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr)
Definition: CGDecl.cpp:1082
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:2787
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition: Decl.h:1104
QualType getType() const
Definition: Decl.h:647
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:114
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:278
SanitizerMetadata * getSanitizerMetadata()
bool isConstant(const ASTContext &Ctx) const
Definition: Type.h:777
bool CurFuncIsThunk
In C++, whether we are code generating a thunk.
const LangOptions & getLangOpts() const
unsigned getTargetAddressSpace(QualType T) const
Definition: ASTContext.h:2498
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:260
void PopCleanupBlock(bool FallThroughIsBranchThrough=false)
PopCleanupBlock - Will pop the cleanup entry on the stack and process all branch fixups.
Definition: CGCleanup.cpp:651
llvm::Value * getPointer() const
Definition: CGValue.h:323
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:2699
SourceLocation getLocation() const
Definition: DeclBase.h:418
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:1936
bool isExternallyVisible() const
Definition: Decl.h:379
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth, signed/unsigned.
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
Definition: Expr.cpp:2543
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:1066