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