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