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 "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"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/CodeGen/CGFunctionInfo.h"
32 #include "clang/Frontend/CodeGenOptions.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"
38 using namespace clang;
39 using namespace CodeGen;
41 void CodeGenFunction::EmitDecl(const Decl &D) {
42 switch (D.getKind()) {
43 case Decl::BuiltinTemplate:
44 case Decl::TranslationUnit:
45 case Decl::ExternCContext:
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:
57 case Decl::CXXConstructor:
58 case Decl::CXXDestructor:
59 case Decl::CXXConversion:
61 case Decl::MSProperty:
62 case Decl::IndirectField:
64 case Decl::ObjCAtDefsField:
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:
85 case Decl::ObjCPropertyImpl:
86 case Decl::FileScopeAsm:
88 case Decl::FriendTemplate:
91 case Decl::ClassScopeFunctionSpecialization:
92 case Decl::UsingShadow:
93 case Decl::ConstructorUsingShadow:
94 case Decl::ObjCTypeParam:
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;
105 case Decl::OMPThreadPrivate:
106 case Decl::OMPCapturedExpr:
108 // None of these decls require codegen support.
111 case Decl::NamespaceAlias:
112 if (CGDebugInfo *DI = getDebugInfo())
113 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
115 case Decl::Using: // using X; [C++]
116 if (CGDebugInfo *DI = getDebugInfo())
117 DI->EmitUsingDecl(cast<UsingDecl>(D));
119 case Decl::UsingPack:
120 for (auto *Using : cast<UsingPackDecl>(D).expansions())
123 case Decl::UsingDirective: // using namespace X; [C++]
124 if (CGDebugInfo *DI = getDebugInfo())
125 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
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!");
133 if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
134 for (auto *B : DD->bindings())
135 if (auto *HD = B->getHoldingVar())
140 case Decl::OMPDeclareReduction:
141 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
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();
148 if (Ty->isVariablyModifiedType())
149 EmitVariablyModifiedType(Ty);
154 /// EmitVarDecl - This method handles emission of any variable declaration
155 /// inside a function, including static vars etc.
156 void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
157 if (D.hasExternalStorage())
158 // Don't emit it now, allow it to be emitted lazily on its first use.
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())
169 llvm::GlobalValue::LinkageTypes Linkage =
170 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
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.
176 return EmitStaticVarDecl(D, Linkage);
179 if (D.getType().getAddressSpace() == LangAS::opencl_local)
180 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
182 assert(D.hasLocalStorage());
183 return EmitAutoVarDecl(D);
186 static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
187 if (CGM.getLangOpts().CPlusPlus)
188 return CGM.getMangledName(&D).str();
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();
203 llvm_unreachable("Unknown context for static var decl");
205 ContextName += "." + D.getNameAsString();
209 llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
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
215 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
218 QualType Ty = D.getType();
219 assert(Ty->isConstantSizeType() && "VLAs can't be static");
221 // Use the label if the variable is renamed with the asm-label extension.
223 if (D.hasAttr<AsmLabelAttr>())
224 Name = getMangledName(&D);
226 Name = getStaticDeclName(*this, D);
228 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
229 LangAS AS = GetGlobalVarAddressSpace(&D);
230 unsigned TargetAS = getContext().getTargetAddressSpace(AS);
232 // Local address space cannot have an initializer.
233 llvm::Constant *Init = nullptr;
234 if (Ty.getAddressSpace() != LangAS::opencl_local)
235 Init = EmitNullConstant(Ty);
237 Init = llvm::UndefValue::get(LTy);
239 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
240 getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name,
241 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
242 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
243 setGlobalVisibility(GV, &D, ForDefinition);
245 if (supportsCOMDAT() && GV->isWeakForLinker())
246 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
251 if (D.isExternallyVisible()) {
252 if (D.hasAttr<DLLImportAttr>())
253 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
254 else if (D.hasAttr<DLLExportAttr>())
255 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
258 // Make sure the result is of the correct type.
259 LangAS ExpectedAS = Ty.getAddressSpace();
260 llvm::Constant *Addr = GV;
261 if (AS != ExpectedAS) {
262 Addr = getTargetCodeGenInfo().performAddrSpaceCast(
263 *this, GV, AS, ExpectedAS,
264 LTy->getPointerTo(getContext().getTargetAddressSpace(ExpectedAS)));
267 setStaticLocalDeclAddress(&D, Addr);
269 // Ensure that the static local gets initialized by making sure the parent
270 // function gets emitted eventually.
271 const Decl *DC = cast<Decl>(D.getDeclContext());
273 // We can't name blocks or captured statements directly, so try to emit their
275 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
276 DC = DC->getNonClosureContext();
277 // FIXME: Ensure that global blocks get emitted.
283 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
284 GD = GlobalDecl(CD, Ctor_Base);
285 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
286 GD = GlobalDecl(DD, Dtor_Base);
287 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
290 // Don't do anything for Obj-C method decls or global closures. We should
292 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
295 (void)GetAddrOfGlobal(GD);
300 /// hasNontrivialDestruction - Determine whether a type's destruction is
301 /// non-trivial. If so, and the variable uses static initialization, we must
302 /// register its destructor to run on exit.
303 static bool hasNontrivialDestruction(QualType T) {
304 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
305 return RD && !RD->hasTrivialDestructor();
308 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
309 /// global variable that has already been created for it. If the initializer
310 /// has a different type than GV does, this may free GV and return a different
311 /// one. Otherwise it just returns GV.
312 llvm::GlobalVariable *
313 CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
314 llvm::GlobalVariable *GV) {
315 ConstantEmitter emitter(*this);
316 llvm::Constant *Init = emitter.tryEmitForInitializer(D);
318 // If constant emission failed, then this should be a C++ static
321 if (!getLangOpts().CPlusPlus)
322 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
323 else if (HaveInsertPoint()) {
324 // Since we have a static initializer, this global variable can't
326 GV->setConstant(false);
328 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
333 // The initializer may differ in type from the global. Rewrite
334 // the global to match the initializer. (We have to do this
335 // because some types, like unions, can't be completely represented
336 // in the LLVM type system.)
337 if (GV->getType()->getElementType() != Init->getType()) {
338 llvm::GlobalVariable *OldGV = GV;
340 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
342 OldGV->getLinkage(), Init, "",
343 /*InsertBefore*/ OldGV,
344 OldGV->getThreadLocalMode(),
345 CGM.getContext().getTargetAddressSpace(D.getType()));
346 GV->setVisibility(OldGV->getVisibility());
347 GV->setComdat(OldGV->getComdat());
349 // Steal the name of the old global
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);
357 // Erase the old global, since it is no longer used.
358 OldGV->eraseFromParent();
361 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
362 GV->setInitializer(Init);
364 emitter.finalize(GV);
366 if (hasNontrivialDestruction(D.getType()) && HaveInsertPoint()) {
367 // We have a constant initializer, but a nontrivial destructor. We still
368 // need to perform a guarded "initialization" in order to register the
370 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
376 void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
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);
384 // Store into LocalDeclMap before generating initializer to handle
385 // circular references.
386 setAddrOfLocalVar(&D, Address(addr, alignment));
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())
392 EmitVariablyModifiedType(D.getType());
394 // Save the type in case adding the initializer forces a type change.
395 llvm::Type *expectedType = addr->getType();
397 llvm::GlobalVariable *var =
398 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
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);
410 var->setAlignment(alignment.getQuantity());
412 if (D.hasAttr<AnnotateAttr>())
413 CGM.AddGlobalAnnotations(&D, var);
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());
422 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
423 var->setSection(SA->getName());
425 if (D.hasAttr<UsedAttr>())
426 CGM.addUsedGlobal(var);
428 // We may have to cast the constant because of the initializer
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);
439 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
441 // Emit global variable debug descriptor for static vars.
442 CGDebugInfo *DI = getDebugInfo();
444 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
445 DI->setLocation(D.getLocation());
446 DI->EmitGlobalVariable(var, &D);
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) {}
460 CodeGenFunction::Destroyer *destroyer;
461 bool useEHCleanupForArray;
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;
468 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
472 struct DestroyNRVOVariable final : EHScopeStack::Cleanup {
473 DestroyNRVOVariable(Address addr,
474 const CXXDestructorDecl *Dtor,
475 llvm::Value *NRVOFlag)
476 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
478 const CXXDestructorDecl *Dtor;
479 llvm::Value *NRVOFlag;
482 void Emit(CodeGenFunction &CGF, Flags flags) override {
483 // Along the exceptions path we always execute the dtor.
484 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
486 llvm::BasicBlock *SkipDtorBB = nullptr;
488 // If we exited via NRVO, we skip the destructor call.
489 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
490 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
491 llvm::Value *DidNRVO =
492 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
493 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
494 CGF.EmitBlock(RunDtorBB);
497 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
498 /*ForVirtualBase=*/false,
499 /*Delegating=*/false,
502 if (NRVO) CGF.EmitBlock(SkipDtorBB);
506 struct CallStackRestore final : EHScopeStack::Cleanup {
508 CallStackRestore(Address Stack) : Stack(Stack) {}
509 void Emit(CodeGenFunction &CGF, Flags flags) override {
510 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
511 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
512 CGF.Builder.CreateCall(F, V);
516 struct ExtendGCLifetime final : EHScopeStack::Cleanup {
518 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
520 void Emit(CodeGenFunction &CGF, Flags flags) override {
521 // Compute the address of the local variable, in case it's a
522 // byref or something.
523 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
524 Var.getType(), VK_LValue, SourceLocation());
525 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
527 CGF.EmitExtendGCLifetime(value);
531 struct CallCleanupFunction final : EHScopeStack::Cleanup {
532 llvm::Constant *CleanupFn;
533 const CGFunctionInfo &FnInfo;
536 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
538 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
540 void Emit(CodeGenFunction &CGF, Flags flags) override {
541 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
542 Var.getType(), VK_LValue, SourceLocation());
543 // Compute the address of the local variable, in case it's a byref
545 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
547 // In some cases, the type of the function argument will be different from
548 // the type of the pointer. An example of this is
549 // void f(void* arg);
550 // __attribute__((cleanup(f))) void *g;
552 // To fix this we insert a bitcast here.
553 QualType ArgTy = FnInfo.arg_begin()->type;
555 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
558 Args.add(RValue::get(Arg),
559 CGF.getContext().getPointerType(Var.getType()));
560 auto Callee = CGCallee::forDirect(CleanupFn);
561 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
564 } // end anonymous namespace
566 /// EmitAutoVarWithLifetime - Does the setup required for an automatic
567 /// variable with lifetime.
568 static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
570 Qualifiers::ObjCLifetime lifetime) {
572 case Qualifiers::OCL_None:
573 llvm_unreachable("present but none");
575 case Qualifiers::OCL_ExplicitNone:
579 case Qualifiers::OCL_Strong: {
580 CodeGenFunction::Destroyer *destroyer =
581 (var.hasAttr<ObjCPreciseLifetimeAttr>()
582 ? CodeGenFunction::destroyARCStrongPrecise
583 : CodeGenFunction::destroyARCStrongImprecise);
585 CleanupKind cleanupKind = CGF.getARCCleanupKind();
586 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
587 cleanupKind & EHCleanup);
590 case Qualifiers::OCL_Autoreleasing:
594 case Qualifiers::OCL_Weak:
595 // __weak objects always get EH cleanups; otherwise, exceptions
596 // could cause really nasty crashes instead of mere leaks.
597 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
598 CodeGenFunction::destroyARCWeak,
599 /*useEHCleanup*/ true);
604 static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
605 if (const Expr *e = dyn_cast<Expr>(s)) {
606 // Skip the most common kinds of expressions that make
607 // hierarchy-walking expensive.
608 s = e = e->IgnoreParenCasts();
610 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
611 return (ref->getDecl() == &var);
612 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
613 const BlockDecl *block = be->getBlockDecl();
614 for (const auto &I : block->captures()) {
615 if (I.getVariable() == &var)
621 for (const Stmt *SubStmt : s->children())
622 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
623 if (SubStmt && isAccessedBy(var, SubStmt))
629 static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
630 if (!decl) return false;
631 if (!isa<VarDecl>(decl)) return false;
632 const VarDecl *var = cast<VarDecl>(decl);
633 return isAccessedBy(*var, e);
636 static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
637 const LValue &destLV, const Expr *init) {
638 bool needsCast = false;
640 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
641 switch (castExpr->getCastKind()) {
642 // Look through casts that don't require representation changes.
645 case CK_BlockPointerToObjCPointerCast:
649 // If we find an l-value to r-value cast from a __weak variable,
650 // emit this operation as a copy or move.
651 case CK_LValueToRValue: {
652 const Expr *srcExpr = castExpr->getSubExpr();
653 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
656 // Emit the source l-value.
657 LValue srcLV = CGF.EmitLValue(srcExpr);
659 // Handle a formal type change to avoid asserting.
660 auto srcAddr = srcLV.getAddress();
662 srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
663 destLV.getAddress().getElementType());
666 // If it was an l-value, use objc_copyWeak.
667 if (srcExpr->getValueKind() == VK_LValue) {
668 CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
670 assert(srcExpr->getValueKind() == VK_XValue);
671 CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
676 // Stop at anything else.
681 init = castExpr->getSubExpr();
686 static void drillIntoBlockVariable(CodeGenFunction &CGF,
688 const VarDecl *var) {
689 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
692 void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
693 SourceLocation Loc) {
694 if (!SanOpts.has(SanitizerKind::NullabilityAssign))
697 auto Nullability = LHS.getType()->getNullability(getContext());
698 if (!Nullability || *Nullability != NullabilityKind::NonNull)
701 // Check if the right hand side of the assignment is nonnull, if the left
702 // hand side must be nonnull.
703 SanitizerScope SanScope(this);
704 llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
705 llvm::Constant *StaticData[] = {
706 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()),
707 llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.
708 llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
709 EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},
710 SanitizerHandler::TypeMismatch, StaticData, RHS);
713 void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
714 LValue lvalue, bool capturedByInit) {
715 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
717 llvm::Value *value = EmitScalarExpr(init);
719 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
720 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
721 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
725 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
726 init = DIE->getExpr();
728 // If we're emitting a value with lifetime, we have to do the
729 // initialization *before* we leave the cleanup scopes.
730 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
731 enterFullExpression(ewc);
732 init = ewc->getSubExpr();
734 CodeGenFunction::RunCleanupsScope Scope(*this);
736 // We have to maintain the illusion that the variable is
737 // zero-initialized. If the variable might be accessed in its
738 // initializer, zero-initialize before running the initializer, then
739 // actually perform the initialization with an assign.
740 bool accessedByInit = false;
741 if (lifetime != Qualifiers::OCL_ExplicitNone)
742 accessedByInit = (capturedByInit || isAccessedBy(D, init));
743 if (accessedByInit) {
744 LValue tempLV = lvalue;
745 // Drill down to the __block object if necessary.
746 if (capturedByInit) {
747 // We can use a simple GEP for this because it can't have been
749 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
754 auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
755 llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
757 // If __weak, we want to use a barrier under certain conditions.
758 if (lifetime == Qualifiers::OCL_Weak)
759 EmitARCInitWeak(tempLV.getAddress(), zero);
761 // Otherwise just do a simple store.
763 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
766 // Emit the initializer.
767 llvm::Value *value = nullptr;
770 case Qualifiers::OCL_None:
771 llvm_unreachable("present but none");
773 case Qualifiers::OCL_ExplicitNone:
774 value = EmitARCUnsafeUnretainedScalarExpr(init);
777 case Qualifiers::OCL_Strong: {
778 value = EmitARCRetainScalarExpr(init);
782 case Qualifiers::OCL_Weak: {
783 // If it's not accessed by the initializer, try to emit the
784 // initialization with a copy or move.
785 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
789 // No way to optimize a producing initializer into this. It's not
790 // worth optimizing for, because the value will immediately
791 // disappear in the common case.
792 value = EmitScalarExpr(init);
794 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
796 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
798 EmitARCInitWeak(lvalue.getAddress(), value);
802 case Qualifiers::OCL_Autoreleasing:
803 value = EmitARCRetainAutoreleaseScalarExpr(init);
807 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
809 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
811 // If the variable might have been accessed by its initializer, we
812 // might have to initialize with a barrier. We have to do this for
813 // both __weak and __strong, but __weak got filtered out above.
814 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
815 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
816 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
817 EmitARCRelease(oldValue, ARCImpreciseLifetime);
821 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
824 /// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
825 /// non-zero parts of the specified initializer with equal or fewer than
826 /// NumStores scalar stores.
827 static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
828 unsigned &NumStores) {
829 // Zero and Undef never requires any extra stores.
830 if (isa<llvm::ConstantAggregateZero>(Init) ||
831 isa<llvm::ConstantPointerNull>(Init) ||
832 isa<llvm::UndefValue>(Init))
834 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
835 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
836 isa<llvm::ConstantExpr>(Init))
837 return Init->isNullValue() || NumStores--;
839 // See if we can emit each element.
840 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
841 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
842 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
843 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
849 if (llvm::ConstantDataSequential *CDS =
850 dyn_cast<llvm::ConstantDataSequential>(Init)) {
851 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
852 llvm::Constant *Elt = CDS->getElementAsConstant(i);
853 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
859 // Anything else is hard and scary.
863 /// emitStoresForInitAfterMemset - For inits that
864 /// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
865 /// stores that would be required.
866 static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
867 bool isVolatile, CGBuilderTy &Builder) {
868 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
869 "called emitStoresForInitAfterMemset for zero or undef value.");
871 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
872 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
873 isa<llvm::ConstantExpr>(Init)) {
874 Builder.CreateDefaultAlignedStore(Init, Loc, isVolatile);
878 if (llvm::ConstantDataSequential *CDS =
879 dyn_cast<llvm::ConstantDataSequential>(Init)) {
880 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
881 llvm::Constant *Elt = CDS->getElementAsConstant(i);
883 // If necessary, get a pointer to the element and emit it.
884 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
885 emitStoresForInitAfterMemset(
886 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
887 isVolatile, Builder);
892 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
893 "Unknown value type!");
895 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
896 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
898 // If necessary, get a pointer to the element and emit it.
899 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
900 emitStoresForInitAfterMemset(
901 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
902 isVolatile, Builder);
906 /// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
907 /// plus some stores to initialize a local variable instead of using a memcpy
908 /// from a constant global. It is beneficial to use memset if the global is all
909 /// zeros, or mostly zeros and large.
910 static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
911 uint64_t GlobalSize) {
912 // If a global is all zeros, always use a memset.
913 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
915 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
916 // do it if it will require 6 or fewer scalar stores.
917 // TODO: Should budget depends on the size? Avoiding a large global warrants
918 // plopping in more stores.
919 unsigned StoreBudget = 6;
920 uint64_t SizeLimit = 32;
922 return GlobalSize > SizeLimit &&
923 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
926 /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
927 /// variable declaration with auto, register, or no storage class specifier.
928 /// These turn into simple stack objects, or GlobalValues depending on target.
929 void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
930 AutoVarEmission emission = EmitAutoVarAlloca(D);
931 EmitAutoVarInit(emission);
932 EmitAutoVarCleanups(emission);
935 /// Emit a lifetime.begin marker if some criteria are satisfied.
936 /// \return a pointer to the temporary size Value if a marker was emitted, null
938 llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
940 if (!ShouldEmitLifetimeMarkers)
943 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
944 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
946 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
947 C->setDoesNotThrow();
951 void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
952 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
954 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
955 C->setDoesNotThrow();
958 /// EmitAutoVarAlloca - Emit the alloca and debug information for a
959 /// local variable. Does not emit initialization or destruction.
960 CodeGenFunction::AutoVarEmission
961 CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
962 QualType Ty = D.getType();
964 Ty.getAddressSpace() == LangAS::Default ||
965 (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL));
967 AutoVarEmission emission(D);
969 bool isByRef = D.hasAttr<BlocksAttr>();
970 emission.IsByRef = isByRef;
972 CharUnits alignment = getContext().getDeclAlign(&D);
974 // If the type is variably-modified, emit all the VLA sizes for it.
975 if (Ty->isVariablyModifiedType())
976 EmitVariablyModifiedType(Ty);
978 Address address = Address::invalid();
979 if (Ty->isConstantSizeType()) {
980 bool NRVO = getLangOpts().ElideConstructors &&
983 // If this value is an array or struct with a statically determinable
984 // constant initializer, there are optimizations we can do.
986 // TODO: We should constant-evaluate the initializer of any variable,
987 // as long as it is initialized by a constant expression. Currently,
988 // isConstantInitializer produces wrong answers for structs with
989 // reference or bitfield members, and a few other cases, and checking
990 // for POD-ness protects us from some of these.
991 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
993 ((Ty.isPODType(getContext()) ||
994 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
995 D.getInit()->isConstantInitializer(getContext(), false)))) {
997 // If the variable's a const type, and it's neither an NRVO
998 // candidate nor a __block variable and has no mutable members,
999 // emit it as a global instead.
1000 // Exception is if a variable is located in non-constant address space
1002 if ((!getLangOpts().OpenCL ||
1003 Ty.getAddressSpace() == LangAS::opencl_constant) &&
1004 (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
1005 CGM.isTypeConstant(Ty, true))) {
1006 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
1008 // Signal this condition to later callbacks.
1009 emission.Addr = Address::invalid();
1010 assert(emission.wasEmittedAsGlobal());
1014 // Otherwise, tell the initialization code that we're in this case.
1015 emission.IsConstantAggregate = true;
1018 // A normal fixed sized variable becomes an alloca in the entry block,
1019 // unless it's an NRVO variable.
1022 // The named return value optimization: allocate this variable in the
1023 // return slot, so that we can elide the copy when returning this
1024 // variable (C++0x [class.copy]p34).
1025 address = ReturnValue;
1027 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1028 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
1029 // Create a flag that is used to indicate when the NRVO was applied
1030 // to this variable. Set it to zero to indicate that NRVO was not
1032 llvm::Value *Zero = Builder.getFalse();
1034 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
1035 EnsureInsertPoint();
1036 Builder.CreateStore(Zero, NRVOFlag);
1038 // Record the NRVO flag for this variable.
1039 NRVOFlags[&D] = NRVOFlag.getPointer();
1040 emission.NRVOFlag = NRVOFlag.getPointer();
1044 CharUnits allocaAlignment;
1045 llvm::Type *allocaTy;
1047 auto &byrefInfo = getBlockByrefInfo(&D);
1048 allocaTy = byrefInfo.Type;
1049 allocaAlignment = byrefInfo.ByrefAlignment;
1051 allocaTy = ConvertTypeForMem(Ty);
1052 allocaAlignment = alignment;
1055 // Create the alloca. Note that we set the name separately from
1056 // building the instruction so that it's there even in no-asserts
1058 address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName());
1060 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1061 // the catch parameter starts in the catchpad instruction, and we can't
1062 // insert code in those basic blocks.
1063 bool IsMSCatchParam =
1064 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1066 // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1067 // if we don't have a valid insertion point (?).
1068 if (HaveInsertPoint() && !IsMSCatchParam) {
1069 // If there's a jump into the lifetime of this variable, its lifetime
1070 // gets broken up into several regions in IR, which requires more work
1071 // to handle correctly. For now, just omit the intrinsics; this is a
1072 // rare case, and it's better to just be conservatively correct.
1075 // We have to do this in all language modes if there's a jump past the
1076 // declaration. We also have to do it in C if there's a jump to an
1077 // earlier point in the current block because non-VLA lifetimes begin as
1078 // soon as the containing block is entered, not when its variables
1079 // actually come into scope; suppressing the lifetime annotations
1080 // completely in this case is unnecessarily pessimistic, but again, this
1082 if (!Bypasses.IsBypassed(&D) &&
1083 !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
1084 uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1085 emission.SizeForLifetimeMarkers =
1086 EmitLifetimeStart(size, address.getPointer());
1089 assert(!emission.useLifetimeMarkers());
1093 EnsureInsertPoint();
1095 if (!DidCallStackSave) {
1098 CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
1100 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
1101 llvm::Value *V = Builder.CreateCall(F);
1102 Builder.CreateStore(V, Stack);
1104 DidCallStackSave = true;
1106 // Push a cleanup block and restore the stack there.
1107 // FIXME: in general circumstances, this should be an EH cleanup.
1108 pushStackRestore(NormalCleanup, Stack);
1111 llvm::Value *elementCount;
1112 QualType elementType;
1113 std::tie(elementCount, elementType) = getVLASize(Ty);
1115 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
1117 // Allocate memory for the array.
1118 address = CreateTempAlloca(llvmTy, alignment, "vla", elementCount);
1121 setAddrOfLocalVar(&D, address);
1122 emission.Addr = address;
1124 // Emit debug info for local var declaration.
1125 if (HaveInsertPoint())
1126 if (CGDebugInfo *DI = getDebugInfo()) {
1127 if (CGM.getCodeGenOpts().getDebugInfo() >=
1128 codegenoptions::LimitedDebugInfo) {
1129 DI->setLocation(D.getLocation());
1130 DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
1134 if (D.hasAttr<AnnotateAttr>())
1135 EmitVarAnnotations(&D, address.getPointer());
1137 // Make sure we call @llvm.lifetime.end.
1138 if (emission.useLifetimeMarkers())
1139 EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
1140 emission.getAllocatedAddress(),
1141 emission.getSizeForLifetimeMarkers());
1146 /// Determines whether the given __block variable is potentially
1147 /// captured by the given expression.
1148 static bool isCapturedBy(const VarDecl &var, const Expr *e) {
1149 // Skip the most common kinds of expressions that make
1150 // hierarchy-walking expensive.
1151 e = e->IgnoreParenCasts();
1153 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
1154 const BlockDecl *block = be->getBlockDecl();
1155 for (const auto &I : block->captures()) {
1156 if (I.getVariable() == &var)
1160 // No need to walk into the subexpressions.
1164 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1165 const CompoundStmt *CS = SE->getSubStmt();
1166 for (const auto *BI : CS->body())
1167 if (const auto *E = dyn_cast<Expr>(BI)) {
1168 if (isCapturedBy(var, E))
1171 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
1172 // special case declarations
1173 for (const auto *I : DS->decls()) {
1174 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1175 const Expr *Init = VD->getInit();
1176 if (Init && isCapturedBy(var, Init))
1182 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1183 // Later, provide code to poke into statements for capture analysis.
1188 for (const Stmt *SubStmt : e->children())
1189 if (isCapturedBy(var, cast<Expr>(SubStmt)))
1195 /// \brief Determine whether the given initializer is trivial in the sense
1196 /// that it requires no code to be generated.
1197 bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
1201 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1202 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1203 if (Constructor->isTrivial() &&
1204 Constructor->isDefaultConstructor() &&
1205 !Construct->requiresZeroInitialization())
1211 void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
1212 assert(emission.Variable && "emission was not valid!");
1214 // If this was emitted as a global constant, we're done.
1215 if (emission.wasEmittedAsGlobal()) return;
1217 const VarDecl &D = *emission.Variable;
1218 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
1219 QualType type = D.getType();
1221 // If this local has an initializer, emit it now.
1222 const Expr *Init = D.getInit();
1224 // If we are at an unreachable point, we don't need to emit the initializer
1225 // unless it contains a label.
1226 if (!HaveInsertPoint()) {
1227 if (!Init || !ContainsLabel(Init)) return;
1228 EnsureInsertPoint();
1231 // Initialize the structure of a __block variable.
1232 if (emission.IsByRef)
1233 emitByrefStructureInit(emission);
1235 if (isTrivialInitializer(Init))
1238 // Check whether this is a byref variable that's potentially
1239 // captured and moved by its own initializer. If so, we'll need to
1240 // emit the initializer first, then copy into the variable.
1241 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1244 capturedByInit ? emission.Addr : emission.getObjectAddress(*this);
1246 llvm::Constant *constant = nullptr;
1247 if (emission.IsConstantAggregate || D.isConstexpr()) {
1248 assert(!capturedByInit && "constant init contains a capturing block?");
1249 constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
1253 LValue lv = MakeAddrLValue(Loc, type);
1255 return EmitExprAsInit(Init, &D, lv, capturedByInit);
1258 if (!emission.IsConstantAggregate) {
1259 // For simple scalar/complex initialization, store the value directly.
1260 LValue lv = MakeAddrLValue(Loc, type);
1262 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1265 // If this is a simple aggregate initialization, we can optimize it
1267 bool isVolatile = type.isVolatileQualified();
1269 llvm::Value *SizeVal =
1270 llvm::ConstantInt::get(IntPtrTy,
1271 getContext().getTypeSizeInChars(type).getQuantity());
1273 llvm::Type *BP = AllocaInt8PtrTy;
1274 if (Loc.getType() != BP)
1275 Loc = Builder.CreateBitCast(Loc, BP);
1277 // If the initializer is all or mostly zeros, codegen with memset then do
1278 // a few stores afterward.
1279 if (shouldUseMemSetPlusStoresToInitialize(constant,
1280 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
1281 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1283 // Zero and undef don't require a stores.
1284 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
1285 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1286 emitStoresForInitAfterMemset(constant, Loc.getPointer(),
1287 isVolatile, Builder);
1290 // Otherwise, create a temporary global with the initializer then
1291 // memcpy from the global to the alloca.
1292 std::string Name = getStaticDeclName(CGM, D);
1294 if (getLangOpts().OpenCL) {
1295 AS = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
1296 BP = llvm::PointerType::getInt8PtrTy(getLLVMContext(), AS);
1298 llvm::GlobalVariable *GV =
1299 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
1300 llvm::GlobalValue::PrivateLinkage,
1301 constant, Name, nullptr,
1302 llvm::GlobalValue::NotThreadLocal, AS);
1303 GV->setAlignment(Loc.getAlignment().getQuantity());
1304 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1306 Address SrcPtr = Address(GV, Loc.getAlignment());
1307 if (SrcPtr.getType() != BP)
1308 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
1310 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, isVolatile);
1314 /// Emit an expression as an initializer for a variable at the given
1315 /// location. The expression is not necessarily the normal
1316 /// initializer for the variable, and the address is not necessarily
1317 /// its normal location.
1319 /// \param init the initializing expression
1320 /// \param var the variable to act as if we're initializing
1321 /// \param loc the address to initialize; its type is a pointer
1322 /// to the LLVM mapping of the variable's type
1323 /// \param alignment the alignment of the address
1324 /// \param capturedByInit true if the variable is a __block variable
1325 /// whose address is potentially changed by the initializer
1326 void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
1327 LValue lvalue, bool capturedByInit) {
1328 QualType type = D->getType();
1330 if (type->isReferenceType()) {
1331 RValue rvalue = EmitReferenceBindingToExpr(init);
1333 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1334 EmitStoreThroughLValue(rvalue, lvalue, true);
1337 switch (getEvaluationKind(type)) {
1339 EmitScalarInit(init, D, lvalue, capturedByInit);
1342 ComplexPairTy complex = EmitComplexExpr(init);
1344 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1345 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1349 if (type->isAtomicType()) {
1350 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1352 // TODO: how can we delay here if D is captured by its initializer?
1353 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
1354 AggValueSlot::IsDestructed,
1355 AggValueSlot::DoesNotNeedGCBarriers,
1356 AggValueSlot::IsNotAliased));
1360 llvm_unreachable("bad evaluation kind");
1363 /// Enter a destroy cleanup for the given local variable.
1364 void CodeGenFunction::emitAutoVarTypeCleanup(
1365 const CodeGenFunction::AutoVarEmission &emission,
1366 QualType::DestructionKind dtorKind) {
1367 assert(dtorKind != QualType::DK_none);
1369 // Note that for __block variables, we want to destroy the
1370 // original stack object, not the possibly forwarded object.
1371 Address addr = emission.getObjectAddress(*this);
1373 const VarDecl *var = emission.Variable;
1374 QualType type = var->getType();
1376 CleanupKind cleanupKind = NormalAndEHCleanup;
1377 CodeGenFunction::Destroyer *destroyer = nullptr;
1380 case QualType::DK_none:
1381 llvm_unreachable("no cleanup for trivially-destructible variable");
1383 case QualType::DK_cxx_destructor:
1384 // If there's an NRVO flag on the emission, we need a different
1386 if (emission.NRVOFlag) {
1387 assert(!type->isArrayType());
1388 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1389 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr,
1390 dtor, emission.NRVOFlag);
1395 case QualType::DK_objc_strong_lifetime:
1396 // Suppress cleanups for pseudo-strong variables.
1397 if (var->isARCPseudoStrong()) return;
1399 // Otherwise, consider whether to use an EH cleanup or not.
1400 cleanupKind = getARCCleanupKind();
1402 // Use the imprecise destroyer by default.
1403 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1404 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1407 case QualType::DK_objc_weak_lifetime:
1411 // If we haven't chosen a more specific destroyer, use the default.
1412 if (!destroyer) destroyer = getDestroyer(dtorKind);
1414 // Use an EH cleanup in array destructors iff the destructor itself
1415 // is being pushed as an EH cleanup.
1416 bool useEHCleanup = (cleanupKind & EHCleanup);
1417 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1421 void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
1422 assert(emission.Variable && "emission was not valid!");
1424 // If this was emitted as a global constant, we're done.
1425 if (emission.wasEmittedAsGlobal()) return;
1427 // If we don't have an insertion point, we're done. Sema prevents
1428 // us from jumping into any of these scopes anyway.
1429 if (!HaveInsertPoint()) return;
1431 const VarDecl &D = *emission.Variable;
1433 // Check the type for a cleanup.
1434 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1435 emitAutoVarTypeCleanup(emission, dtorKind);
1437 // In GC mode, honor objc_precise_lifetime.
1438 if (getLangOpts().getGC() != LangOptions::NonGC &&
1439 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1440 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1443 // Handle the cleanup attribute.
1444 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
1445 const FunctionDecl *FD = CA->getFunctionDecl();
1447 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
1448 assert(F && "Could not find function!");
1450 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
1451 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
1454 // If this is a block variable, call _Block_object_destroy
1455 // (on the unforwarded address).
1456 if (emission.IsByRef)
1457 enterByrefCleanup(emission);
1460 CodeGenFunction::Destroyer *
1461 CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1463 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
1464 case QualType::DK_cxx_destructor:
1465 return destroyCXXObject;
1466 case QualType::DK_objc_strong_lifetime:
1467 return destroyARCStrongPrecise;
1468 case QualType::DK_objc_weak_lifetime:
1469 return destroyARCWeak;
1471 llvm_unreachable("Unknown DestructionKind");
1474 /// pushEHDestroy - Push the standard destructor for the given type as
1475 /// an EH-only cleanup.
1476 void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
1477 Address addr, QualType type) {
1478 assert(dtorKind && "cannot push destructor for trivial type");
1479 assert(needsEHCleanup(dtorKind));
1481 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1484 /// pushDestroy - Push the standard destructor for the given type as
1485 /// at least a normal cleanup.
1486 void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1487 Address addr, QualType type) {
1488 assert(dtorKind && "cannot push destructor for trivial type");
1490 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1491 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1492 cleanupKind & EHCleanup);
1495 void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
1496 QualType type, Destroyer *destroyer,
1497 bool useEHCleanupForArray) {
1498 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1499 destroyer, useEHCleanupForArray);
1502 void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
1503 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1506 void CodeGenFunction::pushLifetimeExtendedDestroy(
1507 CleanupKind cleanupKind, Address addr, QualType type,
1508 Destroyer *destroyer, bool useEHCleanupForArray) {
1509 assert(!isInConditionalBranch() &&
1510 "performing lifetime extension from within conditional");
1512 // Push an EH-only cleanup for the object now.
1513 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1514 // around in case a temporary's destructor throws an exception.
1515 if (cleanupKind & EHCleanup)
1516 EHStack.pushCleanup<DestroyObject>(
1517 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1518 destroyer, useEHCleanupForArray);
1520 // Remember that we need to push a full cleanup for the object at the
1521 // end of the full-expression.
1522 pushCleanupAfterFullExpr<DestroyObject>(
1523 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1526 /// emitDestroy - Immediately perform the destruction of the given
1529 /// \param addr - the address of the object; a type*
1530 /// \param type - the type of the object; if an array type, all
1531 /// objects are destroyed in reverse order
1532 /// \param destroyer - the function to call to destroy individual
1534 /// \param useEHCleanupForArray - whether an EH cleanup should be
1535 /// used when destroying array elements, in case one of the
1536 /// destructions throws an exception
1537 void CodeGenFunction::emitDestroy(Address addr, QualType type,
1538 Destroyer *destroyer,
1539 bool useEHCleanupForArray) {
1540 const ArrayType *arrayType = getContext().getAsArrayType(type);
1542 return destroyer(*this, addr, type);
1544 llvm::Value *length = emitArrayLength(arrayType, type, addr);
1546 CharUnits elementAlign =
1548 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
1550 // Normally we have to check whether the array is zero-length.
1551 bool checkZeroLength = true;
1553 // But if the array length is constant, we can suppress that.
1554 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1555 // ...and if it's constant zero, we can just skip the entire thing.
1556 if (constLength->isZero()) return;
1557 checkZeroLength = false;
1560 llvm::Value *begin = addr.getPointer();
1561 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
1562 emitArrayDestroy(begin, end, type, elementAlign, destroyer,
1563 checkZeroLength, useEHCleanupForArray);
1566 /// emitArrayDestroy - Destroys all the elements of the given array,
1567 /// beginning from last to first. The array cannot be zero-length.
1569 /// \param begin - a type* denoting the first element of the array
1570 /// \param end - a type* denoting one past the end of the array
1571 /// \param elementType - the element type of the array
1572 /// \param destroyer - the function to call to destroy elements
1573 /// \param useEHCleanup - whether to push an EH cleanup to destroy
1574 /// the remaining elements in case the destruction of a single
1576 void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1578 QualType elementType,
1579 CharUnits elementAlign,
1580 Destroyer *destroyer,
1581 bool checkZeroLength,
1582 bool useEHCleanup) {
1583 assert(!elementType->isArrayType());
1585 // The basic structure here is a do-while loop, because we don't
1586 // need to check for the zero-element case.
1587 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1588 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1590 if (checkZeroLength) {
1591 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1592 "arraydestroy.isempty");
1593 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1596 // Enter the loop body, making that address the current address.
1597 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1599 llvm::PHINode *elementPast =
1600 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1601 elementPast->addIncoming(end, entryBB);
1603 // Shift the address back by one element.
1604 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1605 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1606 "arraydestroy.element");
1609 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
1612 // Perform the actual destruction there.
1613 destroyer(*this, Address(element, elementAlign), elementType);
1618 // Check whether we've reached the end.
1619 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1620 Builder.CreateCondBr(done, doneBB, bodyBB);
1621 elementPast->addIncoming(element, Builder.GetInsertBlock());
1627 /// Perform partial array destruction as if in an EH cleanup. Unlike
1628 /// emitArrayDestroy, the element type here may still be an array type.
1629 static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1630 llvm::Value *begin, llvm::Value *end,
1631 QualType type, CharUnits elementAlign,
1632 CodeGenFunction::Destroyer *destroyer) {
1633 // If the element type is itself an array, drill down.
1634 unsigned arrayDepth = 0;
1635 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1636 // VLAs don't require a GEP index to walk into.
1637 if (!isa<VariableArrayType>(arrayType))
1639 type = arrayType->getElementType();
1643 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
1645 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
1646 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1647 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
1650 // Destroy the array. We don't ever need an EH cleanup because we
1651 // assume that we're in an EH cleanup ourselves, so a throwing
1652 // destructor causes an immediate terminate.
1653 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
1654 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
1658 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1659 /// array destroy where the end pointer is regularly determined and
1660 /// does not need to be loaded from a local.
1661 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
1662 llvm::Value *ArrayBegin;
1663 llvm::Value *ArrayEnd;
1664 QualType ElementType;
1665 CodeGenFunction::Destroyer *Destroyer;
1666 CharUnits ElementAlign;
1668 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1669 QualType elementType, CharUnits elementAlign,
1670 CodeGenFunction::Destroyer *destroyer)
1671 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
1672 ElementType(elementType), Destroyer(destroyer),
1673 ElementAlign(elementAlign) {}
1675 void Emit(CodeGenFunction &CGF, Flags flags) override {
1676 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1677 ElementType, ElementAlign, Destroyer);
1681 /// IrregularPartialArrayDestroy - a cleanup which performs a
1682 /// partial array destroy where the end pointer is irregularly
1683 /// determined and must be loaded from a local.
1684 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
1685 llvm::Value *ArrayBegin;
1686 Address ArrayEndPointer;
1687 QualType ElementType;
1688 CodeGenFunction::Destroyer *Destroyer;
1689 CharUnits ElementAlign;
1691 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1692 Address arrayEndPointer,
1693 QualType elementType,
1694 CharUnits elementAlign,
1695 CodeGenFunction::Destroyer *destroyer)
1696 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
1697 ElementType(elementType), Destroyer(destroyer),
1698 ElementAlign(elementAlign) {}
1700 void Emit(CodeGenFunction &CGF, Flags flags) override {
1701 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
1702 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1703 ElementType, ElementAlign, Destroyer);
1706 } // end anonymous namespace
1708 /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
1709 /// already-constructed elements of the given array. The cleanup
1710 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1712 /// \param elementType - the immediate element type of the array;
1713 /// possibly still an array type
1714 void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
1715 Address arrayEndPointer,
1716 QualType elementType,
1717 CharUnits elementAlign,
1718 Destroyer *destroyer) {
1719 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1720 arrayBegin, arrayEndPointer,
1721 elementType, elementAlign,
1725 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1726 /// already-constructed elements of the given array. The cleanup
1727 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1729 /// \param elementType - the immediate element type of the array;
1730 /// possibly still an array type
1731 void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1732 llvm::Value *arrayEnd,
1733 QualType elementType,
1734 CharUnits elementAlign,
1735 Destroyer *destroyer) {
1736 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
1737 arrayBegin, arrayEnd,
1738 elementType, elementAlign,
1742 /// Lazily declare the @llvm.lifetime.start intrinsic.
1743 llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1744 if (LifetimeStartFn)
1745 return LifetimeStartFn;
1746 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1747 llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
1748 return LifetimeStartFn;
1751 /// Lazily declare the @llvm.lifetime.end intrinsic.
1752 llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1754 return LifetimeEndFn;
1755 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1756 llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
1757 return LifetimeEndFn;
1761 /// A cleanup to perform a release of an object at the end of a
1762 /// function. This is used to balance out the incoming +1 of a
1763 /// ns_consumed argument when we can't reasonably do that just by
1764 /// not doing the initial retain for a __block argument.
1765 struct ConsumeARCParameter final : EHScopeStack::Cleanup {
1766 ConsumeARCParameter(llvm::Value *param,
1767 ARCPreciseLifetime_t precise)
1768 : Param(param), Precise(precise) {}
1771 ARCPreciseLifetime_t Precise;
1773 void Emit(CodeGenFunction &CGF, Flags flags) override {
1774 CGF.EmitARCRelease(Param, Precise);
1777 } // end anonymous namespace
1779 /// Emit an alloca (or GlobalValue depending on target)
1780 /// for the specified parameter and set up LocalDeclMap.
1781 void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
1783 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
1784 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
1785 "Invalid argument to EmitParmDecl");
1787 Arg.getAnyValue()->setName(D.getName());
1789 QualType Ty = D.getType();
1791 // Use better IR generation for certain implicit parameters.
1792 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
1793 // The only implicit argument a block has is its literal.
1794 // We assume this is always passed directly.
1796 setBlockContextParameter(IPD, ArgNo, Arg.getDirectValue());
1801 Address DeclPtr = Address::invalid();
1802 bool DoStore = false;
1803 bool IsScalar = hasScalarEvaluationKind(Ty);
1804 // If we already have a pointer to the argument, reuse the input pointer.
1805 if (Arg.isIndirect()) {
1806 DeclPtr = Arg.getIndirectAddress();
1807 // If we have a prettier pointer type at this point, bitcast to that.
1808 unsigned AS = DeclPtr.getType()->getAddressSpace();
1809 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
1810 if (DeclPtr.getType() != IRTy)
1811 DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
1813 // Push a destructor cleanup for this parameter if the ABI requires it.
1814 // Don't push a cleanup in a thunk for a method that will also emit a
1816 if (!IsScalar && !CurFuncIsThunk &&
1817 getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1818 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1819 if (RD && RD->hasNonTrivialDestructor())
1820 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
1823 // Otherwise, create a temporary to hold the value.
1824 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
1825 D.getName() + ".addr");
1829 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
1831 LValue lv = MakeAddrLValue(DeclPtr, Ty);
1833 Qualifiers qs = Ty.getQualifiers();
1834 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1835 // We honor __attribute__((ns_consumed)) for types with lifetime.
1836 // For __strong, it's handled by just skipping the initial retain;
1837 // otherwise we have to balance out the initial +1 with an extra
1838 // cleanup to do the release at the end of the function.
1839 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1841 // 'self' is always formally __strong, but if this is not an
1842 // init method then we don't want to retain it.
1843 if (D.isARCPseudoStrong()) {
1844 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1845 assert(&D == method->getSelfDecl());
1846 assert(lt == Qualifiers::OCL_Strong);
1847 assert(qs.hasConst());
1848 assert(method->getMethodFamily() != OMF_init);
1850 lt = Qualifiers::OCL_ExplicitNone;
1853 // Load objects passed indirectly.
1854 if (Arg.isIndirect() && !ArgVal)
1855 ArgVal = Builder.CreateLoad(DeclPtr);
1857 if (lt == Qualifiers::OCL_Strong) {
1859 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1860 // use objc_storeStrong(&dest, value) for retaining the
1861 // object. But first, store a null into 'dest' because
1862 // objc_storeStrong attempts to release its old value.
1863 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
1864 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
1865 EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
1869 // Don't use objc_retainBlock for block pointers, because we
1870 // don't want to Block_copy something just because we got it
1872 ArgVal = EmitARCRetainNonBlock(ArgVal);
1875 // Push the cleanup for a consumed parameter.
1877 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1878 ? ARCPreciseLifetime : ARCImpreciseLifetime);
1879 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
1883 if (lt == Qualifiers::OCL_Weak) {
1884 EmitARCInitWeak(DeclPtr, ArgVal);
1885 DoStore = false; // The weak init is a store, no need to do two.
1889 // Enter the cleanup scope.
1890 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1894 // Store the initial value into the alloca.
1896 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
1898 setAddrOfLocalVar(&D, DeclPtr);
1900 // Emit debug info for param declaration.
1901 if (CGDebugInfo *DI = getDebugInfo()) {
1902 if (CGM.getCodeGenOpts().getDebugInfo() >=
1903 codegenoptions::LimitedDebugInfo) {
1904 DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
1908 if (D.hasAttr<AnnotateAttr>())
1909 EmitVarAnnotations(&D, DeclPtr.getPointer());
1911 // We can only check return value nullability if all arguments to the
1912 // function satisfy their nullability preconditions. This makes it necessary
1913 // to emit null checks for args in the function body itself.
1914 if (requiresReturnValueNullabilityCheck()) {
1915 auto Nullability = Ty->getNullability(getContext());
1916 if (Nullability && *Nullability == NullabilityKind::NonNull) {
1917 SanitizerScope SanScope(this);
1918 RetValNullabilityPrecondition =
1919 Builder.CreateAnd(RetValNullabilityPrecondition,
1920 Builder.CreateIsNotNull(Arg.getAnyValue()));
1925 void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1926 CodeGenFunction *CGF) {
1927 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
1929 getOpenMPRuntime().emitUserDefinedReduction(CGF, D);