1 //===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code to emit Decl nodes as LLVM code.
12 //===----------------------------------------------------------------------===//
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 "TargetInfo.h"
23 #include "clang/AST/ASTContext.h"
24 #include "clang/AST/CharUnits.h"
25 #include "clang/AST/Decl.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/AST/DeclOpenMP.h"
28 #include "clang/Basic/SourceManager.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/CodeGen/CGFunctionInfo.h"
31 #include "clang/Frontend/CodeGenOptions.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/IR/Type.h"
37 using namespace clang;
38 using namespace CodeGen;
40 void CodeGenFunction::EmitDecl(const Decl &D) {
41 switch (D.getKind()) {
42 case Decl::BuiltinTemplate:
43 case Decl::TranslationUnit:
44 case Decl::ExternCContext:
46 case Decl::UnresolvedUsingTypename:
47 case Decl::ClassTemplateSpecialization:
48 case Decl::ClassTemplatePartialSpecialization:
49 case Decl::VarTemplateSpecialization:
50 case Decl::VarTemplatePartialSpecialization:
51 case Decl::TemplateTypeParm:
52 case Decl::UnresolvedUsingValue:
53 case Decl::NonTypeTemplateParm:
54 case Decl::CXXDeductionGuide:
56 case Decl::CXXConstructor:
57 case Decl::CXXDestructor:
58 case Decl::CXXConversion:
60 case Decl::MSProperty:
61 case Decl::IndirectField:
63 case Decl::ObjCAtDefsField:
65 case Decl::ImplicitParam:
66 case Decl::ClassTemplate:
67 case Decl::VarTemplate:
68 case Decl::FunctionTemplate:
69 case Decl::TypeAliasTemplate:
70 case Decl::TemplateTemplateParm:
71 case Decl::ObjCMethod:
72 case Decl::ObjCCategory:
73 case Decl::ObjCProtocol:
74 case Decl::ObjCInterface:
75 case Decl::ObjCCategoryImpl:
76 case Decl::ObjCImplementation:
77 case Decl::ObjCProperty:
78 case Decl::ObjCCompatibleAlias:
79 case Decl::PragmaComment:
80 case Decl::PragmaDetectMismatch:
81 case Decl::AccessSpec:
82 case Decl::LinkageSpec:
84 case Decl::ObjCPropertyImpl:
85 case Decl::FileScopeAsm:
87 case Decl::FriendTemplate:
90 case Decl::ClassScopeFunctionSpecialization:
91 case Decl::UsingShadow:
92 case Decl::ConstructorUsingShadow:
93 case Decl::ObjCTypeParam:
95 llvm_unreachable("Declaration should not be in declstmts!");
96 case Decl::Function: // void X();
97 case Decl::Record: // struct/union/class X;
98 case Decl::Enum: // enum X;
99 case Decl::EnumConstant: // enum ? { X = ? }
100 case Decl::CXXRecord: // struct/union/class X; [C++]
101 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
102 case Decl::Label: // __label__ x;
104 case Decl::OMPThreadPrivate:
105 case Decl::OMPCapturedExpr:
107 // None of these decls require codegen support.
110 case Decl::NamespaceAlias:
111 if (CGDebugInfo *DI = getDebugInfo())
112 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
114 case Decl::Using: // using X; [C++]
115 if (CGDebugInfo *DI = getDebugInfo())
116 DI->EmitUsingDecl(cast<UsingDecl>(D));
118 case Decl::UsingPack:
119 for (auto *Using : cast<UsingPackDecl>(D).expansions())
122 case Decl::UsingDirective: // using namespace X; [C++]
123 if (CGDebugInfo *DI = getDebugInfo())
124 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
127 case Decl::Decomposition: {
128 const VarDecl &VD = cast<VarDecl>(D);
129 assert(VD.isLocalVarDecl() &&
130 "Should not see file-scope variables inside a function!");
132 if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
133 for (auto *B : DD->bindings())
134 if (auto *HD = B->getHoldingVar())
139 case Decl::OMPDeclareReduction:
140 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
142 case Decl::Typedef: // typedef int X;
143 case Decl::TypeAlias: { // using X = int; [C++0x]
144 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
145 QualType Ty = TD.getUnderlyingType();
147 if (Ty->isVariablyModifiedType())
148 EmitVariablyModifiedType(Ty);
153 /// EmitVarDecl - This method handles emission of any variable declaration
154 /// inside a function, including static vars etc.
155 void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
156 if (D.hasExternalStorage())
157 // Don't emit it now, allow it to be emitted lazily on its first use.
160 // Some function-scope variable does not have static storage but still
161 // needs to be emitted like a static variable, e.g. a function-scope
162 // variable in constant address space in OpenCL.
163 if (D.getStorageDuration() != SD_Automatic) {
164 llvm::GlobalValue::LinkageTypes Linkage =
165 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
167 // FIXME: We need to force the emission/use of a guard variable for
168 // some variables even if we can constant-evaluate them because
169 // we can't guarantee every translation unit will constant-evaluate them.
171 return EmitStaticVarDecl(D, Linkage);
174 if (D.getType().getAddressSpace() == LangAS::opencl_local)
175 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
177 assert(D.hasLocalStorage());
178 return EmitAutoVarDecl(D);
181 static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
182 if (CGM.getLangOpts().CPlusPlus)
183 return CGM.getMangledName(&D).str();
185 // If this isn't C++, we don't need a mangled name, just a pretty one.
186 assert(!D.isExternallyVisible() && "name shouldn't matter");
187 std::string ContextName;
188 const DeclContext *DC = D.getDeclContext();
189 if (auto *CD = dyn_cast<CapturedDecl>(DC))
190 DC = cast<DeclContext>(CD->getNonClosureContext());
191 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
192 ContextName = CGM.getMangledName(FD);
193 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
194 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
195 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
196 ContextName = OMD->getSelector().getAsString();
198 llvm_unreachable("Unknown context for static var decl");
200 ContextName += "." + D.getNameAsString();
204 llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
205 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
206 // In general, we don't always emit static var decls once before we reference
207 // them. It is possible to reference them before emitting the function that
208 // contains them, and it is possible to emit the containing function multiple
210 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
213 QualType Ty = D.getType();
214 assert(Ty->isConstantSizeType() && "VLAs can't be static");
216 // Use the label if the variable is renamed with the asm-label extension.
218 if (D.hasAttr<AsmLabelAttr>())
219 Name = getMangledName(&D);
221 Name = getStaticDeclName(*this, D);
223 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
225 GetGlobalVarAddressSpace(&D, getContext().getTargetAddressSpace(Ty));
227 // Local address space cannot have an initializer.
228 llvm::Constant *Init = nullptr;
229 if (Ty.getAddressSpace() != LangAS::opencl_local)
230 Init = EmitNullConstant(Ty);
232 Init = llvm::UndefValue::get(LTy);
234 llvm::GlobalVariable *GV =
235 new llvm::GlobalVariable(getModule(), LTy,
236 Ty.isConstant(getContext()), Linkage,
238 llvm::GlobalVariable::NotThreadLocal,
240 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
241 setGlobalVisibility(GV, &D);
243 if (supportsCOMDAT() && GV->isWeakForLinker())
244 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
249 if (D.isExternallyVisible()) {
250 if (D.hasAttr<DLLImportAttr>())
251 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
252 else if (D.hasAttr<DLLExportAttr>())
253 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
256 // Make sure the result is of the correct type.
257 unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(Ty);
258 llvm::Constant *Addr = GV;
259 if (AddrSpace != ExpectedAddrSpace) {
260 llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
261 Addr = llvm::ConstantExpr::getAddrSpaceCast(GV, PTy);
264 setStaticLocalDeclAddress(&D, Addr);
266 // Ensure that the static local gets initialized by making sure the parent
267 // function gets emitted eventually.
268 const Decl *DC = cast<Decl>(D.getDeclContext());
270 // We can't name blocks or captured statements directly, so try to emit their
272 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
273 DC = DC->getNonClosureContext();
274 // FIXME: Ensure that global blocks get emitted.
280 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
281 GD = GlobalDecl(CD, Ctor_Base);
282 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
283 GD = GlobalDecl(DD, Dtor_Base);
284 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
287 // Don't do anything for Obj-C method decls or global closures. We should
289 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
292 (void)GetAddrOfGlobal(GD);
297 /// hasNontrivialDestruction - Determine whether a type's destruction is
298 /// non-trivial. If so, and the variable uses static initialization, we must
299 /// register its destructor to run on exit.
300 static bool hasNontrivialDestruction(QualType T) {
301 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
302 return RD && !RD->hasTrivialDestructor();
305 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
306 /// global variable that has already been created for it. If the initializer
307 /// has a different type than GV does, this may free GV and return a different
308 /// one. Otherwise it just returns GV.
309 llvm::GlobalVariable *
310 CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
311 llvm::GlobalVariable *GV) {
312 llvm::Constant *Init = CGM.EmitConstantInit(D, this);
314 // If constant emission failed, then this should be a C++ static
317 if (!getLangOpts().CPlusPlus)
318 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
319 else if (HaveInsertPoint()) {
320 // Since we have a static initializer, this global variable can't
322 GV->setConstant(false);
324 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
329 // The initializer may differ in type from the global. Rewrite
330 // the global to match the initializer. (We have to do this
331 // because some types, like unions, can't be completely represented
332 // in the LLVM type system.)
333 if (GV->getType()->getElementType() != Init->getType()) {
334 llvm::GlobalVariable *OldGV = GV;
336 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
338 OldGV->getLinkage(), Init, "",
339 /*InsertBefore*/ OldGV,
340 OldGV->getThreadLocalMode(),
341 CGM.getContext().getTargetAddressSpace(D.getType()));
342 GV->setVisibility(OldGV->getVisibility());
343 GV->setComdat(OldGV->getComdat());
345 // Steal the name of the old global
348 // Replace all uses of the old global with the new global
349 llvm::Constant *NewPtrForOldDecl =
350 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
351 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
353 // Erase the old global, since it is no longer used.
354 OldGV->eraseFromParent();
357 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
358 GV->setInitializer(Init);
360 if (hasNontrivialDestruction(D.getType()) && HaveInsertPoint()) {
361 // We have a constant initializer, but a nontrivial destructor. We still
362 // need to perform a guarded "initialization" in order to register the
364 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
370 void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
371 llvm::GlobalValue::LinkageTypes Linkage) {
372 // Check to see if we already have a global variable for this
373 // declaration. This can happen when double-emitting function
374 // bodies, e.g. with complete and base constructors.
375 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
376 CharUnits alignment = getContext().getDeclAlign(&D);
378 // Store into LocalDeclMap before generating initializer to handle
379 // circular references.
380 setAddrOfLocalVar(&D, Address(addr, alignment));
382 // We can't have a VLA here, but we can have a pointer to a VLA,
383 // even though that doesn't really make any sense.
384 // Make sure to evaluate VLA bounds now so that we have them for later.
385 if (D.getType()->isVariablyModifiedType())
386 EmitVariablyModifiedType(D.getType());
388 // Save the type in case adding the initializer forces a type change.
389 llvm::Type *expectedType = addr->getType();
391 llvm::GlobalVariable *var =
392 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
394 // CUDA's local and local static __shared__ variables should not
395 // have any non-empty initializers. This is ensured by Sema.
396 // Whatever initializer such variable may have when it gets here is
397 // a no-op and should not be emitted.
398 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
399 D.hasAttr<CUDASharedAttr>();
400 // If this value has an initializer, emit it.
401 if (D.getInit() && !isCudaSharedVar)
402 var = AddInitializerToStaticVarDecl(D, var);
404 var->setAlignment(alignment.getQuantity());
406 if (D.hasAttr<AnnotateAttr>())
407 CGM.AddGlobalAnnotations(&D, var);
409 if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())
410 var->addAttribute("bss-section", SA->getName());
411 if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())
412 var->addAttribute("data-section", SA->getName());
413 if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())
414 var->addAttribute("rodata-section", SA->getName());
416 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
417 var->setSection(SA->getName());
419 if (D.hasAttr<UsedAttr>())
420 CGM.addUsedGlobal(var);
422 // We may have to cast the constant because of the initializer
425 // FIXME: It is really dangerous to store this in the map; if anyone
426 // RAUW's the GV uses of this constant will be invalid.
427 llvm::Constant *castedAddr =
428 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
429 if (var != castedAddr)
430 LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
431 CGM.setStaticLocalDeclAddress(&D, castedAddr);
433 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
435 // Emit global variable debug descriptor for static vars.
436 CGDebugInfo *DI = getDebugInfo();
438 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
439 DI->setLocation(D.getLocation());
440 DI->EmitGlobalVariable(var, &D);
445 struct DestroyObject final : EHScopeStack::Cleanup {
446 DestroyObject(Address addr, QualType type,
447 CodeGenFunction::Destroyer *destroyer,
448 bool useEHCleanupForArray)
449 : addr(addr), type(type), destroyer(destroyer),
450 useEHCleanupForArray(useEHCleanupForArray) {}
454 CodeGenFunction::Destroyer *destroyer;
455 bool useEHCleanupForArray;
457 void Emit(CodeGenFunction &CGF, Flags flags) override {
458 // Don't use an EH cleanup recursively from an EH cleanup.
459 bool useEHCleanupForArray =
460 flags.isForNormalCleanup() && this->useEHCleanupForArray;
462 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
466 struct DestroyNRVOVariable final : EHScopeStack::Cleanup {
467 DestroyNRVOVariable(Address addr,
468 const CXXDestructorDecl *Dtor,
469 llvm::Value *NRVOFlag)
470 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
472 const CXXDestructorDecl *Dtor;
473 llvm::Value *NRVOFlag;
476 void Emit(CodeGenFunction &CGF, Flags flags) override {
477 // Along the exceptions path we always execute the dtor.
478 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
480 llvm::BasicBlock *SkipDtorBB = nullptr;
482 // If we exited via NRVO, we skip the destructor call.
483 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
484 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
485 llvm::Value *DidNRVO =
486 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
487 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
488 CGF.EmitBlock(RunDtorBB);
491 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
492 /*ForVirtualBase=*/false,
493 /*Delegating=*/false,
496 if (NRVO) CGF.EmitBlock(SkipDtorBB);
500 struct CallStackRestore final : EHScopeStack::Cleanup {
502 CallStackRestore(Address Stack) : Stack(Stack) {}
503 void Emit(CodeGenFunction &CGF, Flags flags) override {
504 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
505 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
506 CGF.Builder.CreateCall(F, V);
510 struct ExtendGCLifetime final : EHScopeStack::Cleanup {
512 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
514 void Emit(CodeGenFunction &CGF, Flags flags) override {
515 // Compute the address of the local variable, in case it's a
516 // byref or something.
517 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
518 Var.getType(), VK_LValue, SourceLocation());
519 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
521 CGF.EmitExtendGCLifetime(value);
525 struct CallCleanupFunction final : EHScopeStack::Cleanup {
526 llvm::Constant *CleanupFn;
527 const CGFunctionInfo &FnInfo;
530 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
532 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
534 void Emit(CodeGenFunction &CGF, Flags flags) override {
535 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
536 Var.getType(), VK_LValue, SourceLocation());
537 // Compute the address of the local variable, in case it's a byref
539 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
541 // In some cases, the type of the function argument will be different from
542 // the type of the pointer. An example of this is
543 // void f(void* arg);
544 // __attribute__((cleanup(f))) void *g;
546 // To fix this we insert a bitcast here.
547 QualType ArgTy = FnInfo.arg_begin()->type;
549 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
552 Args.add(RValue::get(Arg),
553 CGF.getContext().getPointerType(Var.getType()));
554 auto Callee = CGCallee::forDirect(CleanupFn);
555 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
558 } // end anonymous namespace
560 /// EmitAutoVarWithLifetime - Does the setup required for an automatic
561 /// variable with lifetime.
562 static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
564 Qualifiers::ObjCLifetime lifetime) {
566 case Qualifiers::OCL_None:
567 llvm_unreachable("present but none");
569 case Qualifiers::OCL_ExplicitNone:
573 case Qualifiers::OCL_Strong: {
574 CodeGenFunction::Destroyer *destroyer =
575 (var.hasAttr<ObjCPreciseLifetimeAttr>()
576 ? CodeGenFunction::destroyARCStrongPrecise
577 : CodeGenFunction::destroyARCStrongImprecise);
579 CleanupKind cleanupKind = CGF.getARCCleanupKind();
580 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
581 cleanupKind & EHCleanup);
584 case Qualifiers::OCL_Autoreleasing:
588 case Qualifiers::OCL_Weak:
589 // __weak objects always get EH cleanups; otherwise, exceptions
590 // could cause really nasty crashes instead of mere leaks.
591 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
592 CodeGenFunction::destroyARCWeak,
593 /*useEHCleanup*/ true);
598 static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
599 if (const Expr *e = dyn_cast<Expr>(s)) {
600 // Skip the most common kinds of expressions that make
601 // hierarchy-walking expensive.
602 s = e = e->IgnoreParenCasts();
604 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
605 return (ref->getDecl() == &var);
606 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
607 const BlockDecl *block = be->getBlockDecl();
608 for (const auto &I : block->captures()) {
609 if (I.getVariable() == &var)
615 for (const Stmt *SubStmt : s->children())
616 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
617 if (SubStmt && isAccessedBy(var, SubStmt))
623 static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
624 if (!decl) return false;
625 if (!isa<VarDecl>(decl)) return false;
626 const VarDecl *var = cast<VarDecl>(decl);
627 return isAccessedBy(*var, e);
630 static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
631 const LValue &destLV, const Expr *init) {
632 bool needsCast = false;
634 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
635 switch (castExpr->getCastKind()) {
636 // Look through casts that don't require representation changes.
639 case CK_BlockPointerToObjCPointerCast:
643 // If we find an l-value to r-value cast from a __weak variable,
644 // emit this operation as a copy or move.
645 case CK_LValueToRValue: {
646 const Expr *srcExpr = castExpr->getSubExpr();
647 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
650 // Emit the source l-value.
651 LValue srcLV = CGF.EmitLValue(srcExpr);
653 // Handle a formal type change to avoid asserting.
654 auto srcAddr = srcLV.getAddress();
656 srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
657 destLV.getAddress().getElementType());
660 // If it was an l-value, use objc_copyWeak.
661 if (srcExpr->getValueKind() == VK_LValue) {
662 CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
664 assert(srcExpr->getValueKind() == VK_XValue);
665 CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
670 // Stop at anything else.
675 init = castExpr->getSubExpr();
680 static void drillIntoBlockVariable(CodeGenFunction &CGF,
682 const VarDecl *var) {
683 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
686 void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
687 SourceLocation Loc) {
688 if (!SanOpts.has(SanitizerKind::NullabilityAssign))
691 auto Nullability = LHS.getType()->getNullability(getContext());
692 if (!Nullability || *Nullability != NullabilityKind::NonNull)
695 // Check if the right hand side of the assignment is nonnull, if the left
696 // hand side must be nonnull.
697 SanitizerScope SanScope(this);
698 llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
699 llvm::Constant *StaticData[] = {
700 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()),
701 llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.
702 llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
703 EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},
704 SanitizerHandler::TypeMismatch, StaticData, RHS);
707 void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
708 LValue lvalue, bool capturedByInit) {
709 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
711 llvm::Value *value = EmitScalarExpr(init);
713 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
714 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
715 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
719 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
720 init = DIE->getExpr();
722 // If we're emitting a value with lifetime, we have to do the
723 // initialization *before* we leave the cleanup scopes.
724 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
725 enterFullExpression(ewc);
726 init = ewc->getSubExpr();
728 CodeGenFunction::RunCleanupsScope Scope(*this);
730 // We have to maintain the illusion that the variable is
731 // zero-initialized. If the variable might be accessed in its
732 // initializer, zero-initialize before running the initializer, then
733 // actually perform the initialization with an assign.
734 bool accessedByInit = false;
735 if (lifetime != Qualifiers::OCL_ExplicitNone)
736 accessedByInit = (capturedByInit || isAccessedBy(D, init));
737 if (accessedByInit) {
738 LValue tempLV = lvalue;
739 // Drill down to the __block object if necessary.
740 if (capturedByInit) {
741 // We can use a simple GEP for this because it can't have been
743 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
748 auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
749 llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
751 // If __weak, we want to use a barrier under certain conditions.
752 if (lifetime == Qualifiers::OCL_Weak)
753 EmitARCInitWeak(tempLV.getAddress(), zero);
755 // Otherwise just do a simple store.
757 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
760 // Emit the initializer.
761 llvm::Value *value = nullptr;
764 case Qualifiers::OCL_None:
765 llvm_unreachable("present but none");
767 case Qualifiers::OCL_ExplicitNone:
768 value = EmitARCUnsafeUnretainedScalarExpr(init);
771 case Qualifiers::OCL_Strong: {
772 value = EmitARCRetainScalarExpr(init);
776 case Qualifiers::OCL_Weak: {
777 // If it's not accessed by the initializer, try to emit the
778 // initialization with a copy or move.
779 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
783 // No way to optimize a producing initializer into this. It's not
784 // worth optimizing for, because the value will immediately
785 // disappear in the common case.
786 value = EmitScalarExpr(init);
788 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
790 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
792 EmitARCInitWeak(lvalue.getAddress(), value);
796 case Qualifiers::OCL_Autoreleasing:
797 value = EmitARCRetainAutoreleaseScalarExpr(init);
801 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
803 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
805 // If the variable might have been accessed by its initializer, we
806 // might have to initialize with a barrier. We have to do this for
807 // both __weak and __strong, but __weak got filtered out above.
808 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
809 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
810 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
811 EmitARCRelease(oldValue, ARCImpreciseLifetime);
815 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
818 /// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
819 /// non-zero parts of the specified initializer with equal or fewer than
820 /// NumStores scalar stores.
821 static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
822 unsigned &NumStores) {
823 // Zero and Undef never requires any extra stores.
824 if (isa<llvm::ConstantAggregateZero>(Init) ||
825 isa<llvm::ConstantPointerNull>(Init) ||
826 isa<llvm::UndefValue>(Init))
828 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
829 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
830 isa<llvm::ConstantExpr>(Init))
831 return Init->isNullValue() || NumStores--;
833 // See if we can emit each element.
834 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
835 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
836 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
837 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
843 if (llvm::ConstantDataSequential *CDS =
844 dyn_cast<llvm::ConstantDataSequential>(Init)) {
845 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
846 llvm::Constant *Elt = CDS->getElementAsConstant(i);
847 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
853 // Anything else is hard and scary.
857 /// emitStoresForInitAfterMemset - For inits that
858 /// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
859 /// stores that would be required.
860 static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
861 bool isVolatile, CGBuilderTy &Builder) {
862 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
863 "called emitStoresForInitAfterMemset for zero or undef value.");
865 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
866 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
867 isa<llvm::ConstantExpr>(Init)) {
868 Builder.CreateDefaultAlignedStore(Init, Loc, isVolatile);
872 if (llvm::ConstantDataSequential *CDS =
873 dyn_cast<llvm::ConstantDataSequential>(Init)) {
874 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
875 llvm::Constant *Elt = CDS->getElementAsConstant(i);
877 // If necessary, get a pointer to the element and emit it.
878 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
879 emitStoresForInitAfterMemset(
880 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
881 isVolatile, Builder);
886 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
887 "Unknown value type!");
889 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
890 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
892 // If necessary, get a pointer to the element and emit it.
893 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
894 emitStoresForInitAfterMemset(
895 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
896 isVolatile, Builder);
900 /// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
901 /// plus some stores to initialize a local variable instead of using a memcpy
902 /// from a constant global. It is beneficial to use memset if the global is all
903 /// zeros, or mostly zeros and large.
904 static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
905 uint64_t GlobalSize) {
906 // If a global is all zeros, always use a memset.
907 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
909 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
910 // do it if it will require 6 or fewer scalar stores.
911 // TODO: Should budget depends on the size? Avoiding a large global warrants
912 // plopping in more stores.
913 unsigned StoreBudget = 6;
914 uint64_t SizeLimit = 32;
916 return GlobalSize > SizeLimit &&
917 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
920 /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
921 /// variable declaration with auto, register, or no storage class specifier.
922 /// These turn into simple stack objects, or GlobalValues depending on target.
923 void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
924 AutoVarEmission emission = EmitAutoVarAlloca(D);
925 EmitAutoVarInit(emission);
926 EmitAutoVarCleanups(emission);
929 /// Emit a lifetime.begin marker if some criteria are satisfied.
930 /// \return a pointer to the temporary size Value if a marker was emitted, null
932 llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
934 if (!ShouldEmitLifetimeMarkers)
937 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
938 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
940 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
941 C->setDoesNotThrow();
945 void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
946 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
948 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
949 C->setDoesNotThrow();
952 /// EmitAutoVarAlloca - Emit the alloca and debug information for a
953 /// local variable. Does not emit initialization or destruction.
954 CodeGenFunction::AutoVarEmission
955 CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
956 QualType Ty = D.getType();
958 AutoVarEmission emission(D);
960 bool isByRef = D.hasAttr<BlocksAttr>();
961 emission.IsByRef = isByRef;
963 CharUnits alignment = getContext().getDeclAlign(&D);
965 // If the type is variably-modified, emit all the VLA sizes for it.
966 if (Ty->isVariablyModifiedType())
967 EmitVariablyModifiedType(Ty);
969 Address address = Address::invalid();
970 if (Ty->isConstantSizeType()) {
971 bool NRVO = getLangOpts().ElideConstructors &&
974 // If this value is an array or struct with a statically determinable
975 // constant initializer, there are optimizations we can do.
977 // TODO: We should constant-evaluate the initializer of any variable,
978 // as long as it is initialized by a constant expression. Currently,
979 // isConstantInitializer produces wrong answers for structs with
980 // reference or bitfield members, and a few other cases, and checking
981 // for POD-ness protects us from some of these.
982 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
984 ((Ty.isPODType(getContext()) ||
985 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
986 D.getInit()->isConstantInitializer(getContext(), false)))) {
988 // If the variable's a const type, and it's neither an NRVO
989 // candidate nor a __block variable and has no mutable members,
990 // emit it as a global instead.
991 // Exception is if a variable is located in non-constant address space
993 if ((!getLangOpts().OpenCL ||
994 Ty.getAddressSpace() == LangAS::opencl_constant) &&
995 (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
996 CGM.isTypeConstant(Ty, true))) {
997 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
999 // Signal this condition to later callbacks.
1000 emission.Addr = Address::invalid();
1001 assert(emission.wasEmittedAsGlobal());
1005 // Otherwise, tell the initialization code that we're in this case.
1006 emission.IsConstantAggregate = true;
1009 // A normal fixed sized variable becomes an alloca in the entry block,
1010 // unless it's an NRVO variable.
1013 // The named return value optimization: allocate this variable in the
1014 // return slot, so that we can elide the copy when returning this
1015 // variable (C++0x [class.copy]p34).
1016 address = ReturnValue;
1018 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1019 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
1020 // Create a flag that is used to indicate when the NRVO was applied
1021 // to this variable. Set it to zero to indicate that NRVO was not
1023 llvm::Value *Zero = Builder.getFalse();
1025 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
1026 EnsureInsertPoint();
1027 Builder.CreateStore(Zero, NRVOFlag);
1029 // Record the NRVO flag for this variable.
1030 NRVOFlags[&D] = NRVOFlag.getPointer();
1031 emission.NRVOFlag = NRVOFlag.getPointer();
1035 CharUnits allocaAlignment;
1036 llvm::Type *allocaTy;
1038 auto &byrefInfo = getBlockByrefInfo(&D);
1039 allocaTy = byrefInfo.Type;
1040 allocaAlignment = byrefInfo.ByrefAlignment;
1042 allocaTy = ConvertTypeForMem(Ty);
1043 allocaAlignment = alignment;
1046 // Create the alloca. Note that we set the name separately from
1047 // building the instruction so that it's there even in no-asserts
1049 address = CreateTempAlloca(allocaTy, allocaAlignment);
1050 address.getPointer()->setName(D.getName());
1052 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1053 // the catch parameter starts in the catchpad instruction, and we can't
1054 // insert code in those basic blocks.
1055 bool IsMSCatchParam =
1056 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1058 // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1059 // if we don't have a valid insertion point (?).
1060 if (HaveInsertPoint() && !IsMSCatchParam) {
1061 // If there's a jump into the lifetime of this variable, its lifetime
1062 // gets broken up into several regions in IR, which requires more work
1063 // to handle correctly. For now, just omit the intrinsics; this is a
1064 // rare case, and it's better to just be conservatively correct.
1067 // We have to do this in all language modes if there's a jump past the
1068 // declaration. We also have to do it in C if there's a jump to an
1069 // earlier point in the current block because non-VLA lifetimes begin as
1070 // soon as the containing block is entered, not when its variables
1071 // actually come into scope; suppressing the lifetime annotations
1072 // completely in this case is unnecessarily pessimistic, but again, this
1074 if (!Bypasses.IsBypassed(&D) &&
1075 !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
1076 uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1077 emission.SizeForLifetimeMarkers =
1078 EmitLifetimeStart(size, address.getPointer());
1081 assert(!emission.useLifetimeMarkers());
1085 EnsureInsertPoint();
1087 if (!DidCallStackSave) {
1090 CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
1092 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
1093 llvm::Value *V = Builder.CreateCall(F);
1094 Builder.CreateStore(V, Stack);
1096 DidCallStackSave = true;
1098 // Push a cleanup block and restore the stack there.
1099 // FIXME: in general circumstances, this should be an EH cleanup.
1100 pushStackRestore(NormalCleanup, Stack);
1103 llvm::Value *elementCount;
1104 QualType elementType;
1105 std::tie(elementCount, elementType) = getVLASize(Ty);
1107 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
1109 // Allocate memory for the array.
1110 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
1111 vla->setAlignment(alignment.getQuantity());
1113 address = Address(vla, alignment);
1116 // Alloca always returns a pointer in alloca address space, which may
1117 // be different from the type defined by the language. For example,
1118 // in C++ the auto variables are in the default address space. Therefore
1119 // cast alloca to the expected address space when necessary.
1120 auto T = D.getType();
1121 assert(T.getAddressSpace() == LangAS::Default);
1122 if (getASTAllocaAddressSpace() != LangAS::Default) {
1123 auto *Addr = getTargetHooks().performAddrSpaceCast(
1124 *this, address.getPointer(), getASTAllocaAddressSpace(),
1125 T.getAddressSpace(),
1126 address.getElementType()->getPointerTo(
1127 getContext().getTargetAddressSpace(T.getAddressSpace())),
1129 address = Address(Addr, address.getAlignment());
1131 setAddrOfLocalVar(&D, address);
1132 emission.Addr = address;
1134 // Emit debug info for local var declaration.
1135 if (HaveInsertPoint())
1136 if (CGDebugInfo *DI = getDebugInfo()) {
1137 if (CGM.getCodeGenOpts().getDebugInfo() >=
1138 codegenoptions::LimitedDebugInfo) {
1139 DI->setLocation(D.getLocation());
1140 DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
1144 if (D.hasAttr<AnnotateAttr>())
1145 EmitVarAnnotations(&D, address.getPointer());
1147 // Make sure we call @llvm.lifetime.end.
1148 if (emission.useLifetimeMarkers())
1149 EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
1150 emission.getAllocatedAddress(),
1151 emission.getSizeForLifetimeMarkers());
1156 /// Determines whether the given __block variable is potentially
1157 /// captured by the given expression.
1158 static bool isCapturedBy(const VarDecl &var, const Expr *e) {
1159 // Skip the most common kinds of expressions that make
1160 // hierarchy-walking expensive.
1161 e = e->IgnoreParenCasts();
1163 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
1164 const BlockDecl *block = be->getBlockDecl();
1165 for (const auto &I : block->captures()) {
1166 if (I.getVariable() == &var)
1170 // No need to walk into the subexpressions.
1174 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1175 const CompoundStmt *CS = SE->getSubStmt();
1176 for (const auto *BI : CS->body())
1177 if (const auto *E = dyn_cast<Expr>(BI)) {
1178 if (isCapturedBy(var, E))
1181 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
1182 // special case declarations
1183 for (const auto *I : DS->decls()) {
1184 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1185 const Expr *Init = VD->getInit();
1186 if (Init && isCapturedBy(var, Init))
1192 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1193 // Later, provide code to poke into statements for capture analysis.
1198 for (const Stmt *SubStmt : e->children())
1199 if (isCapturedBy(var, cast<Expr>(SubStmt)))
1205 /// \brief Determine whether the given initializer is trivial in the sense
1206 /// that it requires no code to be generated.
1207 bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
1211 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1212 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1213 if (Constructor->isTrivial() &&
1214 Constructor->isDefaultConstructor() &&
1215 !Construct->requiresZeroInitialization())
1221 void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
1222 assert(emission.Variable && "emission was not valid!");
1224 // If this was emitted as a global constant, we're done.
1225 if (emission.wasEmittedAsGlobal()) return;
1227 const VarDecl &D = *emission.Variable;
1228 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
1229 QualType type = D.getType();
1231 // If this local has an initializer, emit it now.
1232 const Expr *Init = D.getInit();
1234 // If we are at an unreachable point, we don't need to emit the initializer
1235 // unless it contains a label.
1236 if (!HaveInsertPoint()) {
1237 if (!Init || !ContainsLabel(Init)) return;
1238 EnsureInsertPoint();
1241 // Initialize the structure of a __block variable.
1242 if (emission.IsByRef)
1243 emitByrefStructureInit(emission);
1245 if (isTrivialInitializer(Init))
1248 // Check whether this is a byref variable that's potentially
1249 // captured and moved by its own initializer. If so, we'll need to
1250 // emit the initializer first, then copy into the variable.
1251 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1254 capturedByInit ? emission.Addr : emission.getObjectAddress(*this);
1256 llvm::Constant *constant = nullptr;
1257 if (emission.IsConstantAggregate || D.isConstexpr()) {
1258 assert(!capturedByInit && "constant init contains a capturing block?");
1259 constant = CGM.EmitConstantInit(D, this);
1263 LValue lv = MakeAddrLValue(Loc, type);
1265 return EmitExprAsInit(Init, &D, lv, capturedByInit);
1268 if (!emission.IsConstantAggregate) {
1269 // For simple scalar/complex initialization, store the value directly.
1270 LValue lv = MakeAddrLValue(Loc, type);
1272 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1275 // If this is a simple aggregate initialization, we can optimize it
1277 bool isVolatile = type.isVolatileQualified();
1279 llvm::Value *SizeVal =
1280 llvm::ConstantInt::get(IntPtrTy,
1281 getContext().getTypeSizeInChars(type).getQuantity());
1283 llvm::Type *BP = Int8PtrTy;
1284 if (Loc.getType() != BP)
1285 Loc = Builder.CreateBitCast(Loc, BP);
1287 // If the initializer is all or mostly zeros, codegen with memset then do
1288 // a few stores afterward.
1289 if (shouldUseMemSetPlusStoresToInitialize(constant,
1290 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
1291 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1293 // Zero and undef don't require a stores.
1294 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
1295 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1296 emitStoresForInitAfterMemset(constant, Loc.getPointer(),
1297 isVolatile, Builder);
1300 // Otherwise, create a temporary global with the initializer then
1301 // memcpy from the global to the alloca.
1302 std::string Name = getStaticDeclName(CGM, D);
1304 if (getLangOpts().OpenCL) {
1305 AS = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
1306 BP = llvm::PointerType::getInt8PtrTy(getLLVMContext(), AS);
1308 llvm::GlobalVariable *GV =
1309 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
1310 llvm::GlobalValue::PrivateLinkage,
1311 constant, Name, nullptr,
1312 llvm::GlobalValue::NotThreadLocal, AS);
1313 GV->setAlignment(Loc.getAlignment().getQuantity());
1314 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1316 Address SrcPtr = Address(GV, Loc.getAlignment());
1317 if (SrcPtr.getType() != BP)
1318 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
1320 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, isVolatile);
1324 /// Emit an expression as an initializer for a variable at the given
1325 /// location. The expression is not necessarily the normal
1326 /// initializer for the variable, and the address is not necessarily
1327 /// its normal location.
1329 /// \param init the initializing expression
1330 /// \param var the variable to act as if we're initializing
1331 /// \param loc the address to initialize; its type is a pointer
1332 /// to the LLVM mapping of the variable's type
1333 /// \param alignment the alignment of the address
1334 /// \param capturedByInit true if the variable is a __block variable
1335 /// whose address is potentially changed by the initializer
1336 void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
1337 LValue lvalue, bool capturedByInit) {
1338 QualType type = D->getType();
1340 if (type->isReferenceType()) {
1341 RValue rvalue = EmitReferenceBindingToExpr(init);
1343 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1344 EmitStoreThroughLValue(rvalue, lvalue, true);
1347 switch (getEvaluationKind(type)) {
1349 EmitScalarInit(init, D, lvalue, capturedByInit);
1352 ComplexPairTy complex = EmitComplexExpr(init);
1354 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1355 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1359 if (type->isAtomicType()) {
1360 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1362 // TODO: how can we delay here if D is captured by its initializer?
1363 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
1364 AggValueSlot::IsDestructed,
1365 AggValueSlot::DoesNotNeedGCBarriers,
1366 AggValueSlot::IsNotAliased));
1370 llvm_unreachable("bad evaluation kind");
1373 /// Enter a destroy cleanup for the given local variable.
1374 void CodeGenFunction::emitAutoVarTypeCleanup(
1375 const CodeGenFunction::AutoVarEmission &emission,
1376 QualType::DestructionKind dtorKind) {
1377 assert(dtorKind != QualType::DK_none);
1379 // Note that for __block variables, we want to destroy the
1380 // original stack object, not the possibly forwarded object.
1381 Address addr = emission.getObjectAddress(*this);
1383 const VarDecl *var = emission.Variable;
1384 QualType type = var->getType();
1386 CleanupKind cleanupKind = NormalAndEHCleanup;
1387 CodeGenFunction::Destroyer *destroyer = nullptr;
1390 case QualType::DK_none:
1391 llvm_unreachable("no cleanup for trivially-destructible variable");
1393 case QualType::DK_cxx_destructor:
1394 // If there's an NRVO flag on the emission, we need a different
1396 if (emission.NRVOFlag) {
1397 assert(!type->isArrayType());
1398 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1399 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr,
1400 dtor, emission.NRVOFlag);
1405 case QualType::DK_objc_strong_lifetime:
1406 // Suppress cleanups for pseudo-strong variables.
1407 if (var->isARCPseudoStrong()) return;
1409 // Otherwise, consider whether to use an EH cleanup or not.
1410 cleanupKind = getARCCleanupKind();
1412 // Use the imprecise destroyer by default.
1413 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1414 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1417 case QualType::DK_objc_weak_lifetime:
1421 // If we haven't chosen a more specific destroyer, use the default.
1422 if (!destroyer) destroyer = getDestroyer(dtorKind);
1424 // Use an EH cleanup in array destructors iff the destructor itself
1425 // is being pushed as an EH cleanup.
1426 bool useEHCleanup = (cleanupKind & EHCleanup);
1427 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1431 void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
1432 assert(emission.Variable && "emission was not valid!");
1434 // If this was emitted as a global constant, we're done.
1435 if (emission.wasEmittedAsGlobal()) return;
1437 // If we don't have an insertion point, we're done. Sema prevents
1438 // us from jumping into any of these scopes anyway.
1439 if (!HaveInsertPoint()) return;
1441 const VarDecl &D = *emission.Variable;
1443 // Check the type for a cleanup.
1444 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1445 emitAutoVarTypeCleanup(emission, dtorKind);
1447 // In GC mode, honor objc_precise_lifetime.
1448 if (getLangOpts().getGC() != LangOptions::NonGC &&
1449 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1450 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1453 // Handle the cleanup attribute.
1454 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
1455 const FunctionDecl *FD = CA->getFunctionDecl();
1457 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
1458 assert(F && "Could not find function!");
1460 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
1461 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
1464 // If this is a block variable, call _Block_object_destroy
1465 // (on the unforwarded address).
1466 if (emission.IsByRef)
1467 enterByrefCleanup(emission);
1470 CodeGenFunction::Destroyer *
1471 CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1473 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
1474 case QualType::DK_cxx_destructor:
1475 return destroyCXXObject;
1476 case QualType::DK_objc_strong_lifetime:
1477 return destroyARCStrongPrecise;
1478 case QualType::DK_objc_weak_lifetime:
1479 return destroyARCWeak;
1481 llvm_unreachable("Unknown DestructionKind");
1484 /// pushEHDestroy - Push the standard destructor for the given type as
1485 /// an EH-only cleanup.
1486 void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
1487 Address addr, QualType type) {
1488 assert(dtorKind && "cannot push destructor for trivial type");
1489 assert(needsEHCleanup(dtorKind));
1491 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1494 /// pushDestroy - Push the standard destructor for the given type as
1495 /// at least a normal cleanup.
1496 void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1497 Address addr, QualType type) {
1498 assert(dtorKind && "cannot push destructor for trivial type");
1500 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1501 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1502 cleanupKind & EHCleanup);
1505 void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
1506 QualType type, Destroyer *destroyer,
1507 bool useEHCleanupForArray) {
1508 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1509 destroyer, useEHCleanupForArray);
1512 void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
1513 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1516 void CodeGenFunction::pushLifetimeExtendedDestroy(
1517 CleanupKind cleanupKind, Address addr, QualType type,
1518 Destroyer *destroyer, bool useEHCleanupForArray) {
1519 assert(!isInConditionalBranch() &&
1520 "performing lifetime extension from within conditional");
1522 // Push an EH-only cleanup for the object now.
1523 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1524 // around in case a temporary's destructor throws an exception.
1525 if (cleanupKind & EHCleanup)
1526 EHStack.pushCleanup<DestroyObject>(
1527 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1528 destroyer, useEHCleanupForArray);
1530 // Remember that we need to push a full cleanup for the object at the
1531 // end of the full-expression.
1532 pushCleanupAfterFullExpr<DestroyObject>(
1533 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1536 /// emitDestroy - Immediately perform the destruction of the given
1539 /// \param addr - the address of the object; a type*
1540 /// \param type - the type of the object; if an array type, all
1541 /// objects are destroyed in reverse order
1542 /// \param destroyer - the function to call to destroy individual
1544 /// \param useEHCleanupForArray - whether an EH cleanup should be
1545 /// used when destroying array elements, in case one of the
1546 /// destructions throws an exception
1547 void CodeGenFunction::emitDestroy(Address addr, QualType type,
1548 Destroyer *destroyer,
1549 bool useEHCleanupForArray) {
1550 const ArrayType *arrayType = getContext().getAsArrayType(type);
1552 return destroyer(*this, addr, type);
1554 llvm::Value *length = emitArrayLength(arrayType, type, addr);
1556 CharUnits elementAlign =
1558 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
1560 // Normally we have to check whether the array is zero-length.
1561 bool checkZeroLength = true;
1563 // But if the array length is constant, we can suppress that.
1564 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1565 // ...and if it's constant zero, we can just skip the entire thing.
1566 if (constLength->isZero()) return;
1567 checkZeroLength = false;
1570 llvm::Value *begin = addr.getPointer();
1571 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
1572 emitArrayDestroy(begin, end, type, elementAlign, destroyer,
1573 checkZeroLength, useEHCleanupForArray);
1576 /// emitArrayDestroy - Destroys all the elements of the given array,
1577 /// beginning from last to first. The array cannot be zero-length.
1579 /// \param begin - a type* denoting the first element of the array
1580 /// \param end - a type* denoting one past the end of the array
1581 /// \param elementType - the element type of the array
1582 /// \param destroyer - the function to call to destroy elements
1583 /// \param useEHCleanup - whether to push an EH cleanup to destroy
1584 /// the remaining elements in case the destruction of a single
1586 void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1588 QualType elementType,
1589 CharUnits elementAlign,
1590 Destroyer *destroyer,
1591 bool checkZeroLength,
1592 bool useEHCleanup) {
1593 assert(!elementType->isArrayType());
1595 // The basic structure here is a do-while loop, because we don't
1596 // need to check for the zero-element case.
1597 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1598 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1600 if (checkZeroLength) {
1601 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1602 "arraydestroy.isempty");
1603 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1606 // Enter the loop body, making that address the current address.
1607 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1609 llvm::PHINode *elementPast =
1610 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1611 elementPast->addIncoming(end, entryBB);
1613 // Shift the address back by one element.
1614 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1615 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1616 "arraydestroy.element");
1619 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
1622 // Perform the actual destruction there.
1623 destroyer(*this, Address(element, elementAlign), elementType);
1628 // Check whether we've reached the end.
1629 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1630 Builder.CreateCondBr(done, doneBB, bodyBB);
1631 elementPast->addIncoming(element, Builder.GetInsertBlock());
1637 /// Perform partial array destruction as if in an EH cleanup. Unlike
1638 /// emitArrayDestroy, the element type here may still be an array type.
1639 static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1640 llvm::Value *begin, llvm::Value *end,
1641 QualType type, CharUnits elementAlign,
1642 CodeGenFunction::Destroyer *destroyer) {
1643 // If the element type is itself an array, drill down.
1644 unsigned arrayDepth = 0;
1645 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1646 // VLAs don't require a GEP index to walk into.
1647 if (!isa<VariableArrayType>(arrayType))
1649 type = arrayType->getElementType();
1653 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
1655 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
1656 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1657 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
1660 // Destroy the array. We don't ever need an EH cleanup because we
1661 // assume that we're in an EH cleanup ourselves, so a throwing
1662 // destructor causes an immediate terminate.
1663 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
1664 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
1668 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1669 /// array destroy where the end pointer is regularly determined and
1670 /// does not need to be loaded from a local.
1671 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
1672 llvm::Value *ArrayBegin;
1673 llvm::Value *ArrayEnd;
1674 QualType ElementType;
1675 CodeGenFunction::Destroyer *Destroyer;
1676 CharUnits ElementAlign;
1678 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1679 QualType elementType, CharUnits elementAlign,
1680 CodeGenFunction::Destroyer *destroyer)
1681 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
1682 ElementType(elementType), Destroyer(destroyer),
1683 ElementAlign(elementAlign) {}
1685 void Emit(CodeGenFunction &CGF, Flags flags) override {
1686 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1687 ElementType, ElementAlign, Destroyer);
1691 /// IrregularPartialArrayDestroy - a cleanup which performs a
1692 /// partial array destroy where the end pointer is irregularly
1693 /// determined and must be loaded from a local.
1694 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
1695 llvm::Value *ArrayBegin;
1696 Address ArrayEndPointer;
1697 QualType ElementType;
1698 CodeGenFunction::Destroyer *Destroyer;
1699 CharUnits ElementAlign;
1701 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1702 Address arrayEndPointer,
1703 QualType elementType,
1704 CharUnits elementAlign,
1705 CodeGenFunction::Destroyer *destroyer)
1706 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
1707 ElementType(elementType), Destroyer(destroyer),
1708 ElementAlign(elementAlign) {}
1710 void Emit(CodeGenFunction &CGF, Flags flags) override {
1711 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
1712 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1713 ElementType, ElementAlign, Destroyer);
1716 } // end anonymous namespace
1718 /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
1719 /// already-constructed elements of the given array. The cleanup
1720 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1722 /// \param elementType - the immediate element type of the array;
1723 /// possibly still an array type
1724 void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
1725 Address arrayEndPointer,
1726 QualType elementType,
1727 CharUnits elementAlign,
1728 Destroyer *destroyer) {
1729 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1730 arrayBegin, arrayEndPointer,
1731 elementType, elementAlign,
1735 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1736 /// already-constructed elements of the given array. The cleanup
1737 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1739 /// \param elementType - the immediate element type of the array;
1740 /// possibly still an array type
1741 void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1742 llvm::Value *arrayEnd,
1743 QualType elementType,
1744 CharUnits elementAlign,
1745 Destroyer *destroyer) {
1746 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
1747 arrayBegin, arrayEnd,
1748 elementType, elementAlign,
1752 /// Lazily declare the @llvm.lifetime.start intrinsic.
1753 llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1754 if (LifetimeStartFn)
1755 return LifetimeStartFn;
1756 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1757 llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
1758 return LifetimeStartFn;
1761 /// Lazily declare the @llvm.lifetime.end intrinsic.
1762 llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1764 return LifetimeEndFn;
1765 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1766 llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
1767 return LifetimeEndFn;
1771 /// A cleanup to perform a release of an object at the end of a
1772 /// function. This is used to balance out the incoming +1 of a
1773 /// ns_consumed argument when we can't reasonably do that just by
1774 /// not doing the initial retain for a __block argument.
1775 struct ConsumeARCParameter final : EHScopeStack::Cleanup {
1776 ConsumeARCParameter(llvm::Value *param,
1777 ARCPreciseLifetime_t precise)
1778 : Param(param), Precise(precise) {}
1781 ARCPreciseLifetime_t Precise;
1783 void Emit(CodeGenFunction &CGF, Flags flags) override {
1784 CGF.EmitARCRelease(Param, Precise);
1787 } // end anonymous namespace
1789 /// Emit an alloca (or GlobalValue depending on target)
1790 /// for the specified parameter and set up LocalDeclMap.
1791 void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
1793 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
1794 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
1795 "Invalid argument to EmitParmDecl");
1797 Arg.getAnyValue()->setName(D.getName());
1799 QualType Ty = D.getType();
1801 // Use better IR generation for certain implicit parameters.
1802 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
1803 // The only implicit argument a block has is its literal.
1804 // We assume this is always passed directly.
1806 setBlockContextParameter(IPD, ArgNo, Arg.getDirectValue());
1810 // Apply any prologue 'this' adjustments required by the ABI. Be careful to
1811 // handle the case where 'this' is passed indirectly as part of an inalloca
1813 if (const CXXMethodDecl *MD =
1814 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
1815 if (MD->isVirtual() && IPD == CXXABIThisDecl) {
1816 llvm::Value *This = Arg.isIndirect()
1817 ? Builder.CreateLoad(Arg.getIndirectAddress())
1818 : Arg.getDirectValue();
1819 This = CGM.getCXXABI().adjustThisParameterInVirtualFunctionPrologue(
1820 *this, CurGD, This);
1821 if (Arg.isIndirect())
1822 Builder.CreateStore(This, Arg.getIndirectAddress());
1824 Arg = ParamValue::forDirect(This);
1829 Address DeclPtr = Address::invalid();
1830 bool DoStore = false;
1831 bool IsScalar = hasScalarEvaluationKind(Ty);
1832 // If we already have a pointer to the argument, reuse the input pointer.
1833 if (Arg.isIndirect()) {
1834 DeclPtr = Arg.getIndirectAddress();
1835 // If we have a prettier pointer type at this point, bitcast to that.
1836 unsigned AS = DeclPtr.getType()->getAddressSpace();
1837 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
1838 if (DeclPtr.getType() != IRTy)
1839 DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
1841 // Push a destructor cleanup for this parameter if the ABI requires it.
1842 // Don't push a cleanup in a thunk for a method that will also emit a
1844 if (!IsScalar && !CurFuncIsThunk &&
1845 getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1846 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1847 if (RD && RD->hasNonTrivialDestructor())
1848 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
1851 // Otherwise, create a temporary to hold the value.
1852 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
1853 D.getName() + ".addr");
1857 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
1859 LValue lv = MakeAddrLValue(DeclPtr, Ty);
1861 Qualifiers qs = Ty.getQualifiers();
1862 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1863 // We honor __attribute__((ns_consumed)) for types with lifetime.
1864 // For __strong, it's handled by just skipping the initial retain;
1865 // otherwise we have to balance out the initial +1 with an extra
1866 // cleanup to do the release at the end of the function.
1867 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1869 // 'self' is always formally __strong, but if this is not an
1870 // init method then we don't want to retain it.
1871 if (D.isARCPseudoStrong()) {
1872 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1873 assert(&D == method->getSelfDecl());
1874 assert(lt == Qualifiers::OCL_Strong);
1875 assert(qs.hasConst());
1876 assert(method->getMethodFamily() != OMF_init);
1878 lt = Qualifiers::OCL_ExplicitNone;
1881 if (lt == Qualifiers::OCL_Strong) {
1883 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1884 // use objc_storeStrong(&dest, value) for retaining the
1885 // object. But first, store a null into 'dest' because
1886 // objc_storeStrong attempts to release its old value.
1887 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
1888 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
1889 EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
1893 // Don't use objc_retainBlock for block pointers, because we
1894 // don't want to Block_copy something just because we got it
1896 ArgVal = EmitARCRetainNonBlock(ArgVal);
1899 // Push the cleanup for a consumed parameter.
1901 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1902 ? ARCPreciseLifetime : ARCImpreciseLifetime);
1903 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
1907 if (lt == Qualifiers::OCL_Weak) {
1908 EmitARCInitWeak(DeclPtr, ArgVal);
1909 DoStore = false; // The weak init is a store, no need to do two.
1913 // Enter the cleanup scope.
1914 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1918 // Store the initial value into the alloca.
1920 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
1922 setAddrOfLocalVar(&D, DeclPtr);
1924 // Emit debug info for param declaration.
1925 if (CGDebugInfo *DI = getDebugInfo()) {
1926 if (CGM.getCodeGenOpts().getDebugInfo() >=
1927 codegenoptions::LimitedDebugInfo) {
1928 DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
1932 if (D.hasAttr<AnnotateAttr>())
1933 EmitVarAnnotations(&D, DeclPtr.getPointer());
1935 // We can only check return value nullability if all arguments to the
1936 // function satisfy their nullability preconditions. This makes it necessary
1937 // to emit null checks for args in the function body itself.
1938 if (requiresReturnValueNullabilityCheck()) {
1939 auto Nullability = Ty->getNullability(getContext());
1940 if (Nullability && *Nullability == NullabilityKind::NonNull) {
1941 SanitizerScope SanScope(this);
1942 RetValNullabilityPrecondition =
1943 Builder.CreateAnd(RetValNullabilityPrecondition,
1944 Builder.CreateIsNotNull(Arg.getAnyValue()));
1949 void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1950 CodeGenFunction *CGF) {
1951 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
1953 getOpenMPRuntime().emitUserDefinedReduction(CGF, D);