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