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