1193326Sed//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// 2193326Sed// 3193326Sed// The LLVM Compiler Infrastructure 4193326Sed// 5193326Sed// This file is distributed under the University of Illinois Open Source 6193326Sed// License. See LICENSE.TXT for details. 7193326Sed// 8193326Sed//===----------------------------------------------------------------------===// 9193326Sed// 10193326Sed// This coordinates the per-module state used while generating code. 11193326Sed// 12193326Sed//===----------------------------------------------------------------------===// 13193326Sed 14193326Sed#include "CodeGenModule.h" 15226633Sdim#include "CGCUDARuntime.h" 16212904Sdim#include "CGCXXABI.h" 17249423Sdim#include "CGCall.h" 18249423Sdim#include "CGDebugInfo.h" 19193326Sed#include "CGObjCRuntime.h" 20226633Sdim#include "CGOpenCLRuntime.h" 21249423Sdim#include "CodeGenFunction.h" 22249423Sdim#include "CodeGenTBAA.h" 23202379Srdivacky#include "TargetInfo.h" 24193326Sed#include "clang/AST/ASTContext.h" 25203955Srdivacky#include "clang/AST/CharUnits.h" 26249423Sdim#include "clang/AST/DeclCXX.h" 27193326Sed#include "clang/AST/DeclObjC.h" 28210299Sed#include "clang/AST/DeclTemplate.h" 29218893Sdim#include "clang/AST/Mangle.h" 30199990Srdivacky#include "clang/AST/RecordLayout.h" 31228379Sdim#include "clang/AST/RecursiveASTVisitor.h" 32234353Sdim#include "clang/Basic/Builtins.h" 33249423Sdim#include "clang/Basic/CharInfo.h" 34193326Sed#include "clang/Basic/Diagnostic.h" 35249423Sdim#include "clang/Basic/Module.h" 36193326Sed#include "clang/Basic/SourceManager.h" 37193326Sed#include "clang/Basic/TargetInfo.h" 38249423Sdim#include "clang/Frontend/CodeGenOptions.h" 39234353Sdim#include "llvm/ADT/APSInt.h" 40204793Srdivacky#include "llvm/ADT/Triple.h" 41249423Sdim#include "llvm/IR/CallingConv.h" 42249423Sdim#include "llvm/IR/DataLayout.h" 43249423Sdim#include "llvm/IR/Intrinsics.h" 44249423Sdim#include "llvm/IR/LLVMContext.h" 45249423Sdim#include "llvm/IR/Module.h" 46207619Srdivacky#include "llvm/Support/CallSite.h" 47249423Sdim#include "llvm/Support/ConvertUTF.h" 48199482Srdivacky#include "llvm/Support/ErrorHandling.h" 49249423Sdim#include "llvm/Target/Mangler.h" 50249423Sdim 51193326Sedusing namespace clang; 52193326Sedusing namespace CodeGen; 53193326Sed 54226633Sdimstatic const char AnnotationSection[] = "llvm.metadata"; 55226633Sdim 56212904Sdimstatic CGCXXABI &createCXXABI(CodeGenModule &CGM) { 57251662Sdim switch (CGM.getTarget().getCXXABI().getKind()) { 58249423Sdim case TargetCXXABI::GenericAArch64: 59249423Sdim case TargetCXXABI::GenericARM: 60249423Sdim case TargetCXXABI::iOS: 61249423Sdim case TargetCXXABI::GenericItanium: 62249423Sdim return *CreateItaniumCXXABI(CGM); 63249423Sdim case TargetCXXABI::Microsoft: 64249423Sdim return *CreateMicrosoftCXXABI(CGM); 65212904Sdim } 66193326Sed 67212904Sdim llvm_unreachable("invalid C++ ABI kind"); 68212904Sdim} 69212904Sdim 70212904Sdim 71199482SrdivackyCodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO, 72251662Sdim llvm::Module &M, const llvm::DataLayout &TD, 73226633Sdim DiagnosticsEngine &diags) 74251662Sdim : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M), 75251662Sdim Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()), 76251662Sdim ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(0), 77251662Sdim TheTargetCodeGenInfo(0), Types(*this), VTables(*this), 78251662Sdim ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0), 79234353Sdim DebugInfo(0), ARCData(0), NoObjCARCExceptionsMetadata(0), 80234353Sdim RRData(0), CFConstantStringClassRef(0), 81226633Sdim ConstantStringClassRef(0), NSConstantStringType(0), 82212904Sdim NSConcreteGlobalBlock(0), NSConcreteStackBlock(0), 83218893Sdim BlockObjectAssign(0), BlockObjectDispose(0), 84249423Sdim BlockDescriptorType(0), GenericBlockLiteralType(0), 85249423Sdim LifetimeStartFn(0), LifetimeEndFn(0), 86249423Sdim SanitizerBlacklist(CGO.SanitizerBlacklistFile), 87249423Sdim SanOpts(SanitizerBlacklist.isIn(M) ? 88249423Sdim SanitizerOptions::Disabled : LangOpts.Sanitize) { 89249423Sdim 90234353Sdim // Initialize the type cache. 91234353Sdim llvm::LLVMContext &LLVMContext = M.getContext(); 92234353Sdim VoidTy = llvm::Type::getVoidTy(LLVMContext); 93234353Sdim Int8Ty = llvm::Type::getInt8Ty(LLVMContext); 94234353Sdim Int16Ty = llvm::Type::getInt16Ty(LLVMContext); 95234353Sdim Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 96234353Sdim Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 97234353Sdim FloatTy = llvm::Type::getFloatTy(LLVMContext); 98234353Sdim DoubleTy = llvm::Type::getDoubleTy(LLVMContext); 99234353Sdim PointerWidthInBits = C.getTargetInfo().getPointerWidth(0); 100234353Sdim PointerAlignInBytes = 101234353Sdim C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity(); 102234353Sdim IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 103234353Sdim IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits); 104234353Sdim Int8PtrTy = Int8Ty->getPointerTo(0); 105234353Sdim Int8PtrPtrTy = Int8PtrTy->getPointerTo(0); 106234353Sdim 107249423Sdim RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); 108249423Sdim 109234353Sdim if (LangOpts.ObjC1) 110226633Sdim createObjCRuntime(); 111234353Sdim if (LangOpts.OpenCL) 112226633Sdim createOpenCLRuntime(); 113234353Sdim if (LangOpts.CUDA) 114226633Sdim createCUDARuntime(); 115193326Sed 116239462Sdim // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. 117249423Sdim if (SanOpts.Thread || 118239462Sdim (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) 119239462Sdim TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(), 120218893Sdim ABI.getMangleContext()); 121218893Sdim 122221345Sdim // If debug info or coverage generation is enabled, create the CGDebugInfo 123221345Sdim // object. 124243830Sdim if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo || 125239462Sdim CodeGenOpts.EmitGcovArcs || 126221345Sdim CodeGenOpts.EmitGcovNotes) 127221345Sdim DebugInfo = new CGDebugInfo(*this); 128218893Sdim 129218893Sdim Block.GlobalUniqueCount = 0; 130218893Sdim 131234353Sdim if (C.getLangOpts().ObjCAutoRefCount) 132224145Sdim ARCData = new ARCEntrypoints(); 133224145Sdim RRData = new RREntrypoints(); 134193326Sed} 135193326Sed 136193326SedCodeGenModule::~CodeGenModule() { 137226633Sdim delete ObjCRuntime; 138226633Sdim delete OpenCLRuntime; 139226633Sdim delete CUDARuntime; 140226633Sdim delete TheTargetCodeGenInfo; 141212904Sdim delete &ABI; 142218893Sdim delete TBAA; 143193326Sed delete DebugInfo; 144224145Sdim delete ARCData; 145224145Sdim delete RRData; 146193326Sed} 147193326Sed 148202879Srdivackyvoid CodeGenModule::createObjCRuntime() { 149239462Sdim // This is just isGNUFamily(), but we want to force implementors of 150239462Sdim // new ABIs to decide how best to do this. 151239462Sdim switch (LangOpts.ObjCRuntime.getKind()) { 152239462Sdim case ObjCRuntime::GNUstep: 153239462Sdim case ObjCRuntime::GCC: 154239462Sdim case ObjCRuntime::ObjFW: 155226633Sdim ObjCRuntime = CreateGNUObjCRuntime(*this); 156239462Sdim return; 157239462Sdim 158239462Sdim case ObjCRuntime::FragileMacOSX: 159239462Sdim case ObjCRuntime::MacOSX: 160239462Sdim case ObjCRuntime::iOS: 161226633Sdim ObjCRuntime = CreateMacObjCRuntime(*this); 162239462Sdim return; 163239462Sdim } 164239462Sdim llvm_unreachable("bad runtime kind"); 165202879Srdivacky} 166202879Srdivacky 167226633Sdimvoid CodeGenModule::createOpenCLRuntime() { 168226633Sdim OpenCLRuntime = new CGOpenCLRuntime(*this); 169226633Sdim} 170226633Sdim 171226633Sdimvoid CodeGenModule::createCUDARuntime() { 172226633Sdim CUDARuntime = CreateNVCUDARuntime(*this); 173226633Sdim} 174226633Sdim 175193326Sedvoid CodeGenModule::Release() { 176202379Srdivacky EmitDeferred(); 177198092Srdivacky EmitCXXGlobalInitFunc(); 178205408Srdivacky EmitCXXGlobalDtorFunc(); 179251662Sdim EmitCXXThreadLocalInitFunc(); 180226633Sdim if (ObjCRuntime) 181226633Sdim if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 182193326Sed AddGlobalCtor(ObjCInitFunction); 183193326Sed EmitCtorList(GlobalCtors, "llvm.global_ctors"); 184193326Sed EmitCtorList(GlobalDtors, "llvm.global_dtors"); 185226633Sdim EmitGlobalAnnotations(); 186251662Sdim EmitStaticExternCAliases(); 187193326Sed EmitLLVMUsed(); 188210299Sed 189251662Sdim if (CodeGenOpts.Autolink && Context.getLangOpts().Modules) { 190249423Sdim EmitModuleLinkOptions(); 191249423Sdim } 192249423Sdim 193218893Sdim SimplifyPersonality(); 194218893Sdim 195210299Sed if (getCodeGenOpts().EmitDeclMetadata) 196210299Sed EmitDeclMetadata(); 197223017Sdim 198223017Sdim if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 199223017Sdim EmitCoverageFile(); 200226633Sdim 201226633Sdim if (DebugInfo) 202226633Sdim DebugInfo->finalize(); 203193326Sed} 204193326Sed 205221345Sdimvoid CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 206221345Sdim // Make sure that this type is translated. 207221345Sdim Types.UpdateCompletedType(TD); 208221345Sdim} 209221345Sdim 210218893Sdimllvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) { 211218893Sdim if (!TBAA) 212218893Sdim return 0; 213218893Sdim return TBAA->getTBAAInfo(QTy); 214218893Sdim} 215218893Sdim 216234353Sdimllvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() { 217234353Sdim if (!TBAA) 218234353Sdim return 0; 219234353Sdim return TBAA->getTBAAInfoForVTablePtr(); 220234353Sdim} 221234353Sdim 222243830Sdimllvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 223243830Sdim if (!TBAA) 224243830Sdim return 0; 225243830Sdim return TBAA->getTBAAStructInfo(QTy); 226243830Sdim} 227243830Sdim 228249423Sdimllvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) { 229249423Sdim if (!TBAA) 230249423Sdim return 0; 231249423Sdim return TBAA->getTBAAStructTypeInfo(QTy); 232249423Sdim} 233249423Sdim 234249423Sdimllvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy, 235249423Sdim llvm::MDNode *AccessN, 236249423Sdim uint64_t O) { 237249423Sdim if (!TBAA) 238249423Sdim return 0; 239249423Sdim return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O); 240249423Sdim} 241249423Sdim 242251662Sdim/// Decorate the instruction with a TBAA tag. For scalar TBAA, the tag 243251662Sdim/// is the same as the type. For struct-path aware TBAA, the tag 244251662Sdim/// is different from the type: base type, access type and offset. 245251662Sdim/// When ConvertTypeToTag is true, we create a tag based on the scalar type. 246218893Sdimvoid CodeGenModule::DecorateInstruction(llvm::Instruction *Inst, 247251662Sdim llvm::MDNode *TBAAInfo, 248251662Sdim bool ConvertTypeToTag) { 249251662Sdim if (ConvertTypeToTag && TBAA && CodeGenOpts.StructPathTBAA) 250251662Sdim Inst->setMetadata(llvm::LLVMContext::MD_tbaa, 251251662Sdim TBAA->getTBAAScalarTagInfo(TBAAInfo)); 252251662Sdim else 253251662Sdim Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo); 254218893Sdim} 255218893Sdim 256226633Sdimvoid CodeGenModule::Error(SourceLocation loc, StringRef error) { 257226633Sdim unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error); 258221345Sdim getDiags().Report(Context.getFullLoc(loc), diagID); 259221345Sdim} 260221345Sdim 261193326Sed/// ErrorUnsupported - Print out an error that codegen doesn't support the 262193326Sed/// specified stmt yet. 263193326Sedvoid CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type, 264193326Sed bool OmitOnError) { 265193326Sed if (OmitOnError && getDiags().hasErrorOccurred()) 266193326Sed return; 267226633Sdim unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 268193326Sed "cannot compile this %0 yet"); 269193326Sed std::string Msg = Type; 270193326Sed getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 271193326Sed << Msg << S->getSourceRange(); 272193326Sed} 273193326Sed 274193326Sed/// ErrorUnsupported - Print out an error that codegen doesn't support the 275193326Sed/// specified decl yet. 276193326Sedvoid CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type, 277193326Sed bool OmitOnError) { 278193326Sed if (OmitOnError && getDiags().hasErrorOccurred()) 279193326Sed return; 280226633Sdim unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 281193326Sed "cannot compile this %0 yet"); 282193326Sed std::string Msg = Type; 283193326Sed getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 284193326Sed} 285193326Sed 286224145Sdimllvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 287224145Sdim return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 288224145Sdim} 289224145Sdim 290198092Srdivackyvoid CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 291218893Sdim const NamedDecl *D) const { 292193326Sed // Internal definitions always have default visibility. 293193326Sed if (GV->hasLocalLinkage()) { 294193326Sed GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 295193326Sed return; 296193326Sed } 297193326Sed 298218893Sdim // Set visibility for definitions. 299249423Sdim LinkageInfo LV = D->getLinkageAndVisibility(); 300249423Sdim if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage()) 301249423Sdim GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 302193326Sed} 303193326Sed 304239462Sdimstatic llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 305239462Sdim return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 306239462Sdim .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 307239462Sdim .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 308239462Sdim .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 309239462Sdim .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 310239462Sdim} 311239462Sdim 312239462Sdimstatic llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel( 313239462Sdim CodeGenOptions::TLSModel M) { 314239462Sdim switch (M) { 315239462Sdim case CodeGenOptions::GeneralDynamicTLSModel: 316239462Sdim return llvm::GlobalVariable::GeneralDynamicTLSModel; 317239462Sdim case CodeGenOptions::LocalDynamicTLSModel: 318239462Sdim return llvm::GlobalVariable::LocalDynamicTLSModel; 319239462Sdim case CodeGenOptions::InitialExecTLSModel: 320239462Sdim return llvm::GlobalVariable::InitialExecTLSModel; 321239462Sdim case CodeGenOptions::LocalExecTLSModel: 322239462Sdim return llvm::GlobalVariable::LocalExecTLSModel; 323239462Sdim } 324239462Sdim llvm_unreachable("Invalid TLS model!"); 325239462Sdim} 326239462Sdim 327239462Sdimvoid CodeGenModule::setTLSMode(llvm::GlobalVariable *GV, 328239462Sdim const VarDecl &D) const { 329251662Sdim assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 330239462Sdim 331239462Sdim llvm::GlobalVariable::ThreadLocalMode TLM; 332243830Sdim TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel()); 333239462Sdim 334239462Sdim // Override the TLS model if it is explicitly specified. 335239462Sdim if (D.hasAttr<TLSModelAttr>()) { 336239462Sdim const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>(); 337239462Sdim TLM = GetLLVMTLSModel(Attr->getModel()); 338239462Sdim } 339239462Sdim 340239462Sdim GV->setThreadLocalMode(TLM); 341239462Sdim} 342239462Sdim 343212904Sdim/// Set the symbol visibility of type information (vtable and RTTI) 344212904Sdim/// associated with the given type. 345212904Sdimvoid CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV, 346212904Sdim const CXXRecordDecl *RD, 347218893Sdim TypeVisibilityKind TVK) const { 348212904Sdim setGlobalVisibility(GV, RD); 349212904Sdim 350212904Sdim if (!CodeGenOpts.HiddenWeakVTables) 351212904Sdim return; 352212904Sdim 353218893Sdim // We never want to drop the visibility for RTTI names. 354218893Sdim if (TVK == TVK_ForRTTIName) 355218893Sdim return; 356218893Sdim 357212904Sdim // We want to drop the visibility to hidden for weak type symbols. 358212904Sdim // This isn't possible if there might be unresolved references 359212904Sdim // elsewhere that rely on this symbol being visible. 360212904Sdim 361212904Sdim // This should be kept roughly in sync with setThunkVisibility 362212904Sdim // in CGVTables.cpp. 363212904Sdim 364212904Sdim // Preconditions. 365218893Sdim if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage || 366212904Sdim GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility) 367212904Sdim return; 368212904Sdim 369212904Sdim // Don't override an explicit visibility attribute. 370249423Sdim if (RD->getExplicitVisibility(NamedDecl::VisibilityForType)) 371212904Sdim return; 372212904Sdim 373212904Sdim switch (RD->getTemplateSpecializationKind()) { 374212904Sdim // We have to disable the optimization if this is an EI definition 375212904Sdim // because there might be EI declarations in other shared objects. 376212904Sdim case TSK_ExplicitInstantiationDefinition: 377212904Sdim case TSK_ExplicitInstantiationDeclaration: 378212904Sdim return; 379212904Sdim 380212904Sdim // Every use of a non-template class's type information has to emit it. 381212904Sdim case TSK_Undeclared: 382212904Sdim break; 383212904Sdim 384212904Sdim // In theory, implicit instantiations can ignore the possibility of 385212904Sdim // an explicit instantiation declaration because there necessarily 386212904Sdim // must be an EI definition somewhere with default visibility. In 387212904Sdim // practice, it's possible to have an explicit instantiation for 388212904Sdim // an arbitrary template class, and linkers aren't necessarily able 389212904Sdim // to deal with mixed-visibility symbols. 390212904Sdim case TSK_ExplicitSpecialization: 391212904Sdim case TSK_ImplicitInstantiation: 392243830Sdim return; 393212904Sdim } 394212904Sdim 395212904Sdim // If there's a key function, there may be translation units 396212904Sdim // that don't have the key function's definition. But ignore 397212904Sdim // this if we're emitting RTTI under -fno-rtti. 398234353Sdim if (!(TVK != TVK_ForRTTI) || LangOpts.RTTI) { 399249423Sdim // FIXME: what should we do if we "lose" the key function during 400249423Sdim // the emission of the file? 401249423Sdim if (Context.getCurrentKeyFunction(RD)) 402212904Sdim return; 403218893Sdim } 404212904Sdim 405212904Sdim // Otherwise, drop the visibility to hidden. 406212904Sdim GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 407218893Sdim GV->setUnnamedAddr(true); 408212904Sdim} 409212904Sdim 410226633SdimStringRef CodeGenModule::getMangledName(GlobalDecl GD) { 411198092Srdivacky const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 412198092Srdivacky 413226633Sdim StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()]; 414210299Sed if (!Str.empty()) 415210299Sed return Str; 416198092Srdivacky 417212904Sdim if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) { 418210299Sed IdentifierInfo *II = ND->getIdentifier(); 419210299Sed assert(II && "Attempt to mangle unnamed decl."); 420193326Sed 421210299Sed Str = II->getName(); 422210299Sed return Str; 423193326Sed } 424210299Sed 425234353Sdim SmallString<256> Buffer; 426218893Sdim llvm::raw_svector_ostream Out(Buffer); 427210299Sed if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND)) 428218893Sdim getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out); 429210299Sed else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND)) 430218893Sdim getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out); 431210299Sed else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND)) 432239462Sdim getCXXABI().getMangleContext().mangleBlock(BD, Out, 433239462Sdim dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl())); 434210299Sed else 435218893Sdim getCXXABI().getMangleContext().mangleName(ND, Out); 436198092Srdivacky 437210299Sed // Allocate space for the mangled name. 438218893Sdim Out.flush(); 439210299Sed size_t Length = Buffer.size(); 440210299Sed char *Name = MangledNamesAllocator.Allocate<char>(Length); 441210299Sed std::copy(Buffer.begin(), Buffer.end(), Name); 442210299Sed 443226633Sdim Str = StringRef(Name, Length); 444210299Sed 445210299Sed return Str; 446193326Sed} 447193326Sed 448218893Sdimvoid CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer, 449218893Sdim const BlockDecl *BD) { 450218893Sdim MangleContext &MangleCtx = getCXXABI().getMangleContext(); 451218893Sdim const Decl *D = GD.getDecl(); 452218893Sdim llvm::raw_svector_ostream Out(Buffer.getBuffer()); 453218893Sdim if (D == 0) 454239462Sdim MangleCtx.mangleGlobalBlock(BD, 455239462Sdim dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 456218893Sdim else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 457218893Sdim MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 458218893Sdim else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D)) 459218893Sdim MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 460218893Sdim else 461218893Sdim MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 462210299Sed} 463210299Sed 464226633Sdimllvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 465205408Srdivacky return getModule().getNamedValue(Name); 466193326Sed} 467193326Sed 468193326Sed/// AddGlobalCtor - Add a function to the list that will be called before 469193326Sed/// main() runs. 470193326Sedvoid CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) { 471193326Sed // FIXME: Type coercion of void()* types. 472193326Sed GlobalCtors.push_back(std::make_pair(Ctor, Priority)); 473193326Sed} 474193326Sed 475193326Sed/// AddGlobalDtor - Add a function to the list that will be called 476193326Sed/// when the module is unloaded. 477193326Sedvoid CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) { 478193326Sed // FIXME: Type coercion of void()* types. 479193326Sed GlobalDtors.push_back(std::make_pair(Dtor, Priority)); 480193326Sed} 481193326Sed 482193326Sedvoid CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 483193326Sed // Ctor function type is void()*. 484223017Sdim llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 485193326Sed llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 486193326Sed 487193326Sed // Get the type of a ctor entry, { i32, void ()* }. 488224145Sdim llvm::StructType *CtorStructTy = 489234353Sdim llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL); 490193326Sed 491193326Sed // Construct the constructor and destructor arrays. 492234353Sdim SmallVector<llvm::Constant*, 8> Ctors; 493193326Sed for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 494234353Sdim llvm::Constant *S[] = { 495234353Sdim llvm::ConstantInt::get(Int32Ty, I->second, false), 496234353Sdim llvm::ConstantExpr::getBitCast(I->first, CtorPFTy) 497234353Sdim }; 498193326Sed Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 499193326Sed } 500193326Sed 501193326Sed if (!Ctors.empty()) { 502193326Sed llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 503198092Srdivacky new llvm::GlobalVariable(TheModule, AT, false, 504193326Sed llvm::GlobalValue::AppendingLinkage, 505193326Sed llvm::ConstantArray::get(AT, Ctors), 506198092Srdivacky GlobalName); 507193326Sed } 508193326Sed} 509193326Sed 510204643Srdivackyllvm::GlobalValue::LinkageTypes 511204643SrdivackyCodeGenModule::getFunctionLinkage(const FunctionDecl *D) { 512212904Sdim GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 513193326Sed 514210299Sed if (Linkage == GVA_Internal) 515204643Srdivacky return llvm::Function::InternalLinkage; 516210299Sed 517210299Sed if (D->hasAttr<DLLExportAttr>()) 518204643Srdivacky return llvm::Function::DLLExportLinkage; 519210299Sed 520210299Sed if (D->hasAttr<WeakAttr>()) 521204643Srdivacky return llvm::Function::WeakAnyLinkage; 522210299Sed 523210299Sed // In C99 mode, 'inline' functions are guaranteed to have a strong 524210299Sed // definition somewhere else, so we can use available_externally linkage. 525210299Sed if (Linkage == GVA_C99Inline) 526204643Srdivacky return llvm::Function::AvailableExternallyLinkage; 527226633Sdim 528226633Sdim // Note that Apple's kernel linker doesn't support symbol 529226633Sdim // coalescing, so we need to avoid linkonce and weak linkages there. 530226633Sdim // Normally, this means we just map to internal, but for explicit 531226633Sdim // instantiations we'll map to external. 532226633Sdim 533210299Sed // In C++, the compiler has to emit a definition in every translation unit 534210299Sed // that references the function. We should use linkonce_odr because 535210299Sed // a) if all references in this translation unit are optimized away, we 536210299Sed // don't need to codegen it. b) if the function persists, it needs to be 537210299Sed // merged with other definitions. c) C++ has the ODR, so we know the 538210299Sed // definition is dependable. 539210299Sed if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) 540234353Sdim return !Context.getLangOpts().AppleKext 541218893Sdim ? llvm::Function::LinkOnceODRLinkage 542218893Sdim : llvm::Function::InternalLinkage; 543210299Sed 544210299Sed // An explicit instantiation of a template has weak linkage, since 545210299Sed // explicit instantiations can occur in multiple translation units 546210299Sed // and must all be equivalent. However, we are not allowed to 547210299Sed // throw away these explicit instantiations. 548210299Sed if (Linkage == GVA_ExplicitTemplateInstantiation) 549234353Sdim return !Context.getLangOpts().AppleKext 550218893Sdim ? llvm::Function::WeakODRLinkage 551226633Sdim : llvm::Function::ExternalLinkage; 552210299Sed 553210299Sed // Otherwise, we have strong external linkage. 554210299Sed assert(Linkage == GVA_StrongExternal); 555210299Sed return llvm::Function::ExternalLinkage; 556204643Srdivacky} 557193326Sed 558204643Srdivacky 559204643Srdivacky/// SetFunctionDefinitionAttributes - Set attributes for a global. 560204643Srdivacky/// 561204643Srdivacky/// FIXME: This is currently only done for aliases and functions, but not for 562204643Srdivacky/// variables (these details are set in EmitGlobalVarDefinition for variables). 563204643Srdivackyvoid CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D, 564204643Srdivacky llvm::GlobalValue *GV) { 565193326Sed SetCommonAttributes(D, GV); 566193326Sed} 567193326Sed 568193326Sedvoid CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 569198092Srdivacky const CGFunctionInfo &Info, 570193326Sed llvm::Function *F) { 571198092Srdivacky unsigned CallingConv; 572193326Sed AttributeListType AttributeList; 573249423Sdim ConstructAttributeList(Info, D, AttributeList, CallingConv, false); 574249423Sdim F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList)); 575198092Srdivacky F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 576193326Sed} 577193326Sed 578226633Sdim/// Determines whether the language options require us to model 579226633Sdim/// unwind exceptions. We treat -fexceptions as mandating this 580226633Sdim/// except under the fragile ObjC ABI with only ObjC exceptions 581226633Sdim/// enabled. This means, for example, that C with -fexceptions 582226633Sdim/// enables this. 583234353Sdimstatic bool hasUnwindExceptions(const LangOptions &LangOpts) { 584226633Sdim // If exceptions are completely disabled, obviously this is false. 585234353Sdim if (!LangOpts.Exceptions) return false; 586226633Sdim 587226633Sdim // If C++ exceptions are enabled, this is true. 588234353Sdim if (LangOpts.CXXExceptions) return true; 589226633Sdim 590226633Sdim // If ObjC exceptions are enabled, this depends on the ABI. 591234353Sdim if (LangOpts.ObjCExceptions) { 592239462Sdim return LangOpts.ObjCRuntime.hasUnwindExceptions(); 593226633Sdim } 594226633Sdim 595226633Sdim return true; 596226633Sdim} 597226633Sdim 598193326Sedvoid CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 599193326Sed llvm::Function *F) { 600223017Sdim if (CodeGenOpts.UnwindTables) 601223017Sdim F->setHasUWTable(); 602223017Sdim 603234353Sdim if (!hasUnwindExceptions(LangOpts)) 604249423Sdim F->addFnAttr(llvm::Attribute::NoUnwind); 605193326Sed 606226633Sdim if (D->hasAttr<NakedAttr>()) { 607226633Sdim // Naked implies noinline: we should not be inlining such functions. 608249423Sdim F->addFnAttr(llvm::Attribute::Naked); 609249423Sdim F->addFnAttr(llvm::Attribute::NoInline); 610226633Sdim } 611218893Sdim 612198092Srdivacky if (D->hasAttr<NoInlineAttr>()) 613249423Sdim F->addFnAttr(llvm::Attribute::NoInline); 614198092Srdivacky 615226633Sdim // (noinline wins over always_inline, and we can't specify both in IR) 616239462Sdim if ((D->hasAttr<AlwaysInlineAttr>() || D->hasAttr<ForceInlineAttr>()) && 617249423Sdim !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex, 618249423Sdim llvm::Attribute::NoInline)) 619249423Sdim F->addFnAttr(llvm::Attribute::AlwaysInline); 620226633Sdim 621239462Sdim // FIXME: Communicate hot and cold attributes to LLVM more directly. 622239462Sdim if (D->hasAttr<ColdAttr>()) 623249423Sdim F->addFnAttr(llvm::Attribute::OptimizeForSize); 624239462Sdim 625243830Sdim if (D->hasAttr<MinSizeAttr>()) 626249423Sdim F->addFnAttr(llvm::Attribute::MinSize); 627243830Sdim 628218893Sdim if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 629218893Sdim F->setUnnamedAddr(true); 630218893Sdim 631243830Sdim if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) 632243830Sdim if (MD->isVirtual()) 633243830Sdim F->setUnnamedAddr(true); 634243830Sdim 635234353Sdim if (LangOpts.getStackProtector() == LangOptions::SSPOn) 636249423Sdim F->addFnAttr(llvm::Attribute::StackProtect); 637234353Sdim else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 638249423Sdim F->addFnAttr(llvm::Attribute::StackProtectReq); 639249423Sdim 640249423Sdim // Add sanitizer attributes if function is not blacklisted. 641249423Sdim if (!SanitizerBlacklist.isIn(*F)) { 642249423Sdim // When AddressSanitizer is enabled, set SanitizeAddress attribute 643249423Sdim // unless __attribute__((no_sanitize_address)) is used. 644249423Sdim if (SanOpts.Address && !D->hasAttr<NoSanitizeAddressAttr>()) 645249423Sdim F->addFnAttr(llvm::Attribute::SanitizeAddress); 646249423Sdim // Same for ThreadSanitizer and __attribute__((no_sanitize_thread)) 647249423Sdim if (SanOpts.Thread && !D->hasAttr<NoSanitizeThreadAttr>()) { 648249423Sdim F->addFnAttr(llvm::Attribute::SanitizeThread); 649249423Sdim } 650249423Sdim // Same for MemorySanitizer and __attribute__((no_sanitize_memory)) 651249423Sdim if (SanOpts.Memory && !D->hasAttr<NoSanitizeMemoryAttr>()) 652249423Sdim F->addFnAttr(llvm::Attribute::SanitizeMemory); 653234353Sdim } 654234353Sdim 655212904Sdim unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 656212904Sdim if (alignment) 657212904Sdim F->setAlignment(alignment); 658212904Sdim 659198092Srdivacky // C++ ABI requires 2-byte alignment for member functions. 660198092Srdivacky if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 661198092Srdivacky F->setAlignment(2); 662193326Sed} 663193326Sed 664198092Srdivackyvoid CodeGenModule::SetCommonAttributes(const Decl *D, 665193326Sed llvm::GlobalValue *GV) { 666218893Sdim if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) 667218893Sdim setGlobalVisibility(GV, ND); 668218893Sdim else 669218893Sdim GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 670193326Sed 671195341Sed if (D->hasAttr<UsedAttr>()) 672193326Sed AddUsedGlobal(GV); 673193326Sed 674195341Sed if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 675193326Sed GV->setSection(SA->getName()); 676202379Srdivacky 677249423Sdim // Alias cannot have attributes. Filter them here. 678249423Sdim if (!isa<llvm::GlobalAlias>(GV)) 679249423Sdim getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this); 680193326Sed} 681193326Sed 682193326Sedvoid CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 683193326Sed llvm::Function *F, 684193326Sed const CGFunctionInfo &FI) { 685193326Sed SetLLVMFunctionAttributes(D, FI, F); 686193326Sed SetLLVMFunctionAttributesForDefinition(D, F); 687193326Sed 688193326Sed F->setLinkage(llvm::Function::InternalLinkage); 689193326Sed 690193326Sed SetCommonAttributes(D, F); 691193326Sed} 692193326Sed 693203955Srdivackyvoid CodeGenModule::SetFunctionAttributes(GlobalDecl GD, 694193326Sed llvm::Function *F, 695193326Sed bool IsIncompleteFunction) { 696221345Sdim if (unsigned IID = F->getIntrinsicID()) { 697221345Sdim // If this is an intrinsic function, set the function's attributes 698221345Sdim // to the intrinsic's attributes. 699243830Sdim F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), 700243830Sdim (llvm::Intrinsic::ID)IID)); 701221345Sdim return; 702221345Sdim } 703221345Sdim 704203955Srdivacky const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 705203955Srdivacky 706193326Sed if (!IsIncompleteFunction) 707234353Sdim SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F); 708198092Srdivacky 709193326Sed // Only a few attributes are set on declarations; these may later be 710193326Sed // overridden by a definition. 711198092Srdivacky 712195341Sed if (FD->hasAttr<DLLImportAttr>()) { 713193326Sed F->setLinkage(llvm::Function::DLLImportLinkage); 714198092Srdivacky } else if (FD->hasAttr<WeakAttr>() || 715221345Sdim FD->isWeakImported()) { 716193326Sed // "extern_weak" is overloaded in LLVM; we probably should have 717198092Srdivacky // separate linkage types for this. 718193326Sed F->setLinkage(llvm::Function::ExternalWeakLinkage); 719193326Sed } else { 720198092Srdivacky F->setLinkage(llvm::Function::ExternalLinkage); 721218893Sdim 722249423Sdim LinkageInfo LV = FD->getLinkageAndVisibility(); 723249423Sdim if (LV.getLinkage() == ExternalLinkage && LV.isVisibilityExplicit()) { 724249423Sdim F->setVisibility(GetLLVMVisibility(LV.getVisibility())); 725218893Sdim } 726193326Sed } 727193326Sed 728195341Sed if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 729193326Sed F->setSection(SA->getName()); 730193326Sed} 731193326Sed 732193326Sedvoid CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) { 733198092Srdivacky assert(!GV->isDeclaration() && 734193326Sed "Only globals with definition can force usage."); 735193326Sed LLVMUsed.push_back(GV); 736193326Sed} 737193326Sed 738193326Sedvoid CodeGenModule::EmitLLVMUsed() { 739193326Sed // Don't create llvm.used if there is no need. 740198092Srdivacky if (LLVMUsed.empty()) 741193326Sed return; 742193326Sed 743193326Sed // Convert LLVMUsed to what ConstantArray needs. 744234353Sdim SmallVector<llvm::Constant*, 8> UsedArray; 745193326Sed UsedArray.resize(LLVMUsed.size()); 746193326Sed for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) { 747198092Srdivacky UsedArray[i] = 748198092Srdivacky llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]), 749234353Sdim Int8PtrTy); 750193326Sed } 751198092Srdivacky 752195099Sed if (UsedArray.empty()) 753195099Sed return; 754234353Sdim llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size()); 755198092Srdivacky 756198092Srdivacky llvm::GlobalVariable *GV = 757198092Srdivacky new llvm::GlobalVariable(getModule(), ATy, false, 758193326Sed llvm::GlobalValue::AppendingLinkage, 759193326Sed llvm::ConstantArray::get(ATy, UsedArray), 760198092Srdivacky "llvm.used"); 761193326Sed 762193326Sed GV->setSection("llvm.metadata"); 763193326Sed} 764193326Sed 765249423Sdim/// \brief Add link options implied by the given module, including modules 766249423Sdim/// it depends on, using a postorder walk. 767249423Sdimstatic void addLinkOptionsPostorder(llvm::LLVMContext &Context, 768249423Sdim Module *Mod, 769249423Sdim SmallVectorImpl<llvm::Value *> &Metadata, 770249423Sdim llvm::SmallPtrSet<Module *, 16> &Visited) { 771249423Sdim // Import this module's parent. 772249423Sdim if (Mod->Parent && Visited.insert(Mod->Parent)) { 773249423Sdim addLinkOptionsPostorder(Context, Mod->Parent, Metadata, Visited); 774249423Sdim } 775249423Sdim 776249423Sdim // Import this module's dependencies. 777249423Sdim for (unsigned I = Mod->Imports.size(); I > 0; --I) { 778249423Sdim if (Visited.insert(Mod->Imports[I-1])) 779249423Sdim addLinkOptionsPostorder(Context, Mod->Imports[I-1], Metadata, Visited); 780249423Sdim } 781249423Sdim 782249423Sdim // Add linker options to link against the libraries/frameworks 783249423Sdim // described by this module. 784249423Sdim for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) { 785249423Sdim // FIXME: -lfoo is Unix-centric and -framework Foo is Darwin-centric. 786249423Sdim // We need to know more about the linker to know how to encode these 787249423Sdim // options propertly. 788249423Sdim 789249423Sdim // Link against a framework. 790249423Sdim if (Mod->LinkLibraries[I-1].IsFramework) { 791249423Sdim llvm::Value *Args[2] = { 792249423Sdim llvm::MDString::get(Context, "-framework"), 793249423Sdim llvm::MDString::get(Context, Mod->LinkLibraries[I-1].Library) 794249423Sdim }; 795249423Sdim 796249423Sdim Metadata.push_back(llvm::MDNode::get(Context, Args)); 797249423Sdim continue; 798249423Sdim } 799249423Sdim 800249423Sdim // Link against a library. 801249423Sdim llvm::Value *OptString 802249423Sdim = llvm::MDString::get(Context, 803249423Sdim "-l" + Mod->LinkLibraries[I-1].Library); 804249423Sdim Metadata.push_back(llvm::MDNode::get(Context, OptString)); 805249423Sdim } 806249423Sdim} 807249423Sdim 808249423Sdimvoid CodeGenModule::EmitModuleLinkOptions() { 809249423Sdim // Collect the set of all of the modules we want to visit to emit link 810249423Sdim // options, which is essentially the imported modules and all of their 811249423Sdim // non-explicit child modules. 812249423Sdim llvm::SetVector<clang::Module *> LinkModules; 813249423Sdim llvm::SmallPtrSet<clang::Module *, 16> Visited; 814249423Sdim SmallVector<clang::Module *, 16> Stack; 815249423Sdim 816249423Sdim // Seed the stack with imported modules. 817249423Sdim for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(), 818249423Sdim MEnd = ImportedModules.end(); 819249423Sdim M != MEnd; ++M) { 820249423Sdim if (Visited.insert(*M)) 821249423Sdim Stack.push_back(*M); 822249423Sdim } 823249423Sdim 824249423Sdim // Find all of the modules to import, making a little effort to prune 825249423Sdim // non-leaf modules. 826249423Sdim while (!Stack.empty()) { 827249423Sdim clang::Module *Mod = Stack.back(); 828249423Sdim Stack.pop_back(); 829249423Sdim 830249423Sdim bool AnyChildren = false; 831249423Sdim 832249423Sdim // Visit the submodules of this module. 833249423Sdim for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 834249423Sdim SubEnd = Mod->submodule_end(); 835249423Sdim Sub != SubEnd; ++Sub) { 836249423Sdim // Skip explicit children; they need to be explicitly imported to be 837249423Sdim // linked against. 838249423Sdim if ((*Sub)->IsExplicit) 839249423Sdim continue; 840249423Sdim 841249423Sdim if (Visited.insert(*Sub)) { 842249423Sdim Stack.push_back(*Sub); 843249423Sdim AnyChildren = true; 844249423Sdim } 845249423Sdim } 846249423Sdim 847249423Sdim // We didn't find any children, so add this module to the list of 848249423Sdim // modules to link against. 849249423Sdim if (!AnyChildren) { 850249423Sdim LinkModules.insert(Mod); 851249423Sdim } 852249423Sdim } 853249423Sdim 854249423Sdim // Add link options for all of the imported modules in reverse topological 855249423Sdim // order. 856249423Sdim SmallVector<llvm::Value *, 16> MetadataArgs; 857249423Sdim Visited.clear(); 858249423Sdim for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(), 859249423Sdim MEnd = LinkModules.end(); 860249423Sdim M != MEnd; ++M) { 861249423Sdim if (Visited.insert(*M)) 862249423Sdim addLinkOptionsPostorder(getLLVMContext(), *M, MetadataArgs, Visited); 863249423Sdim } 864249423Sdim std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 865249423Sdim 866249423Sdim // Add the linker options metadata flag. 867249423Sdim getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options", 868249423Sdim llvm::MDNode::get(getLLVMContext(), MetadataArgs)); 869249423Sdim} 870249423Sdim 871193326Sedvoid CodeGenModule::EmitDeferred() { 872193326Sed // Emit code for any potentially referenced deferred decls. Since a 873193326Sed // previously unused static decl may become used during the generation of code 874226633Sdim // for a static function, iterate until no changes are made. 875204962Srdivacky 876249423Sdim while (true) { 877207619Srdivacky if (!DeferredVTables.empty()) { 878249423Sdim EmitDeferredVTables(); 879249423Sdim 880249423Sdim // Emitting a v-table doesn't directly cause more v-tables to 881249423Sdim // become deferred, although it can cause functions to be 882249423Sdim // emitted that then need those v-tables. 883249423Sdim assert(DeferredVTables.empty()); 884204962Srdivacky } 885204962Srdivacky 886249423Sdim // Stop if we're out of both deferred v-tables and deferred declarations. 887249423Sdim if (DeferredDeclsToEmit.empty()) break; 888249423Sdim 889193326Sed GlobalDecl D = DeferredDeclsToEmit.back(); 890193326Sed DeferredDeclsToEmit.pop_back(); 891193326Sed 892208600Srdivacky // Check to see if we've already emitted this. This is necessary 893208600Srdivacky // for a couple of reasons: first, decls can end up in the 894208600Srdivacky // deferred-decls queue multiple times, and second, decls can end 895208600Srdivacky // up with definitions in unusual ways (e.g. by an extern inline 896208600Srdivacky // function acquiring a strong function redefinition). Just 897208600Srdivacky // ignore these cases. 898208600Srdivacky // 899208600Srdivacky // TODO: That said, looking this up multiple times is very wasteful. 900226633Sdim StringRef Name = getMangledName(D); 901205408Srdivacky llvm::GlobalValue *CGRef = GetGlobalValue(Name); 902193326Sed assert(CGRef && "Deferred decl wasn't referenced?"); 903198092Srdivacky 904193326Sed if (!CGRef->isDeclaration()) 905193326Sed continue; 906198092Srdivacky 907208600Srdivacky // GlobalAlias::isDeclaration() defers to the aliasee, but for our 908208600Srdivacky // purposes an alias counts as a definition. 909208600Srdivacky if (isa<llvm::GlobalAlias>(CGRef)) 910208600Srdivacky continue; 911208600Srdivacky 912193326Sed // Otherwise, emit the definition and move on to the next one. 913193326Sed EmitGlobalDefinition(D); 914193326Sed } 915193326Sed} 916193326Sed 917226633Sdimvoid CodeGenModule::EmitGlobalAnnotations() { 918226633Sdim if (Annotations.empty()) 919226633Sdim return; 920226633Sdim 921226633Sdim // Create a new global variable for the ConstantStruct in the Module. 922226633Sdim llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 923226633Sdim Annotations[0]->getType(), Annotations.size()), Annotations); 924226633Sdim llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), 925226633Sdim Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array, 926226633Sdim "llvm.global.annotations"); 927226633Sdim gv->setSection(AnnotationSection); 928226633Sdim} 929226633Sdim 930249423Sdimllvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 931226633Sdim llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str); 932226633Sdim if (i != AnnotationStrings.end()) 933226633Sdim return i->second; 934226633Sdim 935226633Sdim // Not found yet, create a new global. 936234353Sdim llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 937226633Sdim llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(), 938226633Sdim true, llvm::GlobalValue::PrivateLinkage, s, ".str"); 939226633Sdim gv->setSection(AnnotationSection); 940226633Sdim gv->setUnnamedAddr(true); 941226633Sdim AnnotationStrings[Str] = gv; 942226633Sdim return gv; 943226633Sdim} 944226633Sdim 945226633Sdimllvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 946226633Sdim SourceManager &SM = getContext().getSourceManager(); 947226633Sdim PresumedLoc PLoc = SM.getPresumedLoc(Loc); 948226633Sdim if (PLoc.isValid()) 949226633Sdim return EmitAnnotationString(PLoc.getFilename()); 950226633Sdim return EmitAnnotationString(SM.getBufferName(Loc)); 951226633Sdim} 952226633Sdim 953226633Sdimllvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 954226633Sdim SourceManager &SM = getContext().getSourceManager(); 955226633Sdim PresumedLoc PLoc = SM.getPresumedLoc(L); 956226633Sdim unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 957226633Sdim SM.getExpansionLineNumber(L); 958226633Sdim return llvm::ConstantInt::get(Int32Ty, LineNo); 959226633Sdim} 960226633Sdim 961198092Srdivackyllvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 962193326Sed const AnnotateAttr *AA, 963226633Sdim SourceLocation L) { 964226633Sdim // Get the globals for file name, annotation, and the line number. 965226633Sdim llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 966226633Sdim *UnitGV = EmitAnnotationUnit(L), 967226633Sdim *LineNoCst = EmitAnnotationLineNo(L); 968193326Sed 969193326Sed // Create the ConstantStruct for the global annotation. 970193326Sed llvm::Constant *Fields[4] = { 971226633Sdim llvm::ConstantExpr::getBitCast(GV, Int8PtrTy), 972226633Sdim llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 973226633Sdim llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 974226633Sdim LineNoCst 975193326Sed }; 976224145Sdim return llvm::ConstantStruct::getAnon(Fields); 977193326Sed} 978193326Sed 979226633Sdimvoid CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 980226633Sdim llvm::GlobalValue *GV) { 981226633Sdim assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 982226633Sdim // Get the struct elements for these annotations. 983226633Sdim for (specific_attr_iterator<AnnotateAttr> 984226633Sdim ai = D->specific_attr_begin<AnnotateAttr>(), 985226633Sdim ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai) 986226633Sdim Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation())); 987226633Sdim} 988226633Sdim 989193326Sedbool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) { 990212904Sdim // Never defer when EmitAllDecls is specified. 991234353Sdim if (LangOpts.EmitAllDecls) 992193326Sed return false; 993193326Sed 994212904Sdim return !getContext().DeclMustBeEmitted(Global); 995193326Sed} 996193326Sed 997243830Sdimllvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor( 998243830Sdim const CXXUuidofExpr* E) { 999243830Sdim // Sema has verified that IIDSource has a __declspec(uuid()), and that its 1000243830Sdim // well-formed. 1001243830Sdim StringRef Uuid; 1002243830Sdim if (E->isTypeOperand()) 1003243830Sdim Uuid = CXXUuidofExpr::GetUuidAttrOfType(E->getTypeOperand())->getGuid(); 1004243830Sdim else { 1005243830Sdim // Special case: __uuidof(0) means an all-zero GUID. 1006243830Sdim Expr *Op = E->getExprOperand(); 1007243830Sdim if (!Op->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 1008243830Sdim Uuid = CXXUuidofExpr::GetUuidAttrOfType(Op->getType())->getGuid(); 1009243830Sdim else 1010243830Sdim Uuid = "00000000-0000-0000-0000-000000000000"; 1011243830Sdim } 1012243830Sdim std::string Name = "__uuid_" + Uuid.str(); 1013243830Sdim 1014243830Sdim // Look for an existing global. 1015243830Sdim if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 1016243830Sdim return GV; 1017243830Sdim 1018243830Sdim llvm::Constant *Init = EmitUuidofInitializer(Uuid, E->getType()); 1019243830Sdim assert(Init && "failed to initialize as constant"); 1020243830Sdim 1021243830Sdim // GUIDs are assumed to be 16 bytes, spread over 4-2-2-8 bytes. However, the 1022243830Sdim // first field is declared as "long", which for many targets is 8 bytes. 1023243830Sdim // Those architectures are not supported. (With the MS abi, long is always 4 1024243830Sdim // bytes.) 1025243830Sdim llvm::Type *GuidType = getTypes().ConvertType(E->getType()); 1026243830Sdim if (Init->getType() != GuidType) { 1027243830Sdim DiagnosticsEngine &Diags = getDiags(); 1028243830Sdim unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 1029243830Sdim "__uuidof codegen is not supported on this architecture"); 1030243830Sdim Diags.Report(E->getExprLoc(), DiagID) << E->getSourceRange(); 1031243830Sdim Init = llvm::UndefValue::get(GuidType); 1032243830Sdim } 1033243830Sdim 1034243830Sdim llvm::GlobalVariable *GV = new llvm::GlobalVariable(getModule(), GuidType, 1035243830Sdim /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, Init, Name); 1036243830Sdim GV->setUnnamedAddr(true); 1037243830Sdim return GV; 1038243830Sdim} 1039243830Sdim 1040204793Srdivackyllvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 1041204793Srdivacky const AliasAttr *AA = VD->getAttr<AliasAttr>(); 1042204793Srdivacky assert(AA && "No alias?"); 1043204793Srdivacky 1044226633Sdim llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 1045204793Srdivacky 1046204793Srdivacky // See if there is already something with the target's name in the module. 1047205408Srdivacky llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 1048243830Sdim if (Entry) { 1049243830Sdim unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 1050243830Sdim return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 1051243830Sdim } 1052204793Srdivacky 1053204793Srdivacky llvm::Constant *Aliasee; 1054204793Srdivacky if (isa<llvm::FunctionType>(DeclTy)) 1055243830Sdim Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 1056243830Sdim GlobalDecl(cast<FunctionDecl>(VD)), 1057218893Sdim /*ForVTable=*/false); 1058204793Srdivacky else 1059205408Srdivacky Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 1060204793Srdivacky llvm::PointerType::getUnqual(DeclTy), 0); 1061204793Srdivacky 1062243830Sdim llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee); 1063243830Sdim F->setLinkage(llvm::Function::ExternalWeakLinkage); 1064243830Sdim WeakRefReferences.insert(F); 1065243830Sdim 1066204793Srdivacky return Aliasee; 1067204793Srdivacky} 1068204793Srdivacky 1069193326Sedvoid CodeGenModule::EmitGlobal(GlobalDecl GD) { 1070198092Srdivacky const ValueDecl *Global = cast<ValueDecl>(GD.getDecl()); 1071198092Srdivacky 1072204793Srdivacky // Weak references don't produce any output by themselves. 1073204793Srdivacky if (Global->hasAttr<WeakRefAttr>()) 1074204793Srdivacky return; 1075204793Srdivacky 1076193326Sed // If this is an alias definition (which otherwise looks like a declaration) 1077193326Sed // emit it now. 1078195341Sed if (Global->hasAttr<AliasAttr>()) 1079205408Srdivacky return EmitAliasDefinition(GD); 1080193326Sed 1081226633Sdim // If this is CUDA, be selective about which declarations we emit. 1082234353Sdim if (LangOpts.CUDA) { 1083226633Sdim if (CodeGenOpts.CUDAIsDevice) { 1084226633Sdim if (!Global->hasAttr<CUDADeviceAttr>() && 1085226633Sdim !Global->hasAttr<CUDAGlobalAttr>() && 1086226633Sdim !Global->hasAttr<CUDAConstantAttr>() && 1087226633Sdim !Global->hasAttr<CUDASharedAttr>()) 1088226633Sdim return; 1089226633Sdim } else { 1090226633Sdim if (!Global->hasAttr<CUDAHostAttr>() && ( 1091226633Sdim Global->hasAttr<CUDADeviceAttr>() || 1092226633Sdim Global->hasAttr<CUDAConstantAttr>() || 1093226633Sdim Global->hasAttr<CUDASharedAttr>())) 1094226633Sdim return; 1095226633Sdim } 1096226633Sdim } 1097226633Sdim 1098193326Sed // Ignore declarations, they will be emitted on their first use. 1099193326Sed if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 1100226633Sdim // Forward declarations are emitted lazily on first use. 1101226633Sdim if (!FD->doesThisDeclarationHaveABody()) { 1102226633Sdim if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 1103226633Sdim return; 1104212904Sdim 1105226633Sdim const FunctionDecl *InlineDefinition = 0; 1106226633Sdim FD->getBody(InlineDefinition); 1107226633Sdim 1108226633Sdim StringRef MangledName = getMangledName(GD); 1109234353Sdim DeferredDecls.erase(MangledName); 1110226633Sdim EmitGlobalDefinition(InlineDefinition); 1111193326Sed return; 1112226633Sdim } 1113193326Sed } else { 1114193326Sed const VarDecl *VD = cast<VarDecl>(Global); 1115193326Sed assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 1116193326Sed 1117203955Srdivacky if (VD->isThisDeclarationADefinition() != VarDecl::Definition) 1118193326Sed return; 1119193326Sed } 1120193326Sed 1121193326Sed // Defer code generation when possible if this is a static definition, inline 1122193326Sed // function etc. These we only want to emit if they are used. 1123207619Srdivacky if (!MayDeferGeneration(Global)) { 1124207619Srdivacky // Emit the definition if it can't be deferred. 1125207619Srdivacky EmitGlobalDefinition(GD); 1126193326Sed return; 1127193326Sed } 1128212904Sdim 1129212904Sdim // If we're deferring emission of a C++ variable with an 1130212904Sdim // initializer, remember the order in which it appeared in the file. 1131234353Sdim if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 1132212904Sdim cast<VarDecl>(Global)->hasInit()) { 1133212904Sdim DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 1134212904Sdim CXXGlobalInits.push_back(0); 1135212904Sdim } 1136207619Srdivacky 1137207619Srdivacky // If the value has already been used, add it directly to the 1138207619Srdivacky // DeferredDeclsToEmit list. 1139226633Sdim StringRef MangledName = getMangledName(GD); 1140207619Srdivacky if (GetGlobalValue(MangledName)) 1141207619Srdivacky DeferredDeclsToEmit.push_back(GD); 1142207619Srdivacky else { 1143207619Srdivacky // Otherwise, remember that we saw a deferred decl with this name. The 1144207619Srdivacky // first use of the mangled name will cause it to move into 1145207619Srdivacky // DeferredDeclsToEmit. 1146207619Srdivacky DeferredDecls[MangledName] = GD; 1147207619Srdivacky } 1148193326Sed} 1149193326Sed 1150228379Sdimnamespace { 1151228379Sdim struct FunctionIsDirectlyRecursive : 1152228379Sdim public RecursiveASTVisitor<FunctionIsDirectlyRecursive> { 1153228379Sdim const StringRef Name; 1154234353Sdim const Builtin::Context &BI; 1155228379Sdim bool Result; 1156234353Sdim FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) : 1157234353Sdim Name(N), BI(C), Result(false) { 1158228379Sdim } 1159228379Sdim typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base; 1160228379Sdim 1161228379Sdim bool TraverseCallExpr(CallExpr *E) { 1162234353Sdim const FunctionDecl *FD = E->getDirectCallee(); 1163234353Sdim if (!FD) 1164228379Sdim return true; 1165234353Sdim AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1166234353Sdim if (Attr && Name == Attr->getLabel()) { 1167234353Sdim Result = true; 1168234353Sdim return false; 1169234353Sdim } 1170234353Sdim unsigned BuiltinID = FD->getBuiltinID(); 1171234353Sdim if (!BuiltinID) 1172228379Sdim return true; 1173234353Sdim StringRef BuiltinName = BI.GetName(BuiltinID); 1174234353Sdim if (BuiltinName.startswith("__builtin_") && 1175234353Sdim Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 1176228379Sdim Result = true; 1177228379Sdim return false; 1178228379Sdim } 1179228379Sdim return true; 1180228379Sdim } 1181228379Sdim }; 1182228379Sdim} 1183228379Sdim 1184234353Sdim// isTriviallyRecursive - Check if this function calls another 1185234353Sdim// decl that, because of the asm attribute or the other decl being a builtin, 1186234353Sdim// ends up pointing to itself. 1187228379Sdimbool 1188234353SdimCodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 1189234353Sdim StringRef Name; 1190234353Sdim if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 1191234353Sdim // asm labels are a special kind of mangling we have to support. 1192234353Sdim AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1193234353Sdim if (!Attr) 1194234353Sdim return false; 1195234353Sdim Name = Attr->getLabel(); 1196234353Sdim } else { 1197234353Sdim Name = FD->getName(); 1198234353Sdim } 1199228379Sdim 1200234353Sdim FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 1201234353Sdim Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD)); 1202228379Sdim return Walker.Result; 1203228379Sdim} 1204228379Sdim 1205228379Sdimbool 1206228379SdimCodeGenModule::shouldEmitFunction(const FunctionDecl *F) { 1207228379Sdim if (getFunctionLinkage(F) != llvm::Function::AvailableExternallyLinkage) 1208228379Sdim return true; 1209228379Sdim if (CodeGenOpts.OptimizationLevel == 0 && 1210239462Sdim !F->hasAttr<AlwaysInlineAttr>() && !F->hasAttr<ForceInlineAttr>()) 1211228379Sdim return false; 1212228379Sdim // PR9614. Avoid cases where the source code is lying to us. An available 1213228379Sdim // externally function should have an equivalent function somewhere else, 1214228379Sdim // but a function that calls itself is clearly not equivalent to the real 1215228379Sdim // implementation. 1216228379Sdim // This happens in glibc's btowc and in some configure checks. 1217234353Sdim return !isTriviallyRecursive(F); 1218228379Sdim} 1219228379Sdim 1220193326Sedvoid CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) { 1221198092Srdivacky const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 1222198092Srdivacky 1223207619Srdivacky PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 1224198893Srdivacky Context.getSourceManager(), 1225198893Srdivacky "Generating code for declaration"); 1226198893Srdivacky 1227210299Sed if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 1228210299Sed // At -O0, don't generate IR for functions with available_externally 1229210299Sed // linkage. 1230228379Sdim if (!shouldEmitFunction(Function)) 1231210299Sed return; 1232206084Srdivacky 1233210299Sed if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 1234223017Sdim // Make sure to emit the definition(s) before we emit the thunks. 1235223017Sdim // This is necessary for the generation of certain thunks. 1236223017Sdim if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method)) 1237223017Sdim EmitCXXConstructor(CD, GD.getCtorType()); 1238223017Sdim else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method)) 1239223017Sdim EmitCXXDestructor(DD, GD.getDtorType()); 1240223017Sdim else 1241223017Sdim EmitGlobalFunctionDefinition(GD); 1242223017Sdim 1243210299Sed if (Method->isVirtual()) 1244210299Sed getVTables().EmitThunks(GD); 1245210299Sed 1246223017Sdim return; 1247210299Sed } 1248207619Srdivacky 1249207619Srdivacky return EmitGlobalFunctionDefinition(GD); 1250210299Sed } 1251207619Srdivacky 1252207619Srdivacky if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1253207619Srdivacky return EmitGlobalVarDefinition(VD); 1254207619Srdivacky 1255226633Sdim llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 1256193326Sed} 1257193326Sed 1258193326Sed/// GetOrCreateLLVMFunction - If the specified mangled name is not in the 1259193326Sed/// module, create and return an llvm Function with the specified type. If there 1260193326Sed/// is something in the module with the specified name, return it potentially 1261193326Sed/// bitcasted to the right type. 1262193326Sed/// 1263193326Sed/// If D is non-null, it specifies a decl that correspond to this. This is used 1264193326Sed/// to set the attributes on the function when it is first created. 1265205408Srdivackyllvm::Constant * 1266226633SdimCodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName, 1267226633Sdim llvm::Type *Ty, 1268224145Sdim GlobalDecl D, bool ForVTable, 1269249423Sdim llvm::AttributeSet ExtraAttrs) { 1270193326Sed // Lookup the entry, lazily creating it if necessary. 1271205408Srdivacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1272193326Sed if (Entry) { 1273243830Sdim if (WeakRefReferences.erase(Entry)) { 1274204793Srdivacky const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl()); 1275204793Srdivacky if (FD && !FD->hasAttr<WeakAttr>()) 1276206084Srdivacky Entry->setLinkage(llvm::Function::ExternalLinkage); 1277204793Srdivacky } 1278204793Srdivacky 1279193326Sed if (Entry->getType()->getElementType() == Ty) 1280193326Sed return Entry; 1281198092Srdivacky 1282193326Sed // Make sure the result is of the correct type. 1283224145Sdim return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 1284193326Sed } 1285198092Srdivacky 1286199482Srdivacky // This function doesn't have a complete type (for example, the return 1287199482Srdivacky // type is an incomplete struct). Use a fake type instead, and make 1288199482Srdivacky // sure not to try to set attributes. 1289199482Srdivacky bool IsIncompleteFunction = false; 1290207619Srdivacky 1291226633Sdim llvm::FunctionType *FTy; 1292207619Srdivacky if (isa<llvm::FunctionType>(Ty)) { 1293207619Srdivacky FTy = cast<llvm::FunctionType>(Ty); 1294207619Srdivacky } else { 1295223017Sdim FTy = llvm::FunctionType::get(VoidTy, false); 1296199482Srdivacky IsIncompleteFunction = true; 1297199482Srdivacky } 1298210299Sed 1299207619Srdivacky llvm::Function *F = llvm::Function::Create(FTy, 1300199482Srdivacky llvm::Function::ExternalLinkage, 1301205408Srdivacky MangledName, &getModule()); 1302205408Srdivacky assert(F->getName() == MangledName && "name was uniqued!"); 1303199482Srdivacky if (D.getDecl()) 1304203955Srdivacky SetFunctionAttributes(D, F, IsIncompleteFunction); 1305249423Sdim if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) { 1306249423Sdim llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex); 1307249423Sdim F->addAttributes(llvm::AttributeSet::FunctionIndex, 1308249423Sdim llvm::AttributeSet::get(VMContext, 1309249423Sdim llvm::AttributeSet::FunctionIndex, 1310249423Sdim B)); 1311249423Sdim } 1312199482Srdivacky 1313193326Sed // This is the first use or definition of a mangled name. If there is a 1314193326Sed // deferred decl with this name, remember that we need to emit it at the end 1315193326Sed // of the file. 1316205408Srdivacky llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 1317193326Sed if (DDI != DeferredDecls.end()) { 1318193326Sed // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 1319193326Sed // list, and remove it from DeferredDecls (since we don't need it anymore). 1320193326Sed DeferredDeclsToEmit.push_back(DDI->second); 1321193326Sed DeferredDecls.erase(DDI); 1322218893Sdim 1323218893Sdim // Otherwise, there are cases we have to worry about where we're 1324218893Sdim // using a declaration for which we must emit a definition but where 1325218893Sdim // we might not find a top-level definition: 1326218893Sdim // - member functions defined inline in their classes 1327218893Sdim // - friend functions defined inline in some class 1328218893Sdim // - special member functions with implicit definitions 1329218893Sdim // If we ever change our AST traversal to walk into class methods, 1330218893Sdim // this will be unnecessary. 1331218893Sdim // 1332218893Sdim // We also don't emit a definition for a function if it's going to be an entry 1333218893Sdim // in a vtable, unless it's already marked as used. 1334234353Sdim } else if (getLangOpts().CPlusPlus && D.getDecl()) { 1335218893Sdim // Look for a declaration that's lexically in a record. 1336218893Sdim const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl()); 1337239462Sdim FD = FD->getMostRecentDecl(); 1338218893Sdim do { 1339218893Sdim if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 1340218893Sdim if (FD->isImplicit() && !ForVTable) { 1341218893Sdim assert(FD->isUsed() && "Sema didn't mark implicit function as used!"); 1342218893Sdim DeferredDeclsToEmit.push_back(D.getWithDecl(FD)); 1343218893Sdim break; 1344223017Sdim } else if (FD->doesThisDeclarationHaveABody()) { 1345218893Sdim DeferredDeclsToEmit.push_back(D.getWithDecl(FD)); 1346218893Sdim break; 1347218893Sdim } 1348204643Srdivacky } 1349234353Sdim FD = FD->getPreviousDecl(); 1350218893Sdim } while (FD); 1351193326Sed } 1352198092Srdivacky 1353207619Srdivacky // Make sure the result is of the requested type. 1354207619Srdivacky if (!IsIncompleteFunction) { 1355207619Srdivacky assert(F->getType()->getElementType() == Ty); 1356207619Srdivacky return F; 1357207619Srdivacky } 1358207619Srdivacky 1359224145Sdim llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 1360207619Srdivacky return llvm::ConstantExpr::getBitCast(F, PTy); 1361193326Sed} 1362193326Sed 1363193326Sed/// GetAddrOfFunction - Return the address of the given function. If Ty is 1364193326Sed/// non-null, then this function will use the specified type if it has to 1365193326Sed/// create it (this occurs when we see a definition of the function). 1366193326Sedllvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 1367226633Sdim llvm::Type *Ty, 1368218893Sdim bool ForVTable) { 1369193326Sed // If there was no specific requested type, just convert it now. 1370193326Sed if (!Ty) 1371198092Srdivacky Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType()); 1372210299Sed 1373226633Sdim StringRef MangledName = getMangledName(GD); 1374218893Sdim return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable); 1375193326Sed} 1376193326Sed 1377193326Sed/// CreateRuntimeFunction - Create a new runtime function with the specified 1378193326Sed/// type and name. 1379193326Sedllvm::Constant * 1380226633SdimCodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, 1381226633Sdim StringRef Name, 1382249423Sdim llvm::AttributeSet ExtraAttrs) { 1383249423Sdim llvm::Constant *C 1384249423Sdim = GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 1385249423Sdim ExtraAttrs); 1386249423Sdim if (llvm::Function *F = dyn_cast<llvm::Function>(C)) 1387249423Sdim if (F->empty()) 1388249423Sdim F->setCallingConv(getRuntimeCC()); 1389249423Sdim return C; 1390193326Sed} 1391193326Sed 1392234353Sdim/// isTypeConstant - Determine whether an object of this type can be emitted 1393234353Sdim/// as a constant. 1394234353Sdim/// 1395234353Sdim/// If ExcludeCtor is true, the duration when the object's constructor runs 1396234353Sdim/// will not be considered. The caller will need to verify that the object is 1397234353Sdim/// not written to during its construction. 1398234353Sdimbool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 1399234353Sdim if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 1400200583Srdivacky return false; 1401234353Sdim 1402234353Sdim if (Context.getLangOpts().CPlusPlus) { 1403234353Sdim if (const CXXRecordDecl *Record 1404234353Sdim = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 1405234353Sdim return ExcludeCtor && !Record->hasMutableFields() && 1406234353Sdim Record->hasTrivialDestructor(); 1407200583Srdivacky } 1408234353Sdim 1409200583Srdivacky return true; 1410200583Srdivacky} 1411200583Srdivacky 1412193326Sed/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 1413193326Sed/// create and return an llvm GlobalVariable with the specified type. If there 1414193326Sed/// is something in the module with the specified name, return it potentially 1415193326Sed/// bitcasted to the right type. 1416193326Sed/// 1417193326Sed/// If D is non-null, it specifies a decl that correspond to this. This is used 1418193326Sed/// to set the attributes on the global when it is first created. 1419205408Srdivackyllvm::Constant * 1420226633SdimCodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, 1421226633Sdim llvm::PointerType *Ty, 1422218893Sdim const VarDecl *D, 1423218893Sdim bool UnnamedAddr) { 1424193326Sed // Lookup the entry, lazily creating it if necessary. 1425205408Srdivacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1426193326Sed if (Entry) { 1427243830Sdim if (WeakRefReferences.erase(Entry)) { 1428204793Srdivacky if (D && !D->hasAttr<WeakAttr>()) 1429206084Srdivacky Entry->setLinkage(llvm::Function::ExternalLinkage); 1430204793Srdivacky } 1431204793Srdivacky 1432218893Sdim if (UnnamedAddr) 1433218893Sdim Entry->setUnnamedAddr(true); 1434218893Sdim 1435193326Sed if (Entry->getType() == Ty) 1436193326Sed return Entry; 1437198092Srdivacky 1438193326Sed // Make sure the result is of the correct type. 1439193326Sed return llvm::ConstantExpr::getBitCast(Entry, Ty); 1440193326Sed } 1441198092Srdivacky 1442193326Sed // This is the first use or definition of a mangled name. If there is a 1443193326Sed // deferred decl with this name, remember that we need to emit it at the end 1444193326Sed // of the file. 1445205408Srdivacky llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 1446193326Sed if (DDI != DeferredDecls.end()) { 1447193326Sed // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 1448193326Sed // list, and remove it from DeferredDecls (since we don't need it anymore). 1449193326Sed DeferredDeclsToEmit.push_back(DDI->second); 1450193326Sed DeferredDecls.erase(DDI); 1451193326Sed } 1452198092Srdivacky 1453239462Sdim unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace()); 1454198092Srdivacky llvm::GlobalVariable *GV = 1455198092Srdivacky new llvm::GlobalVariable(getModule(), Ty->getElementType(), false, 1456193326Sed llvm::GlobalValue::ExternalLinkage, 1457205408Srdivacky 0, MangledName, 0, 1458239462Sdim llvm::GlobalVariable::NotThreadLocal, AddrSpace); 1459193326Sed 1460193326Sed // Handle things which are present even on external declarations. 1461193326Sed if (D) { 1462193326Sed // FIXME: This code is overly simple and should be merged with other global 1463193326Sed // handling. 1464234353Sdim GV->setConstant(isTypeConstant(D->getType(), false)); 1465193326Sed 1466218893Sdim // Set linkage and visibility in case we never see a definition. 1467249423Sdim LinkageInfo LV = D->getLinkageAndVisibility(); 1468249423Sdim if (LV.getLinkage() != ExternalLinkage) { 1469218893Sdim // Don't set internal linkage on declarations. 1470218893Sdim } else { 1471218893Sdim if (D->hasAttr<DLLImportAttr>()) 1472218893Sdim GV->setLinkage(llvm::GlobalValue::DLLImportLinkage); 1473221345Sdim else if (D->hasAttr<WeakAttr>() || D->isWeakImported()) 1474218893Sdim GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 1475193326Sed 1476218893Sdim // Set visibility on a declaration only if it's explicit. 1477249423Sdim if (LV.isVisibilityExplicit()) 1478249423Sdim GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 1479218893Sdim } 1480193326Sed 1481251662Sdim if (D->getTLSKind()) { 1482251662Sdim if (D->getTLSKind() == VarDecl::TLS_Dynamic) 1483251662Sdim CXXThreadLocals.push_back(std::make_pair(D, GV)); 1484239462Sdim setTLSMode(GV, *D); 1485251662Sdim } 1486193326Sed } 1487198092Srdivacky 1488239462Sdim if (AddrSpace != Ty->getAddressSpace()) 1489239462Sdim return llvm::ConstantExpr::getBitCast(GV, Ty); 1490239462Sdim else 1491239462Sdim return GV; 1492193326Sed} 1493193326Sed 1494193326Sed 1495218893Sdimllvm::GlobalVariable * 1496226633SdimCodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name, 1497226633Sdim llvm::Type *Ty, 1498218893Sdim llvm::GlobalValue::LinkageTypes Linkage) { 1499218893Sdim llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 1500218893Sdim llvm::GlobalVariable *OldGV = 0; 1501218893Sdim 1502218893Sdim 1503218893Sdim if (GV) { 1504218893Sdim // Check if the variable has the right type. 1505218893Sdim if (GV->getType()->getElementType() == Ty) 1506218893Sdim return GV; 1507218893Sdim 1508218893Sdim // Because C++ name mangling, the only way we can end up with an already 1509218893Sdim // existing global with the same name is if it has been declared extern "C". 1510243830Sdim assert(GV->isDeclaration() && "Declaration has wrong type!"); 1511218893Sdim OldGV = GV; 1512218893Sdim } 1513218893Sdim 1514218893Sdim // Create a new variable. 1515218893Sdim GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 1516218893Sdim Linkage, 0, Name); 1517218893Sdim 1518218893Sdim if (OldGV) { 1519218893Sdim // Replace occurrences of the old variable if needed. 1520218893Sdim GV->takeName(OldGV); 1521218893Sdim 1522218893Sdim if (!OldGV->use_empty()) { 1523218893Sdim llvm::Constant *NewPtrForOldDecl = 1524218893Sdim llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 1525218893Sdim OldGV->replaceAllUsesWith(NewPtrForOldDecl); 1526218893Sdim } 1527218893Sdim 1528218893Sdim OldGV->eraseFromParent(); 1529218893Sdim } 1530218893Sdim 1531218893Sdim return GV; 1532218893Sdim} 1533218893Sdim 1534193326Sed/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 1535193326Sed/// given global variable. If Ty is non-null and if the global doesn't exist, 1536234982Sdim/// then it will be created with the specified type instead of whatever the 1537193326Sed/// normal requested type would be. 1538193326Sedllvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 1539226633Sdim llvm::Type *Ty) { 1540193326Sed assert(D->hasGlobalStorage() && "Not a global variable"); 1541193326Sed QualType ASTTy = D->getType(); 1542193326Sed if (Ty == 0) 1543193326Sed Ty = getTypes().ConvertTypeForMem(ASTTy); 1544198092Srdivacky 1545226633Sdim llvm::PointerType *PTy = 1546221345Sdim llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 1547205408Srdivacky 1548226633Sdim StringRef MangledName = getMangledName(D); 1549205408Srdivacky return GetOrCreateLLVMGlobal(MangledName, PTy, D); 1550193326Sed} 1551193326Sed 1552193326Sed/// CreateRuntimeVariable - Create a new runtime global variable with the 1553193326Sed/// specified type and name. 1554193326Sedllvm::Constant * 1555226633SdimCodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 1556226633Sdim StringRef Name) { 1557221345Sdim return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0, 1558218893Sdim true); 1559193326Sed} 1560193326Sed 1561193326Sedvoid CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 1562193326Sed assert(!D->getInit() && "Cannot emit definite definitions here!"); 1563193326Sed 1564193326Sed if (MayDeferGeneration(D)) { 1565193326Sed // If we have not seen a reference to this variable yet, place it 1566193326Sed // into the deferred declarations table to be emitted if needed 1567193326Sed // later. 1568226633Sdim StringRef MangledName = getMangledName(D); 1569205408Srdivacky if (!GetGlobalValue(MangledName)) { 1570198092Srdivacky DeferredDecls[MangledName] = D; 1571193326Sed return; 1572193326Sed } 1573193326Sed } 1574193326Sed 1575193326Sed // The tentative definition is the only definition. 1576193326Sed EmitGlobalVarDefinition(D); 1577193326Sed} 1578193326Sed 1579226633SdimCharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 1580218893Sdim return Context.toCharUnitsFromBits( 1581243830Sdim TheDataLayout.getTypeStoreSizeInBits(Ty)); 1582203955Srdivacky} 1583203955Srdivacky 1584234353Sdimllvm::Constant * 1585234353SdimCodeGenModule::MaybeEmitGlobalStdInitializerListInitializer(const VarDecl *D, 1586234353Sdim const Expr *rawInit) { 1587234353Sdim ArrayRef<ExprWithCleanups::CleanupObject> cleanups; 1588234353Sdim if (const ExprWithCleanups *withCleanups = 1589234353Sdim dyn_cast<ExprWithCleanups>(rawInit)) { 1590234353Sdim cleanups = withCleanups->getObjects(); 1591234353Sdim rawInit = withCleanups->getSubExpr(); 1592234353Sdim } 1593234353Sdim 1594234353Sdim const InitListExpr *init = dyn_cast<InitListExpr>(rawInit); 1595234353Sdim if (!init || !init->initializesStdInitializerList() || 1596234353Sdim init->getNumInits() == 0) 1597234353Sdim return 0; 1598234353Sdim 1599234353Sdim ASTContext &ctx = getContext(); 1600234353Sdim unsigned numInits = init->getNumInits(); 1601234353Sdim // FIXME: This check is here because we would otherwise silently miscompile 1602234353Sdim // nested global std::initializer_lists. Better would be to have a real 1603234353Sdim // implementation. 1604234353Sdim for (unsigned i = 0; i < numInits; ++i) { 1605234353Sdim const InitListExpr *inner = dyn_cast<InitListExpr>(init->getInit(i)); 1606234353Sdim if (inner && inner->initializesStdInitializerList()) { 1607234353Sdim ErrorUnsupported(inner, "nested global std::initializer_list"); 1608234353Sdim return 0; 1609234353Sdim } 1610234353Sdim } 1611234353Sdim 1612234353Sdim // Synthesize a fake VarDecl for the array and initialize that. 1613234353Sdim QualType elementType = init->getInit(0)->getType(); 1614234353Sdim llvm::APInt numElements(ctx.getTypeSize(ctx.getSizeType()), numInits); 1615234353Sdim QualType arrayType = ctx.getConstantArrayType(elementType, numElements, 1616234353Sdim ArrayType::Normal, 0); 1617234353Sdim 1618234353Sdim IdentifierInfo *name = &ctx.Idents.get(D->getNameAsString() + "__initlist"); 1619234353Sdim TypeSourceInfo *sourceInfo = ctx.getTrivialTypeSourceInfo( 1620234353Sdim arrayType, D->getLocation()); 1621234353Sdim VarDecl *backingArray = VarDecl::Create(ctx, const_cast<DeclContext*>( 1622234353Sdim D->getDeclContext()), 1623234353Sdim D->getLocStart(), D->getLocation(), 1624234353Sdim name, arrayType, sourceInfo, 1625249423Sdim SC_Static); 1626251662Sdim backingArray->setTSCSpec(D->getTSCSpec()); 1627234353Sdim 1628234353Sdim // Now clone the InitListExpr to initialize the array instead. 1629234353Sdim // Incredible hack: we want to use the existing InitListExpr here, so we need 1630234353Sdim // to tell it that it no longer initializes a std::initializer_list. 1631243830Sdim ArrayRef<Expr*> Inits(const_cast<InitListExpr*>(init)->getInits(), 1632243830Sdim init->getNumInits()); 1633243830Sdim Expr *arrayInit = new (ctx) InitListExpr(ctx, init->getLBraceLoc(), Inits, 1634243830Sdim init->getRBraceLoc()); 1635234353Sdim arrayInit->setType(arrayType); 1636234353Sdim 1637234353Sdim if (!cleanups.empty()) 1638234353Sdim arrayInit = ExprWithCleanups::Create(ctx, arrayInit, cleanups); 1639234353Sdim 1640234353Sdim backingArray->setInit(arrayInit); 1641234353Sdim 1642234353Sdim // Emit the definition of the array. 1643234353Sdim EmitGlobalVarDefinition(backingArray); 1644234353Sdim 1645234353Sdim // Inspect the initializer list to validate it and determine its type. 1646234353Sdim // FIXME: doing this every time is probably inefficient; caching would be nice 1647234353Sdim RecordDecl *record = init->getType()->castAs<RecordType>()->getDecl(); 1648234353Sdim RecordDecl::field_iterator field = record->field_begin(); 1649234353Sdim if (field == record->field_end()) { 1650234353Sdim ErrorUnsupported(D, "weird std::initializer_list"); 1651234353Sdim return 0; 1652234353Sdim } 1653234353Sdim QualType elementPtr = ctx.getPointerType(elementType.withConst()); 1654234353Sdim // Start pointer. 1655234353Sdim if (!ctx.hasSameType(field->getType(), elementPtr)) { 1656234353Sdim ErrorUnsupported(D, "weird std::initializer_list"); 1657234353Sdim return 0; 1658234353Sdim } 1659234353Sdim ++field; 1660234353Sdim if (field == record->field_end()) { 1661234353Sdim ErrorUnsupported(D, "weird std::initializer_list"); 1662234353Sdim return 0; 1663234353Sdim } 1664234353Sdim bool isStartEnd = false; 1665234353Sdim if (ctx.hasSameType(field->getType(), elementPtr)) { 1666234353Sdim // End pointer. 1667234353Sdim isStartEnd = true; 1668234353Sdim } else if(!ctx.hasSameType(field->getType(), ctx.getSizeType())) { 1669234353Sdim ErrorUnsupported(D, "weird std::initializer_list"); 1670234353Sdim return 0; 1671234353Sdim } 1672234353Sdim 1673234353Sdim // Now build an APValue representing the std::initializer_list. 1674234353Sdim APValue initListValue(APValue::UninitStruct(), 0, 2); 1675234353Sdim APValue &startField = initListValue.getStructField(0); 1676234353Sdim APValue::LValuePathEntry startOffsetPathEntry; 1677234353Sdim startOffsetPathEntry.ArrayIndex = 0; 1678234353Sdim startField = APValue(APValue::LValueBase(backingArray), 1679234353Sdim CharUnits::fromQuantity(0), 1680234353Sdim llvm::makeArrayRef(startOffsetPathEntry), 1681234353Sdim /*IsOnePastTheEnd=*/false, 0); 1682234353Sdim 1683234353Sdim if (isStartEnd) { 1684234353Sdim APValue &endField = initListValue.getStructField(1); 1685234353Sdim APValue::LValuePathEntry endOffsetPathEntry; 1686234353Sdim endOffsetPathEntry.ArrayIndex = numInits; 1687234353Sdim endField = APValue(APValue::LValueBase(backingArray), 1688234353Sdim ctx.getTypeSizeInChars(elementType) * numInits, 1689234353Sdim llvm::makeArrayRef(endOffsetPathEntry), 1690234353Sdim /*IsOnePastTheEnd=*/true, 0); 1691234353Sdim } else { 1692234353Sdim APValue &sizeField = initListValue.getStructField(1); 1693234353Sdim sizeField = APValue(llvm::APSInt(numElements)); 1694234353Sdim } 1695234353Sdim 1696234353Sdim // Emit the constant for the initializer_list. 1697234353Sdim llvm::Constant *llvmInit = 1698234353Sdim EmitConstantValueForMemory(initListValue, D->getType()); 1699234353Sdim assert(llvmInit && "failed to initialize as constant"); 1700234353Sdim return llvmInit; 1701234353Sdim} 1702234353Sdim 1703239462Sdimunsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D, 1704239462Sdim unsigned AddrSpace) { 1705239462Sdim if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) { 1706239462Sdim if (D->hasAttr<CUDAConstantAttr>()) 1707239462Sdim AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant); 1708239462Sdim else if (D->hasAttr<CUDASharedAttr>()) 1709239462Sdim AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared); 1710239462Sdim else 1711239462Sdim AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device); 1712239462Sdim } 1713239462Sdim 1714239462Sdim return AddrSpace; 1715239462Sdim} 1716239462Sdim 1717251662Sdimtemplate<typename SomeDecl> 1718251662Sdimvoid CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 1719251662Sdim llvm::GlobalValue *GV) { 1720251662Sdim if (!getLangOpts().CPlusPlus) 1721251662Sdim return; 1722251662Sdim 1723251662Sdim // Must have 'used' attribute, or else inline assembly can't rely on 1724251662Sdim // the name existing. 1725251662Sdim if (!D->template hasAttr<UsedAttr>()) 1726251662Sdim return; 1727251662Sdim 1728251662Sdim // Must have internal linkage and an ordinary name. 1729251662Sdim if (!D->getIdentifier() || D->getLinkage() != InternalLinkage) 1730251662Sdim return; 1731251662Sdim 1732251662Sdim // Must be in an extern "C" context. Entities declared directly within 1733251662Sdim // a record are not extern "C" even if the record is in such a context. 1734251662Sdim const SomeDecl *First = D->getFirstDeclaration(); 1735251662Sdim if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 1736251662Sdim return; 1737251662Sdim 1738251662Sdim // OK, this is an internal linkage entity inside an extern "C" linkage 1739251662Sdim // specification. Make a note of that so we can give it the "expected" 1740251662Sdim // mangled name if nothing else is using that name. 1741251662Sdim std::pair<StaticExternCMap::iterator, bool> R = 1742251662Sdim StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 1743251662Sdim 1744251662Sdim // If we have multiple internal linkage entities with the same name 1745251662Sdim // in extern "C" regions, none of them gets that name. 1746251662Sdim if (!R.second) 1747251662Sdim R.first->second = 0; 1748251662Sdim} 1749251662Sdim 1750193326Sedvoid CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 1751193326Sed llvm::Constant *Init = 0; 1752193326Sed QualType ASTTy = D->getType(); 1753234353Sdim CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1754234353Sdim bool NeedsGlobalCtor = false; 1755234353Sdim bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor(); 1756198092Srdivacky 1757234353Sdim const VarDecl *InitDecl; 1758234353Sdim const Expr *InitExpr = D->getAnyInitializer(InitDecl); 1759234353Sdim 1760203955Srdivacky if (!InitExpr) { 1761193326Sed // This is a tentative definition; tentative definitions are 1762193326Sed // implicitly initialized with { 0 }. 1763193326Sed // 1764193326Sed // Note that tentative definitions are only emitted at the end of 1765193326Sed // a translation unit, so they should never have incomplete 1766193326Sed // type. In addition, EmitTentativeDefinition makes sure that we 1767193326Sed // never attempt to emit a tentative definition if a real one 1768193326Sed // exists. A use may still exists, however, so we still may need 1769193326Sed // to do a RAUW. 1770193326Sed assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 1771198092Srdivacky Init = EmitNullConstant(D->getType()); 1772193326Sed } else { 1773234353Sdim // If this is a std::initializer_list, emit the special initializer. 1774234353Sdim Init = MaybeEmitGlobalStdInitializerListInitializer(D, InitExpr); 1775234353Sdim // An empty init list will perform zero-initialization, which happens 1776234353Sdim // to be exactly what we want. 1777234353Sdim // FIXME: It does so in a global constructor, which is *not* what we 1778234353Sdim // want. 1779234353Sdim 1780239462Sdim if (!Init) { 1781239462Sdim initializedGlobalDecl = GlobalDecl(D); 1782234353Sdim Init = EmitConstantInit(*InitDecl); 1783239462Sdim } 1784193326Sed if (!Init) { 1785203955Srdivacky QualType T = InitExpr->getType(); 1786208600Srdivacky if (D->getType()->isReferenceType()) 1787208600Srdivacky T = D->getType(); 1788234353Sdim 1789234353Sdim if (getLangOpts().CPlusPlus) { 1790198092Srdivacky Init = EmitNullConstant(T); 1791234353Sdim NeedsGlobalCtor = true; 1792198092Srdivacky } else { 1793198092Srdivacky ErrorUnsupported(D, "static initializer"); 1794198092Srdivacky Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 1795198092Srdivacky } 1796212904Sdim } else { 1797212904Sdim // We don't need an initializer, so remove the entry for the delayed 1798234353Sdim // initializer position (just in case this entry was delayed) if we 1799234353Sdim // also don't need to register a destructor. 1800234353Sdim if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 1801212904Sdim DelayedCXXInitPosition.erase(D); 1802193326Sed } 1803193326Sed } 1804193326Sed 1805226633Sdim llvm::Type* InitType = Init->getType(); 1806193326Sed llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 1807198092Srdivacky 1808193326Sed // Strip off a bitcast if we got one back. 1809193326Sed if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1810198092Srdivacky assert(CE->getOpcode() == llvm::Instruction::BitCast || 1811198092Srdivacky // all zero index gep. 1812198092Srdivacky CE->getOpcode() == llvm::Instruction::GetElementPtr); 1813193326Sed Entry = CE->getOperand(0); 1814193326Sed } 1815198092Srdivacky 1816193326Sed // Entry is now either a Function or GlobalVariable. 1817193326Sed llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry); 1818198092Srdivacky 1819193326Sed // We have a definition after a declaration with the wrong type. 1820193326Sed // We must make a new GlobalVariable* and update everything that used OldGV 1821193326Sed // (a declaration or tentative definition) with the new GlobalVariable* 1822193326Sed // (which will be a definition). 1823193326Sed // 1824193326Sed // This happens if there is a prototype for a global (e.g. 1825193326Sed // "extern int x[];") and then a definition of a different type (e.g. 1826193326Sed // "int x[10];"). This also happens when an initializer has a different type 1827193326Sed // from the type of the global (this happens with unions). 1828193326Sed if (GV == 0 || 1829193326Sed GV->getType()->getElementType() != InitType || 1830221345Sdim GV->getType()->getAddressSpace() != 1831239462Sdim GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) { 1832198092Srdivacky 1833205408Srdivacky // Move the old entry aside so that we'll create a new one. 1834226633Sdim Entry->setName(StringRef()); 1835193326Sed 1836193326Sed // Make a new global with the correct type, this is now guaranteed to work. 1837193326Sed GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 1838193326Sed 1839193326Sed // Replace all uses of the old global with the new global 1840198092Srdivacky llvm::Constant *NewPtrForOldDecl = 1841193326Sed llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 1842193326Sed Entry->replaceAllUsesWith(NewPtrForOldDecl); 1843193326Sed 1844193326Sed // Erase the old global, since it is no longer used. 1845193326Sed cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 1846193326Sed } 1847193326Sed 1848251662Sdim MaybeHandleStaticInExternC(D, GV); 1849251662Sdim 1850226633Sdim if (D->hasAttr<AnnotateAttr>()) 1851226633Sdim AddGlobalAnnotations(D, GV); 1852193326Sed 1853193326Sed GV->setInitializer(Init); 1854198092Srdivacky 1855198092Srdivacky // If it is safe to mark the global 'constant', do so now. 1856234353Sdim GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 1857234353Sdim isTypeConstant(D->getType(), true)); 1858198092Srdivacky 1859203955Srdivacky GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 1860234353Sdim 1861218893Sdim // Set the llvm linkage type as appropriate. 1862218893Sdim llvm::GlobalValue::LinkageTypes Linkage = 1863218893Sdim GetLLVMLinkageVarDefinition(D, GV); 1864218893Sdim GV->setLinkage(Linkage); 1865218893Sdim if (Linkage == llvm::GlobalVariable::CommonLinkage) 1866218893Sdim // common vars aren't constant even if declared const. 1867218893Sdim GV->setConstant(false); 1868193326Sed 1869218893Sdim SetCommonAttributes(D, GV); 1870218893Sdim 1871218893Sdim // Emit the initializer function if necessary. 1872234353Sdim if (NeedsGlobalCtor || NeedsGlobalDtor) 1873234353Sdim EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 1874218893Sdim 1875243830Sdim // If we are compiling with ASan, add metadata indicating dynamically 1876243830Sdim // initialized globals. 1877249423Sdim if (SanOpts.Address && NeedsGlobalCtor) { 1878243830Sdim llvm::Module &M = getModule(); 1879243830Sdim 1880243830Sdim llvm::NamedMDNode *DynamicInitializers = 1881243830Sdim M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals"); 1882243830Sdim llvm::Value *GlobalToAdd[] = { GV }; 1883243830Sdim llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd); 1884243830Sdim DynamicInitializers->addOperand(ThisGlobal); 1885243830Sdim } 1886243830Sdim 1887218893Sdim // Emit global variable debug information. 1888226633Sdim if (CGDebugInfo *DI = getModuleDebugInfo()) 1889243830Sdim if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 1890239462Sdim DI->EmitGlobalVariable(GV, D); 1891218893Sdim} 1892218893Sdim 1893218893Sdimllvm::GlobalValue::LinkageTypes 1894218893SdimCodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D, 1895218893Sdim llvm::GlobalVariable *GV) { 1896212904Sdim GVALinkage Linkage = getContext().GetGVALinkageForVariable(D); 1897198112Srdivacky if (Linkage == GVA_Internal) 1898218893Sdim return llvm::Function::InternalLinkage; 1899195341Sed else if (D->hasAttr<DLLImportAttr>()) 1900218893Sdim return llvm::Function::DLLImportLinkage; 1901195341Sed else if (D->hasAttr<DLLExportAttr>()) 1902218893Sdim return llvm::Function::DLLExportLinkage; 1903198092Srdivacky else if (D->hasAttr<WeakAttr>()) { 1904198092Srdivacky if (GV->isConstant()) 1905218893Sdim return llvm::GlobalVariable::WeakODRLinkage; 1906198092Srdivacky else 1907218893Sdim return llvm::GlobalVariable::WeakAnyLinkage; 1908205219Srdivacky } else if (Linkage == GVA_TemplateInstantiation || 1909205219Srdivacky Linkage == GVA_ExplicitTemplateInstantiation) 1910221345Sdim return llvm::GlobalVariable::WeakODRLinkage; 1911234353Sdim else if (!getLangOpts().CPlusPlus && 1912218893Sdim ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) || 1913218893Sdim D->getAttr<CommonAttr>()) && 1914198092Srdivacky !D->hasExternalStorage() && !D->getInit() && 1915251662Sdim !D->getAttr<SectionAttr>() && !D->getTLSKind() && 1916224145Sdim !D->getAttr<WeakImportAttr>()) { 1917212904Sdim // Thread local vars aren't considered common linkage. 1918218893Sdim return llvm::GlobalVariable::CommonLinkage; 1919251662Sdim } else if (D->getTLSKind() == VarDecl::TLS_Dynamic && 1920251662Sdim getTarget().getTriple().isMacOSX()) 1921251662Sdim // On Darwin, the backing variable for a C++11 thread_local variable always 1922251662Sdim // has internal linkage; all accesses should just be calls to the 1923251662Sdim // Itanium-specified entry point, which has the normal linkage of the 1924251662Sdim // variable. 1925251662Sdim return llvm::GlobalValue::InternalLinkage; 1926218893Sdim return llvm::GlobalVariable::ExternalLinkage; 1927193326Sed} 1928193326Sed 1929249423Sdim/// Replace the uses of a function that was declared with a non-proto type. 1930249423Sdim/// We want to silently drop extra arguments from call sites 1931249423Sdimstatic void replaceUsesOfNonProtoConstant(llvm::Constant *old, 1932249423Sdim llvm::Function *newFn) { 1933249423Sdim // Fast path. 1934249423Sdim if (old->use_empty()) return; 1935198092Srdivacky 1936249423Sdim llvm::Type *newRetTy = newFn->getReturnType(); 1937249423Sdim SmallVector<llvm::Value*, 4> newArgs; 1938193326Sed 1939249423Sdim for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 1940249423Sdim ui != ue; ) { 1941249423Sdim llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 1942249423Sdim llvm::User *user = *use; 1943198092Srdivacky 1944249423Sdim // Recognize and replace uses of bitcasts. Most calls to 1945249423Sdim // unprototyped functions will use bitcasts. 1946249423Sdim if (llvm::ConstantExpr *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 1947249423Sdim if (bitcast->getOpcode() == llvm::Instruction::BitCast) 1948249423Sdim replaceUsesOfNonProtoConstant(bitcast, newFn); 1949193326Sed continue; 1950249423Sdim } 1951193326Sed 1952249423Sdim // Recognize calls to the function. 1953249423Sdim llvm::CallSite callSite(user); 1954249423Sdim if (!callSite) continue; 1955249423Sdim if (!callSite.isCallee(use)) continue; 1956226633Sdim 1957249423Sdim // If the return types don't match exactly, then we can't 1958249423Sdim // transform this call unless it's dead. 1959249423Sdim if (callSite->getType() != newRetTy && !callSite->use_empty()) 1960249423Sdim continue; 1961226633Sdim 1962249423Sdim // Get the call site's attribute list. 1963249423Sdim SmallVector<llvm::AttributeSet, 8> newAttrs; 1964249423Sdim llvm::AttributeSet oldAttrs = callSite.getAttributes(); 1965226633Sdim 1966249423Sdim // Collect any return attributes from the call. 1967249423Sdim if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex)) 1968249423Sdim newAttrs.push_back( 1969249423Sdim llvm::AttributeSet::get(newFn->getContext(), 1970249423Sdim oldAttrs.getRetAttributes())); 1971249423Sdim 1972249423Sdim // If the function was passed too few arguments, don't transform. 1973249423Sdim unsigned newNumArgs = newFn->arg_size(); 1974249423Sdim if (callSite.arg_size() < newNumArgs) continue; 1975249423Sdim 1976249423Sdim // If extra arguments were passed, we silently drop them. 1977249423Sdim // If any of the types mismatch, we don't transform. 1978249423Sdim unsigned argNo = 0; 1979249423Sdim bool dontTransform = false; 1980249423Sdim for (llvm::Function::arg_iterator ai = newFn->arg_begin(), 1981249423Sdim ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) { 1982249423Sdim if (callSite.getArgument(argNo)->getType() != ai->getType()) { 1983249423Sdim dontTransform = true; 1984193326Sed break; 1985193326Sed } 1986226633Sdim 1987226633Sdim // Add any parameter attributes. 1988249423Sdim if (oldAttrs.hasAttributes(argNo + 1)) 1989249423Sdim newAttrs. 1990249423Sdim push_back(llvm:: 1991249423Sdim AttributeSet::get(newFn->getContext(), 1992249423Sdim oldAttrs.getParamAttributes(argNo + 1))); 1993193326Sed } 1994249423Sdim if (dontTransform) 1995193326Sed continue; 1996198092Srdivacky 1997249423Sdim if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) 1998249423Sdim newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(), 1999249423Sdim oldAttrs.getFnAttributes())); 2000226633Sdim 2001193326Sed // Okay, we can transform this. Create the new call instruction and copy 2002193326Sed // over the required information. 2003249423Sdim newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo); 2004193326Sed 2005249423Sdim llvm::CallSite newCall; 2006249423Sdim if (callSite.isCall()) { 2007249423Sdim newCall = llvm::CallInst::Create(newFn, newArgs, "", 2008249423Sdim callSite.getInstruction()); 2009249423Sdim } else { 2010249423Sdim llvm::InvokeInst *oldInvoke = 2011249423Sdim cast<llvm::InvokeInst>(callSite.getInstruction()); 2012249423Sdim newCall = llvm::InvokeInst::Create(newFn, 2013249423Sdim oldInvoke->getNormalDest(), 2014249423Sdim oldInvoke->getUnwindDest(), 2015249423Sdim newArgs, "", 2016249423Sdim callSite.getInstruction()); 2017249423Sdim } 2018249423Sdim newArgs.clear(); // for the next iteration 2019249423Sdim 2020249423Sdim if (!newCall->getType()->isVoidTy()) 2021249423Sdim newCall->takeName(callSite.getInstruction()); 2022249423Sdim newCall.setAttributes( 2023249423Sdim llvm::AttributeSet::get(newFn->getContext(), newAttrs)); 2024249423Sdim newCall.setCallingConv(callSite.getCallingConv()); 2025249423Sdim 2026193326Sed // Finally, remove the old call, replacing any uses with the new one. 2027249423Sdim if (!callSite->use_empty()) 2028249423Sdim callSite->replaceAllUsesWith(newCall.getInstruction()); 2029198092Srdivacky 2030206084Srdivacky // Copy debug location attached to CI. 2031249423Sdim if (!callSite->getDebugLoc().isUnknown()) 2032249423Sdim newCall->setDebugLoc(callSite->getDebugLoc()); 2033249423Sdim callSite->eraseFromParent(); 2034193326Sed } 2035193326Sed} 2036193326Sed 2037249423Sdim/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 2038249423Sdim/// implement a function with no prototype, e.g. "int foo() {}". If there are 2039249423Sdim/// existing call uses of the old function in the module, this adjusts them to 2040249423Sdim/// call the new function directly. 2041249423Sdim/// 2042249423Sdim/// This is not just a cleanup: the always_inline pass requires direct calls to 2043249423Sdim/// functions to be able to inline them. If there is a bitcast in the way, it 2044249423Sdim/// won't inline them. Instcombine normally deletes these calls, but it isn't 2045249423Sdim/// run at -O0. 2046249423Sdimstatic void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 2047249423Sdim llvm::Function *NewFn) { 2048249423Sdim // If we're redefining a global as a function, don't transform it. 2049249423Sdim if (!isa<llvm::Function>(Old)) return; 2050249423Sdim 2051249423Sdim replaceUsesOfNonProtoConstant(Old, NewFn); 2052249423Sdim} 2053249423Sdim 2054234353Sdimvoid CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 2055234353Sdim TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 2056234353Sdim // If we have a definition, this might be a deferred decl. If the 2057234353Sdim // instantiation is explicit, make sure we emit it at the end. 2058234353Sdim if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 2059234353Sdim GetAddrOfGlobalVar(VD); 2060249423Sdim 2061249423Sdim EmitTopLevelDecl(VD); 2062234353Sdim} 2063193326Sed 2064193326Sedvoid CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) { 2065193326Sed const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl()); 2066221345Sdim 2067221345Sdim // Compute the function info and LLVM type. 2068234353Sdim const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 2069234353Sdim llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 2070221345Sdim 2071193326Sed // Get or create the prototype for the function. 2072193326Sed llvm::Constant *Entry = GetAddrOfFunction(GD, Ty); 2073198092Srdivacky 2074193326Sed // Strip off a bitcast if we got one back. 2075193326Sed if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 2076193326Sed assert(CE->getOpcode() == llvm::Instruction::BitCast); 2077193326Sed Entry = CE->getOperand(0); 2078193326Sed } 2079198092Srdivacky 2080198092Srdivacky 2081193326Sed if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) { 2082193326Sed llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry); 2083198092Srdivacky 2084193326Sed // If the types mismatch then we have to rewrite the definition. 2085193326Sed assert(OldFn->isDeclaration() && 2086193326Sed "Shouldn't replace non-declaration"); 2087193326Sed 2088193326Sed // F is the Function* for the one with the wrong type, we must make a new 2089193326Sed // Function* and update everything that used F (a declaration) with the new 2090193326Sed // Function* (which will be a definition). 2091193326Sed // 2092193326Sed // This happens if there is a prototype for a function 2093193326Sed // (e.g. "int f()") and then a definition of a different type 2094205408Srdivacky // (e.g. "int f(int x)"). Move the old function aside so that it 2095205408Srdivacky // doesn't interfere with GetAddrOfFunction. 2096226633Sdim OldFn->setName(StringRef()); 2097193326Sed llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty)); 2098198092Srdivacky 2099249423Sdim // This might be an implementation of a function without a 2100249423Sdim // prototype, in which case, try to do special replacement of 2101249423Sdim // calls which match the new prototype. The really key thing here 2102249423Sdim // is that we also potentially drop arguments from the call site 2103249423Sdim // so as to make a direct call, which makes the inliner happier 2104249423Sdim // and suppresses a number of optimizer warnings (!) about 2105249423Sdim // dropping arguments. 2106249423Sdim if (!OldFn->use_empty()) { 2107193326Sed ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn); 2108193326Sed OldFn->removeDeadConstantUsers(); 2109193326Sed } 2110198092Srdivacky 2111193326Sed // Replace uses of F with the Function we will endow with a body. 2112193326Sed if (!Entry->use_empty()) { 2113198092Srdivacky llvm::Constant *NewPtrForOldDecl = 2114193326Sed llvm::ConstantExpr::getBitCast(NewFn, Entry->getType()); 2115193326Sed Entry->replaceAllUsesWith(NewPtrForOldDecl); 2116193326Sed } 2117198092Srdivacky 2118193326Sed // Ok, delete the old function now, which is dead. 2119193326Sed OldFn->eraseFromParent(); 2120198092Srdivacky 2121193326Sed Entry = NewFn; 2122193326Sed } 2123198092Srdivacky 2124218893Sdim // We need to set linkage and visibility on the function before 2125218893Sdim // generating code for it because various parts of IR generation 2126218893Sdim // want to propagate this information down (e.g. to local static 2127218893Sdim // declarations). 2128193326Sed llvm::Function *Fn = cast<llvm::Function>(Entry); 2129208600Srdivacky setFunctionLinkage(D, Fn); 2130193326Sed 2131218893Sdim // FIXME: this is redundant with part of SetFunctionDefinitionAttributes 2132218893Sdim setGlobalVisibility(Fn, D); 2133218893Sdim 2134251662Sdim MaybeHandleStaticInExternC(D, Fn); 2135251662Sdim 2136221345Sdim CodeGenFunction(*this).GenerateCode(D, Fn, FI); 2137193326Sed 2138193326Sed SetFunctionDefinitionAttributes(D, Fn); 2139193326Sed SetLLVMFunctionAttributesForDefinition(D, Fn); 2140198092Srdivacky 2141195341Sed if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 2142193326Sed AddGlobalCtor(Fn, CA->getPriority()); 2143195341Sed if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 2144193326Sed AddGlobalDtor(Fn, DA->getPriority()); 2145226633Sdim if (D->hasAttr<AnnotateAttr>()) 2146226633Sdim AddGlobalAnnotations(D, Fn); 2147193326Sed} 2148193326Sed 2149205408Srdivackyvoid CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 2150205408Srdivacky const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 2151195341Sed const AliasAttr *AA = D->getAttr<AliasAttr>(); 2152193326Sed assert(AA && "Not an alias?"); 2153193326Sed 2154226633Sdim StringRef MangledName = getMangledName(GD); 2155205408Srdivacky 2156205408Srdivacky // If there is a definition in the module, then it wins over the alias. 2157205408Srdivacky // This is dubious, but allow it to be safe. Just ignore the alias. 2158205408Srdivacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2159205408Srdivacky if (Entry && !Entry->isDeclaration()) 2160205408Srdivacky return; 2161205408Srdivacky 2162226633Sdim llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 2163198092Srdivacky 2164193326Sed // Create a reference to the named value. This ensures that it is emitted 2165193326Sed // if a deferred decl. 2166193326Sed llvm::Constant *Aliasee; 2167193326Sed if (isa<llvm::FunctionType>(DeclTy)) 2168243830Sdim Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 2169218893Sdim /*ForVTable=*/false); 2170193326Sed else 2171205408Srdivacky Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 2172193326Sed llvm::PointerType::getUnqual(DeclTy), 0); 2173193326Sed 2174193326Sed // Create the new alias itself, but don't set a name yet. 2175198092Srdivacky llvm::GlobalValue *GA = 2176193326Sed new llvm::GlobalAlias(Aliasee->getType(), 2177193326Sed llvm::Function::ExternalLinkage, 2178193326Sed "", Aliasee, &getModule()); 2179198092Srdivacky 2180205408Srdivacky if (Entry) { 2181205408Srdivacky assert(Entry->isDeclaration()); 2182198092Srdivacky 2183193326Sed // If there is a declaration in the module, then we had an extern followed 2184193326Sed // by the alias, as in: 2185193326Sed // extern int test6(); 2186193326Sed // ... 2187193326Sed // int test6() __attribute__((alias("test7"))); 2188193326Sed // 2189193326Sed // Remove it and replace uses of it with the alias. 2190205408Srdivacky GA->takeName(Entry); 2191198092Srdivacky 2192193326Sed Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 2193193326Sed Entry->getType())); 2194193326Sed Entry->eraseFromParent(); 2195205408Srdivacky } else { 2196210299Sed GA->setName(MangledName); 2197193326Sed } 2198198092Srdivacky 2199193326Sed // Set attributes which are particular to an alias; this is a 2200193326Sed // specialization of the attributes which may be set on a global 2201193326Sed // variable/function. 2202195341Sed if (D->hasAttr<DLLExportAttr>()) { 2203193326Sed if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2204193326Sed // The dllexport attribute is ignored for undefined symbols. 2205210299Sed if (FD->hasBody()) 2206193326Sed GA->setLinkage(llvm::Function::DLLExportLinkage); 2207193326Sed } else { 2208193326Sed GA->setLinkage(llvm::Function::DLLExportLinkage); 2209193326Sed } 2210198092Srdivacky } else if (D->hasAttr<WeakAttr>() || 2211204643Srdivacky D->hasAttr<WeakRefAttr>() || 2212221345Sdim D->isWeakImported()) { 2213193326Sed GA->setLinkage(llvm::Function::WeakAnyLinkage); 2214193326Sed } 2215193326Sed 2216193326Sed SetCommonAttributes(D, GA); 2217193326Sed} 2218193326Sed 2219224145Sdimllvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 2220226633Sdim ArrayRef<llvm::Type*> Tys) { 2221224145Sdim return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 2222224145Sdim Tys); 2223193326Sed} 2224193326Sed 2225198092Srdivackystatic llvm::StringMapEntry<llvm::Constant*> & 2226198092SrdivackyGetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map, 2227198092Srdivacky const StringLiteral *Literal, 2228198092Srdivacky bool TargetIsLSB, 2229198092Srdivacky bool &IsUTF16, 2230198092Srdivacky unsigned &StringLength) { 2231226633Sdim StringRef String = Literal->getString(); 2232212904Sdim unsigned NumBytes = String.size(); 2233198092Srdivacky 2234198092Srdivacky // Check for simple case. 2235198092Srdivacky if (!Literal->containsNonAsciiOrNull()) { 2236198092Srdivacky StringLength = NumBytes; 2237212904Sdim return Map.GetOrCreateValue(String); 2238193326Sed } 2239198092Srdivacky 2240234353Sdim // Otherwise, convert the UTF8 literals into a string of shorts. 2241234353Sdim IsUTF16 = true; 2242234353Sdim 2243234353Sdim SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 2244243830Sdim const UTF8 *FromPtr = (const UTF8 *)String.data(); 2245198092Srdivacky UTF16 *ToPtr = &ToBuf[0]; 2246198092Srdivacky 2247218893Sdim (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 2248218893Sdim &ToPtr, ToPtr + NumBytes, 2249218893Sdim strictConversion); 2250198092Srdivacky 2251198092Srdivacky // ConvertUTF8toUTF16 returns the length in ToPtr. 2252198092Srdivacky StringLength = ToPtr - &ToBuf[0]; 2253198092Srdivacky 2254234353Sdim // Add an explicit null. 2255234353Sdim *ToPtr = 0; 2256234353Sdim return Map. 2257234353Sdim GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()), 2258234353Sdim (StringLength + 1) * 2)); 2259193326Sed} 2260193326Sed 2261223017Sdimstatic llvm::StringMapEntry<llvm::Constant*> & 2262223017SdimGetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map, 2263234353Sdim const StringLiteral *Literal, 2264234353Sdim unsigned &StringLength) { 2265234353Sdim StringRef String = Literal->getString(); 2266234353Sdim StringLength = String.size(); 2267234353Sdim return Map.GetOrCreateValue(String); 2268223017Sdim} 2269223017Sdim 2270198092Srdivackyllvm::Constant * 2271198092SrdivackyCodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 2272193326Sed unsigned StringLength = 0; 2273193326Sed bool isUTF16 = false; 2274198092Srdivacky llvm::StringMapEntry<llvm::Constant*> &Entry = 2275198092Srdivacky GetConstantCFStringEntry(CFConstantStringMap, Literal, 2276243830Sdim getDataLayout().isLittleEndian(), 2277198092Srdivacky isUTF16, StringLength); 2278198092Srdivacky 2279193326Sed if (llvm::Constant *C = Entry.getValue()) 2280193326Sed return C; 2281198092Srdivacky 2282234353Sdim llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 2283193326Sed llvm::Constant *Zeros[] = { Zero, Zero }; 2284251662Sdim llvm::Value *V; 2285251662Sdim 2286198092Srdivacky // If we don't already have it, get __CFConstantStringClassReference. 2287193326Sed if (!CFConstantStringClassRef) { 2288226633Sdim llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 2289193326Sed Ty = llvm::ArrayType::get(Ty, 0); 2290198092Srdivacky llvm::Constant *GV = CreateRuntimeVariable(Ty, 2291198092Srdivacky "__CFConstantStringClassReference"); 2292193326Sed // Decay array -> ptr 2293251662Sdim V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2294251662Sdim CFConstantStringClassRef = V; 2295193326Sed } 2296251662Sdim else 2297251662Sdim V = CFConstantStringClassRef; 2298198092Srdivacky 2299193326Sed QualType CFTy = getContext().getCFConstantStringType(); 2300193326Sed 2301226633Sdim llvm::StructType *STy = 2302193326Sed cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 2303193326Sed 2304234353Sdim llvm::Constant *Fields[4]; 2305193326Sed 2306193326Sed // Class pointer. 2307251662Sdim Fields[0] = cast<llvm::ConstantExpr>(V); 2308198092Srdivacky 2309193326Sed // Flags. 2310226633Sdim llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 2311198092Srdivacky Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 2312198092Srdivacky llvm::ConstantInt::get(Ty, 0x07C8); 2313198092Srdivacky 2314193326Sed // String pointer. 2315234353Sdim llvm::Constant *C = 0; 2316234353Sdim if (isUTF16) { 2317234353Sdim ArrayRef<uint16_t> Arr = 2318249423Sdim llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>( 2319249423Sdim const_cast<char *>(Entry.getKey().data())), 2320234353Sdim Entry.getKey().size() / 2); 2321234353Sdim C = llvm::ConstantDataArray::get(VMContext, Arr); 2322234353Sdim } else { 2323234353Sdim C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey()); 2324234353Sdim } 2325193326Sed 2326198092Srdivacky llvm::GlobalValue::LinkageTypes Linkage; 2327234353Sdim if (isUTF16) 2328198092Srdivacky // FIXME: why do utf strings get "_" labels instead of "L" labels? 2329198092Srdivacky Linkage = llvm::GlobalValue::InternalLinkage; 2330234353Sdim else 2331221345Sdim // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error 2332221345Sdim // when using private linkage. It is not clear if this is a bug in ld 2333221345Sdim // or a reasonable new restriction. 2334221345Sdim Linkage = llvm::GlobalValue::LinkerPrivateLinkage; 2335198092Srdivacky 2336234353Sdim // Note: -fwritable-strings doesn't make the backing store strings of 2337234353Sdim // CFStrings writable. (See <rdar://problem/10657500>) 2338198092Srdivacky llvm::GlobalVariable *GV = 2339234353Sdim new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 2340234353Sdim Linkage, C, ".str"); 2341218893Sdim GV->setUnnamedAddr(true); 2342251662Sdim // Don't enforce the target's minimum global alignment, since the only use 2343251662Sdim // of the string is via this class initializer. 2344193326Sed if (isUTF16) { 2345203955Srdivacky CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 2346203955Srdivacky GV->setAlignment(Align.getQuantity()); 2347221345Sdim } else { 2348221345Sdim CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 2349221345Sdim GV->setAlignment(Align.getQuantity()); 2350193326Sed } 2351234353Sdim 2352234353Sdim // String. 2353226633Sdim Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2354198092Srdivacky 2355234353Sdim if (isUTF16) 2356234353Sdim // Cast the UTF16 string to the correct type. 2357234353Sdim Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy); 2358234353Sdim 2359193326Sed // String length. 2360193326Sed Ty = getTypes().ConvertType(getContext().LongTy); 2361198092Srdivacky Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 2362198092Srdivacky 2363193326Sed // The struct. 2364193326Sed C = llvm::ConstantStruct::get(STy, Fields); 2365198092Srdivacky GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 2366198092Srdivacky llvm::GlobalVariable::PrivateLinkage, C, 2367198092Srdivacky "_unnamed_cfstring_"); 2368251662Sdim if (const char *Sect = getTarget().getCFStringSection()) 2369193326Sed GV->setSection(Sect); 2370193326Sed Entry.setValue(GV); 2371198092Srdivacky 2372193326Sed return GV; 2373193326Sed} 2374193326Sed 2375226633Sdimstatic RecordDecl * 2376226633SdimCreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK, 2377226633Sdim DeclContext *DC, IdentifierInfo *Id) { 2378226633Sdim SourceLocation Loc; 2379234353Sdim if (Ctx.getLangOpts().CPlusPlus) 2380226633Sdim return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 2381226633Sdim else 2382226633Sdim return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 2383226633Sdim} 2384226633Sdim 2385207619Srdivackyllvm::Constant * 2386218893SdimCodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) { 2387207619Srdivacky unsigned StringLength = 0; 2388207619Srdivacky llvm::StringMapEntry<llvm::Constant*> &Entry = 2389223017Sdim GetConstantStringEntry(CFConstantStringMap, Literal, StringLength); 2390207619Srdivacky 2391207619Srdivacky if (llvm::Constant *C = Entry.getValue()) 2392207619Srdivacky return C; 2393207619Srdivacky 2394234353Sdim llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 2395207619Srdivacky llvm::Constant *Zeros[] = { Zero, Zero }; 2396251662Sdim llvm::Value *V; 2397207619Srdivacky // If we don't already have it, get _NSConstantStringClassReference. 2398218893Sdim if (!ConstantStringClassRef) { 2399234353Sdim std::string StringClass(getLangOpts().ObjCConstantStringClass); 2400226633Sdim llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 2401218893Sdim llvm::Constant *GV; 2402239462Sdim if (LangOpts.ObjCRuntime.isNonFragile()) { 2403223017Sdim std::string str = 2404223017Sdim StringClass.empty() ? "OBJC_CLASS_$_NSConstantString" 2405223017Sdim : "OBJC_CLASS_$_" + StringClass; 2406223017Sdim GV = getObjCRuntime().GetClassGlobal(str); 2407223017Sdim // Make sure the result is of the correct type. 2408226633Sdim llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 2409251662Sdim V = llvm::ConstantExpr::getBitCast(GV, PTy); 2410251662Sdim ConstantStringClassRef = V; 2411223017Sdim } else { 2412223017Sdim std::string str = 2413223017Sdim StringClass.empty() ? "_NSConstantStringClassReference" 2414223017Sdim : "_" + StringClass + "ClassReference"; 2415226633Sdim llvm::Type *PTy = llvm::ArrayType::get(Ty, 0); 2416223017Sdim GV = CreateRuntimeVariable(PTy, str); 2417223017Sdim // Decay array -> ptr 2418251662Sdim V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2419251662Sdim ConstantStringClassRef = V; 2420218893Sdim } 2421207619Srdivacky } 2422251662Sdim else 2423251662Sdim V = ConstantStringClassRef; 2424226633Sdim 2425226633Sdim if (!NSConstantStringType) { 2426226633Sdim // Construct the type for a constant NSString. 2427226633Sdim RecordDecl *D = CreateRecordDecl(Context, TTK_Struct, 2428226633Sdim Context.getTranslationUnitDecl(), 2429226633Sdim &Context.Idents.get("__builtin_NSString")); 2430226633Sdim D->startDefinition(); 2431226633Sdim 2432226633Sdim QualType FieldTypes[3]; 2433226633Sdim 2434226633Sdim // const int *isa; 2435226633Sdim FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst()); 2436226633Sdim // const char *str; 2437226633Sdim FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst()); 2438226633Sdim // unsigned int length; 2439226633Sdim FieldTypes[2] = Context.UnsignedIntTy; 2440226633Sdim 2441226633Sdim // Create fields 2442226633Sdim for (unsigned i = 0; i < 3; ++i) { 2443226633Sdim FieldDecl *Field = FieldDecl::Create(Context, D, 2444226633Sdim SourceLocation(), 2445226633Sdim SourceLocation(), 0, 2446226633Sdim FieldTypes[i], /*TInfo=*/0, 2447226633Sdim /*BitWidth=*/0, 2448226633Sdim /*Mutable=*/false, 2449239462Sdim ICIS_NoInit); 2450226633Sdim Field->setAccess(AS_public); 2451226633Sdim D->addDecl(Field); 2452226633Sdim } 2453226633Sdim 2454226633Sdim D->completeDefinition(); 2455226633Sdim QualType NSTy = Context.getTagDeclType(D); 2456226633Sdim NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy)); 2457226633Sdim } 2458207619Srdivacky 2459234353Sdim llvm::Constant *Fields[3]; 2460207619Srdivacky 2461207619Srdivacky // Class pointer. 2462251662Sdim Fields[0] = cast<llvm::ConstantExpr>(V); 2463207619Srdivacky 2464207619Srdivacky // String pointer. 2465234353Sdim llvm::Constant *C = 2466234353Sdim llvm::ConstantDataArray::getString(VMContext, Entry.getKey()); 2467207619Srdivacky 2468207619Srdivacky llvm::GlobalValue::LinkageTypes Linkage; 2469207619Srdivacky bool isConstant; 2470223017Sdim Linkage = llvm::GlobalValue::PrivateLinkage; 2471234353Sdim isConstant = !LangOpts.WritableStrings; 2472207619Srdivacky 2473207619Srdivacky llvm::GlobalVariable *GV = 2474207619Srdivacky new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 2475207619Srdivacky ".str"); 2476218893Sdim GV->setUnnamedAddr(true); 2477251662Sdim // Don't enforce the target's minimum global alignment, since the only use 2478251662Sdim // of the string is via this class initializer. 2479223017Sdim CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 2480223017Sdim GV->setAlignment(Align.getQuantity()); 2481226633Sdim Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2482207619Srdivacky 2483207619Srdivacky // String length. 2484226633Sdim llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 2485207619Srdivacky Fields[2] = llvm::ConstantInt::get(Ty, StringLength); 2486207619Srdivacky 2487207619Srdivacky // The struct. 2488226633Sdim C = llvm::ConstantStruct::get(NSConstantStringType, Fields); 2489207619Srdivacky GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 2490207619Srdivacky llvm::GlobalVariable::PrivateLinkage, C, 2491207619Srdivacky "_unnamed_nsstring_"); 2492207619Srdivacky // FIXME. Fix section. 2493207619Srdivacky if (const char *Sect = 2494239462Sdim LangOpts.ObjCRuntime.isNonFragile() 2495251662Sdim ? getTarget().getNSStringNonFragileABISection() 2496251662Sdim : getTarget().getNSStringSection()) 2497207619Srdivacky GV->setSection(Sect); 2498207619Srdivacky Entry.setValue(GV); 2499207619Srdivacky 2500207619Srdivacky return GV; 2501207619Srdivacky} 2502207619Srdivacky 2503226633SdimQualType CodeGenModule::getObjCFastEnumerationStateType() { 2504226633Sdim if (ObjCFastEnumerationStateType.isNull()) { 2505226633Sdim RecordDecl *D = CreateRecordDecl(Context, TTK_Struct, 2506226633Sdim Context.getTranslationUnitDecl(), 2507226633Sdim &Context.Idents.get("__objcFastEnumerationState")); 2508226633Sdim D->startDefinition(); 2509226633Sdim 2510226633Sdim QualType FieldTypes[] = { 2511226633Sdim Context.UnsignedLongTy, 2512226633Sdim Context.getPointerType(Context.getObjCIdType()), 2513226633Sdim Context.getPointerType(Context.UnsignedLongTy), 2514226633Sdim Context.getConstantArrayType(Context.UnsignedLongTy, 2515226633Sdim llvm::APInt(32, 5), ArrayType::Normal, 0) 2516226633Sdim }; 2517226633Sdim 2518226633Sdim for (size_t i = 0; i < 4; ++i) { 2519226633Sdim FieldDecl *Field = FieldDecl::Create(Context, 2520226633Sdim D, 2521226633Sdim SourceLocation(), 2522226633Sdim SourceLocation(), 0, 2523226633Sdim FieldTypes[i], /*TInfo=*/0, 2524226633Sdim /*BitWidth=*/0, 2525226633Sdim /*Mutable=*/false, 2526239462Sdim ICIS_NoInit); 2527226633Sdim Field->setAccess(AS_public); 2528226633Sdim D->addDecl(Field); 2529226633Sdim } 2530226633Sdim 2531226633Sdim D->completeDefinition(); 2532226633Sdim ObjCFastEnumerationStateType = Context.getTagDeclType(D); 2533226633Sdim } 2534226633Sdim 2535226633Sdim return ObjCFastEnumerationStateType; 2536226633Sdim} 2537226633Sdim 2538234353Sdimllvm::Constant * 2539234353SdimCodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 2540234353Sdim assert(!E->getType()->isPointerType() && "Strings are always arrays"); 2541234353Sdim 2542234353Sdim // Don't emit it as the address of the string, emit the string data itself 2543234353Sdim // as an inline array. 2544234353Sdim if (E->getCharByteWidth() == 1) { 2545234353Sdim SmallString<64> Str(E->getString()); 2546198092Srdivacky 2547234353Sdim // Resize the string to the right size, which is indicated by its type. 2548234353Sdim const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 2549234353Sdim Str.resize(CAT->getSize().getZExtValue()); 2550234353Sdim return llvm::ConstantDataArray::getString(VMContext, Str, false); 2551226633Sdim } 2552234353Sdim 2553234353Sdim llvm::ArrayType *AType = 2554234353Sdim cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 2555234353Sdim llvm::Type *ElemTy = AType->getElementType(); 2556234353Sdim unsigned NumElements = AType->getNumElements(); 2557198092Srdivacky 2558234353Sdim // Wide strings have either 2-byte or 4-byte elements. 2559234353Sdim if (ElemTy->getPrimitiveSizeInBits() == 16) { 2560234353Sdim SmallVector<uint16_t, 32> Elements; 2561234353Sdim Elements.reserve(NumElements); 2562198092Srdivacky 2563234353Sdim for(unsigned i = 0, e = E->getLength(); i != e; ++i) 2564234353Sdim Elements.push_back(E->getCodeUnit(i)); 2565234353Sdim Elements.resize(NumElements); 2566234353Sdim return llvm::ConstantDataArray::get(VMContext, Elements); 2567234353Sdim } 2568234353Sdim 2569234353Sdim assert(ElemTy->getPrimitiveSizeInBits() == 32); 2570234353Sdim SmallVector<uint32_t, 32> Elements; 2571234353Sdim Elements.reserve(NumElements); 2572234353Sdim 2573234353Sdim for(unsigned i = 0, e = E->getLength(); i != e; ++i) 2574234353Sdim Elements.push_back(E->getCodeUnit(i)); 2575234353Sdim Elements.resize(NumElements); 2576234353Sdim return llvm::ConstantDataArray::get(VMContext, Elements); 2577193326Sed} 2578193326Sed 2579193326Sed/// GetAddrOfConstantStringFromLiteral - Return a pointer to a 2580193326Sed/// constant array for the given string literal. 2581193326Sedllvm::Constant * 2582193326SedCodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 2583251662Sdim CharUnits Align = getContext().getAlignOfGlobalVarInChars(S->getType()); 2584234353Sdim if (S->isAscii() || S->isUTF8()) { 2585234353Sdim SmallString<64> Str(S->getString()); 2586234353Sdim 2587234353Sdim // Resize the string to the right size, which is indicated by its type. 2588234353Sdim const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType()); 2589234353Sdim Str.resize(CAT->getSize().getZExtValue()); 2590234353Sdim return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity()); 2591199482Srdivacky } 2592234353Sdim 2593234353Sdim // FIXME: the following does not memoize wide strings. 2594234353Sdim llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 2595234353Sdim llvm::GlobalVariable *GV = 2596234353Sdim new llvm::GlobalVariable(getModule(),C->getType(), 2597234353Sdim !LangOpts.WritableStrings, 2598234353Sdim llvm::GlobalValue::PrivateLinkage, 2599234353Sdim C,".str"); 2600234353Sdim 2601234353Sdim GV->setAlignment(Align.getQuantity()); 2602234353Sdim GV->setUnnamedAddr(true); 2603234353Sdim return GV; 2604193326Sed} 2605193326Sed 2606193326Sed/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 2607193326Sed/// array for the given ObjCEncodeExpr node. 2608193326Sedllvm::Constant * 2609193326SedCodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 2610193326Sed std::string Str; 2611193326Sed getContext().getObjCEncodingForType(E->getEncodedType(), Str); 2612193326Sed 2613193326Sed return GetAddrOfConstantCString(Str); 2614193326Sed} 2615193326Sed 2616193326Sed 2617193326Sed/// GenerateWritableString -- Creates storage for a string literal. 2618226633Sdimstatic llvm::GlobalVariable *GenerateStringLiteral(StringRef str, 2619193326Sed bool constant, 2620193326Sed CodeGenModule &CGM, 2621226633Sdim const char *GlobalName, 2622226633Sdim unsigned Alignment) { 2623193326Sed // Create Constant for this string literal. Don't add a '\0'. 2624198092Srdivacky llvm::Constant *C = 2625234353Sdim llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false); 2626198092Srdivacky 2627193326Sed // Create a global variable for this string 2628218893Sdim llvm::GlobalVariable *GV = 2629218893Sdim new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant, 2630218893Sdim llvm::GlobalValue::PrivateLinkage, 2631218893Sdim C, GlobalName); 2632226633Sdim GV->setAlignment(Alignment); 2633218893Sdim GV->setUnnamedAddr(true); 2634218893Sdim return GV; 2635193326Sed} 2636193326Sed 2637193326Sed/// GetAddrOfConstantString - Returns a pointer to a character array 2638193326Sed/// containing the literal. This contents are exactly that of the 2639193326Sed/// given string, i.e. it will not be null terminated automatically; 2640193326Sed/// see GetAddrOfConstantCString. Note that whether the result is 2641193326Sed/// actually a pointer to an LLVM constant depends on 2642193326Sed/// Feature.WriteableStrings. 2643193326Sed/// 2644193326Sed/// The result has pointer to array type. 2645226633Sdimllvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str, 2646226633Sdim const char *GlobalName, 2647226633Sdim unsigned Alignment) { 2648193326Sed // Get the default prefix if a name wasn't specified. 2649193326Sed if (!GlobalName) 2650198092Srdivacky GlobalName = ".str"; 2651193326Sed 2652251662Sdim if (Alignment == 0) 2653251662Sdim Alignment = getContext().getAlignOfGlobalVarInChars(getContext().CharTy) 2654251662Sdim .getQuantity(); 2655251662Sdim 2656193326Sed // Don't share any string literals if strings aren't constant. 2657234353Sdim if (LangOpts.WritableStrings) 2658226633Sdim return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment); 2659193326Sed 2660226633Sdim llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 2661221345Sdim ConstantStringMap.GetOrCreateValue(Str); 2662198092Srdivacky 2663226633Sdim if (llvm::GlobalVariable *GV = Entry.getValue()) { 2664226633Sdim if (Alignment > GV->getAlignment()) { 2665226633Sdim GV->setAlignment(Alignment); 2666226633Sdim } 2667226633Sdim return GV; 2668226633Sdim } 2669193326Sed 2670193326Sed // Create a global variable for this. 2671234353Sdim llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName, 2672234353Sdim Alignment); 2673226633Sdim Entry.setValue(GV); 2674226633Sdim return GV; 2675193326Sed} 2676193326Sed 2677193326Sed/// GetAddrOfConstantCString - Returns a pointer to a character 2678221345Sdim/// array containing the literal and a terminating '\0' 2679193326Sed/// character. The result has pointer to array type. 2680221345Sdimllvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str, 2681226633Sdim const char *GlobalName, 2682226633Sdim unsigned Alignment) { 2683226633Sdim StringRef StrWithNull(Str.c_str(), Str.size() + 1); 2684226633Sdim return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment); 2685193326Sed} 2686193326Sed 2687193326Sed/// EmitObjCPropertyImplementations - Emit information for synthesized 2688193326Sed/// properties for an implementation. 2689198092Srdivackyvoid CodeGenModule::EmitObjCPropertyImplementations(const 2690193326Sed ObjCImplementationDecl *D) { 2691198092Srdivacky for (ObjCImplementationDecl::propimpl_iterator 2692195341Sed i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) { 2693193326Sed ObjCPropertyImplDecl *PID = *i; 2694198092Srdivacky 2695193326Sed // Dynamic is just for type-checking. 2696193326Sed if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 2697193326Sed ObjCPropertyDecl *PD = PID->getPropertyDecl(); 2698193326Sed 2699193326Sed // Determine which methods need to be implemented, some may have 2700243830Sdim // been overridden. Note that ::isPropertyAccessor is not the method 2701193326Sed // we want, that just indicates if the decl came from a 2702193326Sed // property. What we want to know is if the method is defined in 2703193326Sed // this implementation. 2704195341Sed if (!D->getInstanceMethod(PD->getGetterName())) 2705193326Sed CodeGenFunction(*this).GenerateObjCGetter( 2706193326Sed const_cast<ObjCImplementationDecl *>(D), PID); 2707193326Sed if (!PD->isReadOnly() && 2708195341Sed !D->getInstanceMethod(PD->getSetterName())) 2709193326Sed CodeGenFunction(*this).GenerateObjCSetter( 2710193326Sed const_cast<ObjCImplementationDecl *>(D), PID); 2711193326Sed } 2712193326Sed } 2713193326Sed} 2714193326Sed 2715221345Sdimstatic bool needsDestructMethod(ObjCImplementationDecl *impl) { 2716226633Sdim const ObjCInterfaceDecl *iface = impl->getClassInterface(); 2717226633Sdim for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 2718221345Sdim ivar; ivar = ivar->getNextIvar()) 2719221345Sdim if (ivar->getType().isDestructedType()) 2720221345Sdim return true; 2721221345Sdim 2722221345Sdim return false; 2723221345Sdim} 2724221345Sdim 2725207619Srdivacky/// EmitObjCIvarInitializations - Emit information for ivar initialization 2726207619Srdivacky/// for an implementation. 2727207619Srdivackyvoid CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 2728221345Sdim // We might need a .cxx_destruct even if we don't have any ivar initializers. 2729221345Sdim if (needsDestructMethod(D)) { 2730221345Sdim IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 2731221345Sdim Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 2732221345Sdim ObjCMethodDecl *DTORMethod = 2733221345Sdim ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(), 2734226633Sdim cxxSelector, getContext().VoidTy, 0, D, 2735226633Sdim /*isInstance=*/true, /*isVariadic=*/false, 2736243830Sdim /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true, 2737226633Sdim /*isDefined=*/false, ObjCMethodDecl::Required); 2738221345Sdim D->addInstanceMethod(DTORMethod); 2739221345Sdim CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 2740243830Sdim D->setHasDestructors(true); 2741221345Sdim } 2742221345Sdim 2743221345Sdim // If the implementation doesn't have any ivar initializers, we don't need 2744221345Sdim // a .cxx_construct. 2745221345Sdim if (D->getNumIvarInitializers() == 0) 2746207619Srdivacky return; 2747221345Sdim 2748221345Sdim IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 2749207619Srdivacky Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 2750207619Srdivacky // The constructor returns 'self'. 2751207619Srdivacky ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 2752207619Srdivacky D->getLocation(), 2753226633Sdim D->getLocation(), 2754226633Sdim cxxSelector, 2755207619Srdivacky getContext().getObjCIdType(), 0, 2756226633Sdim D, /*isInstance=*/true, 2757226633Sdim /*isVariadic=*/false, 2758243830Sdim /*isPropertyAccessor=*/true, 2759226633Sdim /*isImplicitlyDeclared=*/true, 2760226633Sdim /*isDefined=*/false, 2761207619Srdivacky ObjCMethodDecl::Required); 2762207619Srdivacky D->addInstanceMethod(CTORMethod); 2763207619Srdivacky CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 2764243830Sdim D->setHasNonZeroConstructors(true); 2765207619Srdivacky} 2766207619Srdivacky 2767193326Sed/// EmitNamespace - Emit all declarations in a namespace. 2768193326Sedvoid CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 2769195341Sed for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end(); 2770193326Sed I != E; ++I) 2771193326Sed EmitTopLevelDecl(*I); 2772193326Sed} 2773193326Sed 2774193326Sed// EmitLinkageSpec - Emit all declarations in a linkage spec. 2775193326Sedvoid CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 2776198092Srdivacky if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 2777198092Srdivacky LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 2778193326Sed ErrorUnsupported(LSD, "linkage spec"); 2779193326Sed return; 2780193326Sed } 2781193326Sed 2782195341Sed for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end(); 2783243830Sdim I != E; ++I) { 2784243830Sdim // Meta-data for ObjC class includes references to implemented methods. 2785243830Sdim // Generate class's method definitions first. 2786243830Sdim if (ObjCImplDecl *OID = dyn_cast<ObjCImplDecl>(*I)) { 2787243830Sdim for (ObjCContainerDecl::method_iterator M = OID->meth_begin(), 2788243830Sdim MEnd = OID->meth_end(); 2789243830Sdim M != MEnd; ++M) 2790243830Sdim EmitTopLevelDecl(*M); 2791243830Sdim } 2792193326Sed EmitTopLevelDecl(*I); 2793243830Sdim } 2794193326Sed} 2795193326Sed 2796193326Sed/// EmitTopLevelDecl - Emit code for a single top level declaration. 2797193326Sedvoid CodeGenModule::EmitTopLevelDecl(Decl *D) { 2798193326Sed // If an error has occurred, stop code generation, but continue 2799193326Sed // parsing and semantic analysis (to ensure all warnings and errors 2800193326Sed // are emitted). 2801193326Sed if (Diags.hasErrorOccurred()) 2802193326Sed return; 2803193326Sed 2804195341Sed // Ignore dependent declarations. 2805195341Sed if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 2806195341Sed return; 2807198092Srdivacky 2808193326Sed switch (D->getKind()) { 2809198092Srdivacky case Decl::CXXConversion: 2810193326Sed case Decl::CXXMethod: 2811193326Sed case Decl::Function: 2812195341Sed // Skip function templates 2813221345Sdim if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 2814221345Sdim cast<FunctionDecl>(D)->isLateTemplateParsed()) 2815195341Sed return; 2816198092Srdivacky 2817198092Srdivacky EmitGlobal(cast<FunctionDecl>(D)); 2818198092Srdivacky break; 2819195341Sed 2820193326Sed case Decl::Var: 2821198092Srdivacky EmitGlobal(cast<VarDecl>(D)); 2822193326Sed break; 2823193326Sed 2824221345Sdim // Indirect fields from global anonymous structs and unions can be 2825221345Sdim // ignored; only the actual variable requires IR gen support. 2826221345Sdim case Decl::IndirectField: 2827221345Sdim break; 2828221345Sdim 2829193326Sed // C++ Decls 2830193326Sed case Decl::Namespace: 2831193326Sed EmitNamespace(cast<NamespaceDecl>(D)); 2832193326Sed break; 2833194613Sed // No code generation needed. 2834199482Srdivacky case Decl::UsingShadow: 2835194613Sed case Decl::Using: 2836195341Sed case Decl::ClassTemplate: 2837195341Sed case Decl::FunctionTemplate: 2838223017Sdim case Decl::TypeAliasTemplate: 2839198092Srdivacky case Decl::NamespaceAlias: 2840223017Sdim case Decl::Block: 2841249423Sdim case Decl::Empty: 2842194613Sed break; 2843251662Sdim case Decl::UsingDirective: // using namespace X; [C++] 2844251662Sdim if (CGDebugInfo *DI = getModuleDebugInfo()) 2845251662Sdim DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 2846251662Sdim return; 2847193326Sed case Decl::CXXConstructor: 2848199990Srdivacky // Skip function templates 2849221345Sdim if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 2850221345Sdim cast<FunctionDecl>(D)->isLateTemplateParsed()) 2851199990Srdivacky return; 2852199990Srdivacky 2853193326Sed EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 2854193326Sed break; 2855193326Sed case Decl::CXXDestructor: 2856221345Sdim if (cast<FunctionDecl>(D)->isLateTemplateParsed()) 2857221345Sdim return; 2858193326Sed EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 2859193326Sed break; 2860194179Sed 2861194179Sed case Decl::StaticAssert: 2862194179Sed // Nothing to do. 2863194179Sed break; 2864194179Sed 2865193326Sed // Objective-C Decls 2866198092Srdivacky 2867193326Sed // Forward declarations, no (immediate) code generation. 2868193326Sed case Decl::ObjCInterface: 2869239462Sdim case Decl::ObjCCategory: 2870193326Sed break; 2871193326Sed 2872234353Sdim case Decl::ObjCProtocol: { 2873234353Sdim ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D); 2874234353Sdim if (Proto->isThisDeclarationADefinition()) 2875234353Sdim ObjCRuntime->GenerateProtocol(Proto); 2876193326Sed break; 2877234353Sdim } 2878234353Sdim 2879193326Sed case Decl::ObjCCategoryImpl: 2880193326Sed // Categories have properties but don't support synthesize so we 2881193326Sed // can ignore them here. 2882226633Sdim ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 2883193326Sed break; 2884193326Sed 2885193326Sed case Decl::ObjCImplementation: { 2886193326Sed ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D); 2887193326Sed EmitObjCPropertyImplementations(OMD); 2888207619Srdivacky EmitObjCIvarInitializations(OMD); 2889226633Sdim ObjCRuntime->GenerateClass(OMD); 2890234353Sdim // Emit global variable debug information. 2891234353Sdim if (CGDebugInfo *DI = getModuleDebugInfo()) 2892249423Sdim if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 2893249423Sdim DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 2894249423Sdim OMD->getClassInterface()), OMD->getLocation()); 2895193326Sed break; 2896198092Srdivacky } 2897193326Sed case Decl::ObjCMethod: { 2898193326Sed ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D); 2899193326Sed // If this is not a prototype, emit the body. 2900195341Sed if (OMD->getBody()) 2901193326Sed CodeGenFunction(*this).GenerateObjCMethod(OMD); 2902193326Sed break; 2903193326Sed } 2904198092Srdivacky case Decl::ObjCCompatibleAlias: 2905234353Sdim ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 2906193326Sed break; 2907193326Sed 2908193326Sed case Decl::LinkageSpec: 2909193326Sed EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 2910193326Sed break; 2911193326Sed 2912193326Sed case Decl::FileScopeAsm: { 2913193326Sed FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D); 2914226633Sdim StringRef AsmString = AD->getAsmString()->getString(); 2915198092Srdivacky 2916193326Sed const std::string &S = getModule().getModuleInlineAsm(); 2917193326Sed if (S.empty()) 2918193326Sed getModule().setModuleInlineAsm(AsmString); 2919239462Sdim else if (S.end()[-1] == '\n') 2920226633Sdim getModule().setModuleInlineAsm(S + AsmString.str()); 2921193326Sed else 2922200583Srdivacky getModule().setModuleInlineAsm(S + '\n' + AsmString.str()); 2923193326Sed break; 2924193326Sed } 2925198092Srdivacky 2926249423Sdim case Decl::Import: { 2927249423Sdim ImportDecl *Import = cast<ImportDecl>(D); 2928249423Sdim 2929249423Sdim // Ignore import declarations that come from imported modules. 2930249423Sdim if (clang::Module *Owner = Import->getOwningModule()) { 2931249423Sdim if (getLangOpts().CurrentModule.empty() || 2932249423Sdim Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule) 2933249423Sdim break; 2934249423Sdim } 2935249423Sdim 2936249423Sdim ImportedModules.insert(Import->getImportedModule()); 2937249423Sdim break; 2938249423Sdim } 2939249423Sdim 2940198092Srdivacky default: 2941193326Sed // Make sure we handled everything we should, every other kind is a 2942193326Sed // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 2943193326Sed // function. Need to recode Decl::Kind to do that easily. 2944193326Sed assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 2945193326Sed } 2946193326Sed} 2947210299Sed 2948210299Sed/// Turns the given pointer into a constant. 2949210299Sedstatic llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 2950210299Sed const void *Ptr) { 2951210299Sed uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 2952226633Sdim llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 2953210299Sed return llvm::ConstantInt::get(i64, PtrInt); 2954210299Sed} 2955210299Sed 2956210299Sedstatic void EmitGlobalDeclMetadata(CodeGenModule &CGM, 2957210299Sed llvm::NamedMDNode *&GlobalMetadata, 2958210299Sed GlobalDecl D, 2959210299Sed llvm::GlobalValue *Addr) { 2960210299Sed if (!GlobalMetadata) 2961210299Sed GlobalMetadata = 2962210299Sed CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 2963210299Sed 2964210299Sed // TODO: should we report variant information for ctors/dtors? 2965210299Sed llvm::Value *Ops[] = { 2966210299Sed Addr, 2967210299Sed GetPointerConstant(CGM.getLLVMContext(), D.getDecl()) 2968210299Sed }; 2969221345Sdim GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 2970210299Sed} 2971210299Sed 2972251662Sdim/// For each function which is declared within an extern "C" region and marked 2973251662Sdim/// as 'used', but has internal linkage, create an alias from the unmangled 2974251662Sdim/// name to the mangled name if possible. People expect to be able to refer 2975251662Sdim/// to such functions with an unmangled name from inline assembly within the 2976251662Sdim/// same translation unit. 2977251662Sdimvoid CodeGenModule::EmitStaticExternCAliases() { 2978251662Sdim for (StaticExternCMap::iterator I = StaticExternCValues.begin(), 2979251662Sdim E = StaticExternCValues.end(); 2980251662Sdim I != E; ++I) { 2981251662Sdim IdentifierInfo *Name = I->first; 2982251662Sdim llvm::GlobalValue *Val = I->second; 2983251662Sdim if (Val && !getModule().getNamedValue(Name->getName())) 2984251662Sdim AddUsedGlobal(new llvm::GlobalAlias(Val->getType(), Val->getLinkage(), 2985251662Sdim Name->getName(), Val, &getModule())); 2986251662Sdim } 2987251662Sdim} 2988251662Sdim 2989210299Sed/// Emits metadata nodes associating all the global values in the 2990210299Sed/// current module with the Decls they came from. This is useful for 2991210299Sed/// projects using IR gen as a subroutine. 2992210299Sed/// 2993210299Sed/// Since there's currently no way to associate an MDNode directly 2994210299Sed/// with an llvm::GlobalValue, we create a global named metadata 2995210299Sed/// with the name 'clang.global.decl.ptrs'. 2996210299Sedvoid CodeGenModule::EmitDeclMetadata() { 2997210299Sed llvm::NamedMDNode *GlobalMetadata = 0; 2998210299Sed 2999210299Sed // StaticLocalDeclMap 3000226633Sdim for (llvm::DenseMap<GlobalDecl,StringRef>::iterator 3001210299Sed I = MangledDeclNames.begin(), E = MangledDeclNames.end(); 3002210299Sed I != E; ++I) { 3003210299Sed llvm::GlobalValue *Addr = getModule().getNamedValue(I->second); 3004210299Sed EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr); 3005210299Sed } 3006210299Sed} 3007210299Sed 3008210299Sed/// Emits metadata nodes for all the local variables in the current 3009210299Sed/// function. 3010210299Sedvoid CodeGenFunction::EmitDeclMetadata() { 3011210299Sed if (LocalDeclMap.empty()) return; 3012210299Sed 3013210299Sed llvm::LLVMContext &Context = getLLVMContext(); 3014210299Sed 3015210299Sed // Find the unique metadata ID for this name. 3016210299Sed unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 3017210299Sed 3018210299Sed llvm::NamedMDNode *GlobalMetadata = 0; 3019210299Sed 3020210299Sed for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator 3021210299Sed I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) { 3022210299Sed const Decl *D = I->first; 3023210299Sed llvm::Value *Addr = I->second; 3024210299Sed 3025210299Sed if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 3026210299Sed llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 3027221345Sdim Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr)); 3028210299Sed } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 3029210299Sed GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 3030210299Sed EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 3031210299Sed } 3032210299Sed } 3033210299Sed} 3034212904Sdim 3035223017Sdimvoid CodeGenModule::EmitCoverageFile() { 3036223017Sdim if (!getCodeGenOpts().CoverageFile.empty()) { 3037223017Sdim if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) { 3038223017Sdim llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 3039223017Sdim llvm::LLVMContext &Ctx = TheModule.getContext(); 3040223017Sdim llvm::MDString *CoverageFile = 3041223017Sdim llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile); 3042223017Sdim for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 3043223017Sdim llvm::MDNode *CU = CUNode->getOperand(i); 3044223017Sdim llvm::Value *node[] = { CoverageFile, CU }; 3045223017Sdim llvm::MDNode *N = llvm::MDNode::get(Ctx, node); 3046223017Sdim GCov->addOperand(N); 3047223017Sdim } 3048223017Sdim } 3049223017Sdim } 3050223017Sdim} 3051243830Sdim 3052243830Sdimllvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid, 3053243830Sdim QualType GuidType) { 3054243830Sdim // Sema has checked that all uuid strings are of the form 3055243830Sdim // "12345678-1234-1234-1234-1234567890ab". 3056243830Sdim assert(Uuid.size() == 36); 3057243830Sdim const char *Uuidstr = Uuid.data(); 3058243830Sdim for (int i = 0; i < 36; ++i) { 3059243830Sdim if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuidstr[i] == '-'); 3060249423Sdim else assert(isHexDigit(Uuidstr[i])); 3061243830Sdim } 3062243830Sdim 3063243830Sdim llvm::APInt Field0(32, StringRef(Uuidstr , 8), 16); 3064243830Sdim llvm::APInt Field1(16, StringRef(Uuidstr + 9, 4), 16); 3065243830Sdim llvm::APInt Field2(16, StringRef(Uuidstr + 14, 4), 16); 3066243830Sdim static const int Field3ValueOffsets[] = { 19, 21, 24, 26, 28, 30, 32, 34 }; 3067243830Sdim 3068243830Sdim APValue InitStruct(APValue::UninitStruct(), /*NumBases=*/0, /*NumFields=*/4); 3069243830Sdim InitStruct.getStructField(0) = APValue(llvm::APSInt(Field0)); 3070243830Sdim InitStruct.getStructField(1) = APValue(llvm::APSInt(Field1)); 3071243830Sdim InitStruct.getStructField(2) = APValue(llvm::APSInt(Field2)); 3072243830Sdim APValue& Arr = InitStruct.getStructField(3); 3073243830Sdim Arr = APValue(APValue::UninitArray(), 8, 8); 3074243830Sdim for (int t = 0; t < 8; ++t) 3075243830Sdim Arr.getArrayInitializedElt(t) = APValue(llvm::APSInt( 3076243830Sdim llvm::APInt(8, StringRef(Uuidstr + Field3ValueOffsets[t], 2), 16))); 3077243830Sdim 3078243830Sdim return EmitConstantValue(InitStruct, GuidType); 3079243830Sdim} 3080