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