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