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