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