1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// 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 coordinates the per-module state used while generating code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenModule.h" 15 #include "CGDebugInfo.h" 16 #include "CodeGenFunction.h" 17 #include "CGCall.h" 18 #include "CGObjCRuntime.h" 19 #include "Mangle.h" 20 #include "TargetInfo.h" 21 #include "clang/Frontend/CodeGenOptions.h" 22 #include "clang/AST/ASTContext.h" 23 #include "clang/AST/CharUnits.h" 24 #include "clang/AST/DeclObjC.h" 25 #include "clang/AST/DeclCXX.h" 26 #include "clang/AST/DeclTemplate.h" 27 #include "clang/AST/RecordLayout.h" 28 #include "clang/Basic/Builtins.h" 29 #include "clang/Basic/Diagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Basic/ConvertUTF.h" 33 #include "llvm/CallingConv.h" 34 #include "llvm/Module.h" 35 #include "llvm/Intrinsics.h" 36 #include "llvm/LLVMContext.h" 37 #include "llvm/ADT/Triple.h" 38 #include "llvm/Target/TargetData.h" 39 #include "llvm/Support/CallSite.h" 40 #include "llvm/Support/ErrorHandling.h" 41 using namespace clang; 42 using namespace CodeGen; 43 44 45 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO, 46 llvm::Module &M, const llvm::TargetData &TD, 47 Diagnostic &diags) 48 : BlockModule(C, M, TD, Types, *this), Context(C), 49 Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M), 50 TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags), 51 Types(C, M, TD, getTargetCodeGenInfo().getABIInfo()), 52 VTables(*this), Runtime(0), ABI(0), 53 CFConstantStringClassRef(0), NSConstantStringClassRef(0), 54 VMContext(M.getContext()), 55 NSConcreteGlobalBlockDecl(0), NSConcreteStackBlockDecl(0), 56 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0), 57 BlockObjectAssignDecl(0), BlockObjectDisposeDecl(0), 58 BlockObjectAssign(0), BlockObjectDispose(0){ 59 60 if (!Features.ObjC1) 61 Runtime = 0; 62 else if (!Features.NeXTRuntime) 63 Runtime = CreateGNUObjCRuntime(*this); 64 else if (Features.ObjCNonFragileABI) 65 Runtime = CreateMacNonFragileABIObjCRuntime(*this); 66 else 67 Runtime = CreateMacObjCRuntime(*this); 68 69 if (!Features.CPlusPlus) 70 ABI = 0; 71 else createCXXABI(); 72 73 // If debug info generation is enabled, create the CGDebugInfo object. 74 DebugInfo = CodeGenOpts.DebugInfo ? new CGDebugInfo(*this) : 0; 75 } 76 77 CodeGenModule::~CodeGenModule() { 78 delete Runtime; 79 delete ABI; 80 delete DebugInfo; 81 } 82 83 void CodeGenModule::createObjCRuntime() { 84 if (!Features.NeXTRuntime) 85 Runtime = CreateGNUObjCRuntime(*this); 86 else if (Features.ObjCNonFragileABI) 87 Runtime = CreateMacNonFragileABIObjCRuntime(*this); 88 else 89 Runtime = CreateMacObjCRuntime(*this); 90 } 91 92 void CodeGenModule::createCXXABI() { 93 if (Context.Target.getCXXABI() == "microsoft") 94 ABI = CreateMicrosoftCXXABI(*this); 95 else 96 ABI = CreateItaniumCXXABI(*this); 97 } 98 99 void CodeGenModule::Release() { 100 EmitDeferred(); 101 EmitCXXGlobalInitFunc(); 102 EmitCXXGlobalDtorFunc(); 103 if (Runtime) 104 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction()) 105 AddGlobalCtor(ObjCInitFunction); 106 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 107 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 108 EmitAnnotations(); 109 EmitLLVMUsed(); 110 111 if (getCodeGenOpts().EmitDeclMetadata) 112 EmitDeclMetadata(); 113 } 114 115 bool CodeGenModule::isTargetDarwin() const { 116 return getContext().Target.getTriple().getOS() == llvm::Triple::Darwin; 117 } 118 119 /// ErrorUnsupported - Print out an error that codegen doesn't support the 120 /// specified stmt yet. 121 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type, 122 bool OmitOnError) { 123 if (OmitOnError && getDiags().hasErrorOccurred()) 124 return; 125 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 126 "cannot compile this %0 yet"); 127 std::string Msg = Type; 128 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 129 << Msg << S->getSourceRange(); 130 } 131 132 /// ErrorUnsupported - Print out an error that codegen doesn't support the 133 /// specified decl yet. 134 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type, 135 bool OmitOnError) { 136 if (OmitOnError && getDiags().hasErrorOccurred()) 137 return; 138 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 139 "cannot compile this %0 yet"); 140 std::string Msg = Type; 141 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 142 } 143 144 LangOptions::VisibilityMode 145 CodeGenModule::getDeclVisibilityMode(const Decl *D) const { 146 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 147 if (VD->getStorageClass() == VarDecl::PrivateExtern) 148 return LangOptions::Hidden; 149 150 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) { 151 switch (attr->getVisibility()) { 152 default: assert(0 && "Unknown visibility!"); 153 case VisibilityAttr::DefaultVisibility: 154 return LangOptions::Default; 155 case VisibilityAttr::HiddenVisibility: 156 return LangOptions::Hidden; 157 case VisibilityAttr::ProtectedVisibility: 158 return LangOptions::Protected; 159 } 160 } 161 162 if (getLangOptions().CPlusPlus) { 163 // Entities subject to an explicit instantiation declaration get default 164 // visibility. 165 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 166 if (Function->getTemplateSpecializationKind() 167 == TSK_ExplicitInstantiationDeclaration) 168 return LangOptions::Default; 169 } else if (const ClassTemplateSpecializationDecl *ClassSpec 170 = dyn_cast<ClassTemplateSpecializationDecl>(D)) { 171 if (ClassSpec->getSpecializationKind() 172 == TSK_ExplicitInstantiationDeclaration) 173 return LangOptions::Default; 174 } else if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 175 if (Record->getTemplateSpecializationKind() 176 == TSK_ExplicitInstantiationDeclaration) 177 return LangOptions::Default; 178 } else if (const VarDecl *Var = dyn_cast<VarDecl>(D)) { 179 if (Var->isStaticDataMember() && 180 (Var->getTemplateSpecializationKind() 181 == TSK_ExplicitInstantiationDeclaration)) 182 return LangOptions::Default; 183 } 184 185 // If -fvisibility-inlines-hidden was provided, then inline C++ member 186 // functions get "hidden" visibility by default. 187 if (getLangOptions().InlineVisibilityHidden) 188 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 189 if (Method->isInlined()) 190 return LangOptions::Hidden; 191 } 192 193 // This decl should have the same visibility as its parent. 194 if (const DeclContext *DC = D->getDeclContext()) 195 return getDeclVisibilityMode(cast<Decl>(DC)); 196 197 return getLangOptions().getVisibilityMode(); 198 } 199 200 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 201 const Decl *D) const { 202 // Internal definitions always have default visibility. 203 if (GV->hasLocalLinkage()) { 204 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 205 return; 206 } 207 208 switch (getDeclVisibilityMode(D)) { 209 default: assert(0 && "Unknown visibility!"); 210 case LangOptions::Default: 211 return GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 212 case LangOptions::Hidden: 213 return GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 214 case LangOptions::Protected: 215 return GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 216 } 217 } 218 219 llvm::StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 220 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 221 222 llvm::StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()]; 223 if (!Str.empty()) 224 return Str; 225 226 if (!getMangleContext().shouldMangleDeclName(ND)) { 227 IdentifierInfo *II = ND->getIdentifier(); 228 assert(II && "Attempt to mangle unnamed decl."); 229 230 Str = II->getName(); 231 return Str; 232 } 233 234 llvm::SmallString<256> Buffer; 235 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND)) 236 getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Buffer); 237 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND)) 238 getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Buffer); 239 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND)) 240 getMangleContext().mangleBlock(GD, BD, Buffer); 241 else 242 getMangleContext().mangleName(ND, Buffer); 243 244 // Allocate space for the mangled name. 245 size_t Length = Buffer.size(); 246 char *Name = MangledNamesAllocator.Allocate<char>(Length); 247 std::copy(Buffer.begin(), Buffer.end(), Name); 248 249 Str = llvm::StringRef(Name, Length); 250 251 return Str; 252 } 253 254 void CodeGenModule::getMangledName(GlobalDecl GD, MangleBuffer &Buffer, 255 const BlockDecl *BD) { 256 getMangleContext().mangleBlock(GD, BD, Buffer.getBuffer()); 257 } 258 259 llvm::GlobalValue *CodeGenModule::GetGlobalValue(llvm::StringRef Name) { 260 return getModule().getNamedValue(Name); 261 } 262 263 /// AddGlobalCtor - Add a function to the list that will be called before 264 /// main() runs. 265 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) { 266 // FIXME: Type coercion of void()* types. 267 GlobalCtors.push_back(std::make_pair(Ctor, Priority)); 268 } 269 270 /// AddGlobalDtor - Add a function to the list that will be called 271 /// when the module is unloaded. 272 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) { 273 // FIXME: Type coercion of void()* types. 274 GlobalDtors.push_back(std::make_pair(Dtor, Priority)); 275 } 276 277 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 278 // Ctor function type is void()*. 279 llvm::FunctionType* CtorFTy = 280 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), 281 std::vector<const llvm::Type*>(), 282 false); 283 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 284 285 // Get the type of a ctor entry, { i32, void ()* }. 286 llvm::StructType* CtorStructTy = 287 llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext), 288 llvm::PointerType::getUnqual(CtorFTy), NULL); 289 290 // Construct the constructor and destructor arrays. 291 std::vector<llvm::Constant*> Ctors; 292 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 293 std::vector<llvm::Constant*> S; 294 S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 295 I->second, false)); 296 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)); 297 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 298 } 299 300 if (!Ctors.empty()) { 301 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 302 new llvm::GlobalVariable(TheModule, AT, false, 303 llvm::GlobalValue::AppendingLinkage, 304 llvm::ConstantArray::get(AT, Ctors), 305 GlobalName); 306 } 307 } 308 309 void CodeGenModule::EmitAnnotations() { 310 if (Annotations.empty()) 311 return; 312 313 // Create a new global variable for the ConstantStruct in the Module. 314 llvm::Constant *Array = 315 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(), 316 Annotations.size()), 317 Annotations); 318 llvm::GlobalValue *gv = 319 new llvm::GlobalVariable(TheModule, Array->getType(), false, 320 llvm::GlobalValue::AppendingLinkage, Array, 321 "llvm.global.annotations"); 322 gv->setSection("llvm.metadata"); 323 } 324 325 static CodeGenModule::GVALinkage 326 GetLinkageForFunction(ASTContext &Context, const FunctionDecl *FD, 327 const LangOptions &Features) { 328 CodeGenModule::GVALinkage External = CodeGenModule::GVA_StrongExternal; 329 330 Linkage L = FD->getLinkage(); 331 if (L == ExternalLinkage && Context.getLangOptions().CPlusPlus && 332 FD->getType()->getLinkage() == UniqueExternalLinkage) 333 L = UniqueExternalLinkage; 334 335 switch (L) { 336 case NoLinkage: 337 case InternalLinkage: 338 case UniqueExternalLinkage: 339 return CodeGenModule::GVA_Internal; 340 341 case ExternalLinkage: 342 switch (FD->getTemplateSpecializationKind()) { 343 case TSK_Undeclared: 344 case TSK_ExplicitSpecialization: 345 External = CodeGenModule::GVA_StrongExternal; 346 break; 347 348 case TSK_ExplicitInstantiationDefinition: 349 return CodeGenModule::GVA_ExplicitTemplateInstantiation; 350 351 case TSK_ExplicitInstantiationDeclaration: 352 case TSK_ImplicitInstantiation: 353 External = CodeGenModule::GVA_TemplateInstantiation; 354 break; 355 } 356 } 357 358 if (!FD->isInlined()) 359 return External; 360 361 if (!Features.CPlusPlus || FD->hasAttr<GNUInlineAttr>()) { 362 // GNU or C99 inline semantics. Determine whether this symbol should be 363 // externally visible. 364 if (FD->isInlineDefinitionExternallyVisible()) 365 return External; 366 367 // C99 inline semantics, where the symbol is not externally visible. 368 return CodeGenModule::GVA_C99Inline; 369 } 370 371 // C++0x [temp.explicit]p9: 372 // [ Note: The intent is that an inline function that is the subject of 373 // an explicit instantiation declaration will still be implicitly 374 // instantiated when used so that the body can be considered for 375 // inlining, but that no out-of-line copy of the inline function would be 376 // generated in the translation unit. -- end note ] 377 if (FD->getTemplateSpecializationKind() 378 == TSK_ExplicitInstantiationDeclaration) 379 return CodeGenModule::GVA_C99Inline; 380 381 return CodeGenModule::GVA_CXXInline; 382 } 383 384 llvm::GlobalValue::LinkageTypes 385 CodeGenModule::getFunctionLinkage(const FunctionDecl *D) { 386 GVALinkage Linkage = GetLinkageForFunction(getContext(), D, Features); 387 388 if (Linkage == GVA_Internal) 389 return llvm::Function::InternalLinkage; 390 391 if (D->hasAttr<DLLExportAttr>()) 392 return llvm::Function::DLLExportLinkage; 393 394 if (D->hasAttr<WeakAttr>()) 395 return llvm::Function::WeakAnyLinkage; 396 397 // In C99 mode, 'inline' functions are guaranteed to have a strong 398 // definition somewhere else, so we can use available_externally linkage. 399 if (Linkage == GVA_C99Inline) 400 return llvm::Function::AvailableExternallyLinkage; 401 402 // In C++, the compiler has to emit a definition in every translation unit 403 // that references the function. We should use linkonce_odr because 404 // a) if all references in this translation unit are optimized away, we 405 // don't need to codegen it. b) if the function persists, it needs to be 406 // merged with other definitions. c) C++ has the ODR, so we know the 407 // definition is dependable. 408 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) 409 return llvm::Function::LinkOnceODRLinkage; 410 411 // An explicit instantiation of a template has weak linkage, since 412 // explicit instantiations can occur in multiple translation units 413 // and must all be equivalent. However, we are not allowed to 414 // throw away these explicit instantiations. 415 if (Linkage == GVA_ExplicitTemplateInstantiation) 416 return llvm::Function::WeakODRLinkage; 417 418 // Otherwise, we have strong external linkage. 419 assert(Linkage == GVA_StrongExternal); 420 return llvm::Function::ExternalLinkage; 421 } 422 423 424 /// SetFunctionDefinitionAttributes - Set attributes for a global. 425 /// 426 /// FIXME: This is currently only done for aliases and functions, but not for 427 /// variables (these details are set in EmitGlobalVarDefinition for variables). 428 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D, 429 llvm::GlobalValue *GV) { 430 SetCommonAttributes(D, GV); 431 } 432 433 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 434 const CGFunctionInfo &Info, 435 llvm::Function *F) { 436 unsigned CallingConv; 437 AttributeListType AttributeList; 438 ConstructAttributeList(Info, D, AttributeList, CallingConv); 439 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(), 440 AttributeList.size())); 441 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 442 } 443 444 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 445 llvm::Function *F) { 446 if (!Features.Exceptions && !Features.ObjCNonFragileABI) 447 F->addFnAttr(llvm::Attribute::NoUnwind); 448 449 if (D->hasAttr<AlwaysInlineAttr>()) 450 F->addFnAttr(llvm::Attribute::AlwaysInline); 451 452 if (D->hasAttr<NoInlineAttr>()) 453 F->addFnAttr(llvm::Attribute::NoInline); 454 455 if (Features.getStackProtectorMode() == LangOptions::SSPOn) 456 F->addFnAttr(llvm::Attribute::StackProtect); 457 else if (Features.getStackProtectorMode() == LangOptions::SSPReq) 458 F->addFnAttr(llvm::Attribute::StackProtectReq); 459 460 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>()) { 461 unsigned width = Context.Target.getCharWidth(); 462 F->setAlignment(AA->getAlignment() / width); 463 while ((AA = AA->getNext<AlignedAttr>())) 464 F->setAlignment(std::max(F->getAlignment(), AA->getAlignment() / width)); 465 } 466 // C++ ABI requires 2-byte alignment for member functions. 467 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 468 F->setAlignment(2); 469 } 470 471 void CodeGenModule::SetCommonAttributes(const Decl *D, 472 llvm::GlobalValue *GV) { 473 setGlobalVisibility(GV, D); 474 475 if (D->hasAttr<UsedAttr>()) 476 AddUsedGlobal(GV); 477 478 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 479 GV->setSection(SA->getName()); 480 481 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this); 482 } 483 484 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 485 llvm::Function *F, 486 const CGFunctionInfo &FI) { 487 SetLLVMFunctionAttributes(D, FI, F); 488 SetLLVMFunctionAttributesForDefinition(D, F); 489 490 F->setLinkage(llvm::Function::InternalLinkage); 491 492 SetCommonAttributes(D, F); 493 } 494 495 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, 496 llvm::Function *F, 497 bool IsIncompleteFunction) { 498 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 499 500 if (!IsIncompleteFunction) 501 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F); 502 503 // Only a few attributes are set on declarations; these may later be 504 // overridden by a definition. 505 506 if (FD->hasAttr<DLLImportAttr>()) { 507 F->setLinkage(llvm::Function::DLLImportLinkage); 508 } else if (FD->hasAttr<WeakAttr>() || 509 FD->hasAttr<WeakImportAttr>()) { 510 // "extern_weak" is overloaded in LLVM; we probably should have 511 // separate linkage types for this. 512 F->setLinkage(llvm::Function::ExternalWeakLinkage); 513 } else { 514 F->setLinkage(llvm::Function::ExternalLinkage); 515 } 516 517 if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 518 F->setSection(SA->getName()); 519 } 520 521 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) { 522 assert(!GV->isDeclaration() && 523 "Only globals with definition can force usage."); 524 LLVMUsed.push_back(GV); 525 } 526 527 void CodeGenModule::EmitLLVMUsed() { 528 // Don't create llvm.used if there is no need. 529 if (LLVMUsed.empty()) 530 return; 531 532 const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext); 533 534 // Convert LLVMUsed to what ConstantArray needs. 535 std::vector<llvm::Constant*> UsedArray; 536 UsedArray.resize(LLVMUsed.size()); 537 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) { 538 UsedArray[i] = 539 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]), 540 i8PTy); 541 } 542 543 if (UsedArray.empty()) 544 return; 545 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size()); 546 547 llvm::GlobalVariable *GV = 548 new llvm::GlobalVariable(getModule(), ATy, false, 549 llvm::GlobalValue::AppendingLinkage, 550 llvm::ConstantArray::get(ATy, UsedArray), 551 "llvm.used"); 552 553 GV->setSection("llvm.metadata"); 554 } 555 556 void CodeGenModule::EmitDeferred() { 557 // Emit code for any potentially referenced deferred decls. Since a 558 // previously unused static decl may become used during the generation of code 559 // for a static function, iterate until no changes are made. 560 561 while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) { 562 if (!DeferredVTables.empty()) { 563 const CXXRecordDecl *RD = DeferredVTables.back(); 564 DeferredVTables.pop_back(); 565 getVTables().GenerateClassData(getVTableLinkage(RD), RD); 566 continue; 567 } 568 569 GlobalDecl D = DeferredDeclsToEmit.back(); 570 DeferredDeclsToEmit.pop_back(); 571 572 // Check to see if we've already emitted this. This is necessary 573 // for a couple of reasons: first, decls can end up in the 574 // deferred-decls queue multiple times, and second, decls can end 575 // up with definitions in unusual ways (e.g. by an extern inline 576 // function acquiring a strong function redefinition). Just 577 // ignore these cases. 578 // 579 // TODO: That said, looking this up multiple times is very wasteful. 580 llvm::StringRef Name = getMangledName(D); 581 llvm::GlobalValue *CGRef = GetGlobalValue(Name); 582 assert(CGRef && "Deferred decl wasn't referenced?"); 583 584 if (!CGRef->isDeclaration()) 585 continue; 586 587 // GlobalAlias::isDeclaration() defers to the aliasee, but for our 588 // purposes an alias counts as a definition. 589 if (isa<llvm::GlobalAlias>(CGRef)) 590 continue; 591 592 // Otherwise, emit the definition and move on to the next one. 593 EmitGlobalDefinition(D); 594 } 595 } 596 597 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the 598 /// annotation information for a given GlobalValue. The annotation struct is 599 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the 600 /// GlobalValue being annotated. The second field is the constant string 601 /// created from the AnnotateAttr's annotation. The third field is a constant 602 /// string containing the name of the translation unit. The fourth field is 603 /// the line number in the file of the annotated value declaration. 604 /// 605 /// FIXME: this does not unique the annotation string constants, as llvm-gcc 606 /// appears to. 607 /// 608 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 609 const AnnotateAttr *AA, 610 unsigned LineNo) { 611 llvm::Module *M = &getModule(); 612 613 // get [N x i8] constants for the annotation string, and the filename string 614 // which are the 2nd and 3rd elements of the global annotation structure. 615 const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext); 616 llvm::Constant *anno = llvm::ConstantArray::get(VMContext, 617 AA->getAnnotation(), true); 618 llvm::Constant *unit = llvm::ConstantArray::get(VMContext, 619 M->getModuleIdentifier(), 620 true); 621 622 // Get the two global values corresponding to the ConstantArrays we just 623 // created to hold the bytes of the strings. 624 llvm::GlobalValue *annoGV = 625 new llvm::GlobalVariable(*M, anno->getType(), false, 626 llvm::GlobalValue::PrivateLinkage, anno, 627 GV->getName()); 628 // translation unit name string, emitted into the llvm.metadata section. 629 llvm::GlobalValue *unitGV = 630 new llvm::GlobalVariable(*M, unit->getType(), false, 631 llvm::GlobalValue::PrivateLinkage, unit, 632 ".str"); 633 634 // Create the ConstantStruct for the global annotation. 635 llvm::Constant *Fields[4] = { 636 llvm::ConstantExpr::getBitCast(GV, SBP), 637 llvm::ConstantExpr::getBitCast(annoGV, SBP), 638 llvm::ConstantExpr::getBitCast(unitGV, SBP), 639 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo) 640 }; 641 return llvm::ConstantStruct::get(VMContext, Fields, 4, false); 642 } 643 644 static CodeGenModule::GVALinkage 645 GetLinkageForVariable(ASTContext &Context, const VarDecl *VD) { 646 // If this is a static data member, compute the kind of template 647 // specialization. Otherwise, this variable is not part of a 648 // template. 649 TemplateSpecializationKind TSK = TSK_Undeclared; 650 if (VD->isStaticDataMember()) 651 TSK = VD->getTemplateSpecializationKind(); 652 653 Linkage L = VD->getLinkage(); 654 if (L == ExternalLinkage && Context.getLangOptions().CPlusPlus && 655 VD->getType()->getLinkage() == UniqueExternalLinkage) 656 L = UniqueExternalLinkage; 657 658 switch (L) { 659 case NoLinkage: 660 case InternalLinkage: 661 case UniqueExternalLinkage: 662 return CodeGenModule::GVA_Internal; 663 664 case ExternalLinkage: 665 switch (TSK) { 666 case TSK_Undeclared: 667 case TSK_ExplicitSpecialization: 668 return CodeGenModule::GVA_StrongExternal; 669 670 case TSK_ExplicitInstantiationDeclaration: 671 llvm_unreachable("Variable should not be instantiated"); 672 // Fall through to treat this like any other instantiation. 673 674 case TSK_ExplicitInstantiationDefinition: 675 return CodeGenModule::GVA_ExplicitTemplateInstantiation; 676 677 case TSK_ImplicitInstantiation: 678 return CodeGenModule::GVA_TemplateInstantiation; 679 } 680 } 681 682 return CodeGenModule::GVA_StrongExternal; 683 } 684 685 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) { 686 // Never defer when EmitAllDecls is specified or the decl has 687 // attribute used. 688 if (Features.EmitAllDecls || Global->hasAttr<UsedAttr>()) 689 return false; 690 691 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 692 // Constructors and destructors should never be deferred. 693 if (FD->hasAttr<ConstructorAttr>() || 694 FD->hasAttr<DestructorAttr>()) 695 return false; 696 697 // The key function for a class must never be deferred. 698 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Global)) { 699 const CXXRecordDecl *RD = MD->getParent(); 700 if (MD->isOutOfLine() && RD->isDynamicClass()) { 701 const CXXMethodDecl *KeyFunction = getContext().getKeyFunction(RD); 702 if (KeyFunction && 703 KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl()) 704 return false; 705 } 706 } 707 708 GVALinkage Linkage = GetLinkageForFunction(getContext(), FD, Features); 709 710 // static, static inline, always_inline, and extern inline functions can 711 // always be deferred. Normal inline functions can be deferred in C99/C++. 712 // Implicit template instantiations can also be deferred in C++. 713 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline || 714 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) 715 return true; 716 return false; 717 } 718 719 const VarDecl *VD = cast<VarDecl>(Global); 720 assert(VD->isFileVarDecl() && "Invalid decl"); 721 722 // We never want to defer structs that have non-trivial constructors or 723 // destructors. 724 725 // FIXME: Handle references. 726 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) { 727 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 728 if (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()) 729 return false; 730 } 731 } 732 733 GVALinkage L = GetLinkageForVariable(getContext(), VD); 734 if (L == GVA_Internal || L == GVA_TemplateInstantiation) { 735 if (!(VD->getInit() && VD->getInit()->HasSideEffects(Context))) 736 return true; 737 } 738 739 return false; 740 } 741 742 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 743 const AliasAttr *AA = VD->getAttr<AliasAttr>(); 744 assert(AA && "No alias?"); 745 746 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 747 748 // See if there is already something with the target's name in the module. 749 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 750 751 llvm::Constant *Aliasee; 752 if (isa<llvm::FunctionType>(DeclTy)) 753 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl()); 754 else 755 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 756 llvm::PointerType::getUnqual(DeclTy), 0); 757 if (!Entry) { 758 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee); 759 F->setLinkage(llvm::Function::ExternalWeakLinkage); 760 WeakRefReferences.insert(F); 761 } 762 763 return Aliasee; 764 } 765 766 void CodeGenModule::EmitGlobal(GlobalDecl GD) { 767 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl()); 768 769 // Weak references don't produce any output by themselves. 770 if (Global->hasAttr<WeakRefAttr>()) 771 return; 772 773 // If this is an alias definition (which otherwise looks like a declaration) 774 // emit it now. 775 if (Global->hasAttr<AliasAttr>()) 776 return EmitAliasDefinition(GD); 777 778 // Ignore declarations, they will be emitted on their first use. 779 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 780 if (FD->getIdentifier()) { 781 llvm::StringRef Name = FD->getName(); 782 if (Name == "_Block_object_assign") { 783 BlockObjectAssignDecl = FD; 784 } else if (Name == "_Block_object_dispose") { 785 BlockObjectDisposeDecl = FD; 786 } 787 } 788 789 // Forward declarations are emitted lazily on first use. 790 if (!FD->isThisDeclarationADefinition()) 791 return; 792 } else { 793 const VarDecl *VD = cast<VarDecl>(Global); 794 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 795 796 if (VD->getIdentifier()) { 797 llvm::StringRef Name = VD->getName(); 798 if (Name == "_NSConcreteGlobalBlock") { 799 NSConcreteGlobalBlockDecl = VD; 800 } else if (Name == "_NSConcreteStackBlock") { 801 NSConcreteStackBlockDecl = VD; 802 } 803 } 804 805 806 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) 807 return; 808 } 809 810 // Defer code generation when possible if this is a static definition, inline 811 // function etc. These we only want to emit if they are used. 812 if (!MayDeferGeneration(Global)) { 813 // Emit the definition if it can't be deferred. 814 EmitGlobalDefinition(GD); 815 return; 816 } 817 818 // If we're deferring emission of a C++ variable with an 819 // initializer, remember the order in which it appeared in the file. 820 if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) && 821 cast<VarDecl>(Global)->hasInit()) { 822 DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 823 CXXGlobalInits.push_back(0); 824 } 825 826 // If the value has already been used, add it directly to the 827 // DeferredDeclsToEmit list. 828 llvm::StringRef MangledName = getMangledName(GD); 829 if (GetGlobalValue(MangledName)) 830 DeferredDeclsToEmit.push_back(GD); 831 else { 832 // Otherwise, remember that we saw a deferred decl with this name. The 833 // first use of the mangled name will cause it to move into 834 // DeferredDeclsToEmit. 835 DeferredDecls[MangledName] = GD; 836 } 837 } 838 839 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) { 840 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 841 842 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 843 Context.getSourceManager(), 844 "Generating code for declaration"); 845 846 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 847 // At -O0, don't generate IR for functions with available_externally 848 // linkage. 849 if (CodeGenOpts.OptimizationLevel == 0 && 850 !Function->hasAttr<AlwaysInlineAttr>() && 851 getFunctionLinkage(Function) 852 == llvm::Function::AvailableExternallyLinkage) 853 return; 854 855 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 856 if (Method->isVirtual()) 857 getVTables().EmitThunks(GD); 858 859 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method)) 860 return EmitCXXConstructor(CD, GD.getCtorType()); 861 862 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(Method)) 863 return EmitCXXDestructor(DD, GD.getDtorType()); 864 } 865 866 return EmitGlobalFunctionDefinition(GD); 867 } 868 869 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 870 return EmitGlobalVarDefinition(VD); 871 872 assert(0 && "Invalid argument to EmitGlobalDefinition()"); 873 } 874 875 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 876 /// module, create and return an llvm Function with the specified type. If there 877 /// is something in the module with the specified name, return it potentially 878 /// bitcasted to the right type. 879 /// 880 /// If D is non-null, it specifies a decl that correspond to this. This is used 881 /// to set the attributes on the function when it is first created. 882 llvm::Constant * 883 CodeGenModule::GetOrCreateLLVMFunction(llvm::StringRef MangledName, 884 const llvm::Type *Ty, 885 GlobalDecl D) { 886 // Lookup the entry, lazily creating it if necessary. 887 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 888 if (Entry) { 889 if (WeakRefReferences.count(Entry)) { 890 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl()); 891 if (FD && !FD->hasAttr<WeakAttr>()) 892 Entry->setLinkage(llvm::Function::ExternalLinkage); 893 894 WeakRefReferences.erase(Entry); 895 } 896 897 if (Entry->getType()->getElementType() == Ty) 898 return Entry; 899 900 // Make sure the result is of the correct type. 901 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 902 return llvm::ConstantExpr::getBitCast(Entry, PTy); 903 } 904 905 // This function doesn't have a complete type (for example, the return 906 // type is an incomplete struct). Use a fake type instead, and make 907 // sure not to try to set attributes. 908 bool IsIncompleteFunction = false; 909 910 const llvm::FunctionType *FTy; 911 if (isa<llvm::FunctionType>(Ty)) { 912 FTy = cast<llvm::FunctionType>(Ty); 913 } else { 914 FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), 915 std::vector<const llvm::Type*>(), false); 916 IsIncompleteFunction = true; 917 } 918 919 llvm::Function *F = llvm::Function::Create(FTy, 920 llvm::Function::ExternalLinkage, 921 MangledName, &getModule()); 922 assert(F->getName() == MangledName && "name was uniqued!"); 923 if (D.getDecl()) 924 SetFunctionAttributes(D, F, IsIncompleteFunction); 925 926 // This is the first use or definition of a mangled name. If there is a 927 // deferred decl with this name, remember that we need to emit it at the end 928 // of the file. 929 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 930 if (DDI != DeferredDecls.end()) { 931 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 932 // list, and remove it from DeferredDecls (since we don't need it anymore). 933 DeferredDeclsToEmit.push_back(DDI->second); 934 DeferredDecls.erase(DDI); 935 } else if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl())) { 936 // If this the first reference to a C++ inline function in a class, queue up 937 // the deferred function body for emission. These are not seen as 938 // top-level declarations. 939 if (FD->isThisDeclarationADefinition() && MayDeferGeneration(FD)) 940 DeferredDeclsToEmit.push_back(D); 941 // A called constructor which has no definition or declaration need be 942 // synthesized. 943 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 944 if (CD->isImplicit()) { 945 assert(CD->isUsed() && "Sema doesn't consider constructor as used."); 946 DeferredDeclsToEmit.push_back(D); 947 } 948 } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) { 949 if (DD->isImplicit()) { 950 assert(DD->isUsed() && "Sema doesn't consider destructor as used."); 951 DeferredDeclsToEmit.push_back(D); 952 } 953 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 954 if (MD->isCopyAssignment() && MD->isImplicit()) { 955 assert(MD->isUsed() && "Sema doesn't consider CopyAssignment as used."); 956 DeferredDeclsToEmit.push_back(D); 957 } 958 } 959 } 960 961 // Make sure the result is of the requested type. 962 if (!IsIncompleteFunction) { 963 assert(F->getType()->getElementType() == Ty); 964 return F; 965 } 966 967 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 968 return llvm::ConstantExpr::getBitCast(F, PTy); 969 } 970 971 /// GetAddrOfFunction - Return the address of the given function. If Ty is 972 /// non-null, then this function will use the specified type if it has to 973 /// create it (this occurs when we see a definition of the function). 974 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 975 const llvm::Type *Ty) { 976 // If there was no specific requested type, just convert it now. 977 if (!Ty) 978 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType()); 979 980 llvm::StringRef MangledName = getMangledName(GD); 981 return GetOrCreateLLVMFunction(MangledName, Ty, GD); 982 } 983 984 /// CreateRuntimeFunction - Create a new runtime function with the specified 985 /// type and name. 986 llvm::Constant * 987 CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy, 988 llvm::StringRef Name) { 989 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl()); 990 } 991 992 static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) { 993 if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType()) 994 return false; 995 if (Context.getLangOptions().CPlusPlus && 996 Context.getBaseElementType(D->getType())->getAs<RecordType>()) { 997 // FIXME: We should do something fancier here! 998 return false; 999 } 1000 return true; 1001 } 1002 1003 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 1004 /// create and return an llvm GlobalVariable with the specified type. If there 1005 /// is something in the module with the specified name, return it potentially 1006 /// bitcasted to the right type. 1007 /// 1008 /// If D is non-null, it specifies a decl that correspond to this. This is used 1009 /// to set the attributes on the global when it is first created. 1010 llvm::Constant * 1011 CodeGenModule::GetOrCreateLLVMGlobal(llvm::StringRef MangledName, 1012 const llvm::PointerType *Ty, 1013 const VarDecl *D) { 1014 // Lookup the entry, lazily creating it if necessary. 1015 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1016 if (Entry) { 1017 if (WeakRefReferences.count(Entry)) { 1018 if (D && !D->hasAttr<WeakAttr>()) 1019 Entry->setLinkage(llvm::Function::ExternalLinkage); 1020 1021 WeakRefReferences.erase(Entry); 1022 } 1023 1024 if (Entry->getType() == Ty) 1025 return Entry; 1026 1027 // Make sure the result is of the correct type. 1028 return llvm::ConstantExpr::getBitCast(Entry, Ty); 1029 } 1030 1031 // This is the first use or definition of a mangled name. If there is a 1032 // deferred decl with this name, remember that we need to emit it at the end 1033 // of the file. 1034 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 1035 if (DDI != DeferredDecls.end()) { 1036 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 1037 // list, and remove it from DeferredDecls (since we don't need it anymore). 1038 DeferredDeclsToEmit.push_back(DDI->second); 1039 DeferredDecls.erase(DDI); 1040 } 1041 1042 llvm::GlobalVariable *GV = 1043 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false, 1044 llvm::GlobalValue::ExternalLinkage, 1045 0, MangledName, 0, 1046 false, Ty->getAddressSpace()); 1047 1048 // Handle things which are present even on external declarations. 1049 if (D) { 1050 // FIXME: This code is overly simple and should be merged with other global 1051 // handling. 1052 GV->setConstant(DeclIsConstantGlobal(Context, D)); 1053 1054 // FIXME: Merge with other attribute handling code. 1055 if (D->getStorageClass() == VarDecl::PrivateExtern) 1056 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 1057 1058 if (D->hasAttr<WeakAttr>() || 1059 D->hasAttr<WeakImportAttr>()) 1060 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 1061 1062 GV->setThreadLocal(D->isThreadSpecified()); 1063 } 1064 1065 return GV; 1066 } 1067 1068 1069 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 1070 /// given global variable. If Ty is non-null and if the global doesn't exist, 1071 /// then it will be greated with the specified type instead of whatever the 1072 /// normal requested type would be. 1073 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 1074 const llvm::Type *Ty) { 1075 assert(D->hasGlobalStorage() && "Not a global variable"); 1076 QualType ASTTy = D->getType(); 1077 if (Ty == 0) 1078 Ty = getTypes().ConvertTypeForMem(ASTTy); 1079 1080 const llvm::PointerType *PTy = 1081 llvm::PointerType::get(Ty, ASTTy.getAddressSpace()); 1082 1083 llvm::StringRef MangledName = getMangledName(D); 1084 return GetOrCreateLLVMGlobal(MangledName, PTy, D); 1085 } 1086 1087 /// CreateRuntimeVariable - Create a new runtime global variable with the 1088 /// specified type and name. 1089 llvm::Constant * 1090 CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty, 1091 llvm::StringRef Name) { 1092 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0); 1093 } 1094 1095 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 1096 assert(!D->getInit() && "Cannot emit definite definitions here!"); 1097 1098 if (MayDeferGeneration(D)) { 1099 // If we have not seen a reference to this variable yet, place it 1100 // into the deferred declarations table to be emitted if needed 1101 // later. 1102 llvm::StringRef MangledName = getMangledName(D); 1103 if (!GetGlobalValue(MangledName)) { 1104 DeferredDecls[MangledName] = D; 1105 return; 1106 } 1107 } 1108 1109 // The tentative definition is the only definition. 1110 EmitGlobalVarDefinition(D); 1111 } 1112 1113 void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) { 1114 if (DefinitionRequired) 1115 getVTables().GenerateClassData(getVTableLinkage(Class), Class); 1116 } 1117 1118 llvm::GlobalVariable::LinkageTypes 1119 CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) { 1120 if (RD->isInAnonymousNamespace() || !RD->hasLinkage()) 1121 return llvm::GlobalVariable::InternalLinkage; 1122 1123 if (const CXXMethodDecl *KeyFunction 1124 = RD->getASTContext().getKeyFunction(RD)) { 1125 // If this class has a key function, use that to determine the linkage of 1126 // the vtable. 1127 const FunctionDecl *Def = 0; 1128 if (KeyFunction->hasBody(Def)) 1129 KeyFunction = cast<CXXMethodDecl>(Def); 1130 1131 switch (KeyFunction->getTemplateSpecializationKind()) { 1132 case TSK_Undeclared: 1133 case TSK_ExplicitSpecialization: 1134 if (KeyFunction->isInlined()) 1135 return llvm::GlobalVariable::WeakODRLinkage; 1136 1137 return llvm::GlobalVariable::ExternalLinkage; 1138 1139 case TSK_ImplicitInstantiation: 1140 case TSK_ExplicitInstantiationDefinition: 1141 return llvm::GlobalVariable::WeakODRLinkage; 1142 1143 case TSK_ExplicitInstantiationDeclaration: 1144 // FIXME: Use available_externally linkage. However, this currently 1145 // breaks LLVM's build due to undefined symbols. 1146 // return llvm::GlobalVariable::AvailableExternallyLinkage; 1147 return llvm::GlobalVariable::WeakODRLinkage; 1148 } 1149 } 1150 1151 switch (RD->getTemplateSpecializationKind()) { 1152 case TSK_Undeclared: 1153 case TSK_ExplicitSpecialization: 1154 case TSK_ImplicitInstantiation: 1155 case TSK_ExplicitInstantiationDefinition: 1156 return llvm::GlobalVariable::WeakODRLinkage; 1157 1158 case TSK_ExplicitInstantiationDeclaration: 1159 // FIXME: Use available_externally linkage. However, this currently 1160 // breaks LLVM's build due to undefined symbols. 1161 // return llvm::GlobalVariable::AvailableExternallyLinkage; 1162 return llvm::GlobalVariable::WeakODRLinkage; 1163 } 1164 1165 // Silence GCC warning. 1166 return llvm::GlobalVariable::WeakODRLinkage; 1167 } 1168 1169 CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const { 1170 return CharUnits::fromQuantity( 1171 TheTargetData.getTypeStoreSizeInBits(Ty) / Context.getCharWidth()); 1172 } 1173 1174 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 1175 llvm::Constant *Init = 0; 1176 QualType ASTTy = D->getType(); 1177 bool NonConstInit = false; 1178 1179 const Expr *InitExpr = D->getAnyInitializer(); 1180 1181 if (!InitExpr) { 1182 // This is a tentative definition; tentative definitions are 1183 // implicitly initialized with { 0 }. 1184 // 1185 // Note that tentative definitions are only emitted at the end of 1186 // a translation unit, so they should never have incomplete 1187 // type. In addition, EmitTentativeDefinition makes sure that we 1188 // never attempt to emit a tentative definition if a real one 1189 // exists. A use may still exists, however, so we still may need 1190 // to do a RAUW. 1191 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 1192 Init = EmitNullConstant(D->getType()); 1193 } else { 1194 Init = EmitConstantExpr(InitExpr, D->getType()); 1195 if (!Init) { 1196 QualType T = InitExpr->getType(); 1197 if (D->getType()->isReferenceType()) 1198 T = D->getType(); 1199 1200 if (getLangOptions().CPlusPlus) { 1201 EmitCXXGlobalVarDeclInitFunc(D); 1202 Init = EmitNullConstant(T); 1203 NonConstInit = true; 1204 } else { 1205 ErrorUnsupported(D, "static initializer"); 1206 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 1207 } 1208 } else { 1209 // We don't need an initializer, so remove the entry for the delayed 1210 // initializer position (just in case this entry was delayed). 1211 if (getLangOptions().CPlusPlus) 1212 DelayedCXXInitPosition.erase(D); 1213 } 1214 } 1215 1216 const llvm::Type* InitType = Init->getType(); 1217 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 1218 1219 // Strip off a bitcast if we got one back. 1220 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1221 assert(CE->getOpcode() == llvm::Instruction::BitCast || 1222 // all zero index gep. 1223 CE->getOpcode() == llvm::Instruction::GetElementPtr); 1224 Entry = CE->getOperand(0); 1225 } 1226 1227 // Entry is now either a Function or GlobalVariable. 1228 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry); 1229 1230 // We have a definition after a declaration with the wrong type. 1231 // We must make a new GlobalVariable* and update everything that used OldGV 1232 // (a declaration or tentative definition) with the new GlobalVariable* 1233 // (which will be a definition). 1234 // 1235 // This happens if there is a prototype for a global (e.g. 1236 // "extern int x[];") and then a definition of a different type (e.g. 1237 // "int x[10];"). This also happens when an initializer has a different type 1238 // from the type of the global (this happens with unions). 1239 if (GV == 0 || 1240 GV->getType()->getElementType() != InitType || 1241 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) { 1242 1243 // Move the old entry aside so that we'll create a new one. 1244 Entry->setName(llvm::StringRef()); 1245 1246 // Make a new global with the correct type, this is now guaranteed to work. 1247 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 1248 1249 // Replace all uses of the old global with the new global 1250 llvm::Constant *NewPtrForOldDecl = 1251 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 1252 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1253 1254 // Erase the old global, since it is no longer used. 1255 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 1256 } 1257 1258 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) { 1259 SourceManager &SM = Context.getSourceManager(); 1260 AddAnnotation(EmitAnnotateAttr(GV, AA, 1261 SM.getInstantiationLineNumber(D->getLocation()))); 1262 } 1263 1264 GV->setInitializer(Init); 1265 1266 // If it is safe to mark the global 'constant', do so now. 1267 GV->setConstant(false); 1268 if (!NonConstInit && DeclIsConstantGlobal(Context, D)) 1269 GV->setConstant(true); 1270 1271 GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 1272 1273 // Set the llvm linkage type as appropriate. 1274 GVALinkage Linkage = GetLinkageForVariable(getContext(), D); 1275 if (Linkage == GVA_Internal) 1276 GV->setLinkage(llvm::Function::InternalLinkage); 1277 else if (D->hasAttr<DLLImportAttr>()) 1278 GV->setLinkage(llvm::Function::DLLImportLinkage); 1279 else if (D->hasAttr<DLLExportAttr>()) 1280 GV->setLinkage(llvm::Function::DLLExportLinkage); 1281 else if (D->hasAttr<WeakAttr>()) { 1282 if (GV->isConstant()) 1283 GV->setLinkage(llvm::GlobalVariable::WeakODRLinkage); 1284 else 1285 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 1286 } else if (Linkage == GVA_TemplateInstantiation || 1287 Linkage == GVA_ExplicitTemplateInstantiation) 1288 // FIXME: It seems like we can provide more specific linkage here 1289 // (LinkOnceODR, WeakODR). 1290 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 1291 else if (!getLangOptions().CPlusPlus && !CodeGenOpts.NoCommon && 1292 !D->hasExternalStorage() && !D->getInit() && 1293 !D->getAttr<SectionAttr>()) { 1294 GV->setLinkage(llvm::GlobalVariable::CommonLinkage); 1295 // common vars aren't constant even if declared const. 1296 GV->setConstant(false); 1297 } else 1298 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage); 1299 1300 SetCommonAttributes(D, GV); 1301 1302 // Emit global variable debug information. 1303 if (CGDebugInfo *DI = getDebugInfo()) { 1304 DI->setLocation(D->getLocation()); 1305 DI->EmitGlobalVariable(GV, D); 1306 } 1307 } 1308 1309 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 1310 /// implement a function with no prototype, e.g. "int foo() {}". If there are 1311 /// existing call uses of the old function in the module, this adjusts them to 1312 /// call the new function directly. 1313 /// 1314 /// This is not just a cleanup: the always_inline pass requires direct calls to 1315 /// functions to be able to inline them. If there is a bitcast in the way, it 1316 /// won't inline them. Instcombine normally deletes these calls, but it isn't 1317 /// run at -O0. 1318 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 1319 llvm::Function *NewFn) { 1320 // If we're redefining a global as a function, don't transform it. 1321 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old); 1322 if (OldFn == 0) return; 1323 1324 const llvm::Type *NewRetTy = NewFn->getReturnType(); 1325 llvm::SmallVector<llvm::Value*, 4> ArgList; 1326 1327 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end(); 1328 UI != E; ) { 1329 // TODO: Do invokes ever occur in C code? If so, we should handle them too. 1330 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased. 1331 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I); 1332 if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I) 1333 llvm::CallSite CS(CI); 1334 if (!CI || !CS.isCallee(I)) continue; 1335 1336 // If the return types don't match exactly, and if the call isn't dead, then 1337 // we can't transform this call. 1338 if (CI->getType() != NewRetTy && !CI->use_empty()) 1339 continue; 1340 1341 // If the function was passed too few arguments, don't transform. If extra 1342 // arguments were passed, we silently drop them. If any of the types 1343 // mismatch, we don't transform. 1344 unsigned ArgNo = 0; 1345 bool DontTransform = false; 1346 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(), 1347 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) { 1348 if (CS.arg_size() == ArgNo || 1349 CS.getArgument(ArgNo)->getType() != AI->getType()) { 1350 DontTransform = true; 1351 break; 1352 } 1353 } 1354 if (DontTransform) 1355 continue; 1356 1357 // Okay, we can transform this. Create the new call instruction and copy 1358 // over the required information. 1359 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo); 1360 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(), 1361 ArgList.end(), "", CI); 1362 ArgList.clear(); 1363 if (!NewCall->getType()->isVoidTy()) 1364 NewCall->takeName(CI); 1365 NewCall->setAttributes(CI->getAttributes()); 1366 NewCall->setCallingConv(CI->getCallingConv()); 1367 1368 // Finally, remove the old call, replacing any uses with the new one. 1369 if (!CI->use_empty()) 1370 CI->replaceAllUsesWith(NewCall); 1371 1372 // Copy debug location attached to CI. 1373 if (!CI->getDebugLoc().isUnknown()) 1374 NewCall->setDebugLoc(CI->getDebugLoc()); 1375 CI->eraseFromParent(); 1376 } 1377 } 1378 1379 1380 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) { 1381 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl()); 1382 const llvm::FunctionType *Ty = getTypes().GetFunctionType(GD); 1383 getMangleContext().mangleInitDiscriminator(); 1384 // Get or create the prototype for the function. 1385 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty); 1386 1387 // Strip off a bitcast if we got one back. 1388 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1389 assert(CE->getOpcode() == llvm::Instruction::BitCast); 1390 Entry = CE->getOperand(0); 1391 } 1392 1393 1394 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) { 1395 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry); 1396 1397 // If the types mismatch then we have to rewrite the definition. 1398 assert(OldFn->isDeclaration() && 1399 "Shouldn't replace non-declaration"); 1400 1401 // F is the Function* for the one with the wrong type, we must make a new 1402 // Function* and update everything that used F (a declaration) with the new 1403 // Function* (which will be a definition). 1404 // 1405 // This happens if there is a prototype for a function 1406 // (e.g. "int f()") and then a definition of a different type 1407 // (e.g. "int f(int x)"). Move the old function aside so that it 1408 // doesn't interfere with GetAddrOfFunction. 1409 OldFn->setName(llvm::StringRef()); 1410 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty)); 1411 1412 // If this is an implementation of a function without a prototype, try to 1413 // replace any existing uses of the function (which may be calls) with uses 1414 // of the new function 1415 if (D->getType()->isFunctionNoProtoType()) { 1416 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn); 1417 OldFn->removeDeadConstantUsers(); 1418 } 1419 1420 // Replace uses of F with the Function we will endow with a body. 1421 if (!Entry->use_empty()) { 1422 llvm::Constant *NewPtrForOldDecl = 1423 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType()); 1424 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1425 } 1426 1427 // Ok, delete the old function now, which is dead. 1428 OldFn->eraseFromParent(); 1429 1430 Entry = NewFn; 1431 } 1432 1433 llvm::Function *Fn = cast<llvm::Function>(Entry); 1434 setFunctionLinkage(D, Fn); 1435 1436 CodeGenFunction(*this).GenerateCode(D, Fn); 1437 1438 SetFunctionDefinitionAttributes(D, Fn); 1439 SetLLVMFunctionAttributesForDefinition(D, Fn); 1440 1441 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 1442 AddGlobalCtor(Fn, CA->getPriority()); 1443 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 1444 AddGlobalDtor(Fn, DA->getPriority()); 1445 } 1446 1447 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 1448 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 1449 const AliasAttr *AA = D->getAttr<AliasAttr>(); 1450 assert(AA && "Not an alias?"); 1451 1452 llvm::StringRef MangledName = getMangledName(GD); 1453 1454 // If there is a definition in the module, then it wins over the alias. 1455 // This is dubious, but allow it to be safe. Just ignore the alias. 1456 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1457 if (Entry && !Entry->isDeclaration()) 1458 return; 1459 1460 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 1461 1462 // Create a reference to the named value. This ensures that it is emitted 1463 // if a deferred decl. 1464 llvm::Constant *Aliasee; 1465 if (isa<llvm::FunctionType>(DeclTy)) 1466 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl()); 1467 else 1468 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 1469 llvm::PointerType::getUnqual(DeclTy), 0); 1470 1471 // Create the new alias itself, but don't set a name yet. 1472 llvm::GlobalValue *GA = 1473 new llvm::GlobalAlias(Aliasee->getType(), 1474 llvm::Function::ExternalLinkage, 1475 "", Aliasee, &getModule()); 1476 1477 if (Entry) { 1478 assert(Entry->isDeclaration()); 1479 1480 // If there is a declaration in the module, then we had an extern followed 1481 // by the alias, as in: 1482 // extern int test6(); 1483 // ... 1484 // int test6() __attribute__((alias("test7"))); 1485 // 1486 // Remove it and replace uses of it with the alias. 1487 GA->takeName(Entry); 1488 1489 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 1490 Entry->getType())); 1491 Entry->eraseFromParent(); 1492 } else { 1493 GA->setName(MangledName); 1494 } 1495 1496 // Set attributes which are particular to an alias; this is a 1497 // specialization of the attributes which may be set on a global 1498 // variable/function. 1499 if (D->hasAttr<DLLExportAttr>()) { 1500 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1501 // The dllexport attribute is ignored for undefined symbols. 1502 if (FD->hasBody()) 1503 GA->setLinkage(llvm::Function::DLLExportLinkage); 1504 } else { 1505 GA->setLinkage(llvm::Function::DLLExportLinkage); 1506 } 1507 } else if (D->hasAttr<WeakAttr>() || 1508 D->hasAttr<WeakRefAttr>() || 1509 D->hasAttr<WeakImportAttr>()) { 1510 GA->setLinkage(llvm::Function::WeakAnyLinkage); 1511 } 1512 1513 SetCommonAttributes(D, GA); 1514 } 1515 1516 /// getBuiltinLibFunction - Given a builtin id for a function like 1517 /// "__builtin_fabsf", return a Function* for "fabsf". 1518 llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD, 1519 unsigned BuiltinID) { 1520 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) || 1521 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) && 1522 "isn't a lib fn"); 1523 1524 // Get the name, skip over the __builtin_ prefix (if necessary). 1525 const char *Name = Context.BuiltinInfo.GetName(BuiltinID); 1526 if (Context.BuiltinInfo.isLibFunction(BuiltinID)) 1527 Name += 10; 1528 1529 const llvm::FunctionType *Ty = 1530 cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType())); 1531 1532 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD)); 1533 } 1534 1535 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys, 1536 unsigned NumTys) { 1537 return llvm::Intrinsic::getDeclaration(&getModule(), 1538 (llvm::Intrinsic::ID)IID, Tys, NumTys); 1539 } 1540 1541 1542 llvm::Function *CodeGenModule::getMemCpyFn(const llvm::Type *DestType, 1543 const llvm::Type *SrcType, 1544 const llvm::Type *SizeType) { 1545 const llvm::Type *ArgTypes[3] = {DestType, SrcType, SizeType }; 1546 return getIntrinsic(llvm::Intrinsic::memcpy, ArgTypes, 3); 1547 } 1548 1549 llvm::Function *CodeGenModule::getMemMoveFn(const llvm::Type *DestType, 1550 const llvm::Type *SrcType, 1551 const llvm::Type *SizeType) { 1552 const llvm::Type *ArgTypes[3] = {DestType, SrcType, SizeType }; 1553 return getIntrinsic(llvm::Intrinsic::memmove, ArgTypes, 3); 1554 } 1555 1556 llvm::Function *CodeGenModule::getMemSetFn(const llvm::Type *DestType, 1557 const llvm::Type *SizeType) { 1558 const llvm::Type *ArgTypes[2] = { DestType, SizeType }; 1559 return getIntrinsic(llvm::Intrinsic::memset, ArgTypes, 2); 1560 } 1561 1562 static llvm::StringMapEntry<llvm::Constant*> & 1563 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map, 1564 const StringLiteral *Literal, 1565 bool TargetIsLSB, 1566 bool &IsUTF16, 1567 unsigned &StringLength) { 1568 unsigned NumBytes = Literal->getByteLength(); 1569 1570 // Check for simple case. 1571 if (!Literal->containsNonAsciiOrNull()) { 1572 StringLength = NumBytes; 1573 return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(), 1574 StringLength)); 1575 } 1576 1577 // Otherwise, convert the UTF8 literals into a byte string. 1578 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes); 1579 const UTF8 *FromPtr = (UTF8 *)Literal->getStrData(); 1580 UTF16 *ToPtr = &ToBuf[0]; 1581 1582 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 1583 &ToPtr, ToPtr + NumBytes, 1584 strictConversion); 1585 1586 // Check for conversion failure. 1587 if (Result != conversionOK) { 1588 // FIXME: Have Sema::CheckObjCString() validate the UTF-8 string and remove 1589 // this duplicate code. 1590 assert(Result == sourceIllegal && "UTF-8 to UTF-16 conversion failed"); 1591 StringLength = NumBytes; 1592 return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(), 1593 StringLength)); 1594 } 1595 1596 // ConvertUTF8toUTF16 returns the length in ToPtr. 1597 StringLength = ToPtr - &ToBuf[0]; 1598 1599 // Render the UTF-16 string into a byte array and convert to the target byte 1600 // order. 1601 // 1602 // FIXME: This isn't something we should need to do here. 1603 llvm::SmallString<128> AsBytes; 1604 AsBytes.reserve(StringLength * 2); 1605 for (unsigned i = 0; i != StringLength; ++i) { 1606 unsigned short Val = ToBuf[i]; 1607 if (TargetIsLSB) { 1608 AsBytes.push_back(Val & 0xFF); 1609 AsBytes.push_back(Val >> 8); 1610 } else { 1611 AsBytes.push_back(Val >> 8); 1612 AsBytes.push_back(Val & 0xFF); 1613 } 1614 } 1615 // Append one extra null character, the second is automatically added by our 1616 // caller. 1617 AsBytes.push_back(0); 1618 1619 IsUTF16 = true; 1620 return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size())); 1621 } 1622 1623 llvm::Constant * 1624 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 1625 unsigned StringLength = 0; 1626 bool isUTF16 = false; 1627 llvm::StringMapEntry<llvm::Constant*> &Entry = 1628 GetConstantCFStringEntry(CFConstantStringMap, Literal, 1629 getTargetData().isLittleEndian(), 1630 isUTF16, StringLength); 1631 1632 if (llvm::Constant *C = Entry.getValue()) 1633 return C; 1634 1635 llvm::Constant *Zero = 1636 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)); 1637 llvm::Constant *Zeros[] = { Zero, Zero }; 1638 1639 // If we don't already have it, get __CFConstantStringClassReference. 1640 if (!CFConstantStringClassRef) { 1641 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 1642 Ty = llvm::ArrayType::get(Ty, 0); 1643 llvm::Constant *GV = CreateRuntimeVariable(Ty, 1644 "__CFConstantStringClassReference"); 1645 // Decay array -> ptr 1646 CFConstantStringClassRef = 1647 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1648 } 1649 1650 QualType CFTy = getContext().getCFConstantStringType(); 1651 1652 const llvm::StructType *STy = 1653 cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 1654 1655 std::vector<llvm::Constant*> Fields(4); 1656 1657 // Class pointer. 1658 Fields[0] = CFConstantStringClassRef; 1659 1660 // Flags. 1661 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 1662 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 1663 llvm::ConstantInt::get(Ty, 0x07C8); 1664 1665 // String pointer. 1666 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str()); 1667 1668 llvm::GlobalValue::LinkageTypes Linkage; 1669 bool isConstant; 1670 if (isUTF16) { 1671 // FIXME: why do utf strings get "_" labels instead of "L" labels? 1672 Linkage = llvm::GlobalValue::InternalLinkage; 1673 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but 1674 // does make plain ascii ones writable. 1675 isConstant = true; 1676 } else { 1677 Linkage = llvm::GlobalValue::PrivateLinkage; 1678 isConstant = !Features.WritableStrings; 1679 } 1680 1681 llvm::GlobalVariable *GV = 1682 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 1683 ".str"); 1684 if (isUTF16) { 1685 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 1686 GV->setAlignment(Align.getQuantity()); 1687 } 1688 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1689 1690 // String length. 1691 Ty = getTypes().ConvertType(getContext().LongTy); 1692 Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 1693 1694 // The struct. 1695 C = llvm::ConstantStruct::get(STy, Fields); 1696 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 1697 llvm::GlobalVariable::PrivateLinkage, C, 1698 "_unnamed_cfstring_"); 1699 if (const char *Sect = getContext().Target.getCFStringSection()) 1700 GV->setSection(Sect); 1701 Entry.setValue(GV); 1702 1703 return GV; 1704 } 1705 1706 llvm::Constant * 1707 CodeGenModule::GetAddrOfConstantNSString(const StringLiteral *Literal) { 1708 unsigned StringLength = 0; 1709 bool isUTF16 = false; 1710 llvm::StringMapEntry<llvm::Constant*> &Entry = 1711 GetConstantCFStringEntry(CFConstantStringMap, Literal, 1712 getTargetData().isLittleEndian(), 1713 isUTF16, StringLength); 1714 1715 if (llvm::Constant *C = Entry.getValue()) 1716 return C; 1717 1718 llvm::Constant *Zero = 1719 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)); 1720 llvm::Constant *Zeros[] = { Zero, Zero }; 1721 1722 // If we don't already have it, get _NSConstantStringClassReference. 1723 if (!NSConstantStringClassRef) { 1724 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 1725 Ty = llvm::ArrayType::get(Ty, 0); 1726 llvm::Constant *GV = CreateRuntimeVariable(Ty, 1727 Features.ObjCNonFragileABI ? 1728 "OBJC_CLASS_$_NSConstantString" : 1729 "_NSConstantStringClassReference"); 1730 // Decay array -> ptr 1731 NSConstantStringClassRef = 1732 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1733 } 1734 1735 QualType NSTy = getContext().getNSConstantStringType(); 1736 1737 const llvm::StructType *STy = 1738 cast<llvm::StructType>(getTypes().ConvertType(NSTy)); 1739 1740 std::vector<llvm::Constant*> Fields(3); 1741 1742 // Class pointer. 1743 Fields[0] = NSConstantStringClassRef; 1744 1745 // String pointer. 1746 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str()); 1747 1748 llvm::GlobalValue::LinkageTypes Linkage; 1749 bool isConstant; 1750 if (isUTF16) { 1751 // FIXME: why do utf strings get "_" labels instead of "L" labels? 1752 Linkage = llvm::GlobalValue::InternalLinkage; 1753 // Note: -fwritable-strings doesn't make unicode NSStrings writable, but 1754 // does make plain ascii ones writable. 1755 isConstant = true; 1756 } else { 1757 Linkage = llvm::GlobalValue::PrivateLinkage; 1758 isConstant = !Features.WritableStrings; 1759 } 1760 1761 llvm::GlobalVariable *GV = 1762 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 1763 ".str"); 1764 if (isUTF16) { 1765 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 1766 GV->setAlignment(Align.getQuantity()); 1767 } 1768 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1769 1770 // String length. 1771 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 1772 Fields[2] = llvm::ConstantInt::get(Ty, StringLength); 1773 1774 // The struct. 1775 C = llvm::ConstantStruct::get(STy, Fields); 1776 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 1777 llvm::GlobalVariable::PrivateLinkage, C, 1778 "_unnamed_nsstring_"); 1779 // FIXME. Fix section. 1780 if (const char *Sect = 1781 Features.ObjCNonFragileABI 1782 ? getContext().Target.getNSStringNonFragileABISection() 1783 : getContext().Target.getNSStringSection()) 1784 GV->setSection(Sect); 1785 Entry.setValue(GV); 1786 1787 return GV; 1788 } 1789 1790 /// GetStringForStringLiteral - Return the appropriate bytes for a 1791 /// string literal, properly padded to match the literal type. 1792 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) { 1793 const char *StrData = E->getStrData(); 1794 unsigned Len = E->getByteLength(); 1795 1796 const ConstantArrayType *CAT = 1797 getContext().getAsConstantArrayType(E->getType()); 1798 assert(CAT && "String isn't pointer or array!"); 1799 1800 // Resize the string to the right size. 1801 std::string Str(StrData, StrData+Len); 1802 uint64_t RealLen = CAT->getSize().getZExtValue(); 1803 1804 if (E->isWide()) 1805 RealLen *= getContext().Target.getWCharWidth()/8; 1806 1807 Str.resize(RealLen, '\0'); 1808 1809 return Str; 1810 } 1811 1812 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 1813 /// constant array for the given string literal. 1814 llvm::Constant * 1815 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 1816 // FIXME: This can be more efficient. 1817 // FIXME: We shouldn't need to bitcast the constant in the wide string case. 1818 llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S)); 1819 if (S->isWide()) { 1820 llvm::Type *DestTy = 1821 llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType())); 1822 C = llvm::ConstantExpr::getBitCast(C, DestTy); 1823 } 1824 return C; 1825 } 1826 1827 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 1828 /// array for the given ObjCEncodeExpr node. 1829 llvm::Constant * 1830 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 1831 std::string Str; 1832 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 1833 1834 return GetAddrOfConstantCString(Str); 1835 } 1836 1837 1838 /// GenerateWritableString -- Creates storage for a string literal. 1839 static llvm::Constant *GenerateStringLiteral(const std::string &str, 1840 bool constant, 1841 CodeGenModule &CGM, 1842 const char *GlobalName) { 1843 // Create Constant for this string literal. Don't add a '\0'. 1844 llvm::Constant *C = 1845 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false); 1846 1847 // Create a global variable for this string 1848 return new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant, 1849 llvm::GlobalValue::PrivateLinkage, 1850 C, GlobalName); 1851 } 1852 1853 /// GetAddrOfConstantString - Returns a pointer to a character array 1854 /// containing the literal. This contents are exactly that of the 1855 /// given string, i.e. it will not be null terminated automatically; 1856 /// see GetAddrOfConstantCString. Note that whether the result is 1857 /// actually a pointer to an LLVM constant depends on 1858 /// Feature.WriteableStrings. 1859 /// 1860 /// The result has pointer to array type. 1861 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str, 1862 const char *GlobalName) { 1863 bool IsConstant = !Features.WritableStrings; 1864 1865 // Get the default prefix if a name wasn't specified. 1866 if (!GlobalName) 1867 GlobalName = ".str"; 1868 1869 // Don't share any string literals if strings aren't constant. 1870 if (!IsConstant) 1871 return GenerateStringLiteral(str, false, *this, GlobalName); 1872 1873 llvm::StringMapEntry<llvm::Constant *> &Entry = 1874 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 1875 1876 if (Entry.getValue()) 1877 return Entry.getValue(); 1878 1879 // Create a global variable for this. 1880 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName); 1881 Entry.setValue(C); 1882 return C; 1883 } 1884 1885 /// GetAddrOfConstantCString - Returns a pointer to a character 1886 /// array containing the literal and a terminating '\-' 1887 /// character. The result has pointer to array type. 1888 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str, 1889 const char *GlobalName){ 1890 return GetAddrOfConstantString(str + '\0', GlobalName); 1891 } 1892 1893 /// EmitObjCPropertyImplementations - Emit information for synthesized 1894 /// properties for an implementation. 1895 void CodeGenModule::EmitObjCPropertyImplementations(const 1896 ObjCImplementationDecl *D) { 1897 for (ObjCImplementationDecl::propimpl_iterator 1898 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) { 1899 ObjCPropertyImplDecl *PID = *i; 1900 1901 // Dynamic is just for type-checking. 1902 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 1903 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 1904 1905 // Determine which methods need to be implemented, some may have 1906 // been overridden. Note that ::isSynthesized is not the method 1907 // we want, that just indicates if the decl came from a 1908 // property. What we want to know is if the method is defined in 1909 // this implementation. 1910 if (!D->getInstanceMethod(PD->getGetterName())) 1911 CodeGenFunction(*this).GenerateObjCGetter( 1912 const_cast<ObjCImplementationDecl *>(D), PID); 1913 if (!PD->isReadOnly() && 1914 !D->getInstanceMethod(PD->getSetterName())) 1915 CodeGenFunction(*this).GenerateObjCSetter( 1916 const_cast<ObjCImplementationDecl *>(D), PID); 1917 } 1918 } 1919 } 1920 1921 /// EmitObjCIvarInitializations - Emit information for ivar initialization 1922 /// for an implementation. 1923 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 1924 if (!Features.NeXTRuntime || D->getNumIvarInitializers() == 0) 1925 return; 1926 DeclContext* DC = const_cast<DeclContext*>(dyn_cast<DeclContext>(D)); 1927 assert(DC && "EmitObjCIvarInitializations - null DeclContext"); 1928 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 1929 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 1930 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(getContext(), 1931 D->getLocation(), 1932 D->getLocation(), cxxSelector, 1933 getContext().VoidTy, 0, 1934 DC, true, false, true, false, 1935 ObjCMethodDecl::Required); 1936 D->addInstanceMethod(DTORMethod); 1937 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 1938 1939 II = &getContext().Idents.get(".cxx_construct"); 1940 cxxSelector = getContext().Selectors.getSelector(0, &II); 1941 // The constructor returns 'self'. 1942 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 1943 D->getLocation(), 1944 D->getLocation(), cxxSelector, 1945 getContext().getObjCIdType(), 0, 1946 DC, true, false, true, false, 1947 ObjCMethodDecl::Required); 1948 D->addInstanceMethod(CTORMethod); 1949 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 1950 1951 1952 } 1953 1954 /// EmitNamespace - Emit all declarations in a namespace. 1955 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 1956 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end(); 1957 I != E; ++I) 1958 EmitTopLevelDecl(*I); 1959 } 1960 1961 // EmitLinkageSpec - Emit all declarations in a linkage spec. 1962 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 1963 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 1964 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 1965 ErrorUnsupported(LSD, "linkage spec"); 1966 return; 1967 } 1968 1969 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end(); 1970 I != E; ++I) 1971 EmitTopLevelDecl(*I); 1972 } 1973 1974 /// EmitTopLevelDecl - Emit code for a single top level declaration. 1975 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 1976 // If an error has occurred, stop code generation, but continue 1977 // parsing and semantic analysis (to ensure all warnings and errors 1978 // are emitted). 1979 if (Diags.hasErrorOccurred()) 1980 return; 1981 1982 // Ignore dependent declarations. 1983 if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 1984 return; 1985 1986 switch (D->getKind()) { 1987 case Decl::CXXConversion: 1988 case Decl::CXXMethod: 1989 case Decl::Function: 1990 // Skip function templates 1991 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate()) 1992 return; 1993 1994 EmitGlobal(cast<FunctionDecl>(D)); 1995 break; 1996 1997 case Decl::Var: 1998 EmitGlobal(cast<VarDecl>(D)); 1999 break; 2000 2001 // C++ Decls 2002 case Decl::Namespace: 2003 EmitNamespace(cast<NamespaceDecl>(D)); 2004 break; 2005 // No code generation needed. 2006 case Decl::UsingShadow: 2007 case Decl::Using: 2008 case Decl::UsingDirective: 2009 case Decl::ClassTemplate: 2010 case Decl::FunctionTemplate: 2011 case Decl::NamespaceAlias: 2012 break; 2013 case Decl::CXXConstructor: 2014 // Skip function templates 2015 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate()) 2016 return; 2017 2018 EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 2019 break; 2020 case Decl::CXXDestructor: 2021 EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 2022 break; 2023 2024 case Decl::StaticAssert: 2025 // Nothing to do. 2026 break; 2027 2028 // Objective-C Decls 2029 2030 // Forward declarations, no (immediate) code generation. 2031 case Decl::ObjCClass: 2032 case Decl::ObjCForwardProtocol: 2033 case Decl::ObjCCategory: 2034 case Decl::ObjCInterface: 2035 break; 2036 2037 case Decl::ObjCProtocol: 2038 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D)); 2039 break; 2040 2041 case Decl::ObjCCategoryImpl: 2042 // Categories have properties but don't support synthesize so we 2043 // can ignore them here. 2044 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 2045 break; 2046 2047 case Decl::ObjCImplementation: { 2048 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D); 2049 EmitObjCPropertyImplementations(OMD); 2050 EmitObjCIvarInitializations(OMD); 2051 Runtime->GenerateClass(OMD); 2052 break; 2053 } 2054 case Decl::ObjCMethod: { 2055 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D); 2056 // If this is not a prototype, emit the body. 2057 if (OMD->getBody()) 2058 CodeGenFunction(*this).GenerateObjCMethod(OMD); 2059 break; 2060 } 2061 case Decl::ObjCCompatibleAlias: 2062 // compatibility-alias is a directive and has no code gen. 2063 break; 2064 2065 case Decl::LinkageSpec: 2066 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 2067 break; 2068 2069 case Decl::FileScopeAsm: { 2070 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D); 2071 llvm::StringRef AsmString = AD->getAsmString()->getString(); 2072 2073 const std::string &S = getModule().getModuleInlineAsm(); 2074 if (S.empty()) 2075 getModule().setModuleInlineAsm(AsmString); 2076 else 2077 getModule().setModuleInlineAsm(S + '\n' + AsmString.str()); 2078 break; 2079 } 2080 2081 default: 2082 // Make sure we handled everything we should, every other kind is a 2083 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 2084 // function. Need to recode Decl::Kind to do that easily. 2085 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 2086 } 2087 } 2088 2089 /// Turns the given pointer into a constant. 2090 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 2091 const void *Ptr) { 2092 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 2093 const llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 2094 return llvm::ConstantInt::get(i64, PtrInt); 2095 } 2096 2097 static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 2098 llvm::NamedMDNode *&GlobalMetadata, 2099 GlobalDecl D, 2100 llvm::GlobalValue *Addr) { 2101 if (!GlobalMetadata) 2102 GlobalMetadata = 2103 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 2104 2105 // TODO: should we report variant information for ctors/dtors? 2106 llvm::Value *Ops[] = { 2107 Addr, 2108 GetPointerConstant(CGM.getLLVMContext(), D.getDecl()) 2109 }; 2110 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops, 2)); 2111 } 2112 2113 /// Emits metadata nodes associating all the global values in the 2114 /// current module with the Decls they came from. This is useful for 2115 /// projects using IR gen as a subroutine. 2116 /// 2117 /// Since there's currently no way to associate an MDNode directly 2118 /// with an llvm::GlobalValue, we create a global named metadata 2119 /// with the name 'clang.global.decl.ptrs'. 2120 void CodeGenModule::EmitDeclMetadata() { 2121 llvm::NamedMDNode *GlobalMetadata = 0; 2122 2123 // StaticLocalDeclMap 2124 for (llvm::DenseMap<GlobalDecl,llvm::StringRef>::iterator 2125 I = MangledDeclNames.begin(), E = MangledDeclNames.end(); 2126 I != E; ++I) { 2127 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second); 2128 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr); 2129 } 2130 } 2131 2132 /// Emits metadata nodes for all the local variables in the current 2133 /// function. 2134 void CodeGenFunction::EmitDeclMetadata() { 2135 if (LocalDeclMap.empty()) return; 2136 2137 llvm::LLVMContext &Context = getLLVMContext(); 2138 2139 // Find the unique metadata ID for this name. 2140 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 2141 2142 llvm::NamedMDNode *GlobalMetadata = 0; 2143 2144 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator 2145 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) { 2146 const Decl *D = I->first; 2147 llvm::Value *Addr = I->second; 2148 2149 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 2150 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 2151 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, &DAddr, 1)); 2152 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 2153 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 2154 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 2155 } 2156 } 2157 } 2158 2159 ///@name Custom Runtime Function Interfaces 2160 ///@{ 2161 // 2162 // FIXME: These can be eliminated once we can have clients just get the required 2163 // AST nodes from the builtin tables. 2164 2165 llvm::Constant *CodeGenModule::getBlockObjectDispose() { 2166 if (BlockObjectDispose) 2167 return BlockObjectDispose; 2168 2169 // If we saw an explicit decl, use that. 2170 if (BlockObjectDisposeDecl) { 2171 return BlockObjectDispose = GetAddrOfFunction( 2172 BlockObjectDisposeDecl, 2173 getTypes().GetFunctionType(BlockObjectDisposeDecl)); 2174 } 2175 2176 // Otherwise construct the function by hand. 2177 const llvm::FunctionType *FTy; 2178 std::vector<const llvm::Type*> ArgTys; 2179 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext); 2180 ArgTys.push_back(PtrToInt8Ty); 2181 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext)); 2182 FTy = llvm::FunctionType::get(ResultType, ArgTys, false); 2183 return BlockObjectDispose = 2184 CreateRuntimeFunction(FTy, "_Block_object_dispose"); 2185 } 2186 2187 llvm::Constant *CodeGenModule::getBlockObjectAssign() { 2188 if (BlockObjectAssign) 2189 return BlockObjectAssign; 2190 2191 // If we saw an explicit decl, use that. 2192 if (BlockObjectAssignDecl) { 2193 return BlockObjectAssign = GetAddrOfFunction( 2194 BlockObjectAssignDecl, 2195 getTypes().GetFunctionType(BlockObjectAssignDecl)); 2196 } 2197 2198 // Otherwise construct the function by hand. 2199 const llvm::FunctionType *FTy; 2200 std::vector<const llvm::Type*> ArgTys; 2201 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext); 2202 ArgTys.push_back(PtrToInt8Ty); 2203 ArgTys.push_back(PtrToInt8Ty); 2204 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext)); 2205 FTy = llvm::FunctionType::get(ResultType, ArgTys, false); 2206 return BlockObjectAssign = 2207 CreateRuntimeFunction(FTy, "_Block_object_assign"); 2208 } 2209 2210 llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() { 2211 if (NSConcreteGlobalBlock) 2212 return NSConcreteGlobalBlock; 2213 2214 // If we saw an explicit decl, use that. 2215 if (NSConcreteGlobalBlockDecl) { 2216 return NSConcreteGlobalBlock = GetAddrOfGlobalVar( 2217 NSConcreteGlobalBlockDecl, 2218 getTypes().ConvertType(NSConcreteGlobalBlockDecl->getType())); 2219 } 2220 2221 // Otherwise construct the variable by hand. 2222 return NSConcreteGlobalBlock = CreateRuntimeVariable( 2223 PtrToInt8Ty, "_NSConcreteGlobalBlock"); 2224 } 2225 2226 llvm::Constant *CodeGenModule::getNSConcreteStackBlock() { 2227 if (NSConcreteStackBlock) 2228 return NSConcreteStackBlock; 2229 2230 // If we saw an explicit decl, use that. 2231 if (NSConcreteStackBlockDecl) { 2232 return NSConcreteStackBlock = GetAddrOfGlobalVar( 2233 NSConcreteStackBlockDecl, 2234 getTypes().ConvertType(NSConcreteStackBlockDecl->getType())); 2235 } 2236 2237 // Otherwise construct the variable by hand. 2238 return NSConcreteStackBlock = CreateRuntimeVariable( 2239 PtrToInt8Ty, "_NSConcreteStackBlock"); 2240 } 2241 2242 ///@} 2243