CGDecl.cpp revision 8a07cd3f59a0ede54906bdc8ed21724815db27ad
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 MaybeEmitStdInitializerListCleanup(lvalue.getAddress(), init); 1191 return; 1192 } 1193 llvm_unreachable("bad evaluation kind"); 1194} 1195 1196/// Enter a destroy cleanup for the given local variable. 1197void CodeGenFunction::emitAutoVarTypeCleanup( 1198 const CodeGenFunction::AutoVarEmission &emission, 1199 QualType::DestructionKind dtorKind) { 1200 assert(dtorKind != QualType::DK_none); 1201 1202 // Note that for __block variables, we want to destroy the 1203 // original stack object, not the possibly forwarded object. 1204 llvm::Value *addr = emission.getObjectAddress(*this); 1205 1206 const VarDecl *var = emission.Variable; 1207 QualType type = var->getType(); 1208 1209 CleanupKind cleanupKind = NormalAndEHCleanup; 1210 CodeGenFunction::Destroyer *destroyer = 0; 1211 1212 switch (dtorKind) { 1213 case QualType::DK_none: 1214 llvm_unreachable("no cleanup for trivially-destructible variable"); 1215 1216 case QualType::DK_cxx_destructor: 1217 // If there's an NRVO flag on the emission, we need a different 1218 // cleanup. 1219 if (emission.NRVOFlag) { 1220 assert(!type->isArrayType()); 1221 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor(); 1222 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor, 1223 emission.NRVOFlag); 1224 return; 1225 } 1226 break; 1227 1228 case QualType::DK_objc_strong_lifetime: 1229 // Suppress cleanups for pseudo-strong variables. 1230 if (var->isARCPseudoStrong()) return; 1231 1232 // Otherwise, consider whether to use an EH cleanup or not. 1233 cleanupKind = getARCCleanupKind(); 1234 1235 // Use the imprecise destroyer by default. 1236 if (!var->hasAttr<ObjCPreciseLifetimeAttr>()) 1237 destroyer = CodeGenFunction::destroyARCStrongImprecise; 1238 break; 1239 1240 case QualType::DK_objc_weak_lifetime: 1241 break; 1242 } 1243 1244 // If we haven't chosen a more specific destroyer, use the default. 1245 if (!destroyer) destroyer = getDestroyer(dtorKind); 1246 1247 // Use an EH cleanup in array destructors iff the destructor itself 1248 // is being pushed as an EH cleanup. 1249 bool useEHCleanup = (cleanupKind & EHCleanup); 1250 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer, 1251 useEHCleanup); 1252} 1253 1254void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) { 1255 assert(emission.Variable && "emission was not valid!"); 1256 1257 // If this was emitted as a global constant, we're done. 1258 if (emission.wasEmittedAsGlobal()) return; 1259 1260 // If we don't have an insertion point, we're done. Sema prevents 1261 // us from jumping into any of these scopes anyway. 1262 if (!HaveInsertPoint()) return; 1263 1264 const VarDecl &D = *emission.Variable; 1265 1266 // Make sure we call @llvm.lifetime.end. This needs to happen 1267 // *last*, so the cleanup needs to be pushed *first*. 1268 if (emission.useLifetimeMarkers()) { 1269 EHStack.pushCleanup<CallLifetimeEnd>(NormalCleanup, 1270 emission.getAllocatedAddress(), 1271 emission.getSizeForLifetimeMarkers()); 1272 } 1273 1274 // Check the type for a cleanup. 1275 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType()) 1276 emitAutoVarTypeCleanup(emission, dtorKind); 1277 1278 // In GC mode, honor objc_precise_lifetime. 1279 if (getLangOpts().getGC() != LangOptions::NonGC && 1280 D.hasAttr<ObjCPreciseLifetimeAttr>()) { 1281 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D); 1282 } 1283 1284 // Handle the cleanup attribute. 1285 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) { 1286 const FunctionDecl *FD = CA->getFunctionDecl(); 1287 1288 llvm::Constant *F = CGM.GetAddrOfFunction(FD); 1289 assert(F && "Could not find function!"); 1290 1291 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD); 1292 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D); 1293 } 1294 1295 // If this is a block variable, call _Block_object_destroy 1296 // (on the unforwarded address). 1297 if (emission.IsByRef) 1298 enterByrefCleanup(emission); 1299} 1300 1301CodeGenFunction::Destroyer * 1302CodeGenFunction::getDestroyer(QualType::DestructionKind kind) { 1303 switch (kind) { 1304 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor"); 1305 case QualType::DK_cxx_destructor: 1306 return destroyCXXObject; 1307 case QualType::DK_objc_strong_lifetime: 1308 return destroyARCStrongPrecise; 1309 case QualType::DK_objc_weak_lifetime: 1310 return destroyARCWeak; 1311 } 1312 llvm_unreachable("Unknown DestructionKind"); 1313} 1314 1315/// pushEHDestroy - Push the standard destructor for the given type as 1316/// an EH-only cleanup. 1317void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind, 1318 llvm::Value *addr, QualType type) { 1319 assert(dtorKind && "cannot push destructor for trivial type"); 1320 assert(needsEHCleanup(dtorKind)); 1321 1322 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true); 1323} 1324 1325/// pushDestroy - Push the standard destructor for the given type as 1326/// at least a normal cleanup. 1327void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind, 1328 llvm::Value *addr, QualType type) { 1329 assert(dtorKind && "cannot push destructor for trivial type"); 1330 1331 CleanupKind cleanupKind = getCleanupKind(dtorKind); 1332 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind), 1333 cleanupKind & EHCleanup); 1334} 1335 1336void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr, 1337 QualType type, Destroyer *destroyer, 1338 bool useEHCleanupForArray) { 1339 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type, 1340 destroyer, useEHCleanupForArray); 1341} 1342 1343void CodeGenFunction::pushLifetimeExtendedDestroy( 1344 CleanupKind cleanupKind, llvm::Value *addr, QualType type, 1345 Destroyer *destroyer, bool useEHCleanupForArray) { 1346 assert(!isInConditionalBranch() && 1347 "performing lifetime extension from within conditional"); 1348 1349 // Push an EH-only cleanup for the object now. 1350 // FIXME: When popping normal cleanups, we need to keep this EH cleanup 1351 // around in case a temporary's destructor throws an exception. 1352 if (cleanupKind & EHCleanup) 1353 EHStack.pushCleanup<DestroyObject>( 1354 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type, 1355 destroyer, useEHCleanupForArray); 1356 1357 // Remember that we need to push a full cleanup for the object at the 1358 // end of the full-expression. 1359 pushCleanupAfterFullExpr<DestroyObject>( 1360 cleanupKind, addr, type, destroyer, useEHCleanupForArray); 1361} 1362 1363/// emitDestroy - Immediately perform the destruction of the given 1364/// object. 1365/// 1366/// \param addr - the address of the object; a type* 1367/// \param type - the type of the object; if an array type, all 1368/// objects are destroyed in reverse order 1369/// \param destroyer - the function to call to destroy individual 1370/// elements 1371/// \param useEHCleanupForArray - whether an EH cleanup should be 1372/// used when destroying array elements, in case one of the 1373/// destructions throws an exception 1374void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type, 1375 Destroyer *destroyer, 1376 bool useEHCleanupForArray) { 1377 const ArrayType *arrayType = getContext().getAsArrayType(type); 1378 if (!arrayType) 1379 return destroyer(*this, addr, type); 1380 1381 llvm::Value *begin = addr; 1382 llvm::Value *length = emitArrayLength(arrayType, type, begin); 1383 1384 // Normally we have to check whether the array is zero-length. 1385 bool checkZeroLength = true; 1386 1387 // But if the array length is constant, we can suppress that. 1388 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) { 1389 // ...and if it's constant zero, we can just skip the entire thing. 1390 if (constLength->isZero()) return; 1391 checkZeroLength = false; 1392 } 1393 1394 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length); 1395 emitArrayDestroy(begin, end, type, destroyer, 1396 checkZeroLength, useEHCleanupForArray); 1397} 1398 1399/// emitArrayDestroy - Destroys all the elements of the given array, 1400/// beginning from last to first. The array cannot be zero-length. 1401/// 1402/// \param begin - a type* denoting the first element of the array 1403/// \param end - a type* denoting one past the end of the array 1404/// \param type - the element type of the array 1405/// \param destroyer - the function to call to destroy elements 1406/// \param useEHCleanup - whether to push an EH cleanup to destroy 1407/// the remaining elements in case the destruction of a single 1408/// element throws 1409void CodeGenFunction::emitArrayDestroy(llvm::Value *begin, 1410 llvm::Value *end, 1411 QualType type, 1412 Destroyer *destroyer, 1413 bool checkZeroLength, 1414 bool useEHCleanup) { 1415 assert(!type->isArrayType()); 1416 1417 // The basic structure here is a do-while loop, because we don't 1418 // need to check for the zero-element case. 1419 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body"); 1420 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done"); 1421 1422 if (checkZeroLength) { 1423 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end, 1424 "arraydestroy.isempty"); 1425 Builder.CreateCondBr(isEmpty, doneBB, bodyBB); 1426 } 1427 1428 // Enter the loop body, making that address the current address. 1429 llvm::BasicBlock *entryBB = Builder.GetInsertBlock(); 1430 EmitBlock(bodyBB); 1431 llvm::PHINode *elementPast = 1432 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast"); 1433 elementPast->addIncoming(end, entryBB); 1434 1435 // Shift the address back by one element. 1436 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true); 1437 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne, 1438 "arraydestroy.element"); 1439 1440 if (useEHCleanup) 1441 pushRegularPartialArrayCleanup(begin, element, type, destroyer); 1442 1443 // Perform the actual destruction there. 1444 destroyer(*this, element, type); 1445 1446 if (useEHCleanup) 1447 PopCleanupBlock(); 1448 1449 // Check whether we've reached the end. 1450 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done"); 1451 Builder.CreateCondBr(done, doneBB, bodyBB); 1452 elementPast->addIncoming(element, Builder.GetInsertBlock()); 1453 1454 // Done. 1455 EmitBlock(doneBB); 1456} 1457 1458/// Perform partial array destruction as if in an EH cleanup. Unlike 1459/// emitArrayDestroy, the element type here may still be an array type. 1460static void emitPartialArrayDestroy(CodeGenFunction &CGF, 1461 llvm::Value *begin, llvm::Value *end, 1462 QualType type, 1463 CodeGenFunction::Destroyer *destroyer) { 1464 // If the element type is itself an array, drill down. 1465 unsigned arrayDepth = 0; 1466 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) { 1467 // VLAs don't require a GEP index to walk into. 1468 if (!isa<VariableArrayType>(arrayType)) 1469 arrayDepth++; 1470 type = arrayType->getElementType(); 1471 } 1472 1473 if (arrayDepth) { 1474 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1); 1475 1476 SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero); 1477 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin"); 1478 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend"); 1479 } 1480 1481 // Destroy the array. We don't ever need an EH cleanup because we 1482 // assume that we're in an EH cleanup ourselves, so a throwing 1483 // destructor causes an immediate terminate. 1484 CGF.emitArrayDestroy(begin, end, type, destroyer, 1485 /*checkZeroLength*/ true, /*useEHCleanup*/ false); 1486} 1487 1488namespace { 1489 /// RegularPartialArrayDestroy - a cleanup which performs a partial 1490 /// array destroy where the end pointer is regularly determined and 1491 /// does not need to be loaded from a local. 1492 class RegularPartialArrayDestroy : public EHScopeStack::Cleanup { 1493 llvm::Value *ArrayBegin; 1494 llvm::Value *ArrayEnd; 1495 QualType ElementType; 1496 CodeGenFunction::Destroyer *Destroyer; 1497 public: 1498 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd, 1499 QualType elementType, 1500 CodeGenFunction::Destroyer *destroyer) 1501 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd), 1502 ElementType(elementType), Destroyer(destroyer) {} 1503 1504 void Emit(CodeGenFunction &CGF, Flags flags) { 1505 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd, 1506 ElementType, Destroyer); 1507 } 1508 }; 1509 1510 /// IrregularPartialArrayDestroy - a cleanup which performs a 1511 /// partial array destroy where the end pointer is irregularly 1512 /// determined and must be loaded from a local. 1513 class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup { 1514 llvm::Value *ArrayBegin; 1515 llvm::Value *ArrayEndPointer; 1516 QualType ElementType; 1517 CodeGenFunction::Destroyer *Destroyer; 1518 public: 1519 IrregularPartialArrayDestroy(llvm::Value *arrayBegin, 1520 llvm::Value *arrayEndPointer, 1521 QualType elementType, 1522 CodeGenFunction::Destroyer *destroyer) 1523 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer), 1524 ElementType(elementType), Destroyer(destroyer) {} 1525 1526 void Emit(CodeGenFunction &CGF, Flags flags) { 1527 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer); 1528 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd, 1529 ElementType, Destroyer); 1530 } 1531 }; 1532} 1533 1534/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy 1535/// already-constructed elements of the given array. The cleanup 1536/// may be popped with DeactivateCleanupBlock or PopCleanupBlock. 1537/// 1538/// \param elementType - the immediate element type of the array; 1539/// possibly still an array type 1540void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin, 1541 llvm::Value *arrayEndPointer, 1542 QualType elementType, 1543 Destroyer *destroyer) { 1544 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup, 1545 arrayBegin, arrayEndPointer, 1546 elementType, destroyer); 1547} 1548 1549/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy 1550/// already-constructed elements of the given array. The cleanup 1551/// may be popped with DeactivateCleanupBlock or PopCleanupBlock. 1552/// 1553/// \param elementType - the immediate element type of the array; 1554/// possibly still an array type 1555void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin, 1556 llvm::Value *arrayEnd, 1557 QualType elementType, 1558 Destroyer *destroyer) { 1559 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup, 1560 arrayBegin, arrayEnd, 1561 elementType, destroyer); 1562} 1563 1564/// Lazily declare the @llvm.lifetime.start intrinsic. 1565llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() { 1566 if (LifetimeStartFn) return LifetimeStartFn; 1567 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(), 1568 llvm::Intrinsic::lifetime_start); 1569 return LifetimeStartFn; 1570} 1571 1572/// Lazily declare the @llvm.lifetime.end intrinsic. 1573llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() { 1574 if (LifetimeEndFn) return LifetimeEndFn; 1575 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(), 1576 llvm::Intrinsic::lifetime_end); 1577 return LifetimeEndFn; 1578} 1579 1580namespace { 1581 /// A cleanup to perform a release of an object at the end of a 1582 /// function. This is used to balance out the incoming +1 of a 1583 /// ns_consumed argument when we can't reasonably do that just by 1584 /// not doing the initial retain for a __block argument. 1585 struct ConsumeARCParameter : EHScopeStack::Cleanup { 1586 ConsumeARCParameter(llvm::Value *param, 1587 ARCPreciseLifetime_t precise) 1588 : Param(param), Precise(precise) {} 1589 1590 llvm::Value *Param; 1591 ARCPreciseLifetime_t Precise; 1592 1593 void Emit(CodeGenFunction &CGF, Flags flags) { 1594 CGF.EmitARCRelease(Param, Precise); 1595 } 1596 }; 1597} 1598 1599/// Emit an alloca (or GlobalValue depending on target) 1600/// for the specified parameter and set up LocalDeclMap. 1601void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg, 1602 unsigned ArgNo) { 1603 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl? 1604 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) && 1605 "Invalid argument to EmitParmDecl"); 1606 1607 Arg->setName(D.getName()); 1608 1609 QualType Ty = D.getType(); 1610 1611 // Use better IR generation for certain implicit parameters. 1612 if (isa<ImplicitParamDecl>(D)) { 1613 // The only implicit argument a block has is its literal. 1614 if (BlockInfo) { 1615 LocalDeclMap[&D] = Arg; 1616 llvm::Value *LocalAddr = 0; 1617 if (CGM.getCodeGenOpts().OptimizationLevel == 0) { 1618 // Allocate a stack slot to let the debug info survive the RA. 1619 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty), 1620 D.getName() + ".addr"); 1621 Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity()); 1622 LValue lv = MakeAddrLValue(Alloc, Ty, getContext().getDeclAlign(&D)); 1623 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true); 1624 LocalAddr = Builder.CreateLoad(Alloc); 1625 } 1626 1627 if (CGDebugInfo *DI = getDebugInfo()) { 1628 if (CGM.getCodeGenOpts().getDebugInfo() 1629 >= CodeGenOptions::LimitedDebugInfo) { 1630 DI->setLocation(D.getLocation()); 1631 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, LocalAddr, Builder); 1632 } 1633 } 1634 1635 return; 1636 } 1637 } 1638 1639 llvm::Value *DeclPtr; 1640 // If this is an aggregate or variable sized value, reuse the input pointer. 1641 if (!Ty->isConstantSizeType() || 1642 !CodeGenFunction::hasScalarEvaluationKind(Ty)) { 1643 DeclPtr = Arg; 1644 } else { 1645 // Otherwise, create a temporary to hold the value. 1646 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty), 1647 D.getName() + ".addr"); 1648 CharUnits Align = getContext().getDeclAlign(&D); 1649 Alloc->setAlignment(Align.getQuantity()); 1650 DeclPtr = Alloc; 1651 1652 bool doStore = true; 1653 1654 Qualifiers qs = Ty.getQualifiers(); 1655 LValue lv = MakeAddrLValue(DeclPtr, Ty, Align); 1656 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) { 1657 // We honor __attribute__((ns_consumed)) for types with lifetime. 1658 // For __strong, it's handled by just skipping the initial retain; 1659 // otherwise we have to balance out the initial +1 with an extra 1660 // cleanup to do the release at the end of the function. 1661 bool isConsumed = D.hasAttr<NSConsumedAttr>(); 1662 1663 // 'self' is always formally __strong, but if this is not an 1664 // init method then we don't want to retain it. 1665 if (D.isARCPseudoStrong()) { 1666 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl); 1667 assert(&D == method->getSelfDecl()); 1668 assert(lt == Qualifiers::OCL_Strong); 1669 assert(qs.hasConst()); 1670 assert(method->getMethodFamily() != OMF_init); 1671 (void) method; 1672 lt = Qualifiers::OCL_ExplicitNone; 1673 } 1674 1675 if (lt == Qualifiers::OCL_Strong) { 1676 if (!isConsumed) { 1677 if (CGM.getCodeGenOpts().OptimizationLevel == 0) { 1678 // use objc_storeStrong(&dest, value) for retaining the 1679 // object. But first, store a null into 'dest' because 1680 // objc_storeStrong attempts to release its old value. 1681 llvm::Value * Null = CGM.EmitNullConstant(D.getType()); 1682 EmitStoreOfScalar(Null, lv, /* isInitialization */ true); 1683 EmitARCStoreStrongCall(lv.getAddress(), Arg, true); 1684 doStore = false; 1685 } 1686 else 1687 // Don't use objc_retainBlock for block pointers, because we 1688 // don't want to Block_copy something just because we got it 1689 // as a parameter. 1690 Arg = EmitARCRetainNonBlock(Arg); 1691 } 1692 } else { 1693 // Push the cleanup for a consumed parameter. 1694 if (isConsumed) { 1695 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>() 1696 ? ARCPreciseLifetime : ARCImpreciseLifetime); 1697 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg, 1698 precise); 1699 } 1700 1701 if (lt == Qualifiers::OCL_Weak) { 1702 EmitARCInitWeak(DeclPtr, Arg); 1703 doStore = false; // The weak init is a store, no need to do two. 1704 } 1705 } 1706 1707 // Enter the cleanup scope. 1708 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt); 1709 } 1710 1711 // Store the initial value into the alloca. 1712 if (doStore) 1713 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true); 1714 } 1715 1716 llvm::Value *&DMEntry = LocalDeclMap[&D]; 1717 assert(DMEntry == 0 && "Decl already exists in localdeclmap!"); 1718 DMEntry = DeclPtr; 1719 1720 // Emit debug info for param declaration. 1721 if (CGDebugInfo *DI = getDebugInfo()) { 1722 if (CGM.getCodeGenOpts().getDebugInfo() 1723 >= CodeGenOptions::LimitedDebugInfo) { 1724 DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder); 1725 } 1726 } 1727 1728 if (D.hasAttr<AnnotateAttr>()) 1729 EmitVarAnnotations(&D, DeclPtr); 1730} 1731