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