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