1f22ef01cSRoman Divacky //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// 2f22ef01cSRoman Divacky // 3f22ef01cSRoman Divacky // The LLVM Compiler Infrastructure 4f22ef01cSRoman Divacky // 5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source 6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details. 7f22ef01cSRoman Divacky // 8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 9f22ef01cSRoman Divacky // 10f22ef01cSRoman Divacky // This coordinates the per-module state used while generating code. 11f22ef01cSRoman Divacky // 12f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 13f22ef01cSRoman Divacky 14f22ef01cSRoman Divacky #include "CodeGenModule.h" 15f22ef01cSRoman Divacky #include "CGDebugInfo.h" 16f22ef01cSRoman Divacky #include "CodeGenFunction.h" 172754fe60SDimitry Andric #include "CodeGenTBAA.h" 18f22ef01cSRoman Divacky #include "CGCall.h" 196122f3e6SDimitry Andric #include "CGCUDARuntime.h" 20e580952dSDimitry Andric #include "CGCXXABI.h" 21f22ef01cSRoman Divacky #include "CGObjCRuntime.h" 226122f3e6SDimitry Andric #include "CGOpenCLRuntime.h" 23f22ef01cSRoman Divacky #include "TargetInfo.h" 24ffd1746dSEd Schouten #include "clang/Frontend/CodeGenOptions.h" 25f22ef01cSRoman Divacky #include "clang/AST/ASTContext.h" 26f22ef01cSRoman Divacky #include "clang/AST/CharUnits.h" 27f22ef01cSRoman Divacky #include "clang/AST/DeclObjC.h" 28f22ef01cSRoman Divacky #include "clang/AST/DeclCXX.h" 29ffd1746dSEd Schouten #include "clang/AST/DeclTemplate.h" 302754fe60SDimitry Andric #include "clang/AST/Mangle.h" 31f22ef01cSRoman Divacky #include "clang/AST/RecordLayout.h" 32f8254f43SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h" 33f22ef01cSRoman Divacky #include "clang/Basic/Diagnostic.h" 34f22ef01cSRoman Divacky #include "clang/Basic/SourceManager.h" 35f22ef01cSRoman Divacky #include "clang/Basic/TargetInfo.h" 36f22ef01cSRoman Divacky #include "clang/Basic/ConvertUTF.h" 37f22ef01cSRoman Divacky #include "llvm/CallingConv.h" 38f22ef01cSRoman Divacky #include "llvm/Module.h" 39f22ef01cSRoman Divacky #include "llvm/Intrinsics.h" 40f22ef01cSRoman Divacky #include "llvm/LLVMContext.h" 41f22ef01cSRoman Divacky #include "llvm/ADT/Triple.h" 422754fe60SDimitry Andric #include "llvm/Target/Mangler.h" 43f22ef01cSRoman Divacky #include "llvm/Target/TargetData.h" 44f22ef01cSRoman Divacky #include "llvm/Support/CallSite.h" 45f22ef01cSRoman Divacky #include "llvm/Support/ErrorHandling.h" 46f22ef01cSRoman Divacky using namespace clang; 47f22ef01cSRoman Divacky using namespace CodeGen; 48f22ef01cSRoman Divacky 496122f3e6SDimitry Andric static const char AnnotationSection[] = "llvm.metadata"; 506122f3e6SDimitry Andric 51e580952dSDimitry Andric static CGCXXABI &createCXXABI(CodeGenModule &CGM) { 526122f3e6SDimitry Andric switch (CGM.getContext().getTargetInfo().getCXXABI()) { 53e580952dSDimitry Andric case CXXABI_ARM: return *CreateARMCXXABI(CGM); 54e580952dSDimitry Andric case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM); 55e580952dSDimitry Andric case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM); 56e580952dSDimitry Andric } 57e580952dSDimitry Andric 58e580952dSDimitry Andric llvm_unreachable("invalid C++ ABI kind"); 59e580952dSDimitry Andric return *CreateItaniumCXXABI(CGM); 60e580952dSDimitry Andric } 61e580952dSDimitry Andric 62f22ef01cSRoman Divacky 63f22ef01cSRoman Divacky CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO, 64f22ef01cSRoman Divacky llvm::Module &M, const llvm::TargetData &TD, 656122f3e6SDimitry Andric DiagnosticsEngine &diags) 662754fe60SDimitry Andric : Context(C), Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M), 67f22ef01cSRoman Divacky TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags), 68e580952dSDimitry Andric ABI(createCXXABI(*this)), 6917a519f9SDimitry Andric Types(C, M, TD, getTargetCodeGenInfo().getABIInfo(), ABI, CGO), 702754fe60SDimitry Andric TBAA(0), 716122f3e6SDimitry Andric VTables(*this), ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0), 726122f3e6SDimitry Andric DebugInfo(0), ARCData(0), RRData(0), CFConstantStringClassRef(0), 736122f3e6SDimitry Andric ConstantStringClassRef(0), NSConstantStringType(0), 74e580952dSDimitry Andric VMContext(M.getContext()), 75e580952dSDimitry Andric NSConcreteGlobalBlock(0), NSConcreteStackBlock(0), 762754fe60SDimitry Andric BlockObjectAssign(0), BlockObjectDispose(0), 772754fe60SDimitry Andric BlockDescriptorType(0), GenericBlockLiteralType(0) { 783b0f4066SDimitry Andric if (Features.ObjC1) 793b0f4066SDimitry Andric createObjCRuntime(); 806122f3e6SDimitry Andric if (Features.OpenCL) 816122f3e6SDimitry Andric createOpenCLRuntime(); 826122f3e6SDimitry Andric if (Features.CUDA) 836122f3e6SDimitry Andric createCUDARuntime(); 84f22ef01cSRoman Divacky 852754fe60SDimitry Andric // Enable TBAA unless it's suppressed. 862754fe60SDimitry Andric if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0) 872754fe60SDimitry Andric TBAA = new CodeGenTBAA(Context, VMContext, getLangOptions(), 882754fe60SDimitry Andric ABI.getMangleContext()); 892754fe60SDimitry Andric 903b0f4066SDimitry Andric // If debug info or coverage generation is enabled, create the CGDebugInfo 913b0f4066SDimitry Andric // object. 923b0f4066SDimitry Andric if (CodeGenOpts.DebugInfo || CodeGenOpts.EmitGcovArcs || 933b0f4066SDimitry Andric CodeGenOpts.EmitGcovNotes) 943b0f4066SDimitry Andric DebugInfo = new CGDebugInfo(*this); 952754fe60SDimitry Andric 962754fe60SDimitry Andric Block.GlobalUniqueCount = 0; 972754fe60SDimitry Andric 9817a519f9SDimitry Andric if (C.getLangOptions().ObjCAutoRefCount) 9917a519f9SDimitry Andric ARCData = new ARCEntrypoints(); 10017a519f9SDimitry Andric RRData = new RREntrypoints(); 10117a519f9SDimitry Andric 1022754fe60SDimitry Andric // Initialize the type cache. 1032754fe60SDimitry Andric llvm::LLVMContext &LLVMContext = M.getContext(); 104bd5abe19SDimitry Andric VoidTy = llvm::Type::getVoidTy(LLVMContext); 1052754fe60SDimitry Andric Int8Ty = llvm::Type::getInt8Ty(LLVMContext); 1062754fe60SDimitry Andric Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 1072754fe60SDimitry Andric Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 1086122f3e6SDimitry Andric PointerWidthInBits = C.getTargetInfo().getPointerWidth(0); 109dd6029ffSDimitry Andric PointerAlignInBytes = 1106122f3e6SDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity(); 1116122f3e6SDimitry Andric IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 1122754fe60SDimitry Andric IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits); 1132754fe60SDimitry Andric Int8PtrTy = Int8Ty->getPointerTo(0); 1142754fe60SDimitry Andric Int8PtrPtrTy = Int8PtrTy->getPointerTo(0); 115f22ef01cSRoman Divacky } 116f22ef01cSRoman Divacky 117f22ef01cSRoman Divacky CodeGenModule::~CodeGenModule() { 1186122f3e6SDimitry Andric delete ObjCRuntime; 1196122f3e6SDimitry Andric delete OpenCLRuntime; 1206122f3e6SDimitry Andric delete CUDARuntime; 1216122f3e6SDimitry Andric delete TheTargetCodeGenInfo; 122e580952dSDimitry Andric delete &ABI; 1232754fe60SDimitry Andric delete TBAA; 124f22ef01cSRoman Divacky delete DebugInfo; 12517a519f9SDimitry Andric delete ARCData; 12617a519f9SDimitry Andric delete RRData; 127f22ef01cSRoman Divacky } 128f22ef01cSRoman Divacky 129f22ef01cSRoman Divacky void CodeGenModule::createObjCRuntime() { 130f22ef01cSRoman Divacky if (!Features.NeXTRuntime) 1316122f3e6SDimitry Andric ObjCRuntime = CreateGNUObjCRuntime(*this); 132f22ef01cSRoman Divacky else 1336122f3e6SDimitry Andric ObjCRuntime = CreateMacObjCRuntime(*this); 1346122f3e6SDimitry Andric } 1356122f3e6SDimitry Andric 1366122f3e6SDimitry Andric void CodeGenModule::createOpenCLRuntime() { 1376122f3e6SDimitry Andric OpenCLRuntime = new CGOpenCLRuntime(*this); 1386122f3e6SDimitry Andric } 1396122f3e6SDimitry Andric 1406122f3e6SDimitry Andric void CodeGenModule::createCUDARuntime() { 1416122f3e6SDimitry Andric CUDARuntime = CreateNVCUDARuntime(*this); 142f22ef01cSRoman Divacky } 143f22ef01cSRoman Divacky 144f22ef01cSRoman Divacky void CodeGenModule::Release() { 145f22ef01cSRoman Divacky EmitDeferred(); 146f22ef01cSRoman Divacky EmitCXXGlobalInitFunc(); 147f22ef01cSRoman Divacky EmitCXXGlobalDtorFunc(); 1486122f3e6SDimitry Andric if (ObjCRuntime) 1496122f3e6SDimitry Andric if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 150f22ef01cSRoman Divacky AddGlobalCtor(ObjCInitFunction); 151f22ef01cSRoman Divacky EmitCtorList(GlobalCtors, "llvm.global_ctors"); 152f22ef01cSRoman Divacky EmitCtorList(GlobalDtors, "llvm.global_dtors"); 1536122f3e6SDimitry Andric EmitGlobalAnnotations(); 154f22ef01cSRoman Divacky EmitLLVMUsed(); 155ffd1746dSEd Schouten 1562754fe60SDimitry Andric SimplifyPersonality(); 1572754fe60SDimitry Andric 158ffd1746dSEd Schouten if (getCodeGenOpts().EmitDeclMetadata) 159ffd1746dSEd Schouten EmitDeclMetadata(); 160bd5abe19SDimitry Andric 161bd5abe19SDimitry Andric if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 162bd5abe19SDimitry Andric EmitCoverageFile(); 1636122f3e6SDimitry Andric 1646122f3e6SDimitry Andric if (DebugInfo) 1656122f3e6SDimitry Andric DebugInfo->finalize(); 166f22ef01cSRoman Divacky } 167f22ef01cSRoman Divacky 1683b0f4066SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 1693b0f4066SDimitry Andric // Make sure that this type is translated. 1703b0f4066SDimitry Andric Types.UpdateCompletedType(TD); 1713b0f4066SDimitry Andric if (DebugInfo) 1723b0f4066SDimitry Andric DebugInfo->UpdateCompletedType(TD); 1733b0f4066SDimitry Andric } 1743b0f4066SDimitry Andric 1752754fe60SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) { 1762754fe60SDimitry Andric if (!TBAA) 1772754fe60SDimitry Andric return 0; 1782754fe60SDimitry Andric return TBAA->getTBAAInfo(QTy); 1792754fe60SDimitry Andric } 1802754fe60SDimitry Andric 1812754fe60SDimitry Andric void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst, 1822754fe60SDimitry Andric llvm::MDNode *TBAAInfo) { 1832754fe60SDimitry Andric Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo); 1842754fe60SDimitry Andric } 1852754fe60SDimitry Andric 186f22ef01cSRoman Divacky bool CodeGenModule::isTargetDarwin() const { 1876122f3e6SDimitry Andric return getContext().getTargetInfo().getTriple().isOSDarwin(); 1883b0f4066SDimitry Andric } 1893b0f4066SDimitry Andric 1906122f3e6SDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef error) { 1916122f3e6SDimitry Andric unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error); 1923b0f4066SDimitry Andric getDiags().Report(Context.getFullLoc(loc), diagID); 193f22ef01cSRoman Divacky } 194f22ef01cSRoman Divacky 195f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the 196f22ef01cSRoman Divacky /// specified stmt yet. 197f22ef01cSRoman Divacky void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type, 198f22ef01cSRoman Divacky bool OmitOnError) { 199f22ef01cSRoman Divacky if (OmitOnError && getDiags().hasErrorOccurred()) 200f22ef01cSRoman Divacky return; 2016122f3e6SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 202f22ef01cSRoman Divacky "cannot compile this %0 yet"); 203f22ef01cSRoman Divacky std::string Msg = Type; 204f22ef01cSRoman Divacky getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 205f22ef01cSRoman Divacky << Msg << S->getSourceRange(); 206f22ef01cSRoman Divacky } 207f22ef01cSRoman Divacky 208f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the 209f22ef01cSRoman Divacky /// specified decl yet. 210f22ef01cSRoman Divacky void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type, 211f22ef01cSRoman Divacky bool OmitOnError) { 212f22ef01cSRoman Divacky if (OmitOnError && getDiags().hasErrorOccurred()) 213f22ef01cSRoman Divacky return; 2146122f3e6SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 215f22ef01cSRoman Divacky "cannot compile this %0 yet"); 216f22ef01cSRoman Divacky std::string Msg = Type; 217f22ef01cSRoman Divacky getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 218f22ef01cSRoman Divacky } 219f22ef01cSRoman Divacky 22017a519f9SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 22117a519f9SDimitry Andric return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 22217a519f9SDimitry Andric } 22317a519f9SDimitry Andric 224f22ef01cSRoman Divacky void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 2252754fe60SDimitry Andric const NamedDecl *D) const { 226f22ef01cSRoman Divacky // Internal definitions always have default visibility. 227f22ef01cSRoman Divacky if (GV->hasLocalLinkage()) { 228f22ef01cSRoman Divacky GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 229f22ef01cSRoman Divacky return; 230f22ef01cSRoman Divacky } 231f22ef01cSRoman Divacky 2322754fe60SDimitry Andric // Set visibility for definitions. 2332754fe60SDimitry Andric NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility(); 2342754fe60SDimitry Andric if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage()) 2352754fe60SDimitry Andric GV->setVisibility(GetLLVMVisibility(LV.visibility())); 236f22ef01cSRoman Divacky } 237f22ef01cSRoman Divacky 238e580952dSDimitry Andric /// Set the symbol visibility of type information (vtable and RTTI) 239e580952dSDimitry Andric /// associated with the given type. 240e580952dSDimitry Andric void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV, 241e580952dSDimitry Andric const CXXRecordDecl *RD, 2422754fe60SDimitry Andric TypeVisibilityKind TVK) const { 243e580952dSDimitry Andric setGlobalVisibility(GV, RD); 244e580952dSDimitry Andric 245e580952dSDimitry Andric if (!CodeGenOpts.HiddenWeakVTables) 246e580952dSDimitry Andric return; 247e580952dSDimitry Andric 2482754fe60SDimitry Andric // We never want to drop the visibility for RTTI names. 2492754fe60SDimitry Andric if (TVK == TVK_ForRTTIName) 2502754fe60SDimitry Andric return; 2512754fe60SDimitry Andric 252e580952dSDimitry Andric // We want to drop the visibility to hidden for weak type symbols. 253e580952dSDimitry Andric // This isn't possible if there might be unresolved references 254e580952dSDimitry Andric // elsewhere that rely on this symbol being visible. 255e580952dSDimitry Andric 256e580952dSDimitry Andric // This should be kept roughly in sync with setThunkVisibility 257e580952dSDimitry Andric // in CGVTables.cpp. 258e580952dSDimitry Andric 259e580952dSDimitry Andric // Preconditions. 2602754fe60SDimitry Andric if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage || 261e580952dSDimitry Andric GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility) 262e580952dSDimitry Andric return; 263e580952dSDimitry Andric 264e580952dSDimitry Andric // Don't override an explicit visibility attribute. 2653b0f4066SDimitry Andric if (RD->getExplicitVisibility()) 266e580952dSDimitry Andric return; 267e580952dSDimitry Andric 268e580952dSDimitry Andric switch (RD->getTemplateSpecializationKind()) { 269e580952dSDimitry Andric // We have to disable the optimization if this is an EI definition 270e580952dSDimitry Andric // because there might be EI declarations in other shared objects. 271e580952dSDimitry Andric case TSK_ExplicitInstantiationDefinition: 272e580952dSDimitry Andric case TSK_ExplicitInstantiationDeclaration: 273e580952dSDimitry Andric return; 274e580952dSDimitry Andric 275e580952dSDimitry Andric // Every use of a non-template class's type information has to emit it. 276e580952dSDimitry Andric case TSK_Undeclared: 277e580952dSDimitry Andric break; 278e580952dSDimitry Andric 279e580952dSDimitry Andric // In theory, implicit instantiations can ignore the possibility of 280e580952dSDimitry Andric // an explicit instantiation declaration because there necessarily 281e580952dSDimitry Andric // must be an EI definition somewhere with default visibility. In 282e580952dSDimitry Andric // practice, it's possible to have an explicit instantiation for 283e580952dSDimitry Andric // an arbitrary template class, and linkers aren't necessarily able 284e580952dSDimitry Andric // to deal with mixed-visibility symbols. 285e580952dSDimitry Andric case TSK_ExplicitSpecialization: 286e580952dSDimitry Andric case TSK_ImplicitInstantiation: 287e580952dSDimitry Andric if (!CodeGenOpts.HiddenWeakTemplateVTables) 288e580952dSDimitry Andric return; 289e580952dSDimitry Andric break; 290e580952dSDimitry Andric } 291e580952dSDimitry Andric 292e580952dSDimitry Andric // If there's a key function, there may be translation units 293e580952dSDimitry Andric // that don't have the key function's definition. But ignore 294e580952dSDimitry Andric // this if we're emitting RTTI under -fno-rtti. 2952754fe60SDimitry Andric if (!(TVK != TVK_ForRTTI) || Features.RTTI) { 296e580952dSDimitry Andric if (Context.getKeyFunction(RD)) 297e580952dSDimitry Andric return; 2982754fe60SDimitry Andric } 299e580952dSDimitry Andric 300e580952dSDimitry Andric // Otherwise, drop the visibility to hidden. 301e580952dSDimitry Andric GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 3022754fe60SDimitry Andric GV->setUnnamedAddr(true); 303e580952dSDimitry Andric } 304e580952dSDimitry Andric 3056122f3e6SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 306f22ef01cSRoman Divacky const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 307f22ef01cSRoman Divacky 3086122f3e6SDimitry Andric StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()]; 309ffd1746dSEd Schouten if (!Str.empty()) 310ffd1746dSEd Schouten return Str; 311f22ef01cSRoman Divacky 312e580952dSDimitry Andric if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) { 313ffd1746dSEd Schouten IdentifierInfo *II = ND->getIdentifier(); 314ffd1746dSEd Schouten assert(II && "Attempt to mangle unnamed decl."); 315ffd1746dSEd Schouten 316ffd1746dSEd Schouten Str = II->getName(); 317ffd1746dSEd Schouten return Str; 318f22ef01cSRoman Divacky } 319f22ef01cSRoman Divacky 320ffd1746dSEd Schouten llvm::SmallString<256> Buffer; 3212754fe60SDimitry Andric llvm::raw_svector_ostream Out(Buffer); 322ffd1746dSEd Schouten if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND)) 3232754fe60SDimitry Andric getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out); 324ffd1746dSEd Schouten else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND)) 3252754fe60SDimitry Andric getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out); 326ffd1746dSEd Schouten else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND)) 3272754fe60SDimitry Andric getCXXABI().getMangleContext().mangleBlock(BD, Out); 328ffd1746dSEd Schouten else 3292754fe60SDimitry Andric getCXXABI().getMangleContext().mangleName(ND, Out); 330ffd1746dSEd Schouten 331ffd1746dSEd Schouten // Allocate space for the mangled name. 3322754fe60SDimitry Andric Out.flush(); 333ffd1746dSEd Schouten size_t Length = Buffer.size(); 334ffd1746dSEd Schouten char *Name = MangledNamesAllocator.Allocate<char>(Length); 335ffd1746dSEd Schouten std::copy(Buffer.begin(), Buffer.end(), Name); 336ffd1746dSEd Schouten 3376122f3e6SDimitry Andric Str = StringRef(Name, Length); 338ffd1746dSEd Schouten 339ffd1746dSEd Schouten return Str; 340ffd1746dSEd Schouten } 341ffd1746dSEd Schouten 3422754fe60SDimitry Andric void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer, 343ffd1746dSEd Schouten const BlockDecl *BD) { 3442754fe60SDimitry Andric MangleContext &MangleCtx = getCXXABI().getMangleContext(); 3452754fe60SDimitry Andric const Decl *D = GD.getDecl(); 3462754fe60SDimitry Andric llvm::raw_svector_ostream Out(Buffer.getBuffer()); 3472754fe60SDimitry Andric if (D == 0) 3482754fe60SDimitry Andric MangleCtx.mangleGlobalBlock(BD, Out); 3492754fe60SDimitry Andric else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 3502754fe60SDimitry Andric MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 3512754fe60SDimitry Andric else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D)) 3522754fe60SDimitry Andric MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 3532754fe60SDimitry Andric else 3542754fe60SDimitry Andric MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 355f22ef01cSRoman Divacky } 356f22ef01cSRoman Divacky 3576122f3e6SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 358f22ef01cSRoman Divacky return getModule().getNamedValue(Name); 359f22ef01cSRoman Divacky } 360f22ef01cSRoman Divacky 361f22ef01cSRoman Divacky /// AddGlobalCtor - Add a function to the list that will be called before 362f22ef01cSRoman Divacky /// main() runs. 363f22ef01cSRoman Divacky void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) { 364f22ef01cSRoman Divacky // FIXME: Type coercion of void()* types. 365f22ef01cSRoman Divacky GlobalCtors.push_back(std::make_pair(Ctor, Priority)); 366f22ef01cSRoman Divacky } 367f22ef01cSRoman Divacky 368f22ef01cSRoman Divacky /// AddGlobalDtor - Add a function to the list that will be called 369f22ef01cSRoman Divacky /// when the module is unloaded. 370f22ef01cSRoman Divacky void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) { 371f22ef01cSRoman Divacky // FIXME: Type coercion of void()* types. 372f22ef01cSRoman Divacky GlobalDtors.push_back(std::make_pair(Dtor, Priority)); 373f22ef01cSRoman Divacky } 374f22ef01cSRoman Divacky 375f22ef01cSRoman Divacky void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 376f22ef01cSRoman Divacky // Ctor function type is void()*. 377bd5abe19SDimitry Andric llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 378f22ef01cSRoman Divacky llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 379f22ef01cSRoman Divacky 380f22ef01cSRoman Divacky // Get the type of a ctor entry, { i32, void ()* }. 381f22ef01cSRoman Divacky llvm::StructType *CtorStructTy = 38217a519f9SDimitry Andric llvm::StructType::get(llvm::Type::getInt32Ty(VMContext), 383f22ef01cSRoman Divacky llvm::PointerType::getUnqual(CtorFTy), NULL); 384f22ef01cSRoman Divacky 385f22ef01cSRoman Divacky // Construct the constructor and destructor arrays. 386f22ef01cSRoman Divacky std::vector<llvm::Constant*> Ctors; 387f22ef01cSRoman Divacky for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 388f22ef01cSRoman Divacky std::vector<llvm::Constant*> S; 389f22ef01cSRoman Divacky S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 390f22ef01cSRoman Divacky I->second, false)); 391f22ef01cSRoman Divacky S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)); 392f22ef01cSRoman Divacky Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 393f22ef01cSRoman Divacky } 394f22ef01cSRoman Divacky 395f22ef01cSRoman Divacky if (!Ctors.empty()) { 396f22ef01cSRoman Divacky llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 397f22ef01cSRoman Divacky new llvm::GlobalVariable(TheModule, AT, false, 398f22ef01cSRoman Divacky llvm::GlobalValue::AppendingLinkage, 399f22ef01cSRoman Divacky llvm::ConstantArray::get(AT, Ctors), 400f22ef01cSRoman Divacky GlobalName); 401f22ef01cSRoman Divacky } 402f22ef01cSRoman Divacky } 403f22ef01cSRoman Divacky 404f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes 405f22ef01cSRoman Divacky CodeGenModule::getFunctionLinkage(const FunctionDecl *D) { 406e580952dSDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 407f22ef01cSRoman Divacky 408ffd1746dSEd Schouten if (Linkage == GVA_Internal) 409f22ef01cSRoman Divacky return llvm::Function::InternalLinkage; 410ffd1746dSEd Schouten 411ffd1746dSEd Schouten if (D->hasAttr<DLLExportAttr>()) 412f22ef01cSRoman Divacky return llvm::Function::DLLExportLinkage; 413ffd1746dSEd Schouten 414ffd1746dSEd Schouten if (D->hasAttr<WeakAttr>()) 415f22ef01cSRoman Divacky return llvm::Function::WeakAnyLinkage; 416ffd1746dSEd Schouten 417f22ef01cSRoman Divacky // In C99 mode, 'inline' functions are guaranteed to have a strong 418f22ef01cSRoman Divacky // definition somewhere else, so we can use available_externally linkage. 419ffd1746dSEd Schouten if (Linkage == GVA_C99Inline) 420f22ef01cSRoman Divacky return llvm::Function::AvailableExternallyLinkage; 421ffd1746dSEd Schouten 4226122f3e6SDimitry Andric // Note that Apple's kernel linker doesn't support symbol 4236122f3e6SDimitry Andric // coalescing, so we need to avoid linkonce and weak linkages there. 4246122f3e6SDimitry Andric // Normally, this means we just map to internal, but for explicit 4256122f3e6SDimitry Andric // instantiations we'll map to external. 4266122f3e6SDimitry Andric 427f22ef01cSRoman Divacky // In C++, the compiler has to emit a definition in every translation unit 428f22ef01cSRoman Divacky // that references the function. We should use linkonce_odr because 429f22ef01cSRoman Divacky // a) if all references in this translation unit are optimized away, we 430f22ef01cSRoman Divacky // don't need to codegen it. b) if the function persists, it needs to be 431f22ef01cSRoman Divacky // merged with other definitions. c) C++ has the ODR, so we know the 432f22ef01cSRoman Divacky // definition is dependable. 433ffd1746dSEd Schouten if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) 4342754fe60SDimitry Andric return !Context.getLangOptions().AppleKext 4352754fe60SDimitry Andric ? llvm::Function::LinkOnceODRLinkage 4362754fe60SDimitry Andric : llvm::Function::InternalLinkage; 437ffd1746dSEd Schouten 438f22ef01cSRoman Divacky // An explicit instantiation of a template has weak linkage, since 439f22ef01cSRoman Divacky // explicit instantiations can occur in multiple translation units 440f22ef01cSRoman Divacky // and must all be equivalent. However, we are not allowed to 441f22ef01cSRoman Divacky // throw away these explicit instantiations. 442ffd1746dSEd Schouten if (Linkage == GVA_ExplicitTemplateInstantiation) 4432754fe60SDimitry Andric return !Context.getLangOptions().AppleKext 4442754fe60SDimitry Andric ? llvm::Function::WeakODRLinkage 4456122f3e6SDimitry Andric : llvm::Function::ExternalLinkage; 446ffd1746dSEd Schouten 447f22ef01cSRoman Divacky // Otherwise, we have strong external linkage. 448ffd1746dSEd Schouten assert(Linkage == GVA_StrongExternal); 449f22ef01cSRoman Divacky return llvm::Function::ExternalLinkage; 450f22ef01cSRoman Divacky } 451f22ef01cSRoman Divacky 452f22ef01cSRoman Divacky 453f22ef01cSRoman Divacky /// SetFunctionDefinitionAttributes - Set attributes for a global. 454f22ef01cSRoman Divacky /// 455f22ef01cSRoman Divacky /// FIXME: This is currently only done for aliases and functions, but not for 456f22ef01cSRoman Divacky /// variables (these details are set in EmitGlobalVarDefinition for variables). 457f22ef01cSRoman Divacky void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D, 458f22ef01cSRoman Divacky llvm::GlobalValue *GV) { 459f22ef01cSRoman Divacky SetCommonAttributes(D, GV); 460f22ef01cSRoman Divacky } 461f22ef01cSRoman Divacky 462f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 463f22ef01cSRoman Divacky const CGFunctionInfo &Info, 464f22ef01cSRoman Divacky llvm::Function *F) { 465f22ef01cSRoman Divacky unsigned CallingConv; 466f22ef01cSRoman Divacky AttributeListType AttributeList; 467f22ef01cSRoman Divacky ConstructAttributeList(Info, D, AttributeList, CallingConv); 468f22ef01cSRoman Divacky F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(), 469f22ef01cSRoman Divacky AttributeList.size())); 470f22ef01cSRoman Divacky F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 471f22ef01cSRoman Divacky } 472f22ef01cSRoman Divacky 4736122f3e6SDimitry Andric /// Determines whether the language options require us to model 4746122f3e6SDimitry Andric /// unwind exceptions. We treat -fexceptions as mandating this 4756122f3e6SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions 4766122f3e6SDimitry Andric /// enabled. This means, for example, that C with -fexceptions 4776122f3e6SDimitry Andric /// enables this. 4786122f3e6SDimitry Andric static bool hasUnwindExceptions(const LangOptions &Features) { 4796122f3e6SDimitry Andric // If exceptions are completely disabled, obviously this is false. 4806122f3e6SDimitry Andric if (!Features.Exceptions) return false; 4816122f3e6SDimitry Andric 4826122f3e6SDimitry Andric // If C++ exceptions are enabled, this is true. 4836122f3e6SDimitry Andric if (Features.CXXExceptions) return true; 4846122f3e6SDimitry Andric 4856122f3e6SDimitry Andric // If ObjC exceptions are enabled, this depends on the ABI. 4866122f3e6SDimitry Andric if (Features.ObjCExceptions) { 4876122f3e6SDimitry Andric if (!Features.ObjCNonFragileABI) return false; 4886122f3e6SDimitry Andric } 4896122f3e6SDimitry Andric 4906122f3e6SDimitry Andric return true; 4916122f3e6SDimitry Andric } 4926122f3e6SDimitry Andric 493f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 494f22ef01cSRoman Divacky llvm::Function *F) { 495bd5abe19SDimitry Andric if (CodeGenOpts.UnwindTables) 496bd5abe19SDimitry Andric F->setHasUWTable(); 497bd5abe19SDimitry Andric 4986122f3e6SDimitry Andric if (!hasUnwindExceptions(Features)) 499f22ef01cSRoman Divacky F->addFnAttr(llvm::Attribute::NoUnwind); 500f22ef01cSRoman Divacky 5016122f3e6SDimitry Andric if (D->hasAttr<NakedAttr>()) { 5026122f3e6SDimitry Andric // Naked implies noinline: we should not be inlining such functions. 5032754fe60SDimitry Andric F->addFnAttr(llvm::Attribute::Naked); 5046122f3e6SDimitry Andric F->addFnAttr(llvm::Attribute::NoInline); 5056122f3e6SDimitry Andric } 5062754fe60SDimitry Andric 507f22ef01cSRoman Divacky if (D->hasAttr<NoInlineAttr>()) 508f22ef01cSRoman Divacky F->addFnAttr(llvm::Attribute::NoInline); 509f22ef01cSRoman Divacky 5106122f3e6SDimitry Andric // (noinline wins over always_inline, and we can't specify both in IR) 5116122f3e6SDimitry Andric if (D->hasAttr<AlwaysInlineAttr>() && 5126122f3e6SDimitry Andric !F->hasFnAttr(llvm::Attribute::NoInline)) 5136122f3e6SDimitry Andric F->addFnAttr(llvm::Attribute::AlwaysInline); 5146122f3e6SDimitry Andric 5152754fe60SDimitry Andric if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 5162754fe60SDimitry Andric F->setUnnamedAddr(true); 5172754fe60SDimitry Andric 5186122f3e6SDimitry Andric if (Features.getStackProtector() == LangOptions::SSPOn) 519f22ef01cSRoman Divacky F->addFnAttr(llvm::Attribute::StackProtect); 5206122f3e6SDimitry Andric else if (Features.getStackProtector() == LangOptions::SSPReq) 521f22ef01cSRoman Divacky F->addFnAttr(llvm::Attribute::StackProtectReq); 522f22ef01cSRoman Divacky 523e580952dSDimitry Andric unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 524e580952dSDimitry Andric if (alignment) 525e580952dSDimitry Andric F->setAlignment(alignment); 526e580952dSDimitry Andric 527f22ef01cSRoman Divacky // C++ ABI requires 2-byte alignment for member functions. 528f22ef01cSRoman Divacky if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 529f22ef01cSRoman Divacky F->setAlignment(2); 530f22ef01cSRoman Divacky } 531f22ef01cSRoman Divacky 532f22ef01cSRoman Divacky void CodeGenModule::SetCommonAttributes(const Decl *D, 533f22ef01cSRoman Divacky llvm::GlobalValue *GV) { 5342754fe60SDimitry Andric if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) 5352754fe60SDimitry Andric setGlobalVisibility(GV, ND); 5362754fe60SDimitry Andric else 5372754fe60SDimitry Andric GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 538f22ef01cSRoman Divacky 539f22ef01cSRoman Divacky if (D->hasAttr<UsedAttr>()) 540f22ef01cSRoman Divacky AddUsedGlobal(GV); 541f22ef01cSRoman Divacky 542f22ef01cSRoman Divacky if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 543f22ef01cSRoman Divacky GV->setSection(SA->getName()); 544f22ef01cSRoman Divacky 545f22ef01cSRoman Divacky getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this); 546f22ef01cSRoman Divacky } 547f22ef01cSRoman Divacky 548f22ef01cSRoman Divacky void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 549f22ef01cSRoman Divacky llvm::Function *F, 550f22ef01cSRoman Divacky const CGFunctionInfo &FI) { 551f22ef01cSRoman Divacky SetLLVMFunctionAttributes(D, FI, F); 552f22ef01cSRoman Divacky SetLLVMFunctionAttributesForDefinition(D, F); 553f22ef01cSRoman Divacky 554f22ef01cSRoman Divacky F->setLinkage(llvm::Function::InternalLinkage); 555f22ef01cSRoman Divacky 556f22ef01cSRoman Divacky SetCommonAttributes(D, F); 557f22ef01cSRoman Divacky } 558f22ef01cSRoman Divacky 559f22ef01cSRoman Divacky void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, 560f22ef01cSRoman Divacky llvm::Function *F, 561f22ef01cSRoman Divacky bool IsIncompleteFunction) { 5623b0f4066SDimitry Andric if (unsigned IID = F->getIntrinsicID()) { 5633b0f4066SDimitry Andric // If this is an intrinsic function, set the function's attributes 5643b0f4066SDimitry Andric // to the intrinsic's attributes. 5653b0f4066SDimitry Andric F->setAttributes(llvm::Intrinsic::getAttributes((llvm::Intrinsic::ID)IID)); 5663b0f4066SDimitry Andric return; 5673b0f4066SDimitry Andric } 5683b0f4066SDimitry Andric 569f22ef01cSRoman Divacky const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 570f22ef01cSRoman Divacky 571f22ef01cSRoman Divacky if (!IsIncompleteFunction) 572f22ef01cSRoman Divacky SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F); 573f22ef01cSRoman Divacky 574f22ef01cSRoman Divacky // Only a few attributes are set on declarations; these may later be 575f22ef01cSRoman Divacky // overridden by a definition. 576f22ef01cSRoman Divacky 577f22ef01cSRoman Divacky if (FD->hasAttr<DLLImportAttr>()) { 578f22ef01cSRoman Divacky F->setLinkage(llvm::Function::DLLImportLinkage); 579f22ef01cSRoman Divacky } else if (FD->hasAttr<WeakAttr>() || 5803b0f4066SDimitry Andric FD->isWeakImported()) { 581f22ef01cSRoman Divacky // "extern_weak" is overloaded in LLVM; we probably should have 582f22ef01cSRoman Divacky // separate linkage types for this. 583f22ef01cSRoman Divacky F->setLinkage(llvm::Function::ExternalWeakLinkage); 584f22ef01cSRoman Divacky } else { 585f22ef01cSRoman Divacky F->setLinkage(llvm::Function::ExternalLinkage); 5862754fe60SDimitry Andric 5872754fe60SDimitry Andric NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility(); 5882754fe60SDimitry Andric if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) { 5892754fe60SDimitry Andric F->setVisibility(GetLLVMVisibility(LV.visibility())); 5902754fe60SDimitry Andric } 591f22ef01cSRoman Divacky } 592f22ef01cSRoman Divacky 593f22ef01cSRoman Divacky if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 594f22ef01cSRoman Divacky F->setSection(SA->getName()); 595f22ef01cSRoman Divacky } 596f22ef01cSRoman Divacky 597f22ef01cSRoman Divacky void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) { 598f22ef01cSRoman Divacky assert(!GV->isDeclaration() && 599f22ef01cSRoman Divacky "Only globals with definition can force usage."); 600f22ef01cSRoman Divacky LLVMUsed.push_back(GV); 601f22ef01cSRoman Divacky } 602f22ef01cSRoman Divacky 603f22ef01cSRoman Divacky void CodeGenModule::EmitLLVMUsed() { 604f22ef01cSRoman Divacky // Don't create llvm.used if there is no need. 605f22ef01cSRoman Divacky if (LLVMUsed.empty()) 606f22ef01cSRoman Divacky return; 607f22ef01cSRoman Divacky 6086122f3e6SDimitry Andric llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext); 609f22ef01cSRoman Divacky 610f22ef01cSRoman Divacky // Convert LLVMUsed to what ConstantArray needs. 611f22ef01cSRoman Divacky std::vector<llvm::Constant*> UsedArray; 612f22ef01cSRoman Divacky UsedArray.resize(LLVMUsed.size()); 613f22ef01cSRoman Divacky for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) { 614f22ef01cSRoman Divacky UsedArray[i] = 615f22ef01cSRoman Divacky llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]), 616f22ef01cSRoman Divacky i8PTy); 617f22ef01cSRoman Divacky } 618f22ef01cSRoman Divacky 619f22ef01cSRoman Divacky if (UsedArray.empty()) 620f22ef01cSRoman Divacky return; 621f22ef01cSRoman Divacky llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size()); 622f22ef01cSRoman Divacky 623f22ef01cSRoman Divacky llvm::GlobalVariable *GV = 624f22ef01cSRoman Divacky new llvm::GlobalVariable(getModule(), ATy, false, 625f22ef01cSRoman Divacky llvm::GlobalValue::AppendingLinkage, 626f22ef01cSRoman Divacky llvm::ConstantArray::get(ATy, UsedArray), 627f22ef01cSRoman Divacky "llvm.used"); 628f22ef01cSRoman Divacky 629f22ef01cSRoman Divacky GV->setSection("llvm.metadata"); 630f22ef01cSRoman Divacky } 631f22ef01cSRoman Divacky 632f22ef01cSRoman Divacky void CodeGenModule::EmitDeferred() { 633f22ef01cSRoman Divacky // Emit code for any potentially referenced deferred decls. Since a 634f22ef01cSRoman Divacky // previously unused static decl may become used during the generation of code 635f22ef01cSRoman Divacky // for a static function, iterate until no changes are made. 636f22ef01cSRoman Divacky 637f22ef01cSRoman Divacky while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) { 638f22ef01cSRoman Divacky if (!DeferredVTables.empty()) { 639f22ef01cSRoman Divacky const CXXRecordDecl *RD = DeferredVTables.back(); 640f22ef01cSRoman Divacky DeferredVTables.pop_back(); 641f22ef01cSRoman Divacky getVTables().GenerateClassData(getVTableLinkage(RD), RD); 642f22ef01cSRoman Divacky continue; 643f22ef01cSRoman Divacky } 644f22ef01cSRoman Divacky 645f22ef01cSRoman Divacky GlobalDecl D = DeferredDeclsToEmit.back(); 646f22ef01cSRoman Divacky DeferredDeclsToEmit.pop_back(); 647f22ef01cSRoman Divacky 648f22ef01cSRoman Divacky // Check to see if we've already emitted this. This is necessary 649f22ef01cSRoman Divacky // for a couple of reasons: first, decls can end up in the 650f22ef01cSRoman Divacky // deferred-decls queue multiple times, and second, decls can end 651f22ef01cSRoman Divacky // up with definitions in unusual ways (e.g. by an extern inline 652f22ef01cSRoman Divacky // function acquiring a strong function redefinition). Just 653f22ef01cSRoman Divacky // ignore these cases. 654f22ef01cSRoman Divacky // 655f22ef01cSRoman Divacky // TODO: That said, looking this up multiple times is very wasteful. 6566122f3e6SDimitry Andric StringRef Name = getMangledName(D); 657f22ef01cSRoman Divacky llvm::GlobalValue *CGRef = GetGlobalValue(Name); 658f22ef01cSRoman Divacky assert(CGRef && "Deferred decl wasn't referenced?"); 659f22ef01cSRoman Divacky 660f22ef01cSRoman Divacky if (!CGRef->isDeclaration()) 661f22ef01cSRoman Divacky continue; 662f22ef01cSRoman Divacky 663f22ef01cSRoman Divacky // GlobalAlias::isDeclaration() defers to the aliasee, but for our 664f22ef01cSRoman Divacky // purposes an alias counts as a definition. 665f22ef01cSRoman Divacky if (isa<llvm::GlobalAlias>(CGRef)) 666f22ef01cSRoman Divacky continue; 667f22ef01cSRoman Divacky 668f22ef01cSRoman Divacky // Otherwise, emit the definition and move on to the next one. 669f22ef01cSRoman Divacky EmitGlobalDefinition(D); 670f22ef01cSRoman Divacky } 671f22ef01cSRoman Divacky } 672f22ef01cSRoman Divacky 6736122f3e6SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() { 6746122f3e6SDimitry Andric if (Annotations.empty()) 6756122f3e6SDimitry Andric return; 6766122f3e6SDimitry Andric 6776122f3e6SDimitry Andric // Create a new global variable for the ConstantStruct in the Module. 6786122f3e6SDimitry Andric llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 6796122f3e6SDimitry Andric Annotations[0]->getType(), Annotations.size()), Annotations); 6806122f3e6SDimitry Andric llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), 6816122f3e6SDimitry Andric Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array, 6826122f3e6SDimitry Andric "llvm.global.annotations"); 6836122f3e6SDimitry Andric gv->setSection(AnnotationSection); 6846122f3e6SDimitry Andric } 6856122f3e6SDimitry Andric 6866122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(llvm::StringRef Str) { 6876122f3e6SDimitry Andric llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str); 6886122f3e6SDimitry Andric if (i != AnnotationStrings.end()) 6896122f3e6SDimitry Andric return i->second; 6906122f3e6SDimitry Andric 6916122f3e6SDimitry Andric // Not found yet, create a new global. 6926122f3e6SDimitry Andric llvm::Constant *s = llvm::ConstantArray::get(getLLVMContext(), Str, true); 6936122f3e6SDimitry Andric llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(), 6946122f3e6SDimitry Andric true, llvm::GlobalValue::PrivateLinkage, s, ".str"); 6956122f3e6SDimitry Andric gv->setSection(AnnotationSection); 6966122f3e6SDimitry Andric gv->setUnnamedAddr(true); 6976122f3e6SDimitry Andric AnnotationStrings[Str] = gv; 6986122f3e6SDimitry Andric return gv; 6996122f3e6SDimitry Andric } 7006122f3e6SDimitry Andric 7016122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 7026122f3e6SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 7036122f3e6SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(Loc); 7046122f3e6SDimitry Andric if (PLoc.isValid()) 7056122f3e6SDimitry Andric return EmitAnnotationString(PLoc.getFilename()); 7066122f3e6SDimitry Andric return EmitAnnotationString(SM.getBufferName(Loc)); 7076122f3e6SDimitry Andric } 7086122f3e6SDimitry Andric 7096122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 7106122f3e6SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 7116122f3e6SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(L); 7126122f3e6SDimitry Andric unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 7136122f3e6SDimitry Andric SM.getExpansionLineNumber(L); 7146122f3e6SDimitry Andric return llvm::ConstantInt::get(Int32Ty, LineNo); 7156122f3e6SDimitry Andric } 7166122f3e6SDimitry Andric 717f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 718f22ef01cSRoman Divacky const AnnotateAttr *AA, 7196122f3e6SDimitry Andric SourceLocation L) { 7206122f3e6SDimitry Andric // Get the globals for file name, annotation, and the line number. 7216122f3e6SDimitry Andric llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 7226122f3e6SDimitry Andric *UnitGV = EmitAnnotationUnit(L), 7236122f3e6SDimitry Andric *LineNoCst = EmitAnnotationLineNo(L); 724f22ef01cSRoman Divacky 725f22ef01cSRoman Divacky // Create the ConstantStruct for the global annotation. 726f22ef01cSRoman Divacky llvm::Constant *Fields[4] = { 7276122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(GV, Int8PtrTy), 7286122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 7296122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 7306122f3e6SDimitry Andric LineNoCst 731f22ef01cSRoman Divacky }; 73217a519f9SDimitry Andric return llvm::ConstantStruct::getAnon(Fields); 733f22ef01cSRoman Divacky } 734f22ef01cSRoman Divacky 7356122f3e6SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 7366122f3e6SDimitry Andric llvm::GlobalValue *GV) { 7376122f3e6SDimitry Andric assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 7386122f3e6SDimitry Andric // Get the struct elements for these annotations. 7396122f3e6SDimitry Andric for (specific_attr_iterator<AnnotateAttr> 7406122f3e6SDimitry Andric ai = D->specific_attr_begin<AnnotateAttr>(), 7416122f3e6SDimitry Andric ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai) 7426122f3e6SDimitry Andric Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation())); 7436122f3e6SDimitry Andric } 7446122f3e6SDimitry Andric 745f22ef01cSRoman Divacky bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) { 746e580952dSDimitry Andric // Never defer when EmitAllDecls is specified. 747e580952dSDimitry Andric if (Features.EmitAllDecls) 748f22ef01cSRoman Divacky return false; 749f22ef01cSRoman Divacky 750e580952dSDimitry Andric return !getContext().DeclMustBeEmitted(Global); 751f22ef01cSRoman Divacky } 752f22ef01cSRoman Divacky 753f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 754f22ef01cSRoman Divacky const AliasAttr *AA = VD->getAttr<AliasAttr>(); 755f22ef01cSRoman Divacky assert(AA && "No alias?"); 756f22ef01cSRoman Divacky 7576122f3e6SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 758f22ef01cSRoman Divacky 759f22ef01cSRoman Divacky // See if there is already something with the target's name in the module. 760f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 761f22ef01cSRoman Divacky 762f22ef01cSRoman Divacky llvm::Constant *Aliasee; 763f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(DeclTy)) 7642754fe60SDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(), 7652754fe60SDimitry Andric /*ForVTable=*/false); 766f22ef01cSRoman Divacky else 767f22ef01cSRoman Divacky Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 768f22ef01cSRoman Divacky llvm::PointerType::getUnqual(DeclTy), 0); 769f22ef01cSRoman Divacky if (!Entry) { 770f22ef01cSRoman Divacky llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee); 771f22ef01cSRoman Divacky F->setLinkage(llvm::Function::ExternalWeakLinkage); 772f22ef01cSRoman Divacky WeakRefReferences.insert(F); 773f22ef01cSRoman Divacky } 774f22ef01cSRoman Divacky 775f22ef01cSRoman Divacky return Aliasee; 776f22ef01cSRoman Divacky } 777f22ef01cSRoman Divacky 778f22ef01cSRoman Divacky void CodeGenModule::EmitGlobal(GlobalDecl GD) { 779f22ef01cSRoman Divacky const ValueDecl *Global = cast<ValueDecl>(GD.getDecl()); 780f22ef01cSRoman Divacky 781f22ef01cSRoman Divacky // Weak references don't produce any output by themselves. 782f22ef01cSRoman Divacky if (Global->hasAttr<WeakRefAttr>()) 783f22ef01cSRoman Divacky return; 784f22ef01cSRoman Divacky 785f22ef01cSRoman Divacky // If this is an alias definition (which otherwise looks like a declaration) 786f22ef01cSRoman Divacky // emit it now. 787f22ef01cSRoman Divacky if (Global->hasAttr<AliasAttr>()) 788f22ef01cSRoman Divacky return EmitAliasDefinition(GD); 789f22ef01cSRoman Divacky 7906122f3e6SDimitry Andric // If this is CUDA, be selective about which declarations we emit. 7916122f3e6SDimitry Andric if (Features.CUDA) { 7926122f3e6SDimitry Andric if (CodeGenOpts.CUDAIsDevice) { 7936122f3e6SDimitry Andric if (!Global->hasAttr<CUDADeviceAttr>() && 7946122f3e6SDimitry Andric !Global->hasAttr<CUDAGlobalAttr>() && 7956122f3e6SDimitry Andric !Global->hasAttr<CUDAConstantAttr>() && 7966122f3e6SDimitry Andric !Global->hasAttr<CUDASharedAttr>()) 7976122f3e6SDimitry Andric return; 7986122f3e6SDimitry Andric } else { 7996122f3e6SDimitry Andric if (!Global->hasAttr<CUDAHostAttr>() && ( 8006122f3e6SDimitry Andric Global->hasAttr<CUDADeviceAttr>() || 8016122f3e6SDimitry Andric Global->hasAttr<CUDAConstantAttr>() || 8026122f3e6SDimitry Andric Global->hasAttr<CUDASharedAttr>())) 8036122f3e6SDimitry Andric return; 804e580952dSDimitry Andric } 805e580952dSDimitry Andric } 806e580952dSDimitry Andric 8076122f3e6SDimitry Andric // Ignore declarations, they will be emitted on their first use. 8086122f3e6SDimitry Andric if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 809f22ef01cSRoman Divacky // Forward declarations are emitted lazily on first use. 8106122f3e6SDimitry Andric if (!FD->doesThisDeclarationHaveABody()) { 8116122f3e6SDimitry Andric if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 812f22ef01cSRoman Divacky return; 8136122f3e6SDimitry Andric 8146122f3e6SDimitry Andric const FunctionDecl *InlineDefinition = 0; 8156122f3e6SDimitry Andric FD->getBody(InlineDefinition); 8166122f3e6SDimitry Andric 8176122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 8186122f3e6SDimitry Andric llvm::StringMap<GlobalDecl>::iterator DDI = 8196122f3e6SDimitry Andric DeferredDecls.find(MangledName); 8206122f3e6SDimitry Andric if (DDI != DeferredDecls.end()) 8216122f3e6SDimitry Andric DeferredDecls.erase(DDI); 8226122f3e6SDimitry Andric EmitGlobalDefinition(InlineDefinition); 8236122f3e6SDimitry Andric return; 8246122f3e6SDimitry Andric } 825f22ef01cSRoman Divacky } else { 826f22ef01cSRoman Divacky const VarDecl *VD = cast<VarDecl>(Global); 827f22ef01cSRoman Divacky assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 828f22ef01cSRoman Divacky 829f22ef01cSRoman Divacky if (VD->isThisDeclarationADefinition() != VarDecl::Definition) 830f22ef01cSRoman Divacky return; 831f22ef01cSRoman Divacky } 832f22ef01cSRoman Divacky 833f22ef01cSRoman Divacky // Defer code generation when possible if this is a static definition, inline 834f22ef01cSRoman Divacky // function etc. These we only want to emit if they are used. 835f22ef01cSRoman Divacky if (!MayDeferGeneration(Global)) { 836f22ef01cSRoman Divacky // Emit the definition if it can't be deferred. 837f22ef01cSRoman Divacky EmitGlobalDefinition(GD); 838f22ef01cSRoman Divacky return; 839f22ef01cSRoman Divacky } 840f22ef01cSRoman Divacky 841e580952dSDimitry Andric // If we're deferring emission of a C++ variable with an 842e580952dSDimitry Andric // initializer, remember the order in which it appeared in the file. 843e580952dSDimitry Andric if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) && 844e580952dSDimitry Andric cast<VarDecl>(Global)->hasInit()) { 845e580952dSDimitry Andric DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 846e580952dSDimitry Andric CXXGlobalInits.push_back(0); 847e580952dSDimitry Andric } 848e580952dSDimitry Andric 849f22ef01cSRoman Divacky // If the value has already been used, add it directly to the 850f22ef01cSRoman Divacky // DeferredDeclsToEmit list. 8516122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 852f22ef01cSRoman Divacky if (GetGlobalValue(MangledName)) 853f22ef01cSRoman Divacky DeferredDeclsToEmit.push_back(GD); 854f22ef01cSRoman Divacky else { 855f22ef01cSRoman Divacky // Otherwise, remember that we saw a deferred decl with this name. The 856f22ef01cSRoman Divacky // first use of the mangled name will cause it to move into 857f22ef01cSRoman Divacky // DeferredDeclsToEmit. 858f22ef01cSRoman Divacky DeferredDecls[MangledName] = GD; 859f22ef01cSRoman Divacky } 860f22ef01cSRoman Divacky } 861f22ef01cSRoman Divacky 862f8254f43SDimitry Andric namespace { 863f8254f43SDimitry Andric struct FunctionIsDirectlyRecursive : 864f8254f43SDimitry Andric public RecursiveASTVisitor<FunctionIsDirectlyRecursive> { 865f8254f43SDimitry Andric const StringRef Name; 866f8254f43SDimitry Andric bool Result; 867f8254f43SDimitry Andric FunctionIsDirectlyRecursive(const FunctionDecl *F) : 868f8254f43SDimitry Andric Name(F->getName()), Result(false) { 869f8254f43SDimitry Andric } 870f8254f43SDimitry Andric typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base; 871f8254f43SDimitry Andric 872f8254f43SDimitry Andric bool TraverseCallExpr(CallExpr *E) { 873f8254f43SDimitry Andric const Decl *D = E->getCalleeDecl(); 874f8254f43SDimitry Andric if (!D) 875f8254f43SDimitry Andric return true; 876f8254f43SDimitry Andric AsmLabelAttr *Attr = D->getAttr<AsmLabelAttr>(); 877f8254f43SDimitry Andric if (!Attr) 878f8254f43SDimitry Andric return true; 879f8254f43SDimitry Andric if (Name == Attr->getLabel()) { 880f8254f43SDimitry Andric Result = true; 881f8254f43SDimitry Andric return false; 882f8254f43SDimitry Andric } 883f8254f43SDimitry Andric return true; 884f8254f43SDimitry Andric } 885f8254f43SDimitry Andric }; 886f8254f43SDimitry Andric } 887f8254f43SDimitry Andric 888f8254f43SDimitry Andric // isTriviallyRecursiveViaAsm - Check if this function calls another 889f8254f43SDimitry Andric // decl that, because of the asm attribute, ends up pointing to itself. 890f8254f43SDimitry Andric bool 891f8254f43SDimitry Andric CodeGenModule::isTriviallyRecursiveViaAsm(const FunctionDecl *F) { 892f8254f43SDimitry Andric if (getCXXABI().getMangleContext().shouldMangleDeclName(F)) 893f8254f43SDimitry Andric return false; 894f8254f43SDimitry Andric 895f8254f43SDimitry Andric FunctionIsDirectlyRecursive Walker(F); 896f8254f43SDimitry Andric Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); 897f8254f43SDimitry Andric return Walker.Result; 898f8254f43SDimitry Andric } 899f8254f43SDimitry Andric 900f8254f43SDimitry Andric bool 901f8254f43SDimitry Andric CodeGenModule::shouldEmitFunction(const FunctionDecl *F) { 902f8254f43SDimitry Andric if (getFunctionLinkage(F) != llvm::Function::AvailableExternallyLinkage) 903f8254f43SDimitry Andric return true; 904f8254f43SDimitry Andric if (CodeGenOpts.OptimizationLevel == 0 && 905f8254f43SDimitry Andric !F->hasAttr<AlwaysInlineAttr>()) 906f8254f43SDimitry Andric return false; 907f8254f43SDimitry Andric // PR9614. Avoid cases where the source code is lying to us. An available 908f8254f43SDimitry Andric // externally function should have an equivalent function somewhere else, 909f8254f43SDimitry Andric // but a function that calls itself is clearly not equivalent to the real 910f8254f43SDimitry Andric // implementation. 911f8254f43SDimitry Andric // This happens in glibc's btowc and in some configure checks. 912f8254f43SDimitry Andric return !isTriviallyRecursiveViaAsm(F); 913f8254f43SDimitry Andric } 914f8254f43SDimitry Andric 915f22ef01cSRoman Divacky void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) { 916f22ef01cSRoman Divacky const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 917f22ef01cSRoman Divacky 918f22ef01cSRoman Divacky PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 919f22ef01cSRoman Divacky Context.getSourceManager(), 920f22ef01cSRoman Divacky "Generating code for declaration"); 921f22ef01cSRoman Divacky 922ffd1746dSEd Schouten if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 923ffd1746dSEd Schouten // At -O0, don't generate IR for functions with available_externally 924ffd1746dSEd Schouten // linkage. 925f8254f43SDimitry Andric if (!shouldEmitFunction(Function)) 926ffd1746dSEd Schouten return; 927ffd1746dSEd Schouten 928ffd1746dSEd Schouten if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 929bd5abe19SDimitry Andric // Make sure to emit the definition(s) before we emit the thunks. 930bd5abe19SDimitry Andric // This is necessary for the generation of certain thunks. 931bd5abe19SDimitry Andric if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method)) 932bd5abe19SDimitry Andric EmitCXXConstructor(CD, GD.getCtorType()); 933bd5abe19SDimitry Andric else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method)) 934bd5abe19SDimitry Andric EmitCXXDestructor(DD, GD.getDtorType()); 935bd5abe19SDimitry Andric else 936bd5abe19SDimitry Andric EmitGlobalFunctionDefinition(GD); 937bd5abe19SDimitry Andric 938f22ef01cSRoman Divacky if (Method->isVirtual()) 939f22ef01cSRoman Divacky getVTables().EmitThunks(GD); 940f22ef01cSRoman Divacky 941bd5abe19SDimitry Andric return; 942ffd1746dSEd Schouten } 943f22ef01cSRoman Divacky 944f22ef01cSRoman Divacky return EmitGlobalFunctionDefinition(GD); 945ffd1746dSEd Schouten } 946f22ef01cSRoman Divacky 947f22ef01cSRoman Divacky if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 948f22ef01cSRoman Divacky return EmitGlobalVarDefinition(VD); 949f22ef01cSRoman Divacky 9506122f3e6SDimitry Andric llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 951f22ef01cSRoman Divacky } 952f22ef01cSRoman Divacky 953f22ef01cSRoman Divacky /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 954f22ef01cSRoman Divacky /// module, create and return an llvm Function with the specified type. If there 955f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially 956f22ef01cSRoman Divacky /// bitcasted to the right type. 957f22ef01cSRoman Divacky /// 958f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this. This is used 959f22ef01cSRoman Divacky /// to set the attributes on the function when it is first created. 960f22ef01cSRoman Divacky llvm::Constant * 9616122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName, 9626122f3e6SDimitry Andric llvm::Type *Ty, 96317a519f9SDimitry Andric GlobalDecl D, bool ForVTable, 96417a519f9SDimitry Andric llvm::Attributes ExtraAttrs) { 965f22ef01cSRoman Divacky // Lookup the entry, lazily creating it if necessary. 966f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 967f22ef01cSRoman Divacky if (Entry) { 968f22ef01cSRoman Divacky if (WeakRefReferences.count(Entry)) { 969f22ef01cSRoman Divacky const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl()); 970f22ef01cSRoman Divacky if (FD && !FD->hasAttr<WeakAttr>()) 971f22ef01cSRoman Divacky Entry->setLinkage(llvm::Function::ExternalLinkage); 972f22ef01cSRoman Divacky 973f22ef01cSRoman Divacky WeakRefReferences.erase(Entry); 974f22ef01cSRoman Divacky } 975f22ef01cSRoman Divacky 976f22ef01cSRoman Divacky if (Entry->getType()->getElementType() == Ty) 977f22ef01cSRoman Divacky return Entry; 978f22ef01cSRoman Divacky 979f22ef01cSRoman Divacky // Make sure the result is of the correct type. 98017a519f9SDimitry Andric return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 981f22ef01cSRoman Divacky } 982f22ef01cSRoman Divacky 983f22ef01cSRoman Divacky // This function doesn't have a complete type (for example, the return 984f22ef01cSRoman Divacky // type is an incomplete struct). Use a fake type instead, and make 985f22ef01cSRoman Divacky // sure not to try to set attributes. 986f22ef01cSRoman Divacky bool IsIncompleteFunction = false; 987f22ef01cSRoman Divacky 9886122f3e6SDimitry Andric llvm::FunctionType *FTy; 989f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(Ty)) { 990f22ef01cSRoman Divacky FTy = cast<llvm::FunctionType>(Ty); 991f22ef01cSRoman Divacky } else { 992bd5abe19SDimitry Andric FTy = llvm::FunctionType::get(VoidTy, false); 993f22ef01cSRoman Divacky IsIncompleteFunction = true; 994f22ef01cSRoman Divacky } 995ffd1746dSEd Schouten 996f22ef01cSRoman Divacky llvm::Function *F = llvm::Function::Create(FTy, 997f22ef01cSRoman Divacky llvm::Function::ExternalLinkage, 998f22ef01cSRoman Divacky MangledName, &getModule()); 999f22ef01cSRoman Divacky assert(F->getName() == MangledName && "name was uniqued!"); 1000f22ef01cSRoman Divacky if (D.getDecl()) 1001f22ef01cSRoman Divacky SetFunctionAttributes(D, F, IsIncompleteFunction); 100217a519f9SDimitry Andric if (ExtraAttrs != llvm::Attribute::None) 100317a519f9SDimitry Andric F->addFnAttr(ExtraAttrs); 1004f22ef01cSRoman Divacky 1005f22ef01cSRoman Divacky // This is the first use or definition of a mangled name. If there is a 1006f22ef01cSRoman Divacky // deferred decl with this name, remember that we need to emit it at the end 1007f22ef01cSRoman Divacky // of the file. 1008f22ef01cSRoman Divacky llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 1009f22ef01cSRoman Divacky if (DDI != DeferredDecls.end()) { 1010f22ef01cSRoman Divacky // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 1011f22ef01cSRoman Divacky // list, and remove it from DeferredDecls (since we don't need it anymore). 1012f22ef01cSRoman Divacky DeferredDeclsToEmit.push_back(DDI->second); 1013f22ef01cSRoman Divacky DeferredDecls.erase(DDI); 10142754fe60SDimitry Andric 10152754fe60SDimitry Andric // Otherwise, there are cases we have to worry about where we're 10162754fe60SDimitry Andric // using a declaration for which we must emit a definition but where 10172754fe60SDimitry Andric // we might not find a top-level definition: 10182754fe60SDimitry Andric // - member functions defined inline in their classes 10192754fe60SDimitry Andric // - friend functions defined inline in some class 10202754fe60SDimitry Andric // - special member functions with implicit definitions 10212754fe60SDimitry Andric // If we ever change our AST traversal to walk into class methods, 10222754fe60SDimitry Andric // this will be unnecessary. 10232754fe60SDimitry Andric // 10242754fe60SDimitry Andric // We also don't emit a definition for a function if it's going to be an entry 10252754fe60SDimitry Andric // in a vtable, unless it's already marked as used. 10262754fe60SDimitry Andric } else if (getLangOptions().CPlusPlus && D.getDecl()) { 10272754fe60SDimitry Andric // Look for a declaration that's lexically in a record. 10282754fe60SDimitry Andric const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl()); 10292754fe60SDimitry Andric do { 10302754fe60SDimitry Andric if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 10312754fe60SDimitry Andric if (FD->isImplicit() && !ForVTable) { 10322754fe60SDimitry Andric assert(FD->isUsed() && "Sema didn't mark implicit function as used!"); 10332754fe60SDimitry Andric DeferredDeclsToEmit.push_back(D.getWithDecl(FD)); 10342754fe60SDimitry Andric break; 1035bd5abe19SDimitry Andric } else if (FD->doesThisDeclarationHaveABody()) { 10362754fe60SDimitry Andric DeferredDeclsToEmit.push_back(D.getWithDecl(FD)); 10372754fe60SDimitry Andric break; 1038f22ef01cSRoman Divacky } 1039f22ef01cSRoman Divacky } 10402754fe60SDimitry Andric FD = FD->getPreviousDeclaration(); 10412754fe60SDimitry Andric } while (FD); 1042f22ef01cSRoman Divacky } 1043f22ef01cSRoman Divacky 1044f22ef01cSRoman Divacky // Make sure the result is of the requested type. 1045f22ef01cSRoman Divacky if (!IsIncompleteFunction) { 1046f22ef01cSRoman Divacky assert(F->getType()->getElementType() == Ty); 1047f22ef01cSRoman Divacky return F; 1048f22ef01cSRoman Divacky } 1049f22ef01cSRoman Divacky 105017a519f9SDimitry Andric llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 1051f22ef01cSRoman Divacky return llvm::ConstantExpr::getBitCast(F, PTy); 1052f22ef01cSRoman Divacky } 1053f22ef01cSRoman Divacky 1054f22ef01cSRoman Divacky /// GetAddrOfFunction - Return the address of the given function. If Ty is 1055f22ef01cSRoman Divacky /// non-null, then this function will use the specified type if it has to 1056f22ef01cSRoman Divacky /// create it (this occurs when we see a definition of the function). 1057f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 10586122f3e6SDimitry Andric llvm::Type *Ty, 10592754fe60SDimitry Andric bool ForVTable) { 1060f22ef01cSRoman Divacky // If there was no specific requested type, just convert it now. 1061f22ef01cSRoman Divacky if (!Ty) 1062f22ef01cSRoman Divacky Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType()); 1063ffd1746dSEd Schouten 10646122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 10652754fe60SDimitry Andric return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable); 1066f22ef01cSRoman Divacky } 1067f22ef01cSRoman Divacky 1068f22ef01cSRoman Divacky /// CreateRuntimeFunction - Create a new runtime function with the specified 1069f22ef01cSRoman Divacky /// type and name. 1070f22ef01cSRoman Divacky llvm::Constant * 10716122f3e6SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, 10726122f3e6SDimitry Andric StringRef Name, 107317a519f9SDimitry Andric llvm::Attributes ExtraAttrs) { 107417a519f9SDimitry Andric return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 107517a519f9SDimitry Andric ExtraAttrs); 1076f22ef01cSRoman Divacky } 1077f22ef01cSRoman Divacky 1078bd5abe19SDimitry Andric static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D, 1079bd5abe19SDimitry Andric bool ConstantInit) { 1080f22ef01cSRoman Divacky if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType()) 1081f22ef01cSRoman Divacky return false; 1082bd5abe19SDimitry Andric 1083bd5abe19SDimitry Andric if (Context.getLangOptions().CPlusPlus) { 1084bd5abe19SDimitry Andric if (const RecordType *Record 1085bd5abe19SDimitry Andric = Context.getBaseElementType(D->getType())->getAs<RecordType>()) 1086bd5abe19SDimitry Andric return ConstantInit && 1087bd5abe19SDimitry Andric cast<CXXRecordDecl>(Record->getDecl())->isPOD() && 1088bd5abe19SDimitry Andric !cast<CXXRecordDecl>(Record->getDecl())->hasMutableFields(); 1089f22ef01cSRoman Divacky } 1090bd5abe19SDimitry Andric 1091f22ef01cSRoman Divacky return true; 1092f22ef01cSRoman Divacky } 1093f22ef01cSRoman Divacky 1094f22ef01cSRoman Divacky /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 1095f22ef01cSRoman Divacky /// create and return an llvm GlobalVariable with the specified type. If there 1096f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially 1097f22ef01cSRoman Divacky /// bitcasted to the right type. 1098f22ef01cSRoman Divacky /// 1099f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this. This is used 1100f22ef01cSRoman Divacky /// to set the attributes on the global when it is first created. 1101f22ef01cSRoman Divacky llvm::Constant * 11026122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, 11036122f3e6SDimitry Andric llvm::PointerType *Ty, 11042754fe60SDimitry Andric const VarDecl *D, 11052754fe60SDimitry Andric bool UnnamedAddr) { 1106f22ef01cSRoman Divacky // Lookup the entry, lazily creating it if necessary. 1107f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1108f22ef01cSRoman Divacky if (Entry) { 1109f22ef01cSRoman Divacky if (WeakRefReferences.count(Entry)) { 1110f22ef01cSRoman Divacky if (D && !D->hasAttr<WeakAttr>()) 1111f22ef01cSRoman Divacky Entry->setLinkage(llvm::Function::ExternalLinkage); 1112f22ef01cSRoman Divacky 1113f22ef01cSRoman Divacky WeakRefReferences.erase(Entry); 1114f22ef01cSRoman Divacky } 1115f22ef01cSRoman Divacky 11162754fe60SDimitry Andric if (UnnamedAddr) 11172754fe60SDimitry Andric Entry->setUnnamedAddr(true); 11182754fe60SDimitry Andric 1119f22ef01cSRoman Divacky if (Entry->getType() == Ty) 1120f22ef01cSRoman Divacky return Entry; 1121f22ef01cSRoman Divacky 1122f22ef01cSRoman Divacky // Make sure the result is of the correct type. 1123f22ef01cSRoman Divacky return llvm::ConstantExpr::getBitCast(Entry, Ty); 1124f22ef01cSRoman Divacky } 1125f22ef01cSRoman Divacky 1126f22ef01cSRoman Divacky // This is the first use or definition of a mangled name. If there is a 1127f22ef01cSRoman Divacky // deferred decl with this name, remember that we need to emit it at the end 1128f22ef01cSRoman Divacky // of the file. 1129f22ef01cSRoman Divacky llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 1130f22ef01cSRoman Divacky if (DDI != DeferredDecls.end()) { 1131f22ef01cSRoman Divacky // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 1132f22ef01cSRoman Divacky // list, and remove it from DeferredDecls (since we don't need it anymore). 1133f22ef01cSRoman Divacky DeferredDeclsToEmit.push_back(DDI->second); 1134f22ef01cSRoman Divacky DeferredDecls.erase(DDI); 1135f22ef01cSRoman Divacky } 1136f22ef01cSRoman Divacky 1137f22ef01cSRoman Divacky llvm::GlobalVariable *GV = 1138f22ef01cSRoman Divacky new llvm::GlobalVariable(getModule(), Ty->getElementType(), false, 1139f22ef01cSRoman Divacky llvm::GlobalValue::ExternalLinkage, 1140f22ef01cSRoman Divacky 0, MangledName, 0, 1141f22ef01cSRoman Divacky false, Ty->getAddressSpace()); 1142f22ef01cSRoman Divacky 1143f22ef01cSRoman Divacky // Handle things which are present even on external declarations. 1144f22ef01cSRoman Divacky if (D) { 1145f22ef01cSRoman Divacky // FIXME: This code is overly simple and should be merged with other global 1146f22ef01cSRoman Divacky // handling. 1147bd5abe19SDimitry Andric GV->setConstant(DeclIsConstantGlobal(Context, D, false)); 1148f22ef01cSRoman Divacky 11492754fe60SDimitry Andric // Set linkage and visibility in case we never see a definition. 11502754fe60SDimitry Andric NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility(); 11512754fe60SDimitry Andric if (LV.linkage() != ExternalLinkage) { 11522754fe60SDimitry Andric // Don't set internal linkage on declarations. 11532754fe60SDimitry Andric } else { 11542754fe60SDimitry Andric if (D->hasAttr<DLLImportAttr>()) 11552754fe60SDimitry Andric GV->setLinkage(llvm::GlobalValue::DLLImportLinkage); 11563b0f4066SDimitry Andric else if (D->hasAttr<WeakAttr>() || D->isWeakImported()) 1157f22ef01cSRoman Divacky GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 1158f22ef01cSRoman Divacky 11592754fe60SDimitry Andric // Set visibility on a declaration only if it's explicit. 11602754fe60SDimitry Andric if (LV.visibilityExplicit()) 11612754fe60SDimitry Andric GV->setVisibility(GetLLVMVisibility(LV.visibility())); 11622754fe60SDimitry Andric } 11632754fe60SDimitry Andric 1164f22ef01cSRoman Divacky GV->setThreadLocal(D->isThreadSpecified()); 1165f22ef01cSRoman Divacky } 1166f22ef01cSRoman Divacky 1167f22ef01cSRoman Divacky return GV; 1168f22ef01cSRoman Divacky } 1169f22ef01cSRoman Divacky 1170f22ef01cSRoman Divacky 11712754fe60SDimitry Andric llvm::GlobalVariable * 11726122f3e6SDimitry Andric CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name, 11736122f3e6SDimitry Andric llvm::Type *Ty, 11742754fe60SDimitry Andric llvm::GlobalValue::LinkageTypes Linkage) { 11752754fe60SDimitry Andric llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 11762754fe60SDimitry Andric llvm::GlobalVariable *OldGV = 0; 11772754fe60SDimitry Andric 11782754fe60SDimitry Andric 11792754fe60SDimitry Andric if (GV) { 11802754fe60SDimitry Andric // Check if the variable has the right type. 11812754fe60SDimitry Andric if (GV->getType()->getElementType() == Ty) 11822754fe60SDimitry Andric return GV; 11832754fe60SDimitry Andric 11842754fe60SDimitry Andric // Because C++ name mangling, the only way we can end up with an already 11852754fe60SDimitry Andric // existing global with the same name is if it has been declared extern "C". 11862754fe60SDimitry Andric assert(GV->isDeclaration() && "Declaration has wrong type!"); 11872754fe60SDimitry Andric OldGV = GV; 11882754fe60SDimitry Andric } 11892754fe60SDimitry Andric 11902754fe60SDimitry Andric // Create a new variable. 11912754fe60SDimitry Andric GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 11922754fe60SDimitry Andric Linkage, 0, Name); 11932754fe60SDimitry Andric 11942754fe60SDimitry Andric if (OldGV) { 11952754fe60SDimitry Andric // Replace occurrences of the old variable if needed. 11962754fe60SDimitry Andric GV->takeName(OldGV); 11972754fe60SDimitry Andric 11982754fe60SDimitry Andric if (!OldGV->use_empty()) { 11992754fe60SDimitry Andric llvm::Constant *NewPtrForOldDecl = 12002754fe60SDimitry Andric llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 12012754fe60SDimitry Andric OldGV->replaceAllUsesWith(NewPtrForOldDecl); 12022754fe60SDimitry Andric } 12032754fe60SDimitry Andric 12042754fe60SDimitry Andric OldGV->eraseFromParent(); 12052754fe60SDimitry Andric } 12062754fe60SDimitry Andric 12072754fe60SDimitry Andric return GV; 12082754fe60SDimitry Andric } 12092754fe60SDimitry Andric 1210f22ef01cSRoman Divacky /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 1211f22ef01cSRoman Divacky /// given global variable. If Ty is non-null and if the global doesn't exist, 1212f22ef01cSRoman Divacky /// then it will be greated with the specified type instead of whatever the 1213f22ef01cSRoman Divacky /// normal requested type would be. 1214f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 12156122f3e6SDimitry Andric llvm::Type *Ty) { 1216f22ef01cSRoman Divacky assert(D->hasGlobalStorage() && "Not a global variable"); 1217f22ef01cSRoman Divacky QualType ASTTy = D->getType(); 1218f22ef01cSRoman Divacky if (Ty == 0) 1219f22ef01cSRoman Divacky Ty = getTypes().ConvertTypeForMem(ASTTy); 1220f22ef01cSRoman Divacky 12216122f3e6SDimitry Andric llvm::PointerType *PTy = 12223b0f4066SDimitry Andric llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 1223f22ef01cSRoman Divacky 12246122f3e6SDimitry Andric StringRef MangledName = getMangledName(D); 1225f22ef01cSRoman Divacky return GetOrCreateLLVMGlobal(MangledName, PTy, D); 1226f22ef01cSRoman Divacky } 1227f22ef01cSRoman Divacky 1228f22ef01cSRoman Divacky /// CreateRuntimeVariable - Create a new runtime global variable with the 1229f22ef01cSRoman Divacky /// specified type and name. 1230f22ef01cSRoman Divacky llvm::Constant * 12316122f3e6SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 12326122f3e6SDimitry Andric StringRef Name) { 12332754fe60SDimitry Andric return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0, 12342754fe60SDimitry Andric true); 1235f22ef01cSRoman Divacky } 1236f22ef01cSRoman Divacky 1237f22ef01cSRoman Divacky void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 1238f22ef01cSRoman Divacky assert(!D->getInit() && "Cannot emit definite definitions here!"); 1239f22ef01cSRoman Divacky 1240f22ef01cSRoman Divacky if (MayDeferGeneration(D)) { 1241f22ef01cSRoman Divacky // If we have not seen a reference to this variable yet, place it 1242f22ef01cSRoman Divacky // into the deferred declarations table to be emitted if needed 1243f22ef01cSRoman Divacky // later. 12446122f3e6SDimitry Andric StringRef MangledName = getMangledName(D); 1245f22ef01cSRoman Divacky if (!GetGlobalValue(MangledName)) { 1246f22ef01cSRoman Divacky DeferredDecls[MangledName] = D; 1247f22ef01cSRoman Divacky return; 1248f22ef01cSRoman Divacky } 1249f22ef01cSRoman Divacky } 1250f22ef01cSRoman Divacky 1251f22ef01cSRoman Divacky // The tentative definition is the only definition. 1252f22ef01cSRoman Divacky EmitGlobalVarDefinition(D); 1253f22ef01cSRoman Divacky } 1254f22ef01cSRoman Divacky 1255f22ef01cSRoman Divacky void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) { 1256f22ef01cSRoman Divacky if (DefinitionRequired) 1257f22ef01cSRoman Divacky getVTables().GenerateClassData(getVTableLinkage(Class), Class); 1258f22ef01cSRoman Divacky } 1259f22ef01cSRoman Divacky 1260f22ef01cSRoman Divacky llvm::GlobalVariable::LinkageTypes 1261f22ef01cSRoman Divacky CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) { 1262bd5abe19SDimitry Andric if (RD->getLinkage() != ExternalLinkage) 1263f22ef01cSRoman Divacky return llvm::GlobalVariable::InternalLinkage; 1264f22ef01cSRoman Divacky 1265f22ef01cSRoman Divacky if (const CXXMethodDecl *KeyFunction 1266f22ef01cSRoman Divacky = RD->getASTContext().getKeyFunction(RD)) { 1267f22ef01cSRoman Divacky // If this class has a key function, use that to determine the linkage of 1268f22ef01cSRoman Divacky // the vtable. 1269f22ef01cSRoman Divacky const FunctionDecl *Def = 0; 1270ffd1746dSEd Schouten if (KeyFunction->hasBody(Def)) 1271f22ef01cSRoman Divacky KeyFunction = cast<CXXMethodDecl>(Def); 1272f22ef01cSRoman Divacky 1273f22ef01cSRoman Divacky switch (KeyFunction->getTemplateSpecializationKind()) { 1274f22ef01cSRoman Divacky case TSK_Undeclared: 1275f22ef01cSRoman Divacky case TSK_ExplicitSpecialization: 12762754fe60SDimitry Andric // When compiling with optimizations turned on, we emit all vtables, 12772754fe60SDimitry Andric // even if the key function is not defined in the current translation 12782754fe60SDimitry Andric // unit. If this is the case, use available_externally linkage. 12792754fe60SDimitry Andric if (!Def && CodeGenOpts.OptimizationLevel) 12802754fe60SDimitry Andric return llvm::GlobalVariable::AvailableExternallyLinkage; 12812754fe60SDimitry Andric 1282f22ef01cSRoman Divacky if (KeyFunction->isInlined()) 12832754fe60SDimitry Andric return !Context.getLangOptions().AppleKext ? 12842754fe60SDimitry Andric llvm::GlobalVariable::LinkOnceODRLinkage : 12852754fe60SDimitry Andric llvm::Function::InternalLinkage; 1286f22ef01cSRoman Divacky 1287f22ef01cSRoman Divacky return llvm::GlobalVariable::ExternalLinkage; 1288f22ef01cSRoman Divacky 1289f22ef01cSRoman Divacky case TSK_ImplicitInstantiation: 12902754fe60SDimitry Andric return !Context.getLangOptions().AppleKext ? 12912754fe60SDimitry Andric llvm::GlobalVariable::LinkOnceODRLinkage : 12922754fe60SDimitry Andric llvm::Function::InternalLinkage; 12932754fe60SDimitry Andric 1294f22ef01cSRoman Divacky case TSK_ExplicitInstantiationDefinition: 12952754fe60SDimitry Andric return !Context.getLangOptions().AppleKext ? 12962754fe60SDimitry Andric llvm::GlobalVariable::WeakODRLinkage : 12972754fe60SDimitry Andric llvm::Function::InternalLinkage; 1298f22ef01cSRoman Divacky 1299f22ef01cSRoman Divacky case TSK_ExplicitInstantiationDeclaration: 1300f22ef01cSRoman Divacky // FIXME: Use available_externally linkage. However, this currently 1301f22ef01cSRoman Divacky // breaks LLVM's build due to undefined symbols. 1302f22ef01cSRoman Divacky // return llvm::GlobalVariable::AvailableExternallyLinkage; 13032754fe60SDimitry Andric return !Context.getLangOptions().AppleKext ? 13042754fe60SDimitry Andric llvm::GlobalVariable::LinkOnceODRLinkage : 13052754fe60SDimitry Andric llvm::Function::InternalLinkage; 1306f22ef01cSRoman Divacky } 1307f22ef01cSRoman Divacky } 1308f22ef01cSRoman Divacky 13092754fe60SDimitry Andric if (Context.getLangOptions().AppleKext) 13102754fe60SDimitry Andric return llvm::Function::InternalLinkage; 13112754fe60SDimitry Andric 1312f22ef01cSRoman Divacky switch (RD->getTemplateSpecializationKind()) { 1313f22ef01cSRoman Divacky case TSK_Undeclared: 1314f22ef01cSRoman Divacky case TSK_ExplicitSpecialization: 1315f22ef01cSRoman Divacky case TSK_ImplicitInstantiation: 1316f22ef01cSRoman Divacky // FIXME: Use available_externally linkage. However, this currently 1317f22ef01cSRoman Divacky // breaks LLVM's build due to undefined symbols. 1318f22ef01cSRoman Divacky // return llvm::GlobalVariable::AvailableExternallyLinkage; 13192754fe60SDimitry Andric case TSK_ExplicitInstantiationDeclaration: 13202754fe60SDimitry Andric return llvm::GlobalVariable::LinkOnceODRLinkage; 13212754fe60SDimitry Andric 13222754fe60SDimitry Andric case TSK_ExplicitInstantiationDefinition: 1323f22ef01cSRoman Divacky return llvm::GlobalVariable::WeakODRLinkage; 1324f22ef01cSRoman Divacky } 1325f22ef01cSRoman Divacky 1326f22ef01cSRoman Divacky // Silence GCC warning. 13272754fe60SDimitry Andric return llvm::GlobalVariable::LinkOnceODRLinkage; 1328f22ef01cSRoman Divacky } 1329f22ef01cSRoman Divacky 13306122f3e6SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 13312754fe60SDimitry Andric return Context.toCharUnitsFromBits( 13322754fe60SDimitry Andric TheTargetData.getTypeStoreSizeInBits(Ty)); 1333f22ef01cSRoman Divacky } 1334f22ef01cSRoman Divacky 1335f22ef01cSRoman Divacky void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 1336f22ef01cSRoman Divacky llvm::Constant *Init = 0; 1337f22ef01cSRoman Divacky QualType ASTTy = D->getType(); 1338f22ef01cSRoman Divacky bool NonConstInit = false; 1339f22ef01cSRoman Divacky 1340f22ef01cSRoman Divacky const Expr *InitExpr = D->getAnyInitializer(); 1341f22ef01cSRoman Divacky 1342f22ef01cSRoman Divacky if (!InitExpr) { 1343f22ef01cSRoman Divacky // This is a tentative definition; tentative definitions are 1344f22ef01cSRoman Divacky // implicitly initialized with { 0 }. 1345f22ef01cSRoman Divacky // 1346f22ef01cSRoman Divacky // Note that tentative definitions are only emitted at the end of 1347f22ef01cSRoman Divacky // a translation unit, so they should never have incomplete 1348f22ef01cSRoman Divacky // type. In addition, EmitTentativeDefinition makes sure that we 1349f22ef01cSRoman Divacky // never attempt to emit a tentative definition if a real one 1350f22ef01cSRoman Divacky // exists. A use may still exists, however, so we still may need 1351f22ef01cSRoman Divacky // to do a RAUW. 1352f22ef01cSRoman Divacky assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 1353f22ef01cSRoman Divacky Init = EmitNullConstant(D->getType()); 1354f22ef01cSRoman Divacky } else { 1355f22ef01cSRoman Divacky Init = EmitConstantExpr(InitExpr, D->getType()); 1356f22ef01cSRoman Divacky if (!Init) { 1357f22ef01cSRoman Divacky QualType T = InitExpr->getType(); 1358f22ef01cSRoman Divacky if (D->getType()->isReferenceType()) 1359f22ef01cSRoman Divacky T = D->getType(); 1360f22ef01cSRoman Divacky 1361f22ef01cSRoman Divacky if (getLangOptions().CPlusPlus) { 1362f22ef01cSRoman Divacky Init = EmitNullConstant(T); 1363f22ef01cSRoman Divacky NonConstInit = true; 1364f22ef01cSRoman Divacky } else { 1365f22ef01cSRoman Divacky ErrorUnsupported(D, "static initializer"); 1366f22ef01cSRoman Divacky Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 1367f22ef01cSRoman Divacky } 1368e580952dSDimitry Andric } else { 1369e580952dSDimitry Andric // We don't need an initializer, so remove the entry for the delayed 1370e580952dSDimitry Andric // initializer position (just in case this entry was delayed). 1371e580952dSDimitry Andric if (getLangOptions().CPlusPlus) 1372e580952dSDimitry Andric DelayedCXXInitPosition.erase(D); 1373f22ef01cSRoman Divacky } 1374f22ef01cSRoman Divacky } 1375f22ef01cSRoman Divacky 13766122f3e6SDimitry Andric llvm::Type* InitType = Init->getType(); 1377f22ef01cSRoman Divacky llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 1378f22ef01cSRoman Divacky 1379f22ef01cSRoman Divacky // Strip off a bitcast if we got one back. 1380f22ef01cSRoman Divacky if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1381f22ef01cSRoman Divacky assert(CE->getOpcode() == llvm::Instruction::BitCast || 1382f22ef01cSRoman Divacky // all zero index gep. 1383f22ef01cSRoman Divacky CE->getOpcode() == llvm::Instruction::GetElementPtr); 1384f22ef01cSRoman Divacky Entry = CE->getOperand(0); 1385f22ef01cSRoman Divacky } 1386f22ef01cSRoman Divacky 1387f22ef01cSRoman Divacky // Entry is now either a Function or GlobalVariable. 1388f22ef01cSRoman Divacky llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry); 1389f22ef01cSRoman Divacky 1390f22ef01cSRoman Divacky // We have a definition after a declaration with the wrong type. 1391f22ef01cSRoman Divacky // We must make a new GlobalVariable* and update everything that used OldGV 1392f22ef01cSRoman Divacky // (a declaration or tentative definition) with the new GlobalVariable* 1393f22ef01cSRoman Divacky // (which will be a definition). 1394f22ef01cSRoman Divacky // 1395f22ef01cSRoman Divacky // This happens if there is a prototype for a global (e.g. 1396f22ef01cSRoman Divacky // "extern int x[];") and then a definition of a different type (e.g. 1397f22ef01cSRoman Divacky // "int x[10];"). This also happens when an initializer has a different type 1398f22ef01cSRoman Divacky // from the type of the global (this happens with unions). 1399f22ef01cSRoman Divacky if (GV == 0 || 1400f22ef01cSRoman Divacky GV->getType()->getElementType() != InitType || 14013b0f4066SDimitry Andric GV->getType()->getAddressSpace() != 14023b0f4066SDimitry Andric getContext().getTargetAddressSpace(ASTTy)) { 1403f22ef01cSRoman Divacky 1404f22ef01cSRoman Divacky // Move the old entry aside so that we'll create a new one. 14056122f3e6SDimitry Andric Entry->setName(StringRef()); 1406f22ef01cSRoman Divacky 1407f22ef01cSRoman Divacky // Make a new global with the correct type, this is now guaranteed to work. 1408f22ef01cSRoman Divacky GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 1409f22ef01cSRoman Divacky 1410f22ef01cSRoman Divacky // Replace all uses of the old global with the new global 1411f22ef01cSRoman Divacky llvm::Constant *NewPtrForOldDecl = 1412f22ef01cSRoman Divacky llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 1413f22ef01cSRoman Divacky Entry->replaceAllUsesWith(NewPtrForOldDecl); 1414f22ef01cSRoman Divacky 1415f22ef01cSRoman Divacky // Erase the old global, since it is no longer used. 1416f22ef01cSRoman Divacky cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 1417f22ef01cSRoman Divacky } 1418f22ef01cSRoman Divacky 14196122f3e6SDimitry Andric if (D->hasAttr<AnnotateAttr>()) 14206122f3e6SDimitry Andric AddGlobalAnnotations(D, GV); 1421f22ef01cSRoman Divacky 1422f22ef01cSRoman Divacky GV->setInitializer(Init); 1423f22ef01cSRoman Divacky 1424f22ef01cSRoman Divacky // If it is safe to mark the global 'constant', do so now. 1425f22ef01cSRoman Divacky GV->setConstant(false); 1426bd5abe19SDimitry Andric if (!NonConstInit && DeclIsConstantGlobal(Context, D, true)) 1427f22ef01cSRoman Divacky GV->setConstant(true); 1428f22ef01cSRoman Divacky 1429f22ef01cSRoman Divacky GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 1430f22ef01cSRoman Divacky 1431f22ef01cSRoman Divacky // Set the llvm linkage type as appropriate. 14322754fe60SDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = 14332754fe60SDimitry Andric GetLLVMLinkageVarDefinition(D, GV); 14342754fe60SDimitry Andric GV->setLinkage(Linkage); 14352754fe60SDimitry Andric if (Linkage == llvm::GlobalVariable::CommonLinkage) 1436f22ef01cSRoman Divacky // common vars aren't constant even if declared const. 1437f22ef01cSRoman Divacky GV->setConstant(false); 1438f22ef01cSRoman Divacky 1439f22ef01cSRoman Divacky SetCommonAttributes(D, GV); 1440f22ef01cSRoman Divacky 14412754fe60SDimitry Andric // Emit the initializer function if necessary. 14422754fe60SDimitry Andric if (NonConstInit) 14432754fe60SDimitry Andric EmitCXXGlobalVarDeclInitFunc(D, GV); 14442754fe60SDimitry Andric 1445f22ef01cSRoman Divacky // Emit global variable debug information. 14466122f3e6SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 1447f22ef01cSRoman Divacky DI->EmitGlobalVariable(GV, D); 1448f22ef01cSRoman Divacky } 1449f22ef01cSRoman Divacky 14502754fe60SDimitry Andric llvm::GlobalValue::LinkageTypes 14512754fe60SDimitry Andric CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D, 14522754fe60SDimitry Andric llvm::GlobalVariable *GV) { 14532754fe60SDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForVariable(D); 14542754fe60SDimitry Andric if (Linkage == GVA_Internal) 14552754fe60SDimitry Andric return llvm::Function::InternalLinkage; 14562754fe60SDimitry Andric else if (D->hasAttr<DLLImportAttr>()) 14572754fe60SDimitry Andric return llvm::Function::DLLImportLinkage; 14582754fe60SDimitry Andric else if (D->hasAttr<DLLExportAttr>()) 14592754fe60SDimitry Andric return llvm::Function::DLLExportLinkage; 14602754fe60SDimitry Andric else if (D->hasAttr<WeakAttr>()) { 14612754fe60SDimitry Andric if (GV->isConstant()) 14622754fe60SDimitry Andric return llvm::GlobalVariable::WeakODRLinkage; 14632754fe60SDimitry Andric else 14642754fe60SDimitry Andric return llvm::GlobalVariable::WeakAnyLinkage; 14652754fe60SDimitry Andric } else if (Linkage == GVA_TemplateInstantiation || 14662754fe60SDimitry Andric Linkage == GVA_ExplicitTemplateInstantiation) 14673b0f4066SDimitry Andric return llvm::GlobalVariable::WeakODRLinkage; 14682754fe60SDimitry Andric else if (!getLangOptions().CPlusPlus && 14692754fe60SDimitry Andric ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) || 14702754fe60SDimitry Andric D->getAttr<CommonAttr>()) && 14712754fe60SDimitry Andric !D->hasExternalStorage() && !D->getInit() && 147217a519f9SDimitry Andric !D->getAttr<SectionAttr>() && !D->isThreadSpecified() && 147317a519f9SDimitry Andric !D->getAttr<WeakImportAttr>()) { 14742754fe60SDimitry Andric // Thread local vars aren't considered common linkage. 14752754fe60SDimitry Andric return llvm::GlobalVariable::CommonLinkage; 14762754fe60SDimitry Andric } 14772754fe60SDimitry Andric return llvm::GlobalVariable::ExternalLinkage; 14782754fe60SDimitry Andric } 14792754fe60SDimitry Andric 1480f22ef01cSRoman Divacky /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 1481f22ef01cSRoman Divacky /// implement a function with no prototype, e.g. "int foo() {}". If there are 1482f22ef01cSRoman Divacky /// existing call uses of the old function in the module, this adjusts them to 1483f22ef01cSRoman Divacky /// call the new function directly. 1484f22ef01cSRoman Divacky /// 1485f22ef01cSRoman Divacky /// This is not just a cleanup: the always_inline pass requires direct calls to 1486f22ef01cSRoman Divacky /// functions to be able to inline them. If there is a bitcast in the way, it 1487f22ef01cSRoman Divacky /// won't inline them. Instcombine normally deletes these calls, but it isn't 1488f22ef01cSRoman Divacky /// run at -O0. 1489f22ef01cSRoman Divacky static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 1490f22ef01cSRoman Divacky llvm::Function *NewFn) { 1491f22ef01cSRoman Divacky // If we're redefining a global as a function, don't transform it. 1492f22ef01cSRoman Divacky llvm::Function *OldFn = dyn_cast<llvm::Function>(Old); 1493f22ef01cSRoman Divacky if (OldFn == 0) return; 1494f22ef01cSRoman Divacky 14956122f3e6SDimitry Andric llvm::Type *NewRetTy = NewFn->getReturnType(); 14966122f3e6SDimitry Andric SmallVector<llvm::Value*, 4> ArgList; 1497f22ef01cSRoman Divacky 1498f22ef01cSRoman Divacky for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end(); 1499f22ef01cSRoman Divacky UI != E; ) { 1500f22ef01cSRoman Divacky // TODO: Do invokes ever occur in C code? If so, we should handle them too. 1501f22ef01cSRoman Divacky llvm::Value::use_iterator I = UI++; // Increment before the CI is erased. 1502f22ef01cSRoman Divacky llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I); 1503e580952dSDimitry Andric if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I) 1504f22ef01cSRoman Divacky llvm::CallSite CS(CI); 1505f22ef01cSRoman Divacky if (!CI || !CS.isCallee(I)) continue; 1506f22ef01cSRoman Divacky 1507f22ef01cSRoman Divacky // If the return types don't match exactly, and if the call isn't dead, then 1508f22ef01cSRoman Divacky // we can't transform this call. 1509f22ef01cSRoman Divacky if (CI->getType() != NewRetTy && !CI->use_empty()) 1510f22ef01cSRoman Divacky continue; 1511f22ef01cSRoman Divacky 15126122f3e6SDimitry Andric // Get the attribute list. 15136122f3e6SDimitry Andric llvm::SmallVector<llvm::AttributeWithIndex, 8> AttrVec; 15146122f3e6SDimitry Andric llvm::AttrListPtr AttrList = CI->getAttributes(); 15156122f3e6SDimitry Andric 15166122f3e6SDimitry Andric // Get any return attributes. 15176122f3e6SDimitry Andric llvm::Attributes RAttrs = AttrList.getRetAttributes(); 15186122f3e6SDimitry Andric 15196122f3e6SDimitry Andric // Add the return attributes. 15206122f3e6SDimitry Andric if (RAttrs) 15216122f3e6SDimitry Andric AttrVec.push_back(llvm::AttributeWithIndex::get(0, RAttrs)); 15226122f3e6SDimitry Andric 1523f22ef01cSRoman Divacky // If the function was passed too few arguments, don't transform. If extra 1524f22ef01cSRoman Divacky // arguments were passed, we silently drop them. If any of the types 1525f22ef01cSRoman Divacky // mismatch, we don't transform. 1526f22ef01cSRoman Divacky unsigned ArgNo = 0; 1527f22ef01cSRoman Divacky bool DontTransform = false; 1528f22ef01cSRoman Divacky for (llvm::Function::arg_iterator AI = NewFn->arg_begin(), 1529f22ef01cSRoman Divacky E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) { 1530f22ef01cSRoman Divacky if (CS.arg_size() == ArgNo || 1531f22ef01cSRoman Divacky CS.getArgument(ArgNo)->getType() != AI->getType()) { 1532f22ef01cSRoman Divacky DontTransform = true; 1533f22ef01cSRoman Divacky break; 1534f22ef01cSRoman Divacky } 15356122f3e6SDimitry Andric 15366122f3e6SDimitry Andric // Add any parameter attributes. 15376122f3e6SDimitry Andric if (llvm::Attributes PAttrs = AttrList.getParamAttributes(ArgNo + 1)) 15386122f3e6SDimitry Andric AttrVec.push_back(llvm::AttributeWithIndex::get(ArgNo + 1, PAttrs)); 1539f22ef01cSRoman Divacky } 1540f22ef01cSRoman Divacky if (DontTransform) 1541f22ef01cSRoman Divacky continue; 1542f22ef01cSRoman Divacky 15436122f3e6SDimitry Andric if (llvm::Attributes FnAttrs = AttrList.getFnAttributes()) 15446122f3e6SDimitry Andric AttrVec.push_back(llvm::AttributeWithIndex::get(~0, FnAttrs)); 15456122f3e6SDimitry Andric 1546f22ef01cSRoman Divacky // Okay, we can transform this. Create the new call instruction and copy 1547f22ef01cSRoman Divacky // over the required information. 1548f22ef01cSRoman Divacky ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo); 154917a519f9SDimitry Andric llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList, "", CI); 1550f22ef01cSRoman Divacky ArgList.clear(); 1551f22ef01cSRoman Divacky if (!NewCall->getType()->isVoidTy()) 1552f22ef01cSRoman Divacky NewCall->takeName(CI); 15536122f3e6SDimitry Andric NewCall->setAttributes(llvm::AttrListPtr::get(AttrVec.begin(), 15546122f3e6SDimitry Andric AttrVec.end())); 1555f22ef01cSRoman Divacky NewCall->setCallingConv(CI->getCallingConv()); 1556f22ef01cSRoman Divacky 1557f22ef01cSRoman Divacky // Finally, remove the old call, replacing any uses with the new one. 1558f22ef01cSRoman Divacky if (!CI->use_empty()) 1559f22ef01cSRoman Divacky CI->replaceAllUsesWith(NewCall); 1560f22ef01cSRoman Divacky 1561f22ef01cSRoman Divacky // Copy debug location attached to CI. 1562f22ef01cSRoman Divacky if (!CI->getDebugLoc().isUnknown()) 1563f22ef01cSRoman Divacky NewCall->setDebugLoc(CI->getDebugLoc()); 1564f22ef01cSRoman Divacky CI->eraseFromParent(); 1565f22ef01cSRoman Divacky } 1566f22ef01cSRoman Divacky } 1567f22ef01cSRoman Divacky 1568f22ef01cSRoman Divacky 1569f22ef01cSRoman Divacky void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) { 1570f22ef01cSRoman Divacky const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl()); 15713b0f4066SDimitry Andric 15723b0f4066SDimitry Andric // Compute the function info and LLVM type. 15733b0f4066SDimitry Andric const CGFunctionInfo &FI = getTypes().getFunctionInfo(GD); 15743b0f4066SDimitry Andric bool variadic = false; 15753b0f4066SDimitry Andric if (const FunctionProtoType *fpt = D->getType()->getAs<FunctionProtoType>()) 15763b0f4066SDimitry Andric variadic = fpt->isVariadic(); 15776122f3e6SDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI, variadic); 15783b0f4066SDimitry Andric 1579f22ef01cSRoman Divacky // Get or create the prototype for the function. 1580f22ef01cSRoman Divacky llvm::Constant *Entry = GetAddrOfFunction(GD, Ty); 1581f22ef01cSRoman Divacky 1582f22ef01cSRoman Divacky // Strip off a bitcast if we got one back. 1583f22ef01cSRoman Divacky if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1584f22ef01cSRoman Divacky assert(CE->getOpcode() == llvm::Instruction::BitCast); 1585f22ef01cSRoman Divacky Entry = CE->getOperand(0); 1586f22ef01cSRoman Divacky } 1587f22ef01cSRoman Divacky 1588f22ef01cSRoman Divacky 1589f22ef01cSRoman Divacky if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) { 1590f22ef01cSRoman Divacky llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry); 1591f22ef01cSRoman Divacky 1592f22ef01cSRoman Divacky // If the types mismatch then we have to rewrite the definition. 1593f22ef01cSRoman Divacky assert(OldFn->isDeclaration() && 1594f22ef01cSRoman Divacky "Shouldn't replace non-declaration"); 1595f22ef01cSRoman Divacky 1596f22ef01cSRoman Divacky // F is the Function* for the one with the wrong type, we must make a new 1597f22ef01cSRoman Divacky // Function* and update everything that used F (a declaration) with the new 1598f22ef01cSRoman Divacky // Function* (which will be a definition). 1599f22ef01cSRoman Divacky // 1600f22ef01cSRoman Divacky // This happens if there is a prototype for a function 1601f22ef01cSRoman Divacky // (e.g. "int f()") and then a definition of a different type 1602f22ef01cSRoman Divacky // (e.g. "int f(int x)"). Move the old function aside so that it 1603f22ef01cSRoman Divacky // doesn't interfere with GetAddrOfFunction. 16046122f3e6SDimitry Andric OldFn->setName(StringRef()); 1605f22ef01cSRoman Divacky llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty)); 1606f22ef01cSRoman Divacky 1607f22ef01cSRoman Divacky // If this is an implementation of a function without a prototype, try to 1608f22ef01cSRoman Divacky // replace any existing uses of the function (which may be calls) with uses 1609f22ef01cSRoman Divacky // of the new function 1610f22ef01cSRoman Divacky if (D->getType()->isFunctionNoProtoType()) { 1611f22ef01cSRoman Divacky ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn); 1612f22ef01cSRoman Divacky OldFn->removeDeadConstantUsers(); 1613f22ef01cSRoman Divacky } 1614f22ef01cSRoman Divacky 1615f22ef01cSRoman Divacky // Replace uses of F with the Function we will endow with a body. 1616f22ef01cSRoman Divacky if (!Entry->use_empty()) { 1617f22ef01cSRoman Divacky llvm::Constant *NewPtrForOldDecl = 1618f22ef01cSRoman Divacky llvm::ConstantExpr::getBitCast(NewFn, Entry->getType()); 1619f22ef01cSRoman Divacky Entry->replaceAllUsesWith(NewPtrForOldDecl); 1620f22ef01cSRoman Divacky } 1621f22ef01cSRoman Divacky 1622f22ef01cSRoman Divacky // Ok, delete the old function now, which is dead. 1623f22ef01cSRoman Divacky OldFn->eraseFromParent(); 1624f22ef01cSRoman Divacky 1625f22ef01cSRoman Divacky Entry = NewFn; 1626f22ef01cSRoman Divacky } 1627f22ef01cSRoman Divacky 16282754fe60SDimitry Andric // We need to set linkage and visibility on the function before 16292754fe60SDimitry Andric // generating code for it because various parts of IR generation 16302754fe60SDimitry Andric // want to propagate this information down (e.g. to local static 16312754fe60SDimitry Andric // declarations). 1632f22ef01cSRoman Divacky llvm::Function *Fn = cast<llvm::Function>(Entry); 1633f22ef01cSRoman Divacky setFunctionLinkage(D, Fn); 1634f22ef01cSRoman Divacky 16352754fe60SDimitry Andric // FIXME: this is redundant with part of SetFunctionDefinitionAttributes 16362754fe60SDimitry Andric setGlobalVisibility(Fn, D); 16372754fe60SDimitry Andric 16383b0f4066SDimitry Andric CodeGenFunction(*this).GenerateCode(D, Fn, FI); 1639f22ef01cSRoman Divacky 1640f22ef01cSRoman Divacky SetFunctionDefinitionAttributes(D, Fn); 1641f22ef01cSRoman Divacky SetLLVMFunctionAttributesForDefinition(D, Fn); 1642f22ef01cSRoman Divacky 1643f22ef01cSRoman Divacky if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 1644f22ef01cSRoman Divacky AddGlobalCtor(Fn, CA->getPriority()); 1645f22ef01cSRoman Divacky if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 1646f22ef01cSRoman Divacky AddGlobalDtor(Fn, DA->getPriority()); 16476122f3e6SDimitry Andric if (D->hasAttr<AnnotateAttr>()) 16486122f3e6SDimitry Andric AddGlobalAnnotations(D, Fn); 1649f22ef01cSRoman Divacky } 1650f22ef01cSRoman Divacky 1651f22ef01cSRoman Divacky void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 1652f22ef01cSRoman Divacky const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 1653f22ef01cSRoman Divacky const AliasAttr *AA = D->getAttr<AliasAttr>(); 1654f22ef01cSRoman Divacky assert(AA && "Not an alias?"); 1655f22ef01cSRoman Divacky 16566122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 1657f22ef01cSRoman Divacky 1658f22ef01cSRoman Divacky // If there is a definition in the module, then it wins over the alias. 1659f22ef01cSRoman Divacky // This is dubious, but allow it to be safe. Just ignore the alias. 1660f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1661f22ef01cSRoman Divacky if (Entry && !Entry->isDeclaration()) 1662f22ef01cSRoman Divacky return; 1663f22ef01cSRoman Divacky 16646122f3e6SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 1665f22ef01cSRoman Divacky 1666f22ef01cSRoman Divacky // Create a reference to the named value. This ensures that it is emitted 1667f22ef01cSRoman Divacky // if a deferred decl. 1668f22ef01cSRoman Divacky llvm::Constant *Aliasee; 1669f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(DeclTy)) 16702754fe60SDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(), 16712754fe60SDimitry Andric /*ForVTable=*/false); 1672f22ef01cSRoman Divacky else 1673f22ef01cSRoman Divacky Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 1674f22ef01cSRoman Divacky llvm::PointerType::getUnqual(DeclTy), 0); 1675f22ef01cSRoman Divacky 1676f22ef01cSRoman Divacky // Create the new alias itself, but don't set a name yet. 1677f22ef01cSRoman Divacky llvm::GlobalValue *GA = 1678f22ef01cSRoman Divacky new llvm::GlobalAlias(Aliasee->getType(), 1679f22ef01cSRoman Divacky llvm::Function::ExternalLinkage, 1680f22ef01cSRoman Divacky "", Aliasee, &getModule()); 1681f22ef01cSRoman Divacky 1682f22ef01cSRoman Divacky if (Entry) { 1683f22ef01cSRoman Divacky assert(Entry->isDeclaration()); 1684f22ef01cSRoman Divacky 1685f22ef01cSRoman Divacky // If there is a declaration in the module, then we had an extern followed 1686f22ef01cSRoman Divacky // by the alias, as in: 1687f22ef01cSRoman Divacky // extern int test6(); 1688f22ef01cSRoman Divacky // ... 1689f22ef01cSRoman Divacky // int test6() __attribute__((alias("test7"))); 1690f22ef01cSRoman Divacky // 1691f22ef01cSRoman Divacky // Remove it and replace uses of it with the alias. 1692f22ef01cSRoman Divacky GA->takeName(Entry); 1693f22ef01cSRoman Divacky 1694f22ef01cSRoman Divacky Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 1695f22ef01cSRoman Divacky Entry->getType())); 1696f22ef01cSRoman Divacky Entry->eraseFromParent(); 1697f22ef01cSRoman Divacky } else { 1698ffd1746dSEd Schouten GA->setName(MangledName); 1699f22ef01cSRoman Divacky } 1700f22ef01cSRoman Divacky 1701f22ef01cSRoman Divacky // Set attributes which are particular to an alias; this is a 1702f22ef01cSRoman Divacky // specialization of the attributes which may be set on a global 1703f22ef01cSRoman Divacky // variable/function. 1704f22ef01cSRoman Divacky if (D->hasAttr<DLLExportAttr>()) { 1705f22ef01cSRoman Divacky if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1706f22ef01cSRoman Divacky // The dllexport attribute is ignored for undefined symbols. 1707ffd1746dSEd Schouten if (FD->hasBody()) 1708f22ef01cSRoman Divacky GA->setLinkage(llvm::Function::DLLExportLinkage); 1709f22ef01cSRoman Divacky } else { 1710f22ef01cSRoman Divacky GA->setLinkage(llvm::Function::DLLExportLinkage); 1711f22ef01cSRoman Divacky } 1712f22ef01cSRoman Divacky } else if (D->hasAttr<WeakAttr>() || 1713f22ef01cSRoman Divacky D->hasAttr<WeakRefAttr>() || 17143b0f4066SDimitry Andric D->isWeakImported()) { 1715f22ef01cSRoman Divacky GA->setLinkage(llvm::Function::WeakAnyLinkage); 1716f22ef01cSRoman Divacky } 1717f22ef01cSRoman Divacky 1718f22ef01cSRoman Divacky SetCommonAttributes(D, GA); 1719f22ef01cSRoman Divacky } 1720f22ef01cSRoman Divacky 172117a519f9SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 17226122f3e6SDimitry Andric ArrayRef<llvm::Type*> Tys) { 172317a519f9SDimitry Andric return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 172417a519f9SDimitry Andric Tys); 1725f22ef01cSRoman Divacky } 1726f22ef01cSRoman Divacky 1727f22ef01cSRoman Divacky static llvm::StringMapEntry<llvm::Constant*> & 1728f22ef01cSRoman Divacky GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map, 1729f22ef01cSRoman Divacky const StringLiteral *Literal, 1730f22ef01cSRoman Divacky bool TargetIsLSB, 1731f22ef01cSRoman Divacky bool &IsUTF16, 1732f22ef01cSRoman Divacky unsigned &StringLength) { 17336122f3e6SDimitry Andric StringRef String = Literal->getString(); 1734e580952dSDimitry Andric unsigned NumBytes = String.size(); 1735f22ef01cSRoman Divacky 1736f22ef01cSRoman Divacky // Check for simple case. 1737f22ef01cSRoman Divacky if (!Literal->containsNonAsciiOrNull()) { 1738f22ef01cSRoman Divacky StringLength = NumBytes; 1739e580952dSDimitry Andric return Map.GetOrCreateValue(String); 1740f22ef01cSRoman Divacky } 1741f22ef01cSRoman Divacky 1742f22ef01cSRoman Divacky // Otherwise, convert the UTF8 literals into a byte string. 17436122f3e6SDimitry Andric SmallVector<UTF16, 128> ToBuf(NumBytes); 1744e580952dSDimitry Andric const UTF8 *FromPtr = (UTF8 *)String.data(); 1745f22ef01cSRoman Divacky UTF16 *ToPtr = &ToBuf[0]; 1746f22ef01cSRoman Divacky 17472754fe60SDimitry Andric (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 1748f22ef01cSRoman Divacky &ToPtr, ToPtr + NumBytes, 1749f22ef01cSRoman Divacky strictConversion); 1750f22ef01cSRoman Divacky 1751f22ef01cSRoman Divacky // ConvertUTF8toUTF16 returns the length in ToPtr. 1752f22ef01cSRoman Divacky StringLength = ToPtr - &ToBuf[0]; 1753f22ef01cSRoman Divacky 1754f22ef01cSRoman Divacky // Render the UTF-16 string into a byte array and convert to the target byte 1755f22ef01cSRoman Divacky // order. 1756f22ef01cSRoman Divacky // 1757f22ef01cSRoman Divacky // FIXME: This isn't something we should need to do here. 1758f22ef01cSRoman Divacky llvm::SmallString<128> AsBytes; 1759f22ef01cSRoman Divacky AsBytes.reserve(StringLength * 2); 1760f22ef01cSRoman Divacky for (unsigned i = 0; i != StringLength; ++i) { 1761f22ef01cSRoman Divacky unsigned short Val = ToBuf[i]; 1762f22ef01cSRoman Divacky if (TargetIsLSB) { 1763f22ef01cSRoman Divacky AsBytes.push_back(Val & 0xFF); 1764f22ef01cSRoman Divacky AsBytes.push_back(Val >> 8); 1765f22ef01cSRoman Divacky } else { 1766f22ef01cSRoman Divacky AsBytes.push_back(Val >> 8); 1767f22ef01cSRoman Divacky AsBytes.push_back(Val & 0xFF); 1768f22ef01cSRoman Divacky } 1769f22ef01cSRoman Divacky } 1770f22ef01cSRoman Divacky // Append one extra null character, the second is automatically added by our 1771f22ef01cSRoman Divacky // caller. 1772f22ef01cSRoman Divacky AsBytes.push_back(0); 1773f22ef01cSRoman Divacky 1774f22ef01cSRoman Divacky IsUTF16 = true; 17756122f3e6SDimitry Andric return Map.GetOrCreateValue(StringRef(AsBytes.data(), AsBytes.size())); 1776f22ef01cSRoman Divacky } 1777f22ef01cSRoman Divacky 1778bd5abe19SDimitry Andric static llvm::StringMapEntry<llvm::Constant*> & 1779bd5abe19SDimitry Andric GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map, 1780bd5abe19SDimitry Andric const StringLiteral *Literal, 1781bd5abe19SDimitry Andric unsigned &StringLength) 1782bd5abe19SDimitry Andric { 17836122f3e6SDimitry Andric StringRef String = Literal->getString(); 1784bd5abe19SDimitry Andric StringLength = String.size(); 1785bd5abe19SDimitry Andric return Map.GetOrCreateValue(String); 1786bd5abe19SDimitry Andric } 1787bd5abe19SDimitry Andric 1788f22ef01cSRoman Divacky llvm::Constant * 1789f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 1790f22ef01cSRoman Divacky unsigned StringLength = 0; 1791f22ef01cSRoman Divacky bool isUTF16 = false; 1792f22ef01cSRoman Divacky llvm::StringMapEntry<llvm::Constant*> &Entry = 1793f22ef01cSRoman Divacky GetConstantCFStringEntry(CFConstantStringMap, Literal, 1794f22ef01cSRoman Divacky getTargetData().isLittleEndian(), 1795f22ef01cSRoman Divacky isUTF16, StringLength); 1796f22ef01cSRoman Divacky 1797f22ef01cSRoman Divacky if (llvm::Constant *C = Entry.getValue()) 1798f22ef01cSRoman Divacky return C; 1799f22ef01cSRoman Divacky 1800f22ef01cSRoman Divacky llvm::Constant *Zero = 1801f22ef01cSRoman Divacky llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)); 1802f22ef01cSRoman Divacky llvm::Constant *Zeros[] = { Zero, Zero }; 1803f22ef01cSRoman Divacky 1804f22ef01cSRoman Divacky // If we don't already have it, get __CFConstantStringClassReference. 1805f22ef01cSRoman Divacky if (!CFConstantStringClassRef) { 18066122f3e6SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 1807f22ef01cSRoman Divacky Ty = llvm::ArrayType::get(Ty, 0); 1808f22ef01cSRoman Divacky llvm::Constant *GV = CreateRuntimeVariable(Ty, 1809f22ef01cSRoman Divacky "__CFConstantStringClassReference"); 1810f22ef01cSRoman Divacky // Decay array -> ptr 1811f22ef01cSRoman Divacky CFConstantStringClassRef = 18126122f3e6SDimitry Andric llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 1813f22ef01cSRoman Divacky } 1814f22ef01cSRoman Divacky 1815f22ef01cSRoman Divacky QualType CFTy = getContext().getCFConstantStringType(); 1816f22ef01cSRoman Divacky 18176122f3e6SDimitry Andric llvm::StructType *STy = 1818f22ef01cSRoman Divacky cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 1819f22ef01cSRoman Divacky 1820f22ef01cSRoman Divacky std::vector<llvm::Constant*> Fields(4); 1821f22ef01cSRoman Divacky 1822f22ef01cSRoman Divacky // Class pointer. 1823f22ef01cSRoman Divacky Fields[0] = CFConstantStringClassRef; 1824f22ef01cSRoman Divacky 1825f22ef01cSRoman Divacky // Flags. 18266122f3e6SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 1827f22ef01cSRoman Divacky Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 1828f22ef01cSRoman Divacky llvm::ConstantInt::get(Ty, 0x07C8); 1829f22ef01cSRoman Divacky 1830f22ef01cSRoman Divacky // String pointer. 1831f22ef01cSRoman Divacky llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str()); 1832f22ef01cSRoman Divacky 1833f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes Linkage; 1834f22ef01cSRoman Divacky bool isConstant; 1835f22ef01cSRoman Divacky if (isUTF16) { 1836f22ef01cSRoman Divacky // FIXME: why do utf strings get "_" labels instead of "L" labels? 1837f22ef01cSRoman Divacky Linkage = llvm::GlobalValue::InternalLinkage; 1838f22ef01cSRoman Divacky // Note: -fwritable-strings doesn't make unicode CFStrings writable, but 1839f22ef01cSRoman Divacky // does make plain ascii ones writable. 1840f22ef01cSRoman Divacky isConstant = true; 1841f22ef01cSRoman Divacky } else { 18423b0f4066SDimitry Andric // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error 18433b0f4066SDimitry Andric // when using private linkage. It is not clear if this is a bug in ld 18443b0f4066SDimitry Andric // or a reasonable new restriction. 18453b0f4066SDimitry Andric Linkage = llvm::GlobalValue::LinkerPrivateLinkage; 1846f22ef01cSRoman Divacky isConstant = !Features.WritableStrings; 1847f22ef01cSRoman Divacky } 1848f22ef01cSRoman Divacky 1849f22ef01cSRoman Divacky llvm::GlobalVariable *GV = 1850f22ef01cSRoman Divacky new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 1851f22ef01cSRoman Divacky ".str"); 18522754fe60SDimitry Andric GV->setUnnamedAddr(true); 1853f22ef01cSRoman Divacky if (isUTF16) { 1854f22ef01cSRoman Divacky CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 1855f22ef01cSRoman Divacky GV->setAlignment(Align.getQuantity()); 18563b0f4066SDimitry Andric } else { 18573b0f4066SDimitry Andric CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 18583b0f4066SDimitry Andric GV->setAlignment(Align.getQuantity()); 1859f22ef01cSRoman Divacky } 18606122f3e6SDimitry Andric Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 1861f22ef01cSRoman Divacky 1862f22ef01cSRoman Divacky // String length. 1863f22ef01cSRoman Divacky Ty = getTypes().ConvertType(getContext().LongTy); 1864f22ef01cSRoman Divacky Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 1865f22ef01cSRoman Divacky 1866f22ef01cSRoman Divacky // The struct. 1867f22ef01cSRoman Divacky C = llvm::ConstantStruct::get(STy, Fields); 1868f22ef01cSRoman Divacky GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 1869f22ef01cSRoman Divacky llvm::GlobalVariable::PrivateLinkage, C, 1870f22ef01cSRoman Divacky "_unnamed_cfstring_"); 18716122f3e6SDimitry Andric if (const char *Sect = getContext().getTargetInfo().getCFStringSection()) 1872f22ef01cSRoman Divacky GV->setSection(Sect); 1873f22ef01cSRoman Divacky Entry.setValue(GV); 1874f22ef01cSRoman Divacky 1875f22ef01cSRoman Divacky return GV; 1876f22ef01cSRoman Divacky } 1877f22ef01cSRoman Divacky 18786122f3e6SDimitry Andric static RecordDecl * 18796122f3e6SDimitry Andric CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK, 18806122f3e6SDimitry Andric DeclContext *DC, IdentifierInfo *Id) { 18816122f3e6SDimitry Andric SourceLocation Loc; 18826122f3e6SDimitry Andric if (Ctx.getLangOptions().CPlusPlus) 18836122f3e6SDimitry Andric return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 18846122f3e6SDimitry Andric else 18856122f3e6SDimitry Andric return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 18866122f3e6SDimitry Andric } 18876122f3e6SDimitry Andric 1888f22ef01cSRoman Divacky llvm::Constant * 18892754fe60SDimitry Andric CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) { 1890f22ef01cSRoman Divacky unsigned StringLength = 0; 1891f22ef01cSRoman Divacky llvm::StringMapEntry<llvm::Constant*> &Entry = 1892bd5abe19SDimitry Andric GetConstantStringEntry(CFConstantStringMap, Literal, StringLength); 1893f22ef01cSRoman Divacky 1894f22ef01cSRoman Divacky if (llvm::Constant *C = Entry.getValue()) 1895f22ef01cSRoman Divacky return C; 1896f22ef01cSRoman Divacky 1897f22ef01cSRoman Divacky llvm::Constant *Zero = 1898f22ef01cSRoman Divacky llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)); 1899f22ef01cSRoman Divacky llvm::Constant *Zeros[] = { Zero, Zero }; 1900f22ef01cSRoman Divacky 1901f22ef01cSRoman Divacky // If we don't already have it, get _NSConstantStringClassReference. 19022754fe60SDimitry Andric if (!ConstantStringClassRef) { 19032754fe60SDimitry Andric std::string StringClass(getLangOptions().ObjCConstantStringClass); 19046122f3e6SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 19052754fe60SDimitry Andric llvm::Constant *GV; 1906bd5abe19SDimitry Andric if (Features.ObjCNonFragileABI) { 1907bd5abe19SDimitry Andric std::string str = 1908bd5abe19SDimitry Andric StringClass.empty() ? "OBJC_CLASS_$_NSConstantString" 1909bd5abe19SDimitry Andric : "OBJC_CLASS_$_" + StringClass; 1910bd5abe19SDimitry Andric GV = getObjCRuntime().GetClassGlobal(str); 1911bd5abe19SDimitry Andric // Make sure the result is of the correct type. 19126122f3e6SDimitry Andric llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 1913bd5abe19SDimitry Andric ConstantStringClassRef = 1914bd5abe19SDimitry Andric llvm::ConstantExpr::getBitCast(GV, PTy); 1915bd5abe19SDimitry Andric } else { 1916bd5abe19SDimitry Andric std::string str = 1917bd5abe19SDimitry Andric StringClass.empty() ? "_NSConstantStringClassReference" 1918bd5abe19SDimitry Andric : "_" + StringClass + "ClassReference"; 19196122f3e6SDimitry Andric llvm::Type *PTy = llvm::ArrayType::get(Ty, 0); 1920bd5abe19SDimitry Andric GV = CreateRuntimeVariable(PTy, str); 1921f22ef01cSRoman Divacky // Decay array -> ptr 19222754fe60SDimitry Andric ConstantStringClassRef = 19236122f3e6SDimitry Andric llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 1924f22ef01cSRoman Divacky } 1925bd5abe19SDimitry Andric } 1926f22ef01cSRoman Divacky 19276122f3e6SDimitry Andric if (!NSConstantStringType) { 19286122f3e6SDimitry Andric // Construct the type for a constant NSString. 19296122f3e6SDimitry Andric RecordDecl *D = CreateRecordDecl(Context, TTK_Struct, 19306122f3e6SDimitry Andric Context.getTranslationUnitDecl(), 19316122f3e6SDimitry Andric &Context.Idents.get("__builtin_NSString")); 19326122f3e6SDimitry Andric D->startDefinition(); 1933f22ef01cSRoman Divacky 19346122f3e6SDimitry Andric QualType FieldTypes[3]; 19356122f3e6SDimitry Andric 19366122f3e6SDimitry Andric // const int *isa; 19376122f3e6SDimitry Andric FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst()); 19386122f3e6SDimitry Andric // const char *str; 19396122f3e6SDimitry Andric FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst()); 19406122f3e6SDimitry Andric // unsigned int length; 19416122f3e6SDimitry Andric FieldTypes[2] = Context.UnsignedIntTy; 19426122f3e6SDimitry Andric 19436122f3e6SDimitry Andric // Create fields 19446122f3e6SDimitry Andric for (unsigned i = 0; i < 3; ++i) { 19456122f3e6SDimitry Andric FieldDecl *Field = FieldDecl::Create(Context, D, 19466122f3e6SDimitry Andric SourceLocation(), 19476122f3e6SDimitry Andric SourceLocation(), 0, 19486122f3e6SDimitry Andric FieldTypes[i], /*TInfo=*/0, 19496122f3e6SDimitry Andric /*BitWidth=*/0, 19506122f3e6SDimitry Andric /*Mutable=*/false, 19516122f3e6SDimitry Andric /*HasInit=*/false); 19526122f3e6SDimitry Andric Field->setAccess(AS_public); 19536122f3e6SDimitry Andric D->addDecl(Field); 19546122f3e6SDimitry Andric } 19556122f3e6SDimitry Andric 19566122f3e6SDimitry Andric D->completeDefinition(); 19576122f3e6SDimitry Andric QualType NSTy = Context.getTagDeclType(D); 19586122f3e6SDimitry Andric NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy)); 19596122f3e6SDimitry Andric } 1960f22ef01cSRoman Divacky 1961f22ef01cSRoman Divacky std::vector<llvm::Constant*> Fields(3); 1962f22ef01cSRoman Divacky 1963f22ef01cSRoman Divacky // Class pointer. 19642754fe60SDimitry Andric Fields[0] = ConstantStringClassRef; 1965f22ef01cSRoman Divacky 1966f22ef01cSRoman Divacky // String pointer. 1967f22ef01cSRoman Divacky llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str()); 1968f22ef01cSRoman Divacky 1969f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes Linkage; 1970f22ef01cSRoman Divacky bool isConstant; 1971f22ef01cSRoman Divacky Linkage = llvm::GlobalValue::PrivateLinkage; 1972f22ef01cSRoman Divacky isConstant = !Features.WritableStrings; 1973f22ef01cSRoman Divacky 1974f22ef01cSRoman Divacky llvm::GlobalVariable *GV = 1975f22ef01cSRoman Divacky new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 1976f22ef01cSRoman Divacky ".str"); 19772754fe60SDimitry Andric GV->setUnnamedAddr(true); 19783b0f4066SDimitry Andric CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 19793b0f4066SDimitry Andric GV->setAlignment(Align.getQuantity()); 19806122f3e6SDimitry Andric Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 1981f22ef01cSRoman Divacky 1982f22ef01cSRoman Divacky // String length. 19836122f3e6SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 1984f22ef01cSRoman Divacky Fields[2] = llvm::ConstantInt::get(Ty, StringLength); 1985f22ef01cSRoman Divacky 1986f22ef01cSRoman Divacky // The struct. 19876122f3e6SDimitry Andric C = llvm::ConstantStruct::get(NSConstantStringType, Fields); 1988f22ef01cSRoman Divacky GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 1989f22ef01cSRoman Divacky llvm::GlobalVariable::PrivateLinkage, C, 1990f22ef01cSRoman Divacky "_unnamed_nsstring_"); 1991f22ef01cSRoman Divacky // FIXME. Fix section. 1992f22ef01cSRoman Divacky if (const char *Sect = 1993f22ef01cSRoman Divacky Features.ObjCNonFragileABI 19946122f3e6SDimitry Andric ? getContext().getTargetInfo().getNSStringNonFragileABISection() 19956122f3e6SDimitry Andric : getContext().getTargetInfo().getNSStringSection()) 1996f22ef01cSRoman Divacky GV->setSection(Sect); 1997f22ef01cSRoman Divacky Entry.setValue(GV); 1998f22ef01cSRoman Divacky 1999f22ef01cSRoman Divacky return GV; 2000f22ef01cSRoman Divacky } 2001f22ef01cSRoman Divacky 20026122f3e6SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() { 20036122f3e6SDimitry Andric if (ObjCFastEnumerationStateType.isNull()) { 20046122f3e6SDimitry Andric RecordDecl *D = CreateRecordDecl(Context, TTK_Struct, 20056122f3e6SDimitry Andric Context.getTranslationUnitDecl(), 20066122f3e6SDimitry Andric &Context.Idents.get("__objcFastEnumerationState")); 20076122f3e6SDimitry Andric D->startDefinition(); 20086122f3e6SDimitry Andric 20096122f3e6SDimitry Andric QualType FieldTypes[] = { 20106122f3e6SDimitry Andric Context.UnsignedLongTy, 20116122f3e6SDimitry Andric Context.getPointerType(Context.getObjCIdType()), 20126122f3e6SDimitry Andric Context.getPointerType(Context.UnsignedLongTy), 20136122f3e6SDimitry Andric Context.getConstantArrayType(Context.UnsignedLongTy, 20146122f3e6SDimitry Andric llvm::APInt(32, 5), ArrayType::Normal, 0) 20156122f3e6SDimitry Andric }; 20166122f3e6SDimitry Andric 20176122f3e6SDimitry Andric for (size_t i = 0; i < 4; ++i) { 20186122f3e6SDimitry Andric FieldDecl *Field = FieldDecl::Create(Context, 20196122f3e6SDimitry Andric D, 20206122f3e6SDimitry Andric SourceLocation(), 20216122f3e6SDimitry Andric SourceLocation(), 0, 20226122f3e6SDimitry Andric FieldTypes[i], /*TInfo=*/0, 20236122f3e6SDimitry Andric /*BitWidth=*/0, 20246122f3e6SDimitry Andric /*Mutable=*/false, 20256122f3e6SDimitry Andric /*HasInit=*/false); 20266122f3e6SDimitry Andric Field->setAccess(AS_public); 20276122f3e6SDimitry Andric D->addDecl(Field); 20286122f3e6SDimitry Andric } 20296122f3e6SDimitry Andric 20306122f3e6SDimitry Andric D->completeDefinition(); 20316122f3e6SDimitry Andric ObjCFastEnumerationStateType = Context.getTagDeclType(D); 20326122f3e6SDimitry Andric } 20336122f3e6SDimitry Andric 20346122f3e6SDimitry Andric return ObjCFastEnumerationStateType; 20356122f3e6SDimitry Andric } 20366122f3e6SDimitry Andric 2037f22ef01cSRoman Divacky /// GetStringForStringLiteral - Return the appropriate bytes for a 2038f22ef01cSRoman Divacky /// string literal, properly padded to match the literal type. 2039f22ef01cSRoman Divacky std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) { 20402754fe60SDimitry Andric const ASTContext &Context = getContext(); 2041f22ef01cSRoman Divacky const ConstantArrayType *CAT = 20422754fe60SDimitry Andric Context.getAsConstantArrayType(E->getType()); 2043f22ef01cSRoman Divacky assert(CAT && "String isn't pointer or array!"); 2044f22ef01cSRoman Divacky 2045f22ef01cSRoman Divacky // Resize the string to the right size. 2046f22ef01cSRoman Divacky uint64_t RealLen = CAT->getSize().getZExtValue(); 2047f22ef01cSRoman Divacky 20486122f3e6SDimitry Andric switch (E->getKind()) { 20496122f3e6SDimitry Andric case StringLiteral::Ascii: 20506122f3e6SDimitry Andric case StringLiteral::UTF8: 20516122f3e6SDimitry Andric break; 20526122f3e6SDimitry Andric case StringLiteral::Wide: 20536122f3e6SDimitry Andric RealLen *= Context.getTargetInfo().getWCharWidth() / Context.getCharWidth(); 20546122f3e6SDimitry Andric break; 20556122f3e6SDimitry Andric case StringLiteral::UTF16: 20566122f3e6SDimitry Andric RealLen *= Context.getTargetInfo().getChar16Width() / Context.getCharWidth(); 20576122f3e6SDimitry Andric break; 20586122f3e6SDimitry Andric case StringLiteral::UTF32: 20596122f3e6SDimitry Andric RealLen *= Context.getTargetInfo().getChar32Width() / Context.getCharWidth(); 20606122f3e6SDimitry Andric break; 20616122f3e6SDimitry Andric } 2062f22ef01cSRoman Divacky 2063e580952dSDimitry Andric std::string Str = E->getString().str(); 2064f22ef01cSRoman Divacky Str.resize(RealLen, '\0'); 2065f22ef01cSRoman Divacky 2066f22ef01cSRoman Divacky return Str; 2067f22ef01cSRoman Divacky } 2068f22ef01cSRoman Divacky 2069f22ef01cSRoman Divacky /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 2070f22ef01cSRoman Divacky /// constant array for the given string literal. 2071f22ef01cSRoman Divacky llvm::Constant * 2072f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 2073f22ef01cSRoman Divacky // FIXME: This can be more efficient. 2074f22ef01cSRoman Divacky // FIXME: We shouldn't need to bitcast the constant in the wide string case. 20756122f3e6SDimitry Andric CharUnits Align = getContext().getTypeAlignInChars(S->getType()); 20766122f3e6SDimitry Andric llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S), 20776122f3e6SDimitry Andric /* GlobalName */ 0, 20786122f3e6SDimitry Andric Align.getQuantity()); 20796122f3e6SDimitry Andric if (S->isWide() || S->isUTF16() || S->isUTF32()) { 2080f22ef01cSRoman Divacky llvm::Type *DestTy = 2081f22ef01cSRoman Divacky llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType())); 2082f22ef01cSRoman Divacky C = llvm::ConstantExpr::getBitCast(C, DestTy); 2083f22ef01cSRoman Divacky } 2084f22ef01cSRoman Divacky return C; 2085f22ef01cSRoman Divacky } 2086f22ef01cSRoman Divacky 2087f22ef01cSRoman Divacky /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 2088f22ef01cSRoman Divacky /// array for the given ObjCEncodeExpr node. 2089f22ef01cSRoman Divacky llvm::Constant * 2090f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 2091f22ef01cSRoman Divacky std::string Str; 2092f22ef01cSRoman Divacky getContext().getObjCEncodingForType(E->getEncodedType(), Str); 2093f22ef01cSRoman Divacky 2094f22ef01cSRoman Divacky return GetAddrOfConstantCString(Str); 2095f22ef01cSRoman Divacky } 2096f22ef01cSRoman Divacky 2097f22ef01cSRoman Divacky 2098f22ef01cSRoman Divacky /// GenerateWritableString -- Creates storage for a string literal. 20996122f3e6SDimitry Andric static llvm::GlobalVariable *GenerateStringLiteral(StringRef str, 2100f22ef01cSRoman Divacky bool constant, 2101f22ef01cSRoman Divacky CodeGenModule &CGM, 21026122f3e6SDimitry Andric const char *GlobalName, 21036122f3e6SDimitry Andric unsigned Alignment) { 2104f22ef01cSRoman Divacky // Create Constant for this string literal. Don't add a '\0'. 2105f22ef01cSRoman Divacky llvm::Constant *C = 2106f22ef01cSRoman Divacky llvm::ConstantArray::get(CGM.getLLVMContext(), str, false); 2107f22ef01cSRoman Divacky 2108f22ef01cSRoman Divacky // Create a global variable for this string 21092754fe60SDimitry Andric llvm::GlobalVariable *GV = 21102754fe60SDimitry Andric new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant, 2111f22ef01cSRoman Divacky llvm::GlobalValue::PrivateLinkage, 2112f22ef01cSRoman Divacky C, GlobalName); 21136122f3e6SDimitry Andric GV->setAlignment(Alignment); 21142754fe60SDimitry Andric GV->setUnnamedAddr(true); 21152754fe60SDimitry Andric return GV; 2116f22ef01cSRoman Divacky } 2117f22ef01cSRoman Divacky 2118f22ef01cSRoman Divacky /// GetAddrOfConstantString - Returns a pointer to a character array 2119f22ef01cSRoman Divacky /// containing the literal. This contents are exactly that of the 2120f22ef01cSRoman Divacky /// given string, i.e. it will not be null terminated automatically; 2121f22ef01cSRoman Divacky /// see GetAddrOfConstantCString. Note that whether the result is 2122f22ef01cSRoman Divacky /// actually a pointer to an LLVM constant depends on 2123f22ef01cSRoman Divacky /// Feature.WriteableStrings. 2124f22ef01cSRoman Divacky /// 2125f22ef01cSRoman Divacky /// The result has pointer to array type. 21266122f3e6SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str, 21276122f3e6SDimitry Andric const char *GlobalName, 21286122f3e6SDimitry Andric unsigned Alignment) { 2129f22ef01cSRoman Divacky bool IsConstant = !Features.WritableStrings; 2130f22ef01cSRoman Divacky 2131f22ef01cSRoman Divacky // Get the default prefix if a name wasn't specified. 2132f22ef01cSRoman Divacky if (!GlobalName) 2133f22ef01cSRoman Divacky GlobalName = ".str"; 2134f22ef01cSRoman Divacky 2135f22ef01cSRoman Divacky // Don't share any string literals if strings aren't constant. 2136f22ef01cSRoman Divacky if (!IsConstant) 21376122f3e6SDimitry Andric return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment); 2138f22ef01cSRoman Divacky 21396122f3e6SDimitry Andric llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 21403b0f4066SDimitry Andric ConstantStringMap.GetOrCreateValue(Str); 2141f22ef01cSRoman Divacky 21426122f3e6SDimitry Andric if (llvm::GlobalVariable *GV = Entry.getValue()) { 21436122f3e6SDimitry Andric if (Alignment > GV->getAlignment()) { 21446122f3e6SDimitry Andric GV->setAlignment(Alignment); 21456122f3e6SDimitry Andric } 21466122f3e6SDimitry Andric return GV; 21476122f3e6SDimitry Andric } 2148f22ef01cSRoman Divacky 2149f22ef01cSRoman Divacky // Create a global variable for this. 21506122f3e6SDimitry Andric llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName, Alignment); 21516122f3e6SDimitry Andric Entry.setValue(GV); 21526122f3e6SDimitry Andric return GV; 2153f22ef01cSRoman Divacky } 2154f22ef01cSRoman Divacky 2155f22ef01cSRoman Divacky /// GetAddrOfConstantCString - Returns a pointer to a character 21563b0f4066SDimitry Andric /// array containing the literal and a terminating '\0' 2157f22ef01cSRoman Divacky /// character. The result has pointer to array type. 21583b0f4066SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str, 21596122f3e6SDimitry Andric const char *GlobalName, 21606122f3e6SDimitry Andric unsigned Alignment) { 21616122f3e6SDimitry Andric StringRef StrWithNull(Str.c_str(), Str.size() + 1); 21626122f3e6SDimitry Andric return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment); 2163f22ef01cSRoman Divacky } 2164f22ef01cSRoman Divacky 2165f22ef01cSRoman Divacky /// EmitObjCPropertyImplementations - Emit information for synthesized 2166f22ef01cSRoman Divacky /// properties for an implementation. 2167f22ef01cSRoman Divacky void CodeGenModule::EmitObjCPropertyImplementations(const 2168f22ef01cSRoman Divacky ObjCImplementationDecl *D) { 2169f22ef01cSRoman Divacky for (ObjCImplementationDecl::propimpl_iterator 2170f22ef01cSRoman Divacky i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) { 2171f22ef01cSRoman Divacky ObjCPropertyImplDecl *PID = *i; 2172f22ef01cSRoman Divacky 2173f22ef01cSRoman Divacky // Dynamic is just for type-checking. 2174f22ef01cSRoman Divacky if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 2175f22ef01cSRoman Divacky ObjCPropertyDecl *PD = PID->getPropertyDecl(); 2176f22ef01cSRoman Divacky 2177f22ef01cSRoman Divacky // Determine which methods need to be implemented, some may have 2178f22ef01cSRoman Divacky // been overridden. Note that ::isSynthesized is not the method 2179f22ef01cSRoman Divacky // we want, that just indicates if the decl came from a 2180f22ef01cSRoman Divacky // property. What we want to know is if the method is defined in 2181f22ef01cSRoman Divacky // this implementation. 2182f22ef01cSRoman Divacky if (!D->getInstanceMethod(PD->getGetterName())) 2183f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCGetter( 2184f22ef01cSRoman Divacky const_cast<ObjCImplementationDecl *>(D), PID); 2185f22ef01cSRoman Divacky if (!PD->isReadOnly() && 2186f22ef01cSRoman Divacky !D->getInstanceMethod(PD->getSetterName())) 2187f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCSetter( 2188f22ef01cSRoman Divacky const_cast<ObjCImplementationDecl *>(D), PID); 2189f22ef01cSRoman Divacky } 2190f22ef01cSRoman Divacky } 2191f22ef01cSRoman Divacky } 2192f22ef01cSRoman Divacky 21933b0f4066SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) { 21946122f3e6SDimitry Andric const ObjCInterfaceDecl *iface = impl->getClassInterface(); 21956122f3e6SDimitry Andric for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 21963b0f4066SDimitry Andric ivar; ivar = ivar->getNextIvar()) 21973b0f4066SDimitry Andric if (ivar->getType().isDestructedType()) 21983b0f4066SDimitry Andric return true; 21993b0f4066SDimitry Andric 22003b0f4066SDimitry Andric return false; 22013b0f4066SDimitry Andric } 22023b0f4066SDimitry Andric 2203f22ef01cSRoman Divacky /// EmitObjCIvarInitializations - Emit information for ivar initialization 2204f22ef01cSRoman Divacky /// for an implementation. 2205f22ef01cSRoman Divacky void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 22063b0f4066SDimitry Andric // We might need a .cxx_destruct even if we don't have any ivar initializers. 22073b0f4066SDimitry Andric if (needsDestructMethod(D)) { 2208f22ef01cSRoman Divacky IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 2209f22ef01cSRoman Divacky Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 22103b0f4066SDimitry Andric ObjCMethodDecl *DTORMethod = 22113b0f4066SDimitry Andric ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(), 22126122f3e6SDimitry Andric cxxSelector, getContext().VoidTy, 0, D, 22136122f3e6SDimitry Andric /*isInstance=*/true, /*isVariadic=*/false, 22146122f3e6SDimitry Andric /*isSynthesized=*/true, /*isImplicitlyDeclared=*/true, 22156122f3e6SDimitry Andric /*isDefined=*/false, ObjCMethodDecl::Required); 2216f22ef01cSRoman Divacky D->addInstanceMethod(DTORMethod); 2217f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 221817a519f9SDimitry Andric D->setHasCXXStructors(true); 22193b0f4066SDimitry Andric } 2220f22ef01cSRoman Divacky 22213b0f4066SDimitry Andric // If the implementation doesn't have any ivar initializers, we don't need 22223b0f4066SDimitry Andric // a .cxx_construct. 22233b0f4066SDimitry Andric if (D->getNumIvarInitializers() == 0) 22243b0f4066SDimitry Andric return; 22253b0f4066SDimitry Andric 22263b0f4066SDimitry Andric IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 22273b0f4066SDimitry Andric Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 2228f22ef01cSRoman Divacky // The constructor returns 'self'. 2229f22ef01cSRoman Divacky ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 2230f22ef01cSRoman Divacky D->getLocation(), 22316122f3e6SDimitry Andric D->getLocation(), 22326122f3e6SDimitry Andric cxxSelector, 2233f22ef01cSRoman Divacky getContext().getObjCIdType(), 0, 22346122f3e6SDimitry Andric D, /*isInstance=*/true, 22356122f3e6SDimitry Andric /*isVariadic=*/false, 22366122f3e6SDimitry Andric /*isSynthesized=*/true, 22376122f3e6SDimitry Andric /*isImplicitlyDeclared=*/true, 22386122f3e6SDimitry Andric /*isDefined=*/false, 2239f22ef01cSRoman Divacky ObjCMethodDecl::Required); 2240f22ef01cSRoman Divacky D->addInstanceMethod(CTORMethod); 2241f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 224217a519f9SDimitry Andric D->setHasCXXStructors(true); 2243f22ef01cSRoman Divacky } 2244f22ef01cSRoman Divacky 2245f22ef01cSRoman Divacky /// EmitNamespace - Emit all declarations in a namespace. 2246f22ef01cSRoman Divacky void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 2247f22ef01cSRoman Divacky for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end(); 2248f22ef01cSRoman Divacky I != E; ++I) 2249f22ef01cSRoman Divacky EmitTopLevelDecl(*I); 2250f22ef01cSRoman Divacky } 2251f22ef01cSRoman Divacky 2252f22ef01cSRoman Divacky // EmitLinkageSpec - Emit all declarations in a linkage spec. 2253f22ef01cSRoman Divacky void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 2254f22ef01cSRoman Divacky if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 2255f22ef01cSRoman Divacky LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 2256f22ef01cSRoman Divacky ErrorUnsupported(LSD, "linkage spec"); 2257f22ef01cSRoman Divacky return; 2258f22ef01cSRoman Divacky } 2259f22ef01cSRoman Divacky 2260f22ef01cSRoman Divacky for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end(); 2261f22ef01cSRoman Divacky I != E; ++I) 2262f22ef01cSRoman Divacky EmitTopLevelDecl(*I); 2263f22ef01cSRoman Divacky } 2264f22ef01cSRoman Divacky 2265f22ef01cSRoman Divacky /// EmitTopLevelDecl - Emit code for a single top level declaration. 2266f22ef01cSRoman Divacky void CodeGenModule::EmitTopLevelDecl(Decl *D) { 2267f22ef01cSRoman Divacky // If an error has occurred, stop code generation, but continue 2268f22ef01cSRoman Divacky // parsing and semantic analysis (to ensure all warnings and errors 2269f22ef01cSRoman Divacky // are emitted). 2270f22ef01cSRoman Divacky if (Diags.hasErrorOccurred()) 2271f22ef01cSRoman Divacky return; 2272f22ef01cSRoman Divacky 2273f22ef01cSRoman Divacky // Ignore dependent declarations. 2274f22ef01cSRoman Divacky if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 2275f22ef01cSRoman Divacky return; 2276f22ef01cSRoman Divacky 2277f22ef01cSRoman Divacky switch (D->getKind()) { 2278f22ef01cSRoman Divacky case Decl::CXXConversion: 2279f22ef01cSRoman Divacky case Decl::CXXMethod: 2280f22ef01cSRoman Divacky case Decl::Function: 2281f22ef01cSRoman Divacky // Skip function templates 22823b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 22833b0f4066SDimitry Andric cast<FunctionDecl>(D)->isLateTemplateParsed()) 2284f22ef01cSRoman Divacky return; 2285f22ef01cSRoman Divacky 2286f22ef01cSRoman Divacky EmitGlobal(cast<FunctionDecl>(D)); 2287f22ef01cSRoman Divacky break; 2288f22ef01cSRoman Divacky 2289f22ef01cSRoman Divacky case Decl::Var: 2290f22ef01cSRoman Divacky EmitGlobal(cast<VarDecl>(D)); 2291f22ef01cSRoman Divacky break; 2292f22ef01cSRoman Divacky 22933b0f4066SDimitry Andric // Indirect fields from global anonymous structs and unions can be 22943b0f4066SDimitry Andric // ignored; only the actual variable requires IR gen support. 22953b0f4066SDimitry Andric case Decl::IndirectField: 22963b0f4066SDimitry Andric break; 22973b0f4066SDimitry Andric 2298f22ef01cSRoman Divacky // C++ Decls 2299f22ef01cSRoman Divacky case Decl::Namespace: 2300f22ef01cSRoman Divacky EmitNamespace(cast<NamespaceDecl>(D)); 2301f22ef01cSRoman Divacky break; 2302f22ef01cSRoman Divacky // No code generation needed. 2303f22ef01cSRoman Divacky case Decl::UsingShadow: 2304f22ef01cSRoman Divacky case Decl::Using: 2305f22ef01cSRoman Divacky case Decl::UsingDirective: 2306f22ef01cSRoman Divacky case Decl::ClassTemplate: 2307f22ef01cSRoman Divacky case Decl::FunctionTemplate: 2308bd5abe19SDimitry Andric case Decl::TypeAliasTemplate: 2309f22ef01cSRoman Divacky case Decl::NamespaceAlias: 2310bd5abe19SDimitry Andric case Decl::Block: 2311f22ef01cSRoman Divacky break; 2312f22ef01cSRoman Divacky case Decl::CXXConstructor: 2313f22ef01cSRoman Divacky // Skip function templates 23143b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 23153b0f4066SDimitry Andric cast<FunctionDecl>(D)->isLateTemplateParsed()) 2316f22ef01cSRoman Divacky return; 2317f22ef01cSRoman Divacky 2318f22ef01cSRoman Divacky EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 2319f22ef01cSRoman Divacky break; 2320f22ef01cSRoman Divacky case Decl::CXXDestructor: 23213b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->isLateTemplateParsed()) 23223b0f4066SDimitry Andric return; 2323f22ef01cSRoman Divacky EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 2324f22ef01cSRoman Divacky break; 2325f22ef01cSRoman Divacky 2326f22ef01cSRoman Divacky case Decl::StaticAssert: 2327f22ef01cSRoman Divacky // Nothing to do. 2328f22ef01cSRoman Divacky break; 2329f22ef01cSRoman Divacky 2330f22ef01cSRoman Divacky // Objective-C Decls 2331f22ef01cSRoman Divacky 2332f22ef01cSRoman Divacky // Forward declarations, no (immediate) code generation. 2333f22ef01cSRoman Divacky case Decl::ObjCClass: 2334f22ef01cSRoman Divacky case Decl::ObjCForwardProtocol: 2335f22ef01cSRoman Divacky case Decl::ObjCInterface: 2336f22ef01cSRoman Divacky break; 2337f22ef01cSRoman Divacky 2338e580952dSDimitry Andric case Decl::ObjCCategory: { 2339e580952dSDimitry Andric ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D); 2340e580952dSDimitry Andric if (CD->IsClassExtension() && CD->hasSynthBitfield()) 2341e580952dSDimitry Andric Context.ResetObjCLayout(CD->getClassInterface()); 2342e580952dSDimitry Andric break; 2343e580952dSDimitry Andric } 2344e580952dSDimitry Andric 2345f22ef01cSRoman Divacky case Decl::ObjCProtocol: 23466122f3e6SDimitry Andric ObjCRuntime->GenerateProtocol(cast<ObjCProtocolDecl>(D)); 2347f22ef01cSRoman Divacky break; 2348f22ef01cSRoman Divacky 2349f22ef01cSRoman Divacky case Decl::ObjCCategoryImpl: 2350f22ef01cSRoman Divacky // Categories have properties but don't support synthesize so we 2351f22ef01cSRoman Divacky // can ignore them here. 23526122f3e6SDimitry Andric ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 2353f22ef01cSRoman Divacky break; 2354f22ef01cSRoman Divacky 2355f22ef01cSRoman Divacky case Decl::ObjCImplementation: { 2356f22ef01cSRoman Divacky ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D); 2357e580952dSDimitry Andric if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield()) 2358e580952dSDimitry Andric Context.ResetObjCLayout(OMD->getClassInterface()); 2359f22ef01cSRoman Divacky EmitObjCPropertyImplementations(OMD); 2360f22ef01cSRoman Divacky EmitObjCIvarInitializations(OMD); 23616122f3e6SDimitry Andric ObjCRuntime->GenerateClass(OMD); 2362f22ef01cSRoman Divacky break; 2363f22ef01cSRoman Divacky } 2364f22ef01cSRoman Divacky case Decl::ObjCMethod: { 2365f22ef01cSRoman Divacky ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D); 2366f22ef01cSRoman Divacky // If this is not a prototype, emit the body. 2367f22ef01cSRoman Divacky if (OMD->getBody()) 2368f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCMethod(OMD); 2369f22ef01cSRoman Divacky break; 2370f22ef01cSRoman Divacky } 2371f22ef01cSRoman Divacky case Decl::ObjCCompatibleAlias: 2372f22ef01cSRoman Divacky // compatibility-alias is a directive and has no code gen. 2373f22ef01cSRoman Divacky break; 2374f22ef01cSRoman Divacky 2375f22ef01cSRoman Divacky case Decl::LinkageSpec: 2376f22ef01cSRoman Divacky EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 2377f22ef01cSRoman Divacky break; 2378f22ef01cSRoman Divacky 2379f22ef01cSRoman Divacky case Decl::FileScopeAsm: { 2380f22ef01cSRoman Divacky FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D); 23816122f3e6SDimitry Andric StringRef AsmString = AD->getAsmString()->getString(); 2382f22ef01cSRoman Divacky 2383f22ef01cSRoman Divacky const std::string &S = getModule().getModuleInlineAsm(); 2384f22ef01cSRoman Divacky if (S.empty()) 2385f22ef01cSRoman Divacky getModule().setModuleInlineAsm(AsmString); 23866122f3e6SDimitry Andric else if (*--S.end() == '\n') 23876122f3e6SDimitry Andric getModule().setModuleInlineAsm(S + AsmString.str()); 2388f22ef01cSRoman Divacky else 2389f22ef01cSRoman Divacky getModule().setModuleInlineAsm(S + '\n' + AsmString.str()); 2390f22ef01cSRoman Divacky break; 2391f22ef01cSRoman Divacky } 2392f22ef01cSRoman Divacky 2393f22ef01cSRoman Divacky default: 2394f22ef01cSRoman Divacky // Make sure we handled everything we should, every other kind is a 2395f22ef01cSRoman Divacky // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 2396f22ef01cSRoman Divacky // function. Need to recode Decl::Kind to do that easily. 2397f22ef01cSRoman Divacky assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 2398f22ef01cSRoman Divacky } 2399f22ef01cSRoman Divacky } 2400ffd1746dSEd Schouten 2401ffd1746dSEd Schouten /// Turns the given pointer into a constant. 2402ffd1746dSEd Schouten static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 2403ffd1746dSEd Schouten const void *Ptr) { 2404ffd1746dSEd Schouten uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 24056122f3e6SDimitry Andric llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 2406ffd1746dSEd Schouten return llvm::ConstantInt::get(i64, PtrInt); 2407ffd1746dSEd Schouten } 2408ffd1746dSEd Schouten 2409ffd1746dSEd Schouten static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 2410ffd1746dSEd Schouten llvm::NamedMDNode *&GlobalMetadata, 2411ffd1746dSEd Schouten GlobalDecl D, 2412ffd1746dSEd Schouten llvm::GlobalValue *Addr) { 2413ffd1746dSEd Schouten if (!GlobalMetadata) 2414ffd1746dSEd Schouten GlobalMetadata = 2415ffd1746dSEd Schouten CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 2416ffd1746dSEd Schouten 2417ffd1746dSEd Schouten // TODO: should we report variant information for ctors/dtors? 2418ffd1746dSEd Schouten llvm::Value *Ops[] = { 2419ffd1746dSEd Schouten Addr, 2420ffd1746dSEd Schouten GetPointerConstant(CGM.getLLVMContext(), D.getDecl()) 2421ffd1746dSEd Schouten }; 24223b0f4066SDimitry Andric GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 2423ffd1746dSEd Schouten } 2424ffd1746dSEd Schouten 2425ffd1746dSEd Schouten /// Emits metadata nodes associating all the global values in the 2426ffd1746dSEd Schouten /// current module with the Decls they came from. This is useful for 2427ffd1746dSEd Schouten /// projects using IR gen as a subroutine. 2428ffd1746dSEd Schouten /// 2429ffd1746dSEd Schouten /// Since there's currently no way to associate an MDNode directly 2430ffd1746dSEd Schouten /// with an llvm::GlobalValue, we create a global named metadata 2431ffd1746dSEd Schouten /// with the name 'clang.global.decl.ptrs'. 2432ffd1746dSEd Schouten void CodeGenModule::EmitDeclMetadata() { 2433ffd1746dSEd Schouten llvm::NamedMDNode *GlobalMetadata = 0; 2434ffd1746dSEd Schouten 2435ffd1746dSEd Schouten // StaticLocalDeclMap 24366122f3e6SDimitry Andric for (llvm::DenseMap<GlobalDecl,StringRef>::iterator 2437ffd1746dSEd Schouten I = MangledDeclNames.begin(), E = MangledDeclNames.end(); 2438ffd1746dSEd Schouten I != E; ++I) { 2439ffd1746dSEd Schouten llvm::GlobalValue *Addr = getModule().getNamedValue(I->second); 2440ffd1746dSEd Schouten EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr); 2441ffd1746dSEd Schouten } 2442ffd1746dSEd Schouten } 2443ffd1746dSEd Schouten 2444ffd1746dSEd Schouten /// Emits metadata nodes for all the local variables in the current 2445ffd1746dSEd Schouten /// function. 2446ffd1746dSEd Schouten void CodeGenFunction::EmitDeclMetadata() { 2447ffd1746dSEd Schouten if (LocalDeclMap.empty()) return; 2448ffd1746dSEd Schouten 2449ffd1746dSEd Schouten llvm::LLVMContext &Context = getLLVMContext(); 2450ffd1746dSEd Schouten 2451ffd1746dSEd Schouten // Find the unique metadata ID for this name. 2452ffd1746dSEd Schouten unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 2453ffd1746dSEd Schouten 2454ffd1746dSEd Schouten llvm::NamedMDNode *GlobalMetadata = 0; 2455ffd1746dSEd Schouten 2456ffd1746dSEd Schouten for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator 2457ffd1746dSEd Schouten I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) { 2458ffd1746dSEd Schouten const Decl *D = I->first; 2459ffd1746dSEd Schouten llvm::Value *Addr = I->second; 2460ffd1746dSEd Schouten 2461ffd1746dSEd Schouten if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 2462ffd1746dSEd Schouten llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 24633b0f4066SDimitry Andric Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr)); 2464ffd1746dSEd Schouten } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 2465ffd1746dSEd Schouten GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 2466ffd1746dSEd Schouten EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 2467ffd1746dSEd Schouten } 2468ffd1746dSEd Schouten } 2469ffd1746dSEd Schouten } 2470e580952dSDimitry Andric 2471bd5abe19SDimitry Andric void CodeGenModule::EmitCoverageFile() { 2472bd5abe19SDimitry Andric if (!getCodeGenOpts().CoverageFile.empty()) { 2473bd5abe19SDimitry Andric if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) { 2474bd5abe19SDimitry Andric llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 2475bd5abe19SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 2476bd5abe19SDimitry Andric llvm::MDString *CoverageFile = 2477bd5abe19SDimitry Andric llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile); 2478bd5abe19SDimitry Andric for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 2479bd5abe19SDimitry Andric llvm::MDNode *CU = CUNode->getOperand(i); 2480bd5abe19SDimitry Andric llvm::Value *node[] = { CoverageFile, CU }; 2481bd5abe19SDimitry Andric llvm::MDNode *N = llvm::MDNode::get(Ctx, node); 2482bd5abe19SDimitry Andric GCov->addOperand(N); 2483bd5abe19SDimitry Andric } 2484bd5abe19SDimitry Andric } 2485bd5abe19SDimitry Andric } 2486bd5abe19SDimitry Andric } 2487