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