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