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