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