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