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" 38263508Sdim#include "clang/Basic/Version.h" 39249423Sdim#include "clang/Frontend/CodeGenOptions.h" 40263508Sdim#include "clang/Sema/SemaDiagnostic.h" 41234353Sdim#include "llvm/ADT/APSInt.h" 42204793Srdivacky#include "llvm/ADT/Triple.h" 43249423Sdim#include "llvm/IR/CallingConv.h" 44249423Sdim#include "llvm/IR/DataLayout.h" 45249423Sdim#include "llvm/IR/Intrinsics.h" 46249423Sdim#include "llvm/IR/LLVMContext.h" 47249423Sdim#include "llvm/IR/Module.h" 48207619Srdivacky#include "llvm/Support/CallSite.h" 49249423Sdim#include "llvm/Support/ConvertUTF.h" 50199482Srdivacky#include "llvm/Support/ErrorHandling.h" 51249423Sdim#include "llvm/Target/Mangler.h" 52249423Sdim 53193326Sedusing namespace clang; 54193326Sedusing namespace CodeGen; 55193326Sed 56226633Sdimstatic const char AnnotationSection[] = "llvm.metadata"; 57226633Sdim 58212904Sdimstatic CGCXXABI &createCXXABI(CodeGenModule &CGM) { 59251662Sdim switch (CGM.getTarget().getCXXABI().getKind()) { 60249423Sdim case TargetCXXABI::GenericAArch64: 61249423Sdim case TargetCXXABI::GenericARM: 62249423Sdim case TargetCXXABI::iOS: 63249423Sdim case TargetCXXABI::GenericItanium: 64249423Sdim return *CreateItaniumCXXABI(CGM); 65249423Sdim case TargetCXXABI::Microsoft: 66249423Sdim return *CreateMicrosoftCXXABI(CGM); 67212904Sdim } 68193326Sed 69212904Sdim llvm_unreachable("invalid C++ ABI kind"); 70212904Sdim} 71212904Sdim 72199482SrdivackyCodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO, 73251662Sdim llvm::Module &M, const llvm::DataLayout &TD, 74226633Sdim DiagnosticsEngine &diags) 75263508Sdim : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M), 76263508Sdim Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()), 77263508Sdim ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(0), 78263508Sdim TheTargetCodeGenInfo(0), Types(*this), VTables(*this), ObjCRuntime(0), 79263508Sdim OpenCLRuntime(0), CUDARuntime(0), DebugInfo(0), ARCData(0), 80263508Sdim NoObjCARCExceptionsMetadata(0), RRData(0), CFConstantStringClassRef(0), 81263508Sdim ConstantStringClassRef(0), NSConstantStringType(0), 82263508Sdim NSConcreteGlobalBlock(0), NSConcreteStackBlock(0), BlockObjectAssign(0), 83263508Sdim BlockObjectDispose(0), BlockDescriptorType(0), GenericBlockLiteralType(0), 84263508Sdim LifetimeStartFn(0), LifetimeEndFn(0), 85263508Sdim SanitizerBlacklist( 86263508Sdim llvm::SpecialCaseList::createOrDie(CGO.SanitizerBlacklistFile)), 87263508Sdim SanOpts(SanitizerBlacklist->isIn(M) ? SanitizerOptions::Disabled 88263508Sdim : 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 175263508Sdimvoid CodeGenModule::applyReplacements() { 176263508Sdim for (ReplacementsTy::iterator I = Replacements.begin(), 177263508Sdim E = Replacements.end(); 178263508Sdim I != E; ++I) { 179263508Sdim StringRef MangledName = I->first(); 180263508Sdim llvm::Constant *Replacement = I->second; 181263508Sdim llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 182263508Sdim if (!Entry) 183263508Sdim continue; 184263508Sdim llvm::Function *OldF = cast<llvm::Function>(Entry); 185263508Sdim llvm::Function *NewF = dyn_cast<llvm::Function>(Replacement); 186263508Sdim if (!NewF) { 187263508Sdim llvm::ConstantExpr *CE = cast<llvm::ConstantExpr>(Replacement); 188263508Sdim assert(CE->getOpcode() == llvm::Instruction::BitCast || 189263508Sdim CE->getOpcode() == llvm::Instruction::GetElementPtr); 190263508Sdim NewF = dyn_cast<llvm::Function>(CE->getOperand(0)); 191263508Sdim } 192263508Sdim 193263508Sdim // Replace old with new, but keep the old order. 194263508Sdim OldF->replaceAllUsesWith(Replacement); 195263508Sdim if (NewF) { 196263508Sdim NewF->removeFromParent(); 197263508Sdim OldF->getParent()->getFunctionList().insertAfter(OldF, NewF); 198263508Sdim } 199263508Sdim OldF->eraseFromParent(); 200263508Sdim } 201263508Sdim} 202263508Sdim 203263508Sdimvoid CodeGenModule::checkAliases() { 204263508Sdim bool Error = false; 205263508Sdim for (std::vector<GlobalDecl>::iterator I = Aliases.begin(), 206263508Sdim E = Aliases.end(); I != E; ++I) { 207263508Sdim const GlobalDecl &GD = *I; 208263508Sdim const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 209263508Sdim const AliasAttr *AA = D->getAttr<AliasAttr>(); 210263508Sdim StringRef MangledName = getMangledName(GD); 211263508Sdim llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 212263508Sdim llvm::GlobalAlias *Alias = cast<llvm::GlobalAlias>(Entry); 213263508Sdim llvm::GlobalValue *GV = Alias->getAliasedGlobal(); 214263508Sdim if (GV->isDeclaration()) { 215263508Sdim Error = true; 216263508Sdim getDiags().Report(AA->getLocation(), diag::err_alias_to_undefined); 217263508Sdim } else if (!Alias->resolveAliasedGlobal(/*stopOnWeak*/ false)) { 218263508Sdim Error = true; 219263508Sdim getDiags().Report(AA->getLocation(), diag::err_cyclic_alias); 220263508Sdim } 221263508Sdim } 222263508Sdim if (!Error) 223263508Sdim return; 224263508Sdim 225263508Sdim for (std::vector<GlobalDecl>::iterator I = Aliases.begin(), 226263508Sdim E = Aliases.end(); I != E; ++I) { 227263508Sdim const GlobalDecl &GD = *I; 228263508Sdim StringRef MangledName = getMangledName(GD); 229263508Sdim llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 230263508Sdim llvm::GlobalAlias *Alias = cast<llvm::GlobalAlias>(Entry); 231263508Sdim Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType())); 232263508Sdim Alias->eraseFromParent(); 233263508Sdim } 234263508Sdim} 235263508Sdim 236193326Sedvoid CodeGenModule::Release() { 237202379Srdivacky EmitDeferred(); 238263508Sdim applyReplacements(); 239263508Sdim checkAliases(); 240198092Srdivacky EmitCXXGlobalInitFunc(); 241205408Srdivacky EmitCXXGlobalDtorFunc(); 242251662Sdim EmitCXXThreadLocalInitFunc(); 243226633Sdim if (ObjCRuntime) 244226633Sdim if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 245193326Sed AddGlobalCtor(ObjCInitFunction); 246193326Sed EmitCtorList(GlobalCtors, "llvm.global_ctors"); 247193326Sed EmitCtorList(GlobalDtors, "llvm.global_dtors"); 248226633Sdim EmitGlobalAnnotations(); 249251662Sdim EmitStaticExternCAliases(); 250193326Sed EmitLLVMUsed(); 251210299Sed 252263508Sdim if (CodeGenOpts.Autolink && 253263508Sdim (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { 254249423Sdim EmitModuleLinkOptions(); 255249423Sdim } 256263508Sdim if (CodeGenOpts.DwarfVersion) 257263508Sdim // We actually want the latest version when there are conflicts. 258263508Sdim // We can change from Warning to Latest if such mode is supported. 259263508Sdim getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version", 260263508Sdim CodeGenOpts.DwarfVersion); 261263508Sdim if (DebugInfo) 262263508Sdim // We support a single version in the linked module: error out when 263263508Sdim // modules do not have the same version. We are going to implement dropping 264263508Sdim // debug info when the version number is not up-to-date. Once that is 265263508Sdim // done, the bitcode linker is not going to see modules with different 266263508Sdim // version numbers. 267263508Sdim getModule().addModuleFlag(llvm::Module::Error, "Debug Info Version", 268263508Sdim llvm::DEBUG_METADATA_VERSION); 269249423Sdim 270218893Sdim SimplifyPersonality(); 271218893Sdim 272210299Sed if (getCodeGenOpts().EmitDeclMetadata) 273210299Sed EmitDeclMetadata(); 274223017Sdim 275223017Sdim if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 276223017Sdim EmitCoverageFile(); 277226633Sdim 278226633Sdim if (DebugInfo) 279226633Sdim DebugInfo->finalize(); 280263508Sdim 281263508Sdim EmitVersionIdentMetadata(); 282193326Sed} 283193326Sed 284221345Sdimvoid CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 285221345Sdim // Make sure that this type is translated. 286221345Sdim Types.UpdateCompletedType(TD); 287221345Sdim} 288221345Sdim 289218893Sdimllvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) { 290218893Sdim if (!TBAA) 291218893Sdim return 0; 292218893Sdim return TBAA->getTBAAInfo(QTy); 293218893Sdim} 294218893Sdim 295234353Sdimllvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() { 296234353Sdim if (!TBAA) 297234353Sdim return 0; 298234353Sdim return TBAA->getTBAAInfoForVTablePtr(); 299234353Sdim} 300234353Sdim 301243830Sdimllvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 302243830Sdim if (!TBAA) 303243830Sdim return 0; 304243830Sdim return TBAA->getTBAAStructInfo(QTy); 305243830Sdim} 306243830Sdim 307249423Sdimllvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) { 308249423Sdim if (!TBAA) 309249423Sdim return 0; 310249423Sdim return TBAA->getTBAAStructTypeInfo(QTy); 311249423Sdim} 312249423Sdim 313249423Sdimllvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy, 314249423Sdim llvm::MDNode *AccessN, 315249423Sdim uint64_t O) { 316249423Sdim if (!TBAA) 317249423Sdim return 0; 318249423Sdim return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O); 319249423Sdim} 320249423Sdim 321263508Sdim/// Decorate the instruction with a TBAA tag. For both scalar TBAA 322263508Sdim/// and struct-path aware TBAA, the tag has the same format: 323263508Sdim/// base type, access type and offset. 324251662Sdim/// When ConvertTypeToTag is true, we create a tag based on the scalar type. 325218893Sdimvoid CodeGenModule::DecorateInstruction(llvm::Instruction *Inst, 326251662Sdim llvm::MDNode *TBAAInfo, 327251662Sdim bool ConvertTypeToTag) { 328263508Sdim if (ConvertTypeToTag && TBAA) 329251662Sdim Inst->setMetadata(llvm::LLVMContext::MD_tbaa, 330251662Sdim TBAA->getTBAAScalarTagInfo(TBAAInfo)); 331251662Sdim else 332251662Sdim Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo); 333218893Sdim} 334218893Sdim 335226633Sdimvoid CodeGenModule::Error(SourceLocation loc, StringRef error) { 336226633Sdim unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error); 337221345Sdim getDiags().Report(Context.getFullLoc(loc), diagID); 338221345Sdim} 339221345Sdim 340193326Sed/// ErrorUnsupported - Print out an error that codegen doesn't support the 341193326Sed/// specified stmt yet. 342263508Sdimvoid CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { 343226633Sdim unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 344193326Sed "cannot compile this %0 yet"); 345193326Sed std::string Msg = Type; 346193326Sed getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 347193326Sed << Msg << S->getSourceRange(); 348193326Sed} 349193326Sed 350193326Sed/// ErrorUnsupported - Print out an error that codegen doesn't support the 351193326Sed/// specified decl yet. 352263508Sdimvoid CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { 353226633Sdim unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 354193326Sed "cannot compile this %0 yet"); 355193326Sed std::string Msg = Type; 356193326Sed getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 357193326Sed} 358193326Sed 359224145Sdimllvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 360224145Sdim return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 361224145Sdim} 362224145Sdim 363198092Srdivackyvoid CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 364218893Sdim const NamedDecl *D) const { 365193326Sed // Internal definitions always have default visibility. 366193326Sed if (GV->hasLocalLinkage()) { 367193326Sed GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 368193326Sed return; 369193326Sed } 370193326Sed 371218893Sdim // Set visibility for definitions. 372249423Sdim LinkageInfo LV = D->getLinkageAndVisibility(); 373249423Sdim if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage()) 374249423Sdim GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 375193326Sed} 376193326Sed 377239462Sdimstatic llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 378239462Sdim return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 379239462Sdim .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 380239462Sdim .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 381239462Sdim .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 382239462Sdim .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 383239462Sdim} 384239462Sdim 385239462Sdimstatic llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel( 386239462Sdim CodeGenOptions::TLSModel M) { 387239462Sdim switch (M) { 388239462Sdim case CodeGenOptions::GeneralDynamicTLSModel: 389239462Sdim return llvm::GlobalVariable::GeneralDynamicTLSModel; 390239462Sdim case CodeGenOptions::LocalDynamicTLSModel: 391239462Sdim return llvm::GlobalVariable::LocalDynamicTLSModel; 392239462Sdim case CodeGenOptions::InitialExecTLSModel: 393239462Sdim return llvm::GlobalVariable::InitialExecTLSModel; 394239462Sdim case CodeGenOptions::LocalExecTLSModel: 395239462Sdim return llvm::GlobalVariable::LocalExecTLSModel; 396239462Sdim } 397239462Sdim llvm_unreachable("Invalid TLS model!"); 398239462Sdim} 399239462Sdim 400239462Sdimvoid CodeGenModule::setTLSMode(llvm::GlobalVariable *GV, 401239462Sdim const VarDecl &D) const { 402251662Sdim assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 403239462Sdim 404239462Sdim llvm::GlobalVariable::ThreadLocalMode TLM; 405243830Sdim TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel()); 406239462Sdim 407239462Sdim // Override the TLS model if it is explicitly specified. 408239462Sdim if (D.hasAttr<TLSModelAttr>()) { 409239462Sdim const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>(); 410239462Sdim TLM = GetLLVMTLSModel(Attr->getModel()); 411239462Sdim } 412239462Sdim 413239462Sdim GV->setThreadLocalMode(TLM); 414239462Sdim} 415239462Sdim 416212904Sdim/// Set the symbol visibility of type information (vtable and RTTI) 417212904Sdim/// associated with the given type. 418212904Sdimvoid CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV, 419212904Sdim const CXXRecordDecl *RD, 420218893Sdim TypeVisibilityKind TVK) const { 421212904Sdim setGlobalVisibility(GV, RD); 422212904Sdim 423212904Sdim if (!CodeGenOpts.HiddenWeakVTables) 424212904Sdim return; 425212904Sdim 426218893Sdim // We never want to drop the visibility for RTTI names. 427218893Sdim if (TVK == TVK_ForRTTIName) 428218893Sdim return; 429218893Sdim 430212904Sdim // We want to drop the visibility to hidden for weak type symbols. 431212904Sdim // This isn't possible if there might be unresolved references 432212904Sdim // elsewhere that rely on this symbol being visible. 433212904Sdim 434212904Sdim // This should be kept roughly in sync with setThunkVisibility 435212904Sdim // in CGVTables.cpp. 436212904Sdim 437212904Sdim // Preconditions. 438218893Sdim if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage || 439212904Sdim GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility) 440212904Sdim return; 441212904Sdim 442212904Sdim // Don't override an explicit visibility attribute. 443249423Sdim if (RD->getExplicitVisibility(NamedDecl::VisibilityForType)) 444212904Sdim return; 445212904Sdim 446212904Sdim switch (RD->getTemplateSpecializationKind()) { 447212904Sdim // We have to disable the optimization if this is an EI definition 448212904Sdim // because there might be EI declarations in other shared objects. 449212904Sdim case TSK_ExplicitInstantiationDefinition: 450212904Sdim case TSK_ExplicitInstantiationDeclaration: 451212904Sdim return; 452212904Sdim 453212904Sdim // Every use of a non-template class's type information has to emit it. 454212904Sdim case TSK_Undeclared: 455212904Sdim break; 456212904Sdim 457212904Sdim // In theory, implicit instantiations can ignore the possibility of 458212904Sdim // an explicit instantiation declaration because there necessarily 459212904Sdim // must be an EI definition somewhere with default visibility. In 460212904Sdim // practice, it's possible to have an explicit instantiation for 461212904Sdim // an arbitrary template class, and linkers aren't necessarily able 462212904Sdim // to deal with mixed-visibility symbols. 463212904Sdim case TSK_ExplicitSpecialization: 464212904Sdim case TSK_ImplicitInstantiation: 465243830Sdim return; 466212904Sdim } 467212904Sdim 468212904Sdim // If there's a key function, there may be translation units 469212904Sdim // that don't have the key function's definition. But ignore 470212904Sdim // this if we're emitting RTTI under -fno-rtti. 471234353Sdim if (!(TVK != TVK_ForRTTI) || LangOpts.RTTI) { 472249423Sdim // FIXME: what should we do if we "lose" the key function during 473249423Sdim // the emission of the file? 474249423Sdim if (Context.getCurrentKeyFunction(RD)) 475212904Sdim return; 476218893Sdim } 477212904Sdim 478212904Sdim // Otherwise, drop the visibility to hidden. 479212904Sdim GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 480218893Sdim GV->setUnnamedAddr(true); 481212904Sdim} 482212904Sdim 483226633SdimStringRef CodeGenModule::getMangledName(GlobalDecl GD) { 484198092Srdivacky const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 485198092Srdivacky 486226633Sdim StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()]; 487210299Sed if (!Str.empty()) 488210299Sed return Str; 489198092Srdivacky 490212904Sdim if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) { 491210299Sed IdentifierInfo *II = ND->getIdentifier(); 492210299Sed assert(II && "Attempt to mangle unnamed decl."); 493193326Sed 494210299Sed Str = II->getName(); 495210299Sed return Str; 496193326Sed } 497210299Sed 498234353Sdim SmallString<256> Buffer; 499218893Sdim llvm::raw_svector_ostream Out(Buffer); 500210299Sed if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND)) 501218893Sdim getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out); 502210299Sed else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND)) 503218893Sdim getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out); 504210299Sed else 505218893Sdim getCXXABI().getMangleContext().mangleName(ND, Out); 506198092Srdivacky 507210299Sed // Allocate space for the mangled name. 508218893Sdim Out.flush(); 509210299Sed size_t Length = Buffer.size(); 510210299Sed char *Name = MangledNamesAllocator.Allocate<char>(Length); 511210299Sed std::copy(Buffer.begin(), Buffer.end(), Name); 512210299Sed 513226633Sdim Str = StringRef(Name, Length); 514210299Sed 515210299Sed return Str; 516193326Sed} 517193326Sed 518218893Sdimvoid CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer, 519218893Sdim const BlockDecl *BD) { 520218893Sdim MangleContext &MangleCtx = getCXXABI().getMangleContext(); 521218893Sdim const Decl *D = GD.getDecl(); 522218893Sdim llvm::raw_svector_ostream Out(Buffer.getBuffer()); 523218893Sdim if (D == 0) 524239462Sdim MangleCtx.mangleGlobalBlock(BD, 525239462Sdim dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 526218893Sdim else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 527218893Sdim MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 528218893Sdim else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D)) 529218893Sdim MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 530218893Sdim else 531218893Sdim MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 532210299Sed} 533210299Sed 534226633Sdimllvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 535205408Srdivacky return getModule().getNamedValue(Name); 536193326Sed} 537193326Sed 538193326Sed/// AddGlobalCtor - Add a function to the list that will be called before 539193326Sed/// main() runs. 540193326Sedvoid CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) { 541193326Sed // FIXME: Type coercion of void()* types. 542193326Sed GlobalCtors.push_back(std::make_pair(Ctor, Priority)); 543193326Sed} 544193326Sed 545193326Sed/// AddGlobalDtor - Add a function to the list that will be called 546193326Sed/// when the module is unloaded. 547193326Sedvoid CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) { 548193326Sed // FIXME: Type coercion of void()* types. 549193326Sed GlobalDtors.push_back(std::make_pair(Dtor, Priority)); 550193326Sed} 551193326Sed 552193326Sedvoid CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 553193326Sed // Ctor function type is void()*. 554223017Sdim llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 555193326Sed llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 556193326Sed 557193326Sed // Get the type of a ctor entry, { i32, void ()* }. 558224145Sdim llvm::StructType *CtorStructTy = 559234353Sdim llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL); 560193326Sed 561193326Sed // Construct the constructor and destructor arrays. 562234353Sdim SmallVector<llvm::Constant*, 8> Ctors; 563193326Sed for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 564234353Sdim llvm::Constant *S[] = { 565234353Sdim llvm::ConstantInt::get(Int32Ty, I->second, false), 566234353Sdim llvm::ConstantExpr::getBitCast(I->first, CtorPFTy) 567234353Sdim }; 568193326Sed Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 569193326Sed } 570193326Sed 571193326Sed if (!Ctors.empty()) { 572193326Sed llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 573198092Srdivacky new llvm::GlobalVariable(TheModule, AT, false, 574193326Sed llvm::GlobalValue::AppendingLinkage, 575193326Sed llvm::ConstantArray::get(AT, Ctors), 576198092Srdivacky GlobalName); 577193326Sed } 578193326Sed} 579193326Sed 580204643Srdivackyllvm::GlobalValue::LinkageTypes 581263508SdimCodeGenModule::getFunctionLinkage(GlobalDecl GD) { 582263508Sdim const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl()); 583263508Sdim 584263508Sdim if (isa<CXXDestructorDecl>(D) && 585263508Sdim getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 586263508Sdim GD.getDtorType())) 587263508Sdim return llvm::Function::LinkOnceODRLinkage; 588263508Sdim 589212904Sdim GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 590193326Sed 591210299Sed if (Linkage == GVA_Internal) 592204643Srdivacky return llvm::Function::InternalLinkage; 593210299Sed 594210299Sed if (D->hasAttr<DLLExportAttr>()) 595204643Srdivacky return llvm::Function::DLLExportLinkage; 596210299Sed 597210299Sed if (D->hasAttr<WeakAttr>()) 598204643Srdivacky return llvm::Function::WeakAnyLinkage; 599210299Sed 600210299Sed // In C99 mode, 'inline' functions are guaranteed to have a strong 601210299Sed // definition somewhere else, so we can use available_externally linkage. 602210299Sed if (Linkage == GVA_C99Inline) 603204643Srdivacky return llvm::Function::AvailableExternallyLinkage; 604226633Sdim 605226633Sdim // Note that Apple's kernel linker doesn't support symbol 606226633Sdim // coalescing, so we need to avoid linkonce and weak linkages there. 607226633Sdim // Normally, this means we just map to internal, but for explicit 608226633Sdim // instantiations we'll map to external. 609226633Sdim 610210299Sed // In C++, the compiler has to emit a definition in every translation unit 611210299Sed // that references the function. We should use linkonce_odr because 612210299Sed // a) if all references in this translation unit are optimized away, we 613210299Sed // don't need to codegen it. b) if the function persists, it needs to be 614210299Sed // merged with other definitions. c) C++ has the ODR, so we know the 615210299Sed // definition is dependable. 616210299Sed if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) 617234353Sdim return !Context.getLangOpts().AppleKext 618218893Sdim ? llvm::Function::LinkOnceODRLinkage 619218893Sdim : llvm::Function::InternalLinkage; 620210299Sed 621210299Sed // An explicit instantiation of a template has weak linkage, since 622210299Sed // explicit instantiations can occur in multiple translation units 623210299Sed // and must all be equivalent. However, we are not allowed to 624210299Sed // throw away these explicit instantiations. 625210299Sed if (Linkage == GVA_ExplicitTemplateInstantiation) 626234353Sdim return !Context.getLangOpts().AppleKext 627218893Sdim ? llvm::Function::WeakODRLinkage 628226633Sdim : llvm::Function::ExternalLinkage; 629210299Sed 630210299Sed // Otherwise, we have strong external linkage. 631210299Sed assert(Linkage == GVA_StrongExternal); 632210299Sed return llvm::Function::ExternalLinkage; 633204643Srdivacky} 634193326Sed 635204643Srdivacky 636204643Srdivacky/// SetFunctionDefinitionAttributes - Set attributes for a global. 637204643Srdivacky/// 638204643Srdivacky/// FIXME: This is currently only done for aliases and functions, but not for 639204643Srdivacky/// variables (these details are set in EmitGlobalVarDefinition for variables). 640204643Srdivackyvoid CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D, 641204643Srdivacky llvm::GlobalValue *GV) { 642193326Sed SetCommonAttributes(D, GV); 643193326Sed} 644193326Sed 645193326Sedvoid CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 646198092Srdivacky const CGFunctionInfo &Info, 647193326Sed llvm::Function *F) { 648198092Srdivacky unsigned CallingConv; 649193326Sed AttributeListType AttributeList; 650249423Sdim ConstructAttributeList(Info, D, AttributeList, CallingConv, false); 651249423Sdim F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList)); 652198092Srdivacky F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 653193326Sed} 654193326Sed 655226633Sdim/// Determines whether the language options require us to model 656226633Sdim/// unwind exceptions. We treat -fexceptions as mandating this 657226633Sdim/// except under the fragile ObjC ABI with only ObjC exceptions 658226633Sdim/// enabled. This means, for example, that C with -fexceptions 659226633Sdim/// enables this. 660234353Sdimstatic bool hasUnwindExceptions(const LangOptions &LangOpts) { 661226633Sdim // If exceptions are completely disabled, obviously this is false. 662234353Sdim if (!LangOpts.Exceptions) return false; 663226633Sdim 664226633Sdim // If C++ exceptions are enabled, this is true. 665234353Sdim if (LangOpts.CXXExceptions) return true; 666226633Sdim 667226633Sdim // If ObjC exceptions are enabled, this depends on the ABI. 668234353Sdim if (LangOpts.ObjCExceptions) { 669239462Sdim return LangOpts.ObjCRuntime.hasUnwindExceptions(); 670226633Sdim } 671226633Sdim 672226633Sdim return true; 673226633Sdim} 674226633Sdim 675193326Sedvoid CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 676193326Sed llvm::Function *F) { 677263508Sdim llvm::AttrBuilder B; 678263508Sdim 679223017Sdim if (CodeGenOpts.UnwindTables) 680263508Sdim B.addAttribute(llvm::Attribute::UWTable); 681223017Sdim 682234353Sdim if (!hasUnwindExceptions(LangOpts)) 683263508Sdim B.addAttribute(llvm::Attribute::NoUnwind); 684193326Sed 685226633Sdim if (D->hasAttr<NakedAttr>()) { 686226633Sdim // Naked implies noinline: we should not be inlining such functions. 687263508Sdim B.addAttribute(llvm::Attribute::Naked); 688263508Sdim B.addAttribute(llvm::Attribute::NoInline); 689263508Sdim } else if (D->hasAttr<NoInlineAttr>()) { 690263508Sdim B.addAttribute(llvm::Attribute::NoInline); 691263508Sdim } else if ((D->hasAttr<AlwaysInlineAttr>() || 692263508Sdim D->hasAttr<ForceInlineAttr>()) && 693263508Sdim !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex, 694263508Sdim llvm::Attribute::NoInline)) { 695263508Sdim // (noinline wins over always_inline, and we can't specify both in IR) 696263508Sdim B.addAttribute(llvm::Attribute::AlwaysInline); 697226633Sdim } 698218893Sdim 699263508Sdim if (D->hasAttr<ColdAttr>()) { 700263508Sdim B.addAttribute(llvm::Attribute::OptimizeForSize); 701263508Sdim B.addAttribute(llvm::Attribute::Cold); 702263508Sdim } 703198092Srdivacky 704243830Sdim if (D->hasAttr<MinSizeAttr>()) 705263508Sdim B.addAttribute(llvm::Attribute::MinSize); 706243830Sdim 707234353Sdim if (LangOpts.getStackProtector() == LangOptions::SSPOn) 708263508Sdim B.addAttribute(llvm::Attribute::StackProtect); 709234353Sdim else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 710263508Sdim B.addAttribute(llvm::Attribute::StackProtectReq); 711249423Sdim 712249423Sdim // Add sanitizer attributes if function is not blacklisted. 713263508Sdim if (!SanitizerBlacklist->isIn(*F)) { 714249423Sdim // When AddressSanitizer is enabled, set SanitizeAddress attribute 715249423Sdim // unless __attribute__((no_sanitize_address)) is used. 716249423Sdim if (SanOpts.Address && !D->hasAttr<NoSanitizeAddressAttr>()) 717263508Sdim B.addAttribute(llvm::Attribute::SanitizeAddress); 718249423Sdim // Same for ThreadSanitizer and __attribute__((no_sanitize_thread)) 719249423Sdim if (SanOpts.Thread && !D->hasAttr<NoSanitizeThreadAttr>()) { 720263508Sdim B.addAttribute(llvm::Attribute::SanitizeThread); 721249423Sdim } 722249423Sdim // Same for MemorySanitizer and __attribute__((no_sanitize_memory)) 723249423Sdim if (SanOpts.Memory && !D->hasAttr<NoSanitizeMemoryAttr>()) 724263508Sdim B.addAttribute(llvm::Attribute::SanitizeMemory); 725234353Sdim } 726234353Sdim 727263508Sdim F->addAttributes(llvm::AttributeSet::FunctionIndex, 728263508Sdim llvm::AttributeSet::get( 729263508Sdim F->getContext(), llvm::AttributeSet::FunctionIndex, B)); 730263508Sdim 731263508Sdim if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 732263508Sdim F->setUnnamedAddr(true); 733263508Sdim else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) 734263508Sdim if (MD->isVirtual()) 735263508Sdim F->setUnnamedAddr(true); 736263508Sdim 737212904Sdim unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 738212904Sdim if (alignment) 739212904Sdim F->setAlignment(alignment); 740212904Sdim 741198092Srdivacky // C++ ABI requires 2-byte alignment for member functions. 742198092Srdivacky if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 743198092Srdivacky F->setAlignment(2); 744193326Sed} 745193326Sed 746198092Srdivackyvoid CodeGenModule::SetCommonAttributes(const Decl *D, 747193326Sed llvm::GlobalValue *GV) { 748218893Sdim if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) 749218893Sdim setGlobalVisibility(GV, ND); 750218893Sdim else 751218893Sdim GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 752193326Sed 753195341Sed if (D->hasAttr<UsedAttr>()) 754193326Sed AddUsedGlobal(GV); 755193326Sed 756195341Sed if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 757193326Sed GV->setSection(SA->getName()); 758202379Srdivacky 759249423Sdim // Alias cannot have attributes. Filter them here. 760249423Sdim if (!isa<llvm::GlobalAlias>(GV)) 761249423Sdim getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this); 762193326Sed} 763193326Sed 764193326Sedvoid CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 765193326Sed llvm::Function *F, 766193326Sed const CGFunctionInfo &FI) { 767193326Sed SetLLVMFunctionAttributes(D, FI, F); 768193326Sed SetLLVMFunctionAttributesForDefinition(D, F); 769193326Sed 770193326Sed F->setLinkage(llvm::Function::InternalLinkage); 771193326Sed 772193326Sed SetCommonAttributes(D, F); 773193326Sed} 774193326Sed 775203955Srdivackyvoid CodeGenModule::SetFunctionAttributes(GlobalDecl GD, 776193326Sed llvm::Function *F, 777193326Sed bool IsIncompleteFunction) { 778221345Sdim if (unsigned IID = F->getIntrinsicID()) { 779221345Sdim // If this is an intrinsic function, set the function's attributes 780221345Sdim // to the intrinsic's attributes. 781243830Sdim F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), 782243830Sdim (llvm::Intrinsic::ID)IID)); 783221345Sdim return; 784221345Sdim } 785221345Sdim 786203955Srdivacky const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 787203955Srdivacky 788193326Sed if (!IsIncompleteFunction) 789234353Sdim SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F); 790198092Srdivacky 791263508Sdim if (getCXXABI().HasThisReturn(GD)) { 792263508Sdim assert(!F->arg_empty() && 793263508Sdim F->arg_begin()->getType() 794263508Sdim ->canLosslesslyBitCastTo(F->getReturnType()) && 795263508Sdim "unexpected this return"); 796263508Sdim F->addAttribute(1, llvm::Attribute::Returned); 797263508Sdim } 798263508Sdim 799193326Sed // Only a few attributes are set on declarations; these may later be 800193326Sed // overridden by a definition. 801198092Srdivacky 802195341Sed if (FD->hasAttr<DLLImportAttr>()) { 803193326Sed F->setLinkage(llvm::Function::DLLImportLinkage); 804198092Srdivacky } else if (FD->hasAttr<WeakAttr>() || 805221345Sdim FD->isWeakImported()) { 806193326Sed // "extern_weak" is overloaded in LLVM; we probably should have 807198092Srdivacky // separate linkage types for this. 808193326Sed F->setLinkage(llvm::Function::ExternalWeakLinkage); 809193326Sed } else { 810198092Srdivacky F->setLinkage(llvm::Function::ExternalLinkage); 811218893Sdim 812249423Sdim LinkageInfo LV = FD->getLinkageAndVisibility(); 813249423Sdim if (LV.getLinkage() == ExternalLinkage && LV.isVisibilityExplicit()) { 814249423Sdim F->setVisibility(GetLLVMVisibility(LV.getVisibility())); 815218893Sdim } 816193326Sed } 817193326Sed 818195341Sed if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 819193326Sed F->setSection(SA->getName()); 820263508Sdim 821263508Sdim // A replaceable global allocation function does not act like a builtin by 822263508Sdim // default, only if it is invoked by a new-expression or delete-expression. 823263508Sdim if (FD->isReplaceableGlobalAllocationFunction()) 824263508Sdim F->addAttribute(llvm::AttributeSet::FunctionIndex, 825263508Sdim llvm::Attribute::NoBuiltin); 826193326Sed} 827193326Sed 828193326Sedvoid CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) { 829198092Srdivacky assert(!GV->isDeclaration() && 830193326Sed "Only globals with definition can force usage."); 831193326Sed LLVMUsed.push_back(GV); 832193326Sed} 833193326Sed 834193326Sedvoid CodeGenModule::EmitLLVMUsed() { 835193326Sed // Don't create llvm.used if there is no need. 836198092Srdivacky if (LLVMUsed.empty()) 837193326Sed return; 838193326Sed 839193326Sed // Convert LLVMUsed to what ConstantArray needs. 840234353Sdim SmallVector<llvm::Constant*, 8> UsedArray; 841193326Sed UsedArray.resize(LLVMUsed.size()); 842193326Sed for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) { 843198092Srdivacky UsedArray[i] = 844198092Srdivacky llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]), 845234353Sdim Int8PtrTy); 846193326Sed } 847198092Srdivacky 848195099Sed if (UsedArray.empty()) 849195099Sed return; 850234353Sdim llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size()); 851198092Srdivacky 852198092Srdivacky llvm::GlobalVariable *GV = 853198092Srdivacky new llvm::GlobalVariable(getModule(), ATy, false, 854193326Sed llvm::GlobalValue::AppendingLinkage, 855193326Sed llvm::ConstantArray::get(ATy, UsedArray), 856198092Srdivacky "llvm.used"); 857193326Sed 858193326Sed GV->setSection("llvm.metadata"); 859193326Sed} 860193326Sed 861263508Sdimvoid CodeGenModule::AppendLinkerOptions(StringRef Opts) { 862263508Sdim llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 863263508Sdim LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 864263508Sdim} 865263508Sdim 866263508Sdimvoid CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 867263508Sdim llvm::SmallString<32> Opt; 868263508Sdim getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 869263508Sdim llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 870263508Sdim LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 871263508Sdim} 872263508Sdim 873263508Sdimvoid CodeGenModule::AddDependentLib(StringRef Lib) { 874263508Sdim llvm::SmallString<24> Opt; 875263508Sdim getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 876263508Sdim llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 877263508Sdim LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 878263508Sdim} 879263508Sdim 880249423Sdim/// \brief Add link options implied by the given module, including modules 881249423Sdim/// it depends on, using a postorder walk. 882263508Sdimstatic void addLinkOptionsPostorder(CodeGenModule &CGM, 883249423Sdim Module *Mod, 884249423Sdim SmallVectorImpl<llvm::Value *> &Metadata, 885249423Sdim llvm::SmallPtrSet<Module *, 16> &Visited) { 886249423Sdim // Import this module's parent. 887249423Sdim if (Mod->Parent && Visited.insert(Mod->Parent)) { 888263508Sdim addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 889249423Sdim } 890249423Sdim 891249423Sdim // Import this module's dependencies. 892249423Sdim for (unsigned I = Mod->Imports.size(); I > 0; --I) { 893249423Sdim if (Visited.insert(Mod->Imports[I-1])) 894263508Sdim addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited); 895249423Sdim } 896249423Sdim 897249423Sdim // Add linker options to link against the libraries/frameworks 898249423Sdim // described by this module. 899263508Sdim llvm::LLVMContext &Context = CGM.getLLVMContext(); 900249423Sdim for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) { 901263508Sdim // Link against a framework. Frameworks are currently Darwin only, so we 902263508Sdim // don't to ask TargetCodeGenInfo for the spelling of the linker option. 903249423Sdim if (Mod->LinkLibraries[I-1].IsFramework) { 904249423Sdim llvm::Value *Args[2] = { 905249423Sdim llvm::MDString::get(Context, "-framework"), 906249423Sdim llvm::MDString::get(Context, Mod->LinkLibraries[I-1].Library) 907249423Sdim }; 908249423Sdim 909249423Sdim Metadata.push_back(llvm::MDNode::get(Context, Args)); 910249423Sdim continue; 911249423Sdim } 912249423Sdim 913249423Sdim // Link against a library. 914263508Sdim llvm::SmallString<24> Opt; 915263508Sdim CGM.getTargetCodeGenInfo().getDependentLibraryOption( 916263508Sdim Mod->LinkLibraries[I-1].Library, Opt); 917263508Sdim llvm::Value *OptString = llvm::MDString::get(Context, Opt); 918249423Sdim Metadata.push_back(llvm::MDNode::get(Context, OptString)); 919249423Sdim } 920249423Sdim} 921249423Sdim 922249423Sdimvoid CodeGenModule::EmitModuleLinkOptions() { 923249423Sdim // Collect the set of all of the modules we want to visit to emit link 924249423Sdim // options, which is essentially the imported modules and all of their 925249423Sdim // non-explicit child modules. 926249423Sdim llvm::SetVector<clang::Module *> LinkModules; 927249423Sdim llvm::SmallPtrSet<clang::Module *, 16> Visited; 928249423Sdim SmallVector<clang::Module *, 16> Stack; 929249423Sdim 930249423Sdim // Seed the stack with imported modules. 931249423Sdim for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(), 932249423Sdim MEnd = ImportedModules.end(); 933249423Sdim M != MEnd; ++M) { 934249423Sdim if (Visited.insert(*M)) 935249423Sdim Stack.push_back(*M); 936249423Sdim } 937249423Sdim 938249423Sdim // Find all of the modules to import, making a little effort to prune 939249423Sdim // non-leaf modules. 940249423Sdim while (!Stack.empty()) { 941263508Sdim clang::Module *Mod = Stack.pop_back_val(); 942249423Sdim 943249423Sdim bool AnyChildren = false; 944249423Sdim 945249423Sdim // Visit the submodules of this module. 946249423Sdim for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 947249423Sdim SubEnd = Mod->submodule_end(); 948249423Sdim Sub != SubEnd; ++Sub) { 949249423Sdim // Skip explicit children; they need to be explicitly imported to be 950249423Sdim // linked against. 951249423Sdim if ((*Sub)->IsExplicit) 952249423Sdim continue; 953249423Sdim 954249423Sdim if (Visited.insert(*Sub)) { 955249423Sdim Stack.push_back(*Sub); 956249423Sdim AnyChildren = true; 957249423Sdim } 958249423Sdim } 959249423Sdim 960249423Sdim // We didn't find any children, so add this module to the list of 961249423Sdim // modules to link against. 962249423Sdim if (!AnyChildren) { 963249423Sdim LinkModules.insert(Mod); 964249423Sdim } 965249423Sdim } 966249423Sdim 967249423Sdim // Add link options for all of the imported modules in reverse topological 968263508Sdim // order. We don't do anything to try to order import link flags with respect 969263508Sdim // to linker options inserted by things like #pragma comment(). 970249423Sdim SmallVector<llvm::Value *, 16> MetadataArgs; 971249423Sdim Visited.clear(); 972249423Sdim for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(), 973249423Sdim MEnd = LinkModules.end(); 974249423Sdim M != MEnd; ++M) { 975249423Sdim if (Visited.insert(*M)) 976263508Sdim addLinkOptionsPostorder(*this, *M, MetadataArgs, Visited); 977249423Sdim } 978249423Sdim std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 979263508Sdim LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 980249423Sdim 981249423Sdim // Add the linker options metadata flag. 982249423Sdim getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options", 983263508Sdim llvm::MDNode::get(getLLVMContext(), 984263508Sdim LinkerOptionsMetadata)); 985249423Sdim} 986249423Sdim 987193326Sedvoid CodeGenModule::EmitDeferred() { 988193326Sed // Emit code for any potentially referenced deferred decls. Since a 989193326Sed // previously unused static decl may become used during the generation of code 990226633Sdim // for a static function, iterate until no changes are made. 991204962Srdivacky 992249423Sdim while (true) { 993207619Srdivacky if (!DeferredVTables.empty()) { 994249423Sdim EmitDeferredVTables(); 995249423Sdim 996249423Sdim // Emitting a v-table doesn't directly cause more v-tables to 997249423Sdim // become deferred, although it can cause functions to be 998249423Sdim // emitted that then need those v-tables. 999249423Sdim assert(DeferredVTables.empty()); 1000204962Srdivacky } 1001204962Srdivacky 1002249423Sdim // Stop if we're out of both deferred v-tables and deferred declarations. 1003249423Sdim if (DeferredDeclsToEmit.empty()) break; 1004249423Sdim 1005193326Sed GlobalDecl D = DeferredDeclsToEmit.back(); 1006193326Sed DeferredDeclsToEmit.pop_back(); 1007193326Sed 1008208600Srdivacky // Check to see if we've already emitted this. This is necessary 1009208600Srdivacky // for a couple of reasons: first, decls can end up in the 1010208600Srdivacky // deferred-decls queue multiple times, and second, decls can end 1011208600Srdivacky // up with definitions in unusual ways (e.g. by an extern inline 1012208600Srdivacky // function acquiring a strong function redefinition). Just 1013208600Srdivacky // ignore these cases. 1014208600Srdivacky // 1015208600Srdivacky // TODO: That said, looking this up multiple times is very wasteful. 1016226633Sdim StringRef Name = getMangledName(D); 1017205408Srdivacky llvm::GlobalValue *CGRef = GetGlobalValue(Name); 1018193326Sed assert(CGRef && "Deferred decl wasn't referenced?"); 1019198092Srdivacky 1020193326Sed if (!CGRef->isDeclaration()) 1021193326Sed continue; 1022198092Srdivacky 1023208600Srdivacky // GlobalAlias::isDeclaration() defers to the aliasee, but for our 1024208600Srdivacky // purposes an alias counts as a definition. 1025208600Srdivacky if (isa<llvm::GlobalAlias>(CGRef)) 1026208600Srdivacky continue; 1027208600Srdivacky 1028193326Sed // Otherwise, emit the definition and move on to the next one. 1029193326Sed EmitGlobalDefinition(D); 1030193326Sed } 1031193326Sed} 1032193326Sed 1033226633Sdimvoid CodeGenModule::EmitGlobalAnnotations() { 1034226633Sdim if (Annotations.empty()) 1035226633Sdim return; 1036226633Sdim 1037226633Sdim // Create a new global variable for the ConstantStruct in the Module. 1038226633Sdim llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 1039226633Sdim Annotations[0]->getType(), Annotations.size()), Annotations); 1040226633Sdim llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), 1041226633Sdim Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array, 1042226633Sdim "llvm.global.annotations"); 1043226633Sdim gv->setSection(AnnotationSection); 1044226633Sdim} 1045226633Sdim 1046249423Sdimllvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 1047263508Sdim llvm::Constant *&AStr = AnnotationStrings[Str]; 1048263508Sdim if (AStr) 1049263508Sdim return AStr; 1050226633Sdim 1051226633Sdim // Not found yet, create a new global. 1052234353Sdim llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 1053226633Sdim llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(), 1054226633Sdim true, llvm::GlobalValue::PrivateLinkage, s, ".str"); 1055226633Sdim gv->setSection(AnnotationSection); 1056226633Sdim gv->setUnnamedAddr(true); 1057263508Sdim AStr = gv; 1058226633Sdim return gv; 1059226633Sdim} 1060226633Sdim 1061226633Sdimllvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 1062226633Sdim SourceManager &SM = getContext().getSourceManager(); 1063226633Sdim PresumedLoc PLoc = SM.getPresumedLoc(Loc); 1064226633Sdim if (PLoc.isValid()) 1065226633Sdim return EmitAnnotationString(PLoc.getFilename()); 1066226633Sdim return EmitAnnotationString(SM.getBufferName(Loc)); 1067226633Sdim} 1068226633Sdim 1069226633Sdimllvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 1070226633Sdim SourceManager &SM = getContext().getSourceManager(); 1071226633Sdim PresumedLoc PLoc = SM.getPresumedLoc(L); 1072226633Sdim unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 1073226633Sdim SM.getExpansionLineNumber(L); 1074226633Sdim return llvm::ConstantInt::get(Int32Ty, LineNo); 1075226633Sdim} 1076226633Sdim 1077198092Srdivackyllvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 1078193326Sed const AnnotateAttr *AA, 1079226633Sdim SourceLocation L) { 1080226633Sdim // Get the globals for file name, annotation, and the line number. 1081226633Sdim llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 1082226633Sdim *UnitGV = EmitAnnotationUnit(L), 1083226633Sdim *LineNoCst = EmitAnnotationLineNo(L); 1084193326Sed 1085193326Sed // Create the ConstantStruct for the global annotation. 1086193326Sed llvm::Constant *Fields[4] = { 1087226633Sdim llvm::ConstantExpr::getBitCast(GV, Int8PtrTy), 1088226633Sdim llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 1089226633Sdim llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 1090226633Sdim LineNoCst 1091193326Sed }; 1092224145Sdim return llvm::ConstantStruct::getAnon(Fields); 1093193326Sed} 1094193326Sed 1095226633Sdimvoid CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 1096226633Sdim llvm::GlobalValue *GV) { 1097226633Sdim assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 1098226633Sdim // Get the struct elements for these annotations. 1099226633Sdim for (specific_attr_iterator<AnnotateAttr> 1100226633Sdim ai = D->specific_attr_begin<AnnotateAttr>(), 1101226633Sdim ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai) 1102226633Sdim Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation())); 1103226633Sdim} 1104226633Sdim 1105193326Sedbool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) { 1106212904Sdim // Never defer when EmitAllDecls is specified. 1107234353Sdim if (LangOpts.EmitAllDecls) 1108193326Sed return false; 1109193326Sed 1110212904Sdim return !getContext().DeclMustBeEmitted(Global); 1111193326Sed} 1112193326Sed 1113243830Sdimllvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor( 1114243830Sdim const CXXUuidofExpr* E) { 1115243830Sdim // Sema has verified that IIDSource has a __declspec(uuid()), and that its 1116243830Sdim // well-formed. 1117263508Sdim StringRef Uuid = E->getUuidAsStringRef(Context); 1118263508Sdim std::string Name = "_GUID_" + Uuid.lower(); 1119263508Sdim std::replace(Name.begin(), Name.end(), '-', '_'); 1120243830Sdim 1121243830Sdim // Look for an existing global. 1122243830Sdim if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 1123243830Sdim return GV; 1124243830Sdim 1125243830Sdim llvm::Constant *Init = EmitUuidofInitializer(Uuid, E->getType()); 1126243830Sdim assert(Init && "failed to initialize as constant"); 1127243830Sdim 1128263508Sdim llvm::GlobalVariable *GV = new llvm::GlobalVariable( 1129263508Sdim getModule(), Init->getType(), 1130263508Sdim /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 1131243830Sdim return GV; 1132243830Sdim} 1133243830Sdim 1134204793Srdivackyllvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 1135204793Srdivacky const AliasAttr *AA = VD->getAttr<AliasAttr>(); 1136204793Srdivacky assert(AA && "No alias?"); 1137204793Srdivacky 1138226633Sdim llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 1139204793Srdivacky 1140204793Srdivacky // See if there is already something with the target's name in the module. 1141205408Srdivacky llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 1142243830Sdim if (Entry) { 1143243830Sdim unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 1144243830Sdim return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 1145243830Sdim } 1146204793Srdivacky 1147204793Srdivacky llvm::Constant *Aliasee; 1148204793Srdivacky if (isa<llvm::FunctionType>(DeclTy)) 1149243830Sdim Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 1150243830Sdim GlobalDecl(cast<FunctionDecl>(VD)), 1151218893Sdim /*ForVTable=*/false); 1152204793Srdivacky else 1153205408Srdivacky Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 1154204793Srdivacky llvm::PointerType::getUnqual(DeclTy), 0); 1155204793Srdivacky 1156243830Sdim llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee); 1157243830Sdim F->setLinkage(llvm::Function::ExternalWeakLinkage); 1158243830Sdim WeakRefReferences.insert(F); 1159243830Sdim 1160204793Srdivacky return Aliasee; 1161204793Srdivacky} 1162204793Srdivacky 1163193326Sedvoid CodeGenModule::EmitGlobal(GlobalDecl GD) { 1164198092Srdivacky const ValueDecl *Global = cast<ValueDecl>(GD.getDecl()); 1165198092Srdivacky 1166204793Srdivacky // Weak references don't produce any output by themselves. 1167204793Srdivacky if (Global->hasAttr<WeakRefAttr>()) 1168204793Srdivacky return; 1169204793Srdivacky 1170193326Sed // If this is an alias definition (which otherwise looks like a declaration) 1171193326Sed // emit it now. 1172195341Sed if (Global->hasAttr<AliasAttr>()) 1173205408Srdivacky return EmitAliasDefinition(GD); 1174193326Sed 1175226633Sdim // If this is CUDA, be selective about which declarations we emit. 1176234353Sdim if (LangOpts.CUDA) { 1177226633Sdim if (CodeGenOpts.CUDAIsDevice) { 1178226633Sdim if (!Global->hasAttr<CUDADeviceAttr>() && 1179226633Sdim !Global->hasAttr<CUDAGlobalAttr>() && 1180226633Sdim !Global->hasAttr<CUDAConstantAttr>() && 1181226633Sdim !Global->hasAttr<CUDASharedAttr>()) 1182226633Sdim return; 1183226633Sdim } else { 1184226633Sdim if (!Global->hasAttr<CUDAHostAttr>() && ( 1185226633Sdim Global->hasAttr<CUDADeviceAttr>() || 1186226633Sdim Global->hasAttr<CUDAConstantAttr>() || 1187226633Sdim Global->hasAttr<CUDASharedAttr>())) 1188226633Sdim return; 1189226633Sdim } 1190226633Sdim } 1191226633Sdim 1192193326Sed // Ignore declarations, they will be emitted on their first use. 1193193326Sed if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 1194226633Sdim // Forward declarations are emitted lazily on first use. 1195226633Sdim if (!FD->doesThisDeclarationHaveABody()) { 1196226633Sdim if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 1197226633Sdim return; 1198212904Sdim 1199226633Sdim const FunctionDecl *InlineDefinition = 0; 1200226633Sdim FD->getBody(InlineDefinition); 1201226633Sdim 1202226633Sdim StringRef MangledName = getMangledName(GD); 1203234353Sdim DeferredDecls.erase(MangledName); 1204226633Sdim EmitGlobalDefinition(InlineDefinition); 1205193326Sed return; 1206226633Sdim } 1207193326Sed } else { 1208193326Sed const VarDecl *VD = cast<VarDecl>(Global); 1209193326Sed assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 1210193326Sed 1211203955Srdivacky if (VD->isThisDeclarationADefinition() != VarDecl::Definition) 1212193326Sed return; 1213193326Sed } 1214193326Sed 1215193326Sed // Defer code generation when possible if this is a static definition, inline 1216193326Sed // function etc. These we only want to emit if they are used. 1217207619Srdivacky if (!MayDeferGeneration(Global)) { 1218207619Srdivacky // Emit the definition if it can't be deferred. 1219207619Srdivacky EmitGlobalDefinition(GD); 1220193326Sed return; 1221193326Sed } 1222212904Sdim 1223212904Sdim // If we're deferring emission of a C++ variable with an 1224212904Sdim // initializer, remember the order in which it appeared in the file. 1225234353Sdim if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 1226212904Sdim cast<VarDecl>(Global)->hasInit()) { 1227212904Sdim DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 1228212904Sdim CXXGlobalInits.push_back(0); 1229212904Sdim } 1230207619Srdivacky 1231207619Srdivacky // If the value has already been used, add it directly to the 1232207619Srdivacky // DeferredDeclsToEmit list. 1233226633Sdim StringRef MangledName = getMangledName(GD); 1234207619Srdivacky if (GetGlobalValue(MangledName)) 1235207619Srdivacky DeferredDeclsToEmit.push_back(GD); 1236207619Srdivacky else { 1237207619Srdivacky // Otherwise, remember that we saw a deferred decl with this name. The 1238207619Srdivacky // first use of the mangled name will cause it to move into 1239207619Srdivacky // DeferredDeclsToEmit. 1240207619Srdivacky DeferredDecls[MangledName] = GD; 1241207619Srdivacky } 1242193326Sed} 1243193326Sed 1244228379Sdimnamespace { 1245228379Sdim struct FunctionIsDirectlyRecursive : 1246228379Sdim public RecursiveASTVisitor<FunctionIsDirectlyRecursive> { 1247228379Sdim const StringRef Name; 1248234353Sdim const Builtin::Context &BI; 1249228379Sdim bool Result; 1250234353Sdim FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) : 1251234353Sdim Name(N), BI(C), Result(false) { 1252228379Sdim } 1253228379Sdim typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base; 1254228379Sdim 1255228379Sdim bool TraverseCallExpr(CallExpr *E) { 1256234353Sdim const FunctionDecl *FD = E->getDirectCallee(); 1257234353Sdim if (!FD) 1258228379Sdim return true; 1259234353Sdim AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1260234353Sdim if (Attr && Name == Attr->getLabel()) { 1261234353Sdim Result = true; 1262234353Sdim return false; 1263234353Sdim } 1264234353Sdim unsigned BuiltinID = FD->getBuiltinID(); 1265234353Sdim if (!BuiltinID) 1266228379Sdim return true; 1267234353Sdim StringRef BuiltinName = BI.GetName(BuiltinID); 1268234353Sdim if (BuiltinName.startswith("__builtin_") && 1269234353Sdim Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 1270228379Sdim Result = true; 1271228379Sdim return false; 1272228379Sdim } 1273228379Sdim return true; 1274228379Sdim } 1275228379Sdim }; 1276228379Sdim} 1277228379Sdim 1278234353Sdim// isTriviallyRecursive - Check if this function calls another 1279234353Sdim// decl that, because of the asm attribute or the other decl being a builtin, 1280234353Sdim// ends up pointing to itself. 1281228379Sdimbool 1282234353SdimCodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 1283234353Sdim StringRef Name; 1284234353Sdim if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 1285234353Sdim // asm labels are a special kind of mangling we have to support. 1286234353Sdim AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1287234353Sdim if (!Attr) 1288234353Sdim return false; 1289234353Sdim Name = Attr->getLabel(); 1290234353Sdim } else { 1291234353Sdim Name = FD->getName(); 1292234353Sdim } 1293228379Sdim 1294234353Sdim FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 1295234353Sdim Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD)); 1296228379Sdim return Walker.Result; 1297228379Sdim} 1298228379Sdim 1299228379Sdimbool 1300263508SdimCodeGenModule::shouldEmitFunction(GlobalDecl GD) { 1301263508Sdim if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 1302228379Sdim return true; 1303263508Sdim const FunctionDecl *F = cast<FunctionDecl>(GD.getDecl()); 1304228379Sdim if (CodeGenOpts.OptimizationLevel == 0 && 1305239462Sdim !F->hasAttr<AlwaysInlineAttr>() && !F->hasAttr<ForceInlineAttr>()) 1306228379Sdim return false; 1307228379Sdim // PR9614. Avoid cases where the source code is lying to us. An available 1308228379Sdim // externally function should have an equivalent function somewhere else, 1309228379Sdim // but a function that calls itself is clearly not equivalent to the real 1310228379Sdim // implementation. 1311228379Sdim // This happens in glibc's btowc and in some configure checks. 1312234353Sdim return !isTriviallyRecursive(F); 1313228379Sdim} 1314228379Sdim 1315263508Sdim/// If the type for the method's class was generated by 1316263508Sdim/// CGDebugInfo::createContextChain(), the cache contains only a 1317263508Sdim/// limited DIType without any declarations. Since EmitFunctionStart() 1318263508Sdim/// needs to find the canonical declaration for each method, we need 1319263508Sdim/// to construct the complete type prior to emitting the method. 1320263508Sdimvoid CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) { 1321263508Sdim if (!D->isInstance()) 1322263508Sdim return; 1323263508Sdim 1324263508Sdim if (CGDebugInfo *DI = getModuleDebugInfo()) 1325263508Sdim if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) { 1326263508Sdim const PointerType *ThisPtr = 1327263508Sdim cast<PointerType>(D->getThisType(getContext())); 1328263508Sdim DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation()); 1329263508Sdim } 1330263508Sdim} 1331263508Sdim 1332193326Sedvoid CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) { 1333198092Srdivacky const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 1334198092Srdivacky 1335207619Srdivacky PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 1336198893Srdivacky Context.getSourceManager(), 1337198893Srdivacky "Generating code for declaration"); 1338198893Srdivacky 1339263508Sdim if (isa<FunctionDecl>(D)) { 1340210299Sed // At -O0, don't generate IR for functions with available_externally 1341210299Sed // linkage. 1342263508Sdim if (!shouldEmitFunction(GD)) 1343210299Sed return; 1344206084Srdivacky 1345210299Sed if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 1346263508Sdim CompleteDIClassType(Method); 1347223017Sdim // Make sure to emit the definition(s) before we emit the thunks. 1348223017Sdim // This is necessary for the generation of certain thunks. 1349223017Sdim if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method)) 1350223017Sdim EmitCXXConstructor(CD, GD.getCtorType()); 1351223017Sdim else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method)) 1352223017Sdim EmitCXXDestructor(DD, GD.getDtorType()); 1353223017Sdim else 1354223017Sdim EmitGlobalFunctionDefinition(GD); 1355223017Sdim 1356210299Sed if (Method->isVirtual()) 1357210299Sed getVTables().EmitThunks(GD); 1358210299Sed 1359223017Sdim return; 1360210299Sed } 1361207619Srdivacky 1362207619Srdivacky return EmitGlobalFunctionDefinition(GD); 1363210299Sed } 1364207619Srdivacky 1365207619Srdivacky if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1366207619Srdivacky return EmitGlobalVarDefinition(VD); 1367207619Srdivacky 1368226633Sdim llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 1369193326Sed} 1370193326Sed 1371193326Sed/// GetOrCreateLLVMFunction - If the specified mangled name is not in the 1372193326Sed/// module, create and return an llvm Function with the specified type. If there 1373193326Sed/// is something in the module with the specified name, return it potentially 1374193326Sed/// bitcasted to the right type. 1375193326Sed/// 1376193326Sed/// If D is non-null, it specifies a decl that correspond to this. This is used 1377193326Sed/// to set the attributes on the function when it is first created. 1378205408Srdivackyllvm::Constant * 1379226633SdimCodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName, 1380226633Sdim llvm::Type *Ty, 1381263508Sdim GlobalDecl GD, bool ForVTable, 1382249423Sdim llvm::AttributeSet ExtraAttrs) { 1383263508Sdim const Decl *D = GD.getDecl(); 1384263508Sdim 1385193326Sed // Lookup the entry, lazily creating it if necessary. 1386205408Srdivacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1387193326Sed if (Entry) { 1388243830Sdim if (WeakRefReferences.erase(Entry)) { 1389263508Sdim const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 1390204793Srdivacky if (FD && !FD->hasAttr<WeakAttr>()) 1391206084Srdivacky Entry->setLinkage(llvm::Function::ExternalLinkage); 1392204793Srdivacky } 1393204793Srdivacky 1394193326Sed if (Entry->getType()->getElementType() == Ty) 1395193326Sed return Entry; 1396198092Srdivacky 1397193326Sed // Make sure the result is of the correct type. 1398224145Sdim return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 1399193326Sed } 1400198092Srdivacky 1401263508Sdim // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 1402263508Sdim // each other bottoming out with the base dtor. Therefore we emit non-base 1403263508Sdim // dtors on usage, even if there is no dtor definition in the TU. 1404263508Sdim if (D && isa<CXXDestructorDecl>(D) && 1405263508Sdim getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 1406263508Sdim GD.getDtorType())) 1407263508Sdim DeferredDeclsToEmit.push_back(GD); 1408263508Sdim 1409199482Srdivacky // This function doesn't have a complete type (for example, the return 1410199482Srdivacky // type is an incomplete struct). Use a fake type instead, and make 1411199482Srdivacky // sure not to try to set attributes. 1412199482Srdivacky bool IsIncompleteFunction = false; 1413207619Srdivacky 1414226633Sdim llvm::FunctionType *FTy; 1415207619Srdivacky if (isa<llvm::FunctionType>(Ty)) { 1416207619Srdivacky FTy = cast<llvm::FunctionType>(Ty); 1417207619Srdivacky } else { 1418223017Sdim FTy = llvm::FunctionType::get(VoidTy, false); 1419199482Srdivacky IsIncompleteFunction = true; 1420199482Srdivacky } 1421210299Sed 1422207619Srdivacky llvm::Function *F = llvm::Function::Create(FTy, 1423199482Srdivacky llvm::Function::ExternalLinkage, 1424205408Srdivacky MangledName, &getModule()); 1425205408Srdivacky assert(F->getName() == MangledName && "name was uniqued!"); 1426263508Sdim if (D) 1427263508Sdim SetFunctionAttributes(GD, F, IsIncompleteFunction); 1428249423Sdim if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) { 1429249423Sdim llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex); 1430249423Sdim F->addAttributes(llvm::AttributeSet::FunctionIndex, 1431249423Sdim llvm::AttributeSet::get(VMContext, 1432249423Sdim llvm::AttributeSet::FunctionIndex, 1433249423Sdim B)); 1434249423Sdim } 1435199482Srdivacky 1436193326Sed // This is the first use or definition of a mangled name. If there is a 1437193326Sed // deferred decl with this name, remember that we need to emit it at the end 1438193326Sed // of the file. 1439205408Srdivacky llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 1440193326Sed if (DDI != DeferredDecls.end()) { 1441193326Sed // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 1442193326Sed // list, and remove it from DeferredDecls (since we don't need it anymore). 1443193326Sed DeferredDeclsToEmit.push_back(DDI->second); 1444193326Sed DeferredDecls.erase(DDI); 1445218893Sdim 1446263508Sdim // Otherwise, if this is a sized deallocation function, emit a weak definition 1447263508Sdim // for it at the end of the translation unit. 1448263508Sdim } else if (D && cast<FunctionDecl>(D) 1449263508Sdim ->getCorrespondingUnsizedGlobalDeallocationFunction()) { 1450263508Sdim DeferredDeclsToEmit.push_back(GD); 1451263508Sdim 1452218893Sdim // Otherwise, there are cases we have to worry about where we're 1453218893Sdim // using a declaration for which we must emit a definition but where 1454218893Sdim // we might not find a top-level definition: 1455218893Sdim // - member functions defined inline in their classes 1456218893Sdim // - friend functions defined inline in some class 1457218893Sdim // - special member functions with implicit definitions 1458218893Sdim // If we ever change our AST traversal to walk into class methods, 1459218893Sdim // this will be unnecessary. 1460218893Sdim // 1461218893Sdim // We also don't emit a definition for a function if it's going to be an entry 1462218893Sdim // in a vtable, unless it's already marked as used. 1463263508Sdim } else if (getLangOpts().CPlusPlus && D) { 1464218893Sdim // Look for a declaration that's lexically in a record. 1465263508Sdim const FunctionDecl *FD = cast<FunctionDecl>(D); 1466239462Sdim FD = FD->getMostRecentDecl(); 1467218893Sdim do { 1468218893Sdim if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 1469218893Sdim if (FD->isImplicit() && !ForVTable) { 1470218893Sdim assert(FD->isUsed() && "Sema didn't mark implicit function as used!"); 1471263508Sdim DeferredDeclsToEmit.push_back(GD.getWithDecl(FD)); 1472218893Sdim break; 1473223017Sdim } else if (FD->doesThisDeclarationHaveABody()) { 1474263508Sdim DeferredDeclsToEmit.push_back(GD.getWithDecl(FD)); 1475218893Sdim break; 1476218893Sdim } 1477204643Srdivacky } 1478234353Sdim FD = FD->getPreviousDecl(); 1479218893Sdim } while (FD); 1480193326Sed } 1481198092Srdivacky 1482207619Srdivacky // Make sure the result is of the requested type. 1483207619Srdivacky if (!IsIncompleteFunction) { 1484207619Srdivacky assert(F->getType()->getElementType() == Ty); 1485207619Srdivacky return F; 1486207619Srdivacky } 1487207619Srdivacky 1488224145Sdim llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 1489207619Srdivacky return llvm::ConstantExpr::getBitCast(F, PTy); 1490193326Sed} 1491193326Sed 1492193326Sed/// GetAddrOfFunction - Return the address of the given function. If Ty is 1493193326Sed/// non-null, then this function will use the specified type if it has to 1494193326Sed/// create it (this occurs when we see a definition of the function). 1495193326Sedllvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 1496226633Sdim llvm::Type *Ty, 1497218893Sdim bool ForVTable) { 1498193326Sed // If there was no specific requested type, just convert it now. 1499193326Sed if (!Ty) 1500198092Srdivacky Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType()); 1501210299Sed 1502226633Sdim StringRef MangledName = getMangledName(GD); 1503218893Sdim return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable); 1504193326Sed} 1505193326Sed 1506193326Sed/// CreateRuntimeFunction - Create a new runtime function with the specified 1507193326Sed/// type and name. 1508193326Sedllvm::Constant * 1509226633SdimCodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, 1510226633Sdim StringRef Name, 1511249423Sdim llvm::AttributeSet ExtraAttrs) { 1512249423Sdim llvm::Constant *C 1513249423Sdim = GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 1514249423Sdim ExtraAttrs); 1515249423Sdim if (llvm::Function *F = dyn_cast<llvm::Function>(C)) 1516249423Sdim if (F->empty()) 1517249423Sdim F->setCallingConv(getRuntimeCC()); 1518249423Sdim return C; 1519193326Sed} 1520193326Sed 1521234353Sdim/// isTypeConstant - Determine whether an object of this type can be emitted 1522234353Sdim/// as a constant. 1523234353Sdim/// 1524234353Sdim/// If ExcludeCtor is true, the duration when the object's constructor runs 1525234353Sdim/// will not be considered. The caller will need to verify that the object is 1526234353Sdim/// not written to during its construction. 1527234353Sdimbool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 1528234353Sdim if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 1529200583Srdivacky return false; 1530234353Sdim 1531234353Sdim if (Context.getLangOpts().CPlusPlus) { 1532234353Sdim if (const CXXRecordDecl *Record 1533234353Sdim = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 1534234353Sdim return ExcludeCtor && !Record->hasMutableFields() && 1535234353Sdim Record->hasTrivialDestructor(); 1536200583Srdivacky } 1537234353Sdim 1538200583Srdivacky return true; 1539200583Srdivacky} 1540200583Srdivacky 1541193326Sed/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 1542193326Sed/// create and return an llvm GlobalVariable with the specified type. If there 1543193326Sed/// is something in the module with the specified name, return it potentially 1544193326Sed/// bitcasted to the right type. 1545193326Sed/// 1546193326Sed/// If D is non-null, it specifies a decl that correspond to this. This is used 1547193326Sed/// to set the attributes on the global when it is first created. 1548205408Srdivackyllvm::Constant * 1549226633SdimCodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, 1550226633Sdim llvm::PointerType *Ty, 1551218893Sdim const VarDecl *D, 1552218893Sdim bool UnnamedAddr) { 1553193326Sed // Lookup the entry, lazily creating it if necessary. 1554205408Srdivacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1555193326Sed if (Entry) { 1556243830Sdim if (WeakRefReferences.erase(Entry)) { 1557204793Srdivacky if (D && !D->hasAttr<WeakAttr>()) 1558206084Srdivacky Entry->setLinkage(llvm::Function::ExternalLinkage); 1559204793Srdivacky } 1560204793Srdivacky 1561218893Sdim if (UnnamedAddr) 1562218893Sdim Entry->setUnnamedAddr(true); 1563218893Sdim 1564193326Sed if (Entry->getType() == Ty) 1565193326Sed return Entry; 1566198092Srdivacky 1567193326Sed // Make sure the result is of the correct type. 1568263508Sdim if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace()) 1569263508Sdim return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty); 1570263508Sdim 1571193326Sed return llvm::ConstantExpr::getBitCast(Entry, Ty); 1572193326Sed } 1573198092Srdivacky 1574193326Sed // This is the first use or definition of a mangled name. If there is a 1575193326Sed // deferred decl with this name, remember that we need to emit it at the end 1576193326Sed // of the file. 1577205408Srdivacky llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 1578193326Sed if (DDI != DeferredDecls.end()) { 1579193326Sed // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 1580193326Sed // list, and remove it from DeferredDecls (since we don't need it anymore). 1581193326Sed DeferredDeclsToEmit.push_back(DDI->second); 1582193326Sed DeferredDecls.erase(DDI); 1583193326Sed } 1584198092Srdivacky 1585239462Sdim unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace()); 1586198092Srdivacky llvm::GlobalVariable *GV = 1587198092Srdivacky new llvm::GlobalVariable(getModule(), Ty->getElementType(), false, 1588193326Sed llvm::GlobalValue::ExternalLinkage, 1589205408Srdivacky 0, MangledName, 0, 1590239462Sdim llvm::GlobalVariable::NotThreadLocal, AddrSpace); 1591193326Sed 1592193326Sed // Handle things which are present even on external declarations. 1593193326Sed if (D) { 1594193326Sed // FIXME: This code is overly simple and should be merged with other global 1595193326Sed // handling. 1596234353Sdim GV->setConstant(isTypeConstant(D->getType(), false)); 1597193326Sed 1598218893Sdim // Set linkage and visibility in case we never see a definition. 1599249423Sdim LinkageInfo LV = D->getLinkageAndVisibility(); 1600249423Sdim if (LV.getLinkage() != ExternalLinkage) { 1601218893Sdim // Don't set internal linkage on declarations. 1602218893Sdim } else { 1603218893Sdim if (D->hasAttr<DLLImportAttr>()) 1604218893Sdim GV->setLinkage(llvm::GlobalValue::DLLImportLinkage); 1605221345Sdim else if (D->hasAttr<WeakAttr>() || D->isWeakImported()) 1606218893Sdim GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 1607193326Sed 1608218893Sdim // Set visibility on a declaration only if it's explicit. 1609249423Sdim if (LV.isVisibilityExplicit()) 1610249423Sdim GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 1611218893Sdim } 1612193326Sed 1613251662Sdim if (D->getTLSKind()) { 1614251662Sdim if (D->getTLSKind() == VarDecl::TLS_Dynamic) 1615251662Sdim CXXThreadLocals.push_back(std::make_pair(D, GV)); 1616239462Sdim setTLSMode(GV, *D); 1617251662Sdim } 1618263508Sdim 1619263508Sdim // If required by the ABI, treat declarations of static data members with 1620263508Sdim // inline initializers as definitions. 1621263508Sdim if (getCXXABI().isInlineInitializedStaticDataMemberLinkOnce() && 1622263508Sdim D->isStaticDataMember() && D->hasInit() && 1623263508Sdim !D->isThisDeclarationADefinition()) 1624263508Sdim EmitGlobalVarDefinition(D); 1625193326Sed } 1626198092Srdivacky 1627239462Sdim if (AddrSpace != Ty->getAddressSpace()) 1628263508Sdim return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty); 1629263508Sdim 1630263508Sdim return GV; 1631193326Sed} 1632193326Sed 1633193326Sed 1634218893Sdimllvm::GlobalVariable * 1635226633SdimCodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name, 1636226633Sdim llvm::Type *Ty, 1637218893Sdim llvm::GlobalValue::LinkageTypes Linkage) { 1638218893Sdim llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 1639218893Sdim llvm::GlobalVariable *OldGV = 0; 1640218893Sdim 1641218893Sdim 1642218893Sdim if (GV) { 1643218893Sdim // Check if the variable has the right type. 1644218893Sdim if (GV->getType()->getElementType() == Ty) 1645218893Sdim return GV; 1646218893Sdim 1647218893Sdim // Because C++ name mangling, the only way we can end up with an already 1648218893Sdim // existing global with the same name is if it has been declared extern "C". 1649243830Sdim assert(GV->isDeclaration() && "Declaration has wrong type!"); 1650218893Sdim OldGV = GV; 1651218893Sdim } 1652218893Sdim 1653218893Sdim // Create a new variable. 1654218893Sdim GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 1655218893Sdim Linkage, 0, Name); 1656218893Sdim 1657218893Sdim if (OldGV) { 1658218893Sdim // Replace occurrences of the old variable if needed. 1659218893Sdim GV->takeName(OldGV); 1660218893Sdim 1661218893Sdim if (!OldGV->use_empty()) { 1662218893Sdim llvm::Constant *NewPtrForOldDecl = 1663218893Sdim llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 1664218893Sdim OldGV->replaceAllUsesWith(NewPtrForOldDecl); 1665218893Sdim } 1666218893Sdim 1667218893Sdim OldGV->eraseFromParent(); 1668218893Sdim } 1669218893Sdim 1670218893Sdim return GV; 1671218893Sdim} 1672218893Sdim 1673193326Sed/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 1674193326Sed/// given global variable. If Ty is non-null and if the global doesn't exist, 1675234982Sdim/// then it will be created with the specified type instead of whatever the 1676193326Sed/// normal requested type would be. 1677193326Sedllvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 1678226633Sdim llvm::Type *Ty) { 1679193326Sed assert(D->hasGlobalStorage() && "Not a global variable"); 1680193326Sed QualType ASTTy = D->getType(); 1681193326Sed if (Ty == 0) 1682193326Sed Ty = getTypes().ConvertTypeForMem(ASTTy); 1683198092Srdivacky 1684226633Sdim llvm::PointerType *PTy = 1685221345Sdim llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 1686205408Srdivacky 1687226633Sdim StringRef MangledName = getMangledName(D); 1688205408Srdivacky return GetOrCreateLLVMGlobal(MangledName, PTy, D); 1689193326Sed} 1690193326Sed 1691193326Sed/// CreateRuntimeVariable - Create a new runtime global variable with the 1692193326Sed/// specified type and name. 1693193326Sedllvm::Constant * 1694226633SdimCodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 1695226633Sdim StringRef Name) { 1696221345Sdim return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0, 1697218893Sdim true); 1698193326Sed} 1699193326Sed 1700193326Sedvoid CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 1701193326Sed assert(!D->getInit() && "Cannot emit definite definitions here!"); 1702193326Sed 1703193326Sed if (MayDeferGeneration(D)) { 1704193326Sed // If we have not seen a reference to this variable yet, place it 1705193326Sed // into the deferred declarations table to be emitted if needed 1706193326Sed // later. 1707226633Sdim StringRef MangledName = getMangledName(D); 1708205408Srdivacky if (!GetGlobalValue(MangledName)) { 1709198092Srdivacky DeferredDecls[MangledName] = D; 1710193326Sed return; 1711193326Sed } 1712193326Sed } 1713193326Sed 1714193326Sed // The tentative definition is the only definition. 1715193326Sed EmitGlobalVarDefinition(D); 1716193326Sed} 1717193326Sed 1718226633SdimCharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 1719218893Sdim return Context.toCharUnitsFromBits( 1720243830Sdim TheDataLayout.getTypeStoreSizeInBits(Ty)); 1721203955Srdivacky} 1722203955Srdivacky 1723239462Sdimunsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D, 1724239462Sdim unsigned AddrSpace) { 1725239462Sdim if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) { 1726239462Sdim if (D->hasAttr<CUDAConstantAttr>()) 1727239462Sdim AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant); 1728239462Sdim else if (D->hasAttr<CUDASharedAttr>()) 1729239462Sdim AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared); 1730239462Sdim else 1731239462Sdim AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device); 1732239462Sdim } 1733239462Sdim 1734239462Sdim return AddrSpace; 1735239462Sdim} 1736239462Sdim 1737251662Sdimtemplate<typename SomeDecl> 1738251662Sdimvoid CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 1739251662Sdim llvm::GlobalValue *GV) { 1740251662Sdim if (!getLangOpts().CPlusPlus) 1741251662Sdim return; 1742251662Sdim 1743251662Sdim // Must have 'used' attribute, or else inline assembly can't rely on 1744251662Sdim // the name existing. 1745251662Sdim if (!D->template hasAttr<UsedAttr>()) 1746251662Sdim return; 1747251662Sdim 1748251662Sdim // Must have internal linkage and an ordinary name. 1749263508Sdim if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 1750251662Sdim return; 1751251662Sdim 1752251662Sdim // Must be in an extern "C" context. Entities declared directly within 1753251662Sdim // a record are not extern "C" even if the record is in such a context. 1754263508Sdim const SomeDecl *First = D->getFirstDecl(); 1755251662Sdim if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 1756251662Sdim return; 1757251662Sdim 1758251662Sdim // OK, this is an internal linkage entity inside an extern "C" linkage 1759251662Sdim // specification. Make a note of that so we can give it the "expected" 1760251662Sdim // mangled name if nothing else is using that name. 1761251662Sdim std::pair<StaticExternCMap::iterator, bool> R = 1762251662Sdim StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 1763251662Sdim 1764251662Sdim // If we have multiple internal linkage entities with the same name 1765251662Sdim // in extern "C" regions, none of them gets that name. 1766251662Sdim if (!R.second) 1767251662Sdim R.first->second = 0; 1768251662Sdim} 1769251662Sdim 1770193326Sedvoid CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 1771193326Sed llvm::Constant *Init = 0; 1772193326Sed QualType ASTTy = D->getType(); 1773234353Sdim CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1774234353Sdim bool NeedsGlobalCtor = false; 1775234353Sdim bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor(); 1776198092Srdivacky 1777234353Sdim const VarDecl *InitDecl; 1778234353Sdim const Expr *InitExpr = D->getAnyInitializer(InitDecl); 1779234353Sdim 1780203955Srdivacky if (!InitExpr) { 1781193326Sed // This is a tentative definition; tentative definitions are 1782193326Sed // implicitly initialized with { 0 }. 1783193326Sed // 1784193326Sed // Note that tentative definitions are only emitted at the end of 1785193326Sed // a translation unit, so they should never have incomplete 1786193326Sed // type. In addition, EmitTentativeDefinition makes sure that we 1787193326Sed // never attempt to emit a tentative definition if a real one 1788193326Sed // exists. A use may still exists, however, so we still may need 1789193326Sed // to do a RAUW. 1790193326Sed assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 1791198092Srdivacky Init = EmitNullConstant(D->getType()); 1792193326Sed } else { 1793263508Sdim initializedGlobalDecl = GlobalDecl(D); 1794263508Sdim Init = EmitConstantInit(*InitDecl); 1795234353Sdim 1796239462Sdim if (!Init) { 1797203955Srdivacky QualType T = InitExpr->getType(); 1798208600Srdivacky if (D->getType()->isReferenceType()) 1799208600Srdivacky T = D->getType(); 1800234353Sdim 1801234353Sdim if (getLangOpts().CPlusPlus) { 1802198092Srdivacky Init = EmitNullConstant(T); 1803234353Sdim NeedsGlobalCtor = true; 1804198092Srdivacky } else { 1805198092Srdivacky ErrorUnsupported(D, "static initializer"); 1806198092Srdivacky Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 1807198092Srdivacky } 1808212904Sdim } else { 1809212904Sdim // We don't need an initializer, so remove the entry for the delayed 1810234353Sdim // initializer position (just in case this entry was delayed) if we 1811234353Sdim // also don't need to register a destructor. 1812234353Sdim if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 1813212904Sdim DelayedCXXInitPosition.erase(D); 1814193326Sed } 1815193326Sed } 1816193326Sed 1817226633Sdim llvm::Type* InitType = Init->getType(); 1818193326Sed llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 1819198092Srdivacky 1820193326Sed // Strip off a bitcast if we got one back. 1821193326Sed if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1822198092Srdivacky assert(CE->getOpcode() == llvm::Instruction::BitCast || 1823263508Sdim CE->getOpcode() == llvm::Instruction::AddrSpaceCast || 1824263508Sdim // All zero index gep. 1825198092Srdivacky CE->getOpcode() == llvm::Instruction::GetElementPtr); 1826193326Sed Entry = CE->getOperand(0); 1827193326Sed } 1828198092Srdivacky 1829193326Sed // Entry is now either a Function or GlobalVariable. 1830193326Sed llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry); 1831198092Srdivacky 1832193326Sed // We have a definition after a declaration with the wrong type. 1833193326Sed // We must make a new GlobalVariable* and update everything that used OldGV 1834193326Sed // (a declaration or tentative definition) with the new GlobalVariable* 1835193326Sed // (which will be a definition). 1836193326Sed // 1837193326Sed // This happens if there is a prototype for a global (e.g. 1838193326Sed // "extern int x[];") and then a definition of a different type (e.g. 1839193326Sed // "int x[10];"). This also happens when an initializer has a different type 1840193326Sed // from the type of the global (this happens with unions). 1841193326Sed if (GV == 0 || 1842193326Sed GV->getType()->getElementType() != InitType || 1843221345Sdim GV->getType()->getAddressSpace() != 1844239462Sdim GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) { 1845198092Srdivacky 1846205408Srdivacky // Move the old entry aside so that we'll create a new one. 1847226633Sdim Entry->setName(StringRef()); 1848193326Sed 1849193326Sed // Make a new global with the correct type, this is now guaranteed to work. 1850193326Sed GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 1851193326Sed 1852193326Sed // Replace all uses of the old global with the new global 1853198092Srdivacky llvm::Constant *NewPtrForOldDecl = 1854193326Sed llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 1855193326Sed Entry->replaceAllUsesWith(NewPtrForOldDecl); 1856193326Sed 1857193326Sed // Erase the old global, since it is no longer used. 1858193326Sed cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 1859193326Sed } 1860193326Sed 1861251662Sdim MaybeHandleStaticInExternC(D, GV); 1862251662Sdim 1863226633Sdim if (D->hasAttr<AnnotateAttr>()) 1864226633Sdim AddGlobalAnnotations(D, GV); 1865193326Sed 1866193326Sed GV->setInitializer(Init); 1867198092Srdivacky 1868198092Srdivacky // If it is safe to mark the global 'constant', do so now. 1869234353Sdim GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 1870234353Sdim isTypeConstant(D->getType(), true)); 1871198092Srdivacky 1872203955Srdivacky GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 1873234353Sdim 1874218893Sdim // Set the llvm linkage type as appropriate. 1875218893Sdim llvm::GlobalValue::LinkageTypes Linkage = 1876263508Sdim GetLLVMLinkageVarDefinition(D, GV->isConstant()); 1877218893Sdim GV->setLinkage(Linkage); 1878263508Sdim 1879263508Sdim // If required by the ABI, give definitions of static data members with inline 1880263508Sdim // initializers linkonce_odr linkage. 1881263508Sdim if (getCXXABI().isInlineInitializedStaticDataMemberLinkOnce() && 1882263508Sdim D->isStaticDataMember() && InitExpr && 1883263508Sdim !InitDecl->isThisDeclarationADefinition()) 1884263508Sdim GV->setLinkage(llvm::GlobalVariable::LinkOnceODRLinkage); 1885263508Sdim 1886218893Sdim if (Linkage == llvm::GlobalVariable::CommonLinkage) 1887218893Sdim // common vars aren't constant even if declared const. 1888218893Sdim GV->setConstant(false); 1889193326Sed 1890218893Sdim SetCommonAttributes(D, GV); 1891218893Sdim 1892218893Sdim // Emit the initializer function if necessary. 1893234353Sdim if (NeedsGlobalCtor || NeedsGlobalDtor) 1894234353Sdim EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 1895218893Sdim 1896243830Sdim // If we are compiling with ASan, add metadata indicating dynamically 1897243830Sdim // initialized globals. 1898249423Sdim if (SanOpts.Address && NeedsGlobalCtor) { 1899243830Sdim llvm::Module &M = getModule(); 1900243830Sdim 1901243830Sdim llvm::NamedMDNode *DynamicInitializers = 1902243830Sdim M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals"); 1903243830Sdim llvm::Value *GlobalToAdd[] = { GV }; 1904243830Sdim llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd); 1905243830Sdim DynamicInitializers->addOperand(ThisGlobal); 1906243830Sdim } 1907243830Sdim 1908218893Sdim // Emit global variable debug information. 1909226633Sdim if (CGDebugInfo *DI = getModuleDebugInfo()) 1910243830Sdim if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 1911239462Sdim DI->EmitGlobalVariable(GV, D); 1912218893Sdim} 1913218893Sdim 1914218893Sdimllvm::GlobalValue::LinkageTypes 1915263508SdimCodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D, bool isConstant) { 1916212904Sdim GVALinkage Linkage = getContext().GetGVALinkageForVariable(D); 1917198112Srdivacky if (Linkage == GVA_Internal) 1918218893Sdim return llvm::Function::InternalLinkage; 1919195341Sed else if (D->hasAttr<DLLImportAttr>()) 1920218893Sdim return llvm::Function::DLLImportLinkage; 1921195341Sed else if (D->hasAttr<DLLExportAttr>()) 1922218893Sdim return llvm::Function::DLLExportLinkage; 1923263508Sdim else if (D->hasAttr<SelectAnyAttr>()) { 1924263508Sdim // selectany symbols are externally visible, so use weak instead of 1925263508Sdim // linkonce. MSVC optimizes away references to const selectany globals, so 1926263508Sdim // all definitions should be the same and ODR linkage should be used. 1927263508Sdim // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 1928263508Sdim return llvm::GlobalVariable::WeakODRLinkage; 1929263508Sdim } else if (D->hasAttr<WeakAttr>()) { 1930263508Sdim if (isConstant) 1931218893Sdim return llvm::GlobalVariable::WeakODRLinkage; 1932198092Srdivacky else 1933218893Sdim return llvm::GlobalVariable::WeakAnyLinkage; 1934205219Srdivacky } else if (Linkage == GVA_TemplateInstantiation || 1935205219Srdivacky Linkage == GVA_ExplicitTemplateInstantiation) 1936221345Sdim return llvm::GlobalVariable::WeakODRLinkage; 1937234353Sdim else if (!getLangOpts().CPlusPlus && 1938218893Sdim ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) || 1939218893Sdim D->getAttr<CommonAttr>()) && 1940198092Srdivacky !D->hasExternalStorage() && !D->getInit() && 1941251662Sdim !D->getAttr<SectionAttr>() && !D->getTLSKind() && 1942224145Sdim !D->getAttr<WeakImportAttr>()) { 1943212904Sdim // Thread local vars aren't considered common linkage. 1944218893Sdim return llvm::GlobalVariable::CommonLinkage; 1945251662Sdim } else if (D->getTLSKind() == VarDecl::TLS_Dynamic && 1946251662Sdim getTarget().getTriple().isMacOSX()) 1947251662Sdim // On Darwin, the backing variable for a C++11 thread_local variable always 1948251662Sdim // has internal linkage; all accesses should just be calls to the 1949251662Sdim // Itanium-specified entry point, which has the normal linkage of the 1950251662Sdim // variable. 1951251662Sdim return llvm::GlobalValue::InternalLinkage; 1952218893Sdim return llvm::GlobalVariable::ExternalLinkage; 1953193326Sed} 1954193326Sed 1955249423Sdim/// Replace the uses of a function that was declared with a non-proto type. 1956249423Sdim/// We want to silently drop extra arguments from call sites 1957249423Sdimstatic void replaceUsesOfNonProtoConstant(llvm::Constant *old, 1958249423Sdim llvm::Function *newFn) { 1959249423Sdim // Fast path. 1960249423Sdim if (old->use_empty()) return; 1961198092Srdivacky 1962249423Sdim llvm::Type *newRetTy = newFn->getReturnType(); 1963249423Sdim SmallVector<llvm::Value*, 4> newArgs; 1964193326Sed 1965249423Sdim for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 1966249423Sdim ui != ue; ) { 1967249423Sdim llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 1968249423Sdim llvm::User *user = *use; 1969198092Srdivacky 1970249423Sdim // Recognize and replace uses of bitcasts. Most calls to 1971249423Sdim // unprototyped functions will use bitcasts. 1972249423Sdim if (llvm::ConstantExpr *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 1973249423Sdim if (bitcast->getOpcode() == llvm::Instruction::BitCast) 1974249423Sdim replaceUsesOfNonProtoConstant(bitcast, newFn); 1975193326Sed continue; 1976249423Sdim } 1977193326Sed 1978249423Sdim // Recognize calls to the function. 1979249423Sdim llvm::CallSite callSite(user); 1980249423Sdim if (!callSite) continue; 1981249423Sdim if (!callSite.isCallee(use)) continue; 1982226633Sdim 1983249423Sdim // If the return types don't match exactly, then we can't 1984249423Sdim // transform this call unless it's dead. 1985249423Sdim if (callSite->getType() != newRetTy && !callSite->use_empty()) 1986249423Sdim continue; 1987226633Sdim 1988249423Sdim // Get the call site's attribute list. 1989249423Sdim SmallVector<llvm::AttributeSet, 8> newAttrs; 1990249423Sdim llvm::AttributeSet oldAttrs = callSite.getAttributes(); 1991226633Sdim 1992249423Sdim // Collect any return attributes from the call. 1993249423Sdim if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex)) 1994249423Sdim newAttrs.push_back( 1995249423Sdim llvm::AttributeSet::get(newFn->getContext(), 1996249423Sdim oldAttrs.getRetAttributes())); 1997249423Sdim 1998249423Sdim // If the function was passed too few arguments, don't transform. 1999249423Sdim unsigned newNumArgs = newFn->arg_size(); 2000249423Sdim if (callSite.arg_size() < newNumArgs) continue; 2001249423Sdim 2002249423Sdim // If extra arguments were passed, we silently drop them. 2003249423Sdim // If any of the types mismatch, we don't transform. 2004249423Sdim unsigned argNo = 0; 2005249423Sdim bool dontTransform = false; 2006249423Sdim for (llvm::Function::arg_iterator ai = newFn->arg_begin(), 2007249423Sdim ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) { 2008249423Sdim if (callSite.getArgument(argNo)->getType() != ai->getType()) { 2009249423Sdim dontTransform = true; 2010193326Sed break; 2011193326Sed } 2012226633Sdim 2013226633Sdim // Add any parameter attributes. 2014249423Sdim if (oldAttrs.hasAttributes(argNo + 1)) 2015249423Sdim newAttrs. 2016249423Sdim push_back(llvm:: 2017249423Sdim AttributeSet::get(newFn->getContext(), 2018249423Sdim oldAttrs.getParamAttributes(argNo + 1))); 2019193326Sed } 2020249423Sdim if (dontTransform) 2021193326Sed continue; 2022198092Srdivacky 2023249423Sdim if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) 2024249423Sdim newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(), 2025249423Sdim oldAttrs.getFnAttributes())); 2026226633Sdim 2027193326Sed // Okay, we can transform this. Create the new call instruction and copy 2028193326Sed // over the required information. 2029249423Sdim newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo); 2030193326Sed 2031249423Sdim llvm::CallSite newCall; 2032249423Sdim if (callSite.isCall()) { 2033249423Sdim newCall = llvm::CallInst::Create(newFn, newArgs, "", 2034249423Sdim callSite.getInstruction()); 2035249423Sdim } else { 2036249423Sdim llvm::InvokeInst *oldInvoke = 2037249423Sdim cast<llvm::InvokeInst>(callSite.getInstruction()); 2038249423Sdim newCall = llvm::InvokeInst::Create(newFn, 2039249423Sdim oldInvoke->getNormalDest(), 2040249423Sdim oldInvoke->getUnwindDest(), 2041249423Sdim newArgs, "", 2042249423Sdim callSite.getInstruction()); 2043249423Sdim } 2044249423Sdim newArgs.clear(); // for the next iteration 2045249423Sdim 2046249423Sdim if (!newCall->getType()->isVoidTy()) 2047249423Sdim newCall->takeName(callSite.getInstruction()); 2048249423Sdim newCall.setAttributes( 2049249423Sdim llvm::AttributeSet::get(newFn->getContext(), newAttrs)); 2050249423Sdim newCall.setCallingConv(callSite.getCallingConv()); 2051249423Sdim 2052193326Sed // Finally, remove the old call, replacing any uses with the new one. 2053249423Sdim if (!callSite->use_empty()) 2054249423Sdim callSite->replaceAllUsesWith(newCall.getInstruction()); 2055198092Srdivacky 2056206084Srdivacky // Copy debug location attached to CI. 2057249423Sdim if (!callSite->getDebugLoc().isUnknown()) 2058249423Sdim newCall->setDebugLoc(callSite->getDebugLoc()); 2059249423Sdim callSite->eraseFromParent(); 2060193326Sed } 2061193326Sed} 2062193326Sed 2063249423Sdim/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 2064249423Sdim/// implement a function with no prototype, e.g. "int foo() {}". If there are 2065249423Sdim/// existing call uses of the old function in the module, this adjusts them to 2066249423Sdim/// call the new function directly. 2067249423Sdim/// 2068249423Sdim/// This is not just a cleanup: the always_inline pass requires direct calls to 2069249423Sdim/// functions to be able to inline them. If there is a bitcast in the way, it 2070249423Sdim/// won't inline them. Instcombine normally deletes these calls, but it isn't 2071249423Sdim/// run at -O0. 2072249423Sdimstatic void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 2073249423Sdim llvm::Function *NewFn) { 2074249423Sdim // If we're redefining a global as a function, don't transform it. 2075249423Sdim if (!isa<llvm::Function>(Old)) return; 2076249423Sdim 2077249423Sdim replaceUsesOfNonProtoConstant(Old, NewFn); 2078249423Sdim} 2079249423Sdim 2080234353Sdimvoid CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 2081234353Sdim TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 2082234353Sdim // If we have a definition, this might be a deferred decl. If the 2083234353Sdim // instantiation is explicit, make sure we emit it at the end. 2084234353Sdim if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 2085234353Sdim GetAddrOfGlobalVar(VD); 2086249423Sdim 2087249423Sdim EmitTopLevelDecl(VD); 2088234353Sdim} 2089193326Sed 2090193326Sedvoid CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) { 2091193326Sed const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl()); 2092221345Sdim 2093221345Sdim // Compute the function info and LLVM type. 2094234353Sdim const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 2095234353Sdim llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 2096221345Sdim 2097193326Sed // Get or create the prototype for the function. 2098193326Sed llvm::Constant *Entry = GetAddrOfFunction(GD, Ty); 2099198092Srdivacky 2100193326Sed // Strip off a bitcast if we got one back. 2101193326Sed if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 2102193326Sed assert(CE->getOpcode() == llvm::Instruction::BitCast); 2103193326Sed Entry = CE->getOperand(0); 2104193326Sed } 2105198092Srdivacky 2106263508Sdim if (!cast<llvm::GlobalValue>(Entry)->isDeclaration()) { 2107263508Sdim getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name); 2108263508Sdim return; 2109263508Sdim } 2110198092Srdivacky 2111193326Sed if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) { 2112193326Sed llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry); 2113198092Srdivacky 2114193326Sed // If the types mismatch then we have to rewrite the definition. 2115193326Sed assert(OldFn->isDeclaration() && 2116193326Sed "Shouldn't replace non-declaration"); 2117193326Sed 2118193326Sed // F is the Function* for the one with the wrong type, we must make a new 2119193326Sed // Function* and update everything that used F (a declaration) with the new 2120193326Sed // Function* (which will be a definition). 2121193326Sed // 2122193326Sed // This happens if there is a prototype for a function 2123193326Sed // (e.g. "int f()") and then a definition of a different type 2124205408Srdivacky // (e.g. "int f(int x)"). Move the old function aside so that it 2125205408Srdivacky // doesn't interfere with GetAddrOfFunction. 2126226633Sdim OldFn->setName(StringRef()); 2127193326Sed llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty)); 2128198092Srdivacky 2129249423Sdim // This might be an implementation of a function without a 2130249423Sdim // prototype, in which case, try to do special replacement of 2131249423Sdim // calls which match the new prototype. The really key thing here 2132249423Sdim // is that we also potentially drop arguments from the call site 2133249423Sdim // so as to make a direct call, which makes the inliner happier 2134249423Sdim // and suppresses a number of optimizer warnings (!) about 2135249423Sdim // dropping arguments. 2136249423Sdim if (!OldFn->use_empty()) { 2137193326Sed ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn); 2138193326Sed OldFn->removeDeadConstantUsers(); 2139193326Sed } 2140198092Srdivacky 2141193326Sed // Replace uses of F with the Function we will endow with a body. 2142193326Sed if (!Entry->use_empty()) { 2143198092Srdivacky llvm::Constant *NewPtrForOldDecl = 2144193326Sed llvm::ConstantExpr::getBitCast(NewFn, Entry->getType()); 2145193326Sed Entry->replaceAllUsesWith(NewPtrForOldDecl); 2146193326Sed } 2147198092Srdivacky 2148193326Sed // Ok, delete the old function now, which is dead. 2149193326Sed OldFn->eraseFromParent(); 2150198092Srdivacky 2151193326Sed Entry = NewFn; 2152193326Sed } 2153198092Srdivacky 2154218893Sdim // We need to set linkage and visibility on the function before 2155218893Sdim // generating code for it because various parts of IR generation 2156218893Sdim // want to propagate this information down (e.g. to local static 2157218893Sdim // declarations). 2158193326Sed llvm::Function *Fn = cast<llvm::Function>(Entry); 2159263508Sdim setFunctionLinkage(GD, Fn); 2160193326Sed 2161218893Sdim // FIXME: this is redundant with part of SetFunctionDefinitionAttributes 2162218893Sdim setGlobalVisibility(Fn, D); 2163218893Sdim 2164251662Sdim MaybeHandleStaticInExternC(D, Fn); 2165251662Sdim 2166221345Sdim CodeGenFunction(*this).GenerateCode(D, Fn, FI); 2167193326Sed 2168193326Sed SetFunctionDefinitionAttributes(D, Fn); 2169193326Sed SetLLVMFunctionAttributesForDefinition(D, Fn); 2170198092Srdivacky 2171195341Sed if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 2172193326Sed AddGlobalCtor(Fn, CA->getPriority()); 2173195341Sed if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 2174193326Sed AddGlobalDtor(Fn, DA->getPriority()); 2175226633Sdim if (D->hasAttr<AnnotateAttr>()) 2176226633Sdim AddGlobalAnnotations(D, Fn); 2177193326Sed} 2178193326Sed 2179205408Srdivackyvoid CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 2180205408Srdivacky const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 2181195341Sed const AliasAttr *AA = D->getAttr<AliasAttr>(); 2182193326Sed assert(AA && "Not an alias?"); 2183193326Sed 2184226633Sdim StringRef MangledName = getMangledName(GD); 2185205408Srdivacky 2186205408Srdivacky // If there is a definition in the module, then it wins over the alias. 2187205408Srdivacky // This is dubious, but allow it to be safe. Just ignore the alias. 2188205408Srdivacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2189205408Srdivacky if (Entry && !Entry->isDeclaration()) 2190205408Srdivacky return; 2191205408Srdivacky 2192263508Sdim Aliases.push_back(GD); 2193263508Sdim 2194226633Sdim llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 2195198092Srdivacky 2196193326Sed // Create a reference to the named value. This ensures that it is emitted 2197193326Sed // if a deferred decl. 2198193326Sed llvm::Constant *Aliasee; 2199193326Sed if (isa<llvm::FunctionType>(DeclTy)) 2200243830Sdim Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 2201218893Sdim /*ForVTable=*/false); 2202193326Sed else 2203205408Srdivacky Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 2204193326Sed llvm::PointerType::getUnqual(DeclTy), 0); 2205193326Sed 2206193326Sed // Create the new alias itself, but don't set a name yet. 2207198092Srdivacky llvm::GlobalValue *GA = 2208193326Sed new llvm::GlobalAlias(Aliasee->getType(), 2209193326Sed llvm::Function::ExternalLinkage, 2210193326Sed "", Aliasee, &getModule()); 2211198092Srdivacky 2212205408Srdivacky if (Entry) { 2213205408Srdivacky assert(Entry->isDeclaration()); 2214198092Srdivacky 2215193326Sed // If there is a declaration in the module, then we had an extern followed 2216193326Sed // by the alias, as in: 2217193326Sed // extern int test6(); 2218193326Sed // ... 2219193326Sed // int test6() __attribute__((alias("test7"))); 2220193326Sed // 2221193326Sed // Remove it and replace uses of it with the alias. 2222205408Srdivacky GA->takeName(Entry); 2223198092Srdivacky 2224193326Sed Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 2225193326Sed Entry->getType())); 2226193326Sed Entry->eraseFromParent(); 2227205408Srdivacky } else { 2228210299Sed GA->setName(MangledName); 2229193326Sed } 2230198092Srdivacky 2231193326Sed // Set attributes which are particular to an alias; this is a 2232193326Sed // specialization of the attributes which may be set on a global 2233193326Sed // variable/function. 2234195341Sed if (D->hasAttr<DLLExportAttr>()) { 2235193326Sed if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2236193326Sed // The dllexport attribute is ignored for undefined symbols. 2237210299Sed if (FD->hasBody()) 2238193326Sed GA->setLinkage(llvm::Function::DLLExportLinkage); 2239193326Sed } else { 2240193326Sed GA->setLinkage(llvm::Function::DLLExportLinkage); 2241193326Sed } 2242198092Srdivacky } else if (D->hasAttr<WeakAttr>() || 2243204643Srdivacky D->hasAttr<WeakRefAttr>() || 2244221345Sdim D->isWeakImported()) { 2245193326Sed GA->setLinkage(llvm::Function::WeakAnyLinkage); 2246193326Sed } 2247193326Sed 2248193326Sed SetCommonAttributes(D, GA); 2249193326Sed} 2250193326Sed 2251224145Sdimllvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 2252226633Sdim ArrayRef<llvm::Type*> Tys) { 2253224145Sdim return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 2254224145Sdim Tys); 2255193326Sed} 2256193326Sed 2257198092Srdivackystatic llvm::StringMapEntry<llvm::Constant*> & 2258198092SrdivackyGetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map, 2259198092Srdivacky const StringLiteral *Literal, 2260198092Srdivacky bool TargetIsLSB, 2261198092Srdivacky bool &IsUTF16, 2262198092Srdivacky unsigned &StringLength) { 2263226633Sdim StringRef String = Literal->getString(); 2264212904Sdim unsigned NumBytes = String.size(); 2265198092Srdivacky 2266198092Srdivacky // Check for simple case. 2267198092Srdivacky if (!Literal->containsNonAsciiOrNull()) { 2268198092Srdivacky StringLength = NumBytes; 2269212904Sdim return Map.GetOrCreateValue(String); 2270193326Sed } 2271198092Srdivacky 2272234353Sdim // Otherwise, convert the UTF8 literals into a string of shorts. 2273234353Sdim IsUTF16 = true; 2274234353Sdim 2275234353Sdim SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 2276243830Sdim const UTF8 *FromPtr = (const UTF8 *)String.data(); 2277198092Srdivacky UTF16 *ToPtr = &ToBuf[0]; 2278198092Srdivacky 2279218893Sdim (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 2280218893Sdim &ToPtr, ToPtr + NumBytes, 2281218893Sdim strictConversion); 2282198092Srdivacky 2283198092Srdivacky // ConvertUTF8toUTF16 returns the length in ToPtr. 2284198092Srdivacky StringLength = ToPtr - &ToBuf[0]; 2285198092Srdivacky 2286234353Sdim // Add an explicit null. 2287234353Sdim *ToPtr = 0; 2288234353Sdim return Map. 2289234353Sdim GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()), 2290234353Sdim (StringLength + 1) * 2)); 2291193326Sed} 2292193326Sed 2293223017Sdimstatic llvm::StringMapEntry<llvm::Constant*> & 2294223017SdimGetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map, 2295234353Sdim const StringLiteral *Literal, 2296234353Sdim unsigned &StringLength) { 2297234353Sdim StringRef String = Literal->getString(); 2298234353Sdim StringLength = String.size(); 2299234353Sdim return Map.GetOrCreateValue(String); 2300223017Sdim} 2301223017Sdim 2302198092Srdivackyllvm::Constant * 2303198092SrdivackyCodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 2304193326Sed unsigned StringLength = 0; 2305193326Sed bool isUTF16 = false; 2306198092Srdivacky llvm::StringMapEntry<llvm::Constant*> &Entry = 2307198092Srdivacky GetConstantCFStringEntry(CFConstantStringMap, Literal, 2308243830Sdim getDataLayout().isLittleEndian(), 2309198092Srdivacky isUTF16, StringLength); 2310198092Srdivacky 2311193326Sed if (llvm::Constant *C = Entry.getValue()) 2312193326Sed return C; 2313198092Srdivacky 2314234353Sdim llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 2315193326Sed llvm::Constant *Zeros[] = { Zero, Zero }; 2316251662Sdim llvm::Value *V; 2317251662Sdim 2318198092Srdivacky // If we don't already have it, get __CFConstantStringClassReference. 2319193326Sed if (!CFConstantStringClassRef) { 2320226633Sdim llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 2321193326Sed Ty = llvm::ArrayType::get(Ty, 0); 2322198092Srdivacky llvm::Constant *GV = CreateRuntimeVariable(Ty, 2323198092Srdivacky "__CFConstantStringClassReference"); 2324193326Sed // Decay array -> ptr 2325251662Sdim V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2326251662Sdim CFConstantStringClassRef = V; 2327193326Sed } 2328251662Sdim else 2329251662Sdim V = CFConstantStringClassRef; 2330198092Srdivacky 2331193326Sed QualType CFTy = getContext().getCFConstantStringType(); 2332193326Sed 2333226633Sdim llvm::StructType *STy = 2334193326Sed cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 2335193326Sed 2336234353Sdim llvm::Constant *Fields[4]; 2337193326Sed 2338193326Sed // Class pointer. 2339251662Sdim Fields[0] = cast<llvm::ConstantExpr>(V); 2340198092Srdivacky 2341193326Sed // Flags. 2342226633Sdim llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 2343198092Srdivacky Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 2344198092Srdivacky llvm::ConstantInt::get(Ty, 0x07C8); 2345198092Srdivacky 2346193326Sed // String pointer. 2347234353Sdim llvm::Constant *C = 0; 2348234353Sdim if (isUTF16) { 2349234353Sdim ArrayRef<uint16_t> Arr = 2350249423Sdim llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>( 2351249423Sdim const_cast<char *>(Entry.getKey().data())), 2352234353Sdim Entry.getKey().size() / 2); 2353234353Sdim C = llvm::ConstantDataArray::get(VMContext, Arr); 2354234353Sdim } else { 2355234353Sdim C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey()); 2356234353Sdim } 2357193326Sed 2358198092Srdivacky llvm::GlobalValue::LinkageTypes Linkage; 2359234353Sdim if (isUTF16) 2360198092Srdivacky // FIXME: why do utf strings get "_" labels instead of "L" labels? 2361198092Srdivacky Linkage = llvm::GlobalValue::InternalLinkage; 2362234353Sdim else 2363221345Sdim // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error 2364221345Sdim // when using private linkage. It is not clear if this is a bug in ld 2365221345Sdim // or a reasonable new restriction. 2366221345Sdim Linkage = llvm::GlobalValue::LinkerPrivateLinkage; 2367198092Srdivacky 2368234353Sdim // Note: -fwritable-strings doesn't make the backing store strings of 2369234353Sdim // CFStrings writable. (See <rdar://problem/10657500>) 2370198092Srdivacky llvm::GlobalVariable *GV = 2371234353Sdim new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 2372234353Sdim Linkage, C, ".str"); 2373218893Sdim GV->setUnnamedAddr(true); 2374251662Sdim // Don't enforce the target's minimum global alignment, since the only use 2375251662Sdim // of the string is via this class initializer. 2376193326Sed if (isUTF16) { 2377203955Srdivacky CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 2378203955Srdivacky GV->setAlignment(Align.getQuantity()); 2379221345Sdim } else { 2380221345Sdim CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 2381221345Sdim GV->setAlignment(Align.getQuantity()); 2382193326Sed } 2383234353Sdim 2384234353Sdim // String. 2385226633Sdim Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2386198092Srdivacky 2387234353Sdim if (isUTF16) 2388234353Sdim // Cast the UTF16 string to the correct type. 2389234353Sdim Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy); 2390234353Sdim 2391193326Sed // String length. 2392193326Sed Ty = getTypes().ConvertType(getContext().LongTy); 2393198092Srdivacky Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 2394198092Srdivacky 2395193326Sed // The struct. 2396193326Sed C = llvm::ConstantStruct::get(STy, Fields); 2397198092Srdivacky GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 2398198092Srdivacky llvm::GlobalVariable::PrivateLinkage, C, 2399198092Srdivacky "_unnamed_cfstring_"); 2400251662Sdim if (const char *Sect = getTarget().getCFStringSection()) 2401193326Sed GV->setSection(Sect); 2402193326Sed Entry.setValue(GV); 2403198092Srdivacky 2404193326Sed return GV; 2405193326Sed} 2406193326Sed 2407226633Sdimstatic RecordDecl * 2408226633SdimCreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK, 2409226633Sdim DeclContext *DC, IdentifierInfo *Id) { 2410226633Sdim SourceLocation Loc; 2411234353Sdim if (Ctx.getLangOpts().CPlusPlus) 2412226633Sdim return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 2413226633Sdim else 2414226633Sdim return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 2415226633Sdim} 2416226633Sdim 2417207619Srdivackyllvm::Constant * 2418218893SdimCodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) { 2419207619Srdivacky unsigned StringLength = 0; 2420207619Srdivacky llvm::StringMapEntry<llvm::Constant*> &Entry = 2421223017Sdim GetConstantStringEntry(CFConstantStringMap, Literal, StringLength); 2422207619Srdivacky 2423207619Srdivacky if (llvm::Constant *C = Entry.getValue()) 2424207619Srdivacky return C; 2425207619Srdivacky 2426234353Sdim llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 2427207619Srdivacky llvm::Constant *Zeros[] = { Zero, Zero }; 2428251662Sdim llvm::Value *V; 2429207619Srdivacky // If we don't already have it, get _NSConstantStringClassReference. 2430218893Sdim if (!ConstantStringClassRef) { 2431234353Sdim std::string StringClass(getLangOpts().ObjCConstantStringClass); 2432226633Sdim llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 2433218893Sdim llvm::Constant *GV; 2434239462Sdim if (LangOpts.ObjCRuntime.isNonFragile()) { 2435223017Sdim std::string str = 2436223017Sdim StringClass.empty() ? "OBJC_CLASS_$_NSConstantString" 2437223017Sdim : "OBJC_CLASS_$_" + StringClass; 2438223017Sdim GV = getObjCRuntime().GetClassGlobal(str); 2439223017Sdim // Make sure the result is of the correct type. 2440226633Sdim llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 2441251662Sdim V = llvm::ConstantExpr::getBitCast(GV, PTy); 2442251662Sdim ConstantStringClassRef = V; 2443223017Sdim } else { 2444223017Sdim std::string str = 2445223017Sdim StringClass.empty() ? "_NSConstantStringClassReference" 2446223017Sdim : "_" + StringClass + "ClassReference"; 2447226633Sdim llvm::Type *PTy = llvm::ArrayType::get(Ty, 0); 2448223017Sdim GV = CreateRuntimeVariable(PTy, str); 2449223017Sdim // Decay array -> ptr 2450251662Sdim V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2451251662Sdim ConstantStringClassRef = V; 2452218893Sdim } 2453207619Srdivacky } 2454251662Sdim else 2455251662Sdim V = ConstantStringClassRef; 2456226633Sdim 2457226633Sdim if (!NSConstantStringType) { 2458226633Sdim // Construct the type for a constant NSString. 2459226633Sdim RecordDecl *D = CreateRecordDecl(Context, TTK_Struct, 2460226633Sdim Context.getTranslationUnitDecl(), 2461226633Sdim &Context.Idents.get("__builtin_NSString")); 2462226633Sdim D->startDefinition(); 2463226633Sdim 2464226633Sdim QualType FieldTypes[3]; 2465226633Sdim 2466226633Sdim // const int *isa; 2467226633Sdim FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst()); 2468226633Sdim // const char *str; 2469226633Sdim FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst()); 2470226633Sdim // unsigned int length; 2471226633Sdim FieldTypes[2] = Context.UnsignedIntTy; 2472226633Sdim 2473226633Sdim // Create fields 2474226633Sdim for (unsigned i = 0; i < 3; ++i) { 2475226633Sdim FieldDecl *Field = FieldDecl::Create(Context, D, 2476226633Sdim SourceLocation(), 2477226633Sdim SourceLocation(), 0, 2478226633Sdim FieldTypes[i], /*TInfo=*/0, 2479226633Sdim /*BitWidth=*/0, 2480226633Sdim /*Mutable=*/false, 2481239462Sdim ICIS_NoInit); 2482226633Sdim Field->setAccess(AS_public); 2483226633Sdim D->addDecl(Field); 2484226633Sdim } 2485226633Sdim 2486226633Sdim D->completeDefinition(); 2487226633Sdim QualType NSTy = Context.getTagDeclType(D); 2488226633Sdim NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy)); 2489226633Sdim } 2490207619Srdivacky 2491234353Sdim llvm::Constant *Fields[3]; 2492207619Srdivacky 2493207619Srdivacky // Class pointer. 2494251662Sdim Fields[0] = cast<llvm::ConstantExpr>(V); 2495207619Srdivacky 2496207619Srdivacky // String pointer. 2497234353Sdim llvm::Constant *C = 2498234353Sdim llvm::ConstantDataArray::getString(VMContext, Entry.getKey()); 2499207619Srdivacky 2500207619Srdivacky llvm::GlobalValue::LinkageTypes Linkage; 2501207619Srdivacky bool isConstant; 2502223017Sdim Linkage = llvm::GlobalValue::PrivateLinkage; 2503234353Sdim isConstant = !LangOpts.WritableStrings; 2504207619Srdivacky 2505207619Srdivacky llvm::GlobalVariable *GV = 2506207619Srdivacky new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 2507207619Srdivacky ".str"); 2508218893Sdim GV->setUnnamedAddr(true); 2509251662Sdim // Don't enforce the target's minimum global alignment, since the only use 2510251662Sdim // of the string is via this class initializer. 2511223017Sdim CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 2512223017Sdim GV->setAlignment(Align.getQuantity()); 2513226633Sdim Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2514207619Srdivacky 2515207619Srdivacky // String length. 2516226633Sdim llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 2517207619Srdivacky Fields[2] = llvm::ConstantInt::get(Ty, StringLength); 2518207619Srdivacky 2519207619Srdivacky // The struct. 2520226633Sdim C = llvm::ConstantStruct::get(NSConstantStringType, Fields); 2521207619Srdivacky GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 2522207619Srdivacky llvm::GlobalVariable::PrivateLinkage, C, 2523207619Srdivacky "_unnamed_nsstring_"); 2524207619Srdivacky // FIXME. Fix section. 2525207619Srdivacky if (const char *Sect = 2526239462Sdim LangOpts.ObjCRuntime.isNonFragile() 2527251662Sdim ? getTarget().getNSStringNonFragileABISection() 2528251662Sdim : getTarget().getNSStringSection()) 2529207619Srdivacky GV->setSection(Sect); 2530207619Srdivacky Entry.setValue(GV); 2531207619Srdivacky 2532207619Srdivacky return GV; 2533207619Srdivacky} 2534207619Srdivacky 2535226633SdimQualType CodeGenModule::getObjCFastEnumerationStateType() { 2536226633Sdim if (ObjCFastEnumerationStateType.isNull()) { 2537226633Sdim RecordDecl *D = CreateRecordDecl(Context, TTK_Struct, 2538226633Sdim Context.getTranslationUnitDecl(), 2539226633Sdim &Context.Idents.get("__objcFastEnumerationState")); 2540226633Sdim D->startDefinition(); 2541226633Sdim 2542226633Sdim QualType FieldTypes[] = { 2543226633Sdim Context.UnsignedLongTy, 2544226633Sdim Context.getPointerType(Context.getObjCIdType()), 2545226633Sdim Context.getPointerType(Context.UnsignedLongTy), 2546226633Sdim Context.getConstantArrayType(Context.UnsignedLongTy, 2547226633Sdim llvm::APInt(32, 5), ArrayType::Normal, 0) 2548226633Sdim }; 2549226633Sdim 2550226633Sdim for (size_t i = 0; i < 4; ++i) { 2551226633Sdim FieldDecl *Field = FieldDecl::Create(Context, 2552226633Sdim D, 2553226633Sdim SourceLocation(), 2554226633Sdim SourceLocation(), 0, 2555226633Sdim FieldTypes[i], /*TInfo=*/0, 2556226633Sdim /*BitWidth=*/0, 2557226633Sdim /*Mutable=*/false, 2558239462Sdim ICIS_NoInit); 2559226633Sdim Field->setAccess(AS_public); 2560226633Sdim D->addDecl(Field); 2561226633Sdim } 2562226633Sdim 2563226633Sdim D->completeDefinition(); 2564226633Sdim ObjCFastEnumerationStateType = Context.getTagDeclType(D); 2565226633Sdim } 2566226633Sdim 2567226633Sdim return ObjCFastEnumerationStateType; 2568226633Sdim} 2569226633Sdim 2570234353Sdimllvm::Constant * 2571234353SdimCodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 2572234353Sdim assert(!E->getType()->isPointerType() && "Strings are always arrays"); 2573234353Sdim 2574234353Sdim // Don't emit it as the address of the string, emit the string data itself 2575234353Sdim // as an inline array. 2576234353Sdim if (E->getCharByteWidth() == 1) { 2577234353Sdim SmallString<64> Str(E->getString()); 2578198092Srdivacky 2579234353Sdim // Resize the string to the right size, which is indicated by its type. 2580234353Sdim const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 2581234353Sdim Str.resize(CAT->getSize().getZExtValue()); 2582234353Sdim return llvm::ConstantDataArray::getString(VMContext, Str, false); 2583226633Sdim } 2584234353Sdim 2585234353Sdim llvm::ArrayType *AType = 2586234353Sdim cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 2587234353Sdim llvm::Type *ElemTy = AType->getElementType(); 2588234353Sdim unsigned NumElements = AType->getNumElements(); 2589198092Srdivacky 2590234353Sdim // Wide strings have either 2-byte or 4-byte elements. 2591234353Sdim if (ElemTy->getPrimitiveSizeInBits() == 16) { 2592234353Sdim SmallVector<uint16_t, 32> Elements; 2593234353Sdim Elements.reserve(NumElements); 2594198092Srdivacky 2595234353Sdim for(unsigned i = 0, e = E->getLength(); i != e; ++i) 2596234353Sdim Elements.push_back(E->getCodeUnit(i)); 2597234353Sdim Elements.resize(NumElements); 2598234353Sdim return llvm::ConstantDataArray::get(VMContext, Elements); 2599234353Sdim } 2600234353Sdim 2601234353Sdim assert(ElemTy->getPrimitiveSizeInBits() == 32); 2602234353Sdim SmallVector<uint32_t, 32> Elements; 2603234353Sdim Elements.reserve(NumElements); 2604234353Sdim 2605234353Sdim for(unsigned i = 0, e = E->getLength(); i != e; ++i) 2606234353Sdim Elements.push_back(E->getCodeUnit(i)); 2607234353Sdim Elements.resize(NumElements); 2608234353Sdim return llvm::ConstantDataArray::get(VMContext, Elements); 2609193326Sed} 2610193326Sed 2611193326Sed/// GetAddrOfConstantStringFromLiteral - Return a pointer to a 2612193326Sed/// constant array for the given string literal. 2613193326Sedllvm::Constant * 2614193326SedCodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 2615251662Sdim CharUnits Align = getContext().getAlignOfGlobalVarInChars(S->getType()); 2616234353Sdim if (S->isAscii() || S->isUTF8()) { 2617234353Sdim SmallString<64> Str(S->getString()); 2618234353Sdim 2619234353Sdim // Resize the string to the right size, which is indicated by its type. 2620234353Sdim const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType()); 2621234353Sdim Str.resize(CAT->getSize().getZExtValue()); 2622234353Sdim return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity()); 2623199482Srdivacky } 2624234353Sdim 2625234353Sdim // FIXME: the following does not memoize wide strings. 2626234353Sdim llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 2627234353Sdim llvm::GlobalVariable *GV = 2628234353Sdim new llvm::GlobalVariable(getModule(),C->getType(), 2629234353Sdim !LangOpts.WritableStrings, 2630234353Sdim llvm::GlobalValue::PrivateLinkage, 2631234353Sdim C,".str"); 2632234353Sdim 2633234353Sdim GV->setAlignment(Align.getQuantity()); 2634234353Sdim GV->setUnnamedAddr(true); 2635234353Sdim return GV; 2636193326Sed} 2637193326Sed 2638193326Sed/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 2639193326Sed/// array for the given ObjCEncodeExpr node. 2640193326Sedllvm::Constant * 2641193326SedCodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 2642193326Sed std::string Str; 2643193326Sed getContext().getObjCEncodingForType(E->getEncodedType(), Str); 2644193326Sed 2645193326Sed return GetAddrOfConstantCString(Str); 2646193326Sed} 2647193326Sed 2648193326Sed 2649193326Sed/// GenerateWritableString -- Creates storage for a string literal. 2650226633Sdimstatic llvm::GlobalVariable *GenerateStringLiteral(StringRef str, 2651193326Sed bool constant, 2652193326Sed CodeGenModule &CGM, 2653226633Sdim const char *GlobalName, 2654226633Sdim unsigned Alignment) { 2655193326Sed // Create Constant for this string literal. Don't add a '\0'. 2656198092Srdivacky llvm::Constant *C = 2657234353Sdim llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false); 2658198092Srdivacky 2659263508Sdim // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 2660263508Sdim unsigned AddrSpace = 0; 2661263508Sdim if (CGM.getLangOpts().OpenCL) 2662263508Sdim AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant); 2663263508Sdim 2664193326Sed // Create a global variable for this string 2665263508Sdim llvm::GlobalVariable *GV = new llvm::GlobalVariable( 2666263508Sdim CGM.getModule(), C->getType(), constant, 2667263508Sdim llvm::GlobalValue::PrivateLinkage, C, GlobalName, 0, 2668263508Sdim llvm::GlobalVariable::NotThreadLocal, AddrSpace); 2669226633Sdim GV->setAlignment(Alignment); 2670218893Sdim GV->setUnnamedAddr(true); 2671218893Sdim return GV; 2672193326Sed} 2673193326Sed 2674193326Sed/// GetAddrOfConstantString - Returns a pointer to a character array 2675193326Sed/// containing the literal. This contents are exactly that of the 2676193326Sed/// given string, i.e. it will not be null terminated automatically; 2677193326Sed/// see GetAddrOfConstantCString. Note that whether the result is 2678193326Sed/// actually a pointer to an LLVM constant depends on 2679193326Sed/// Feature.WriteableStrings. 2680193326Sed/// 2681193326Sed/// The result has pointer to array type. 2682226633Sdimllvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str, 2683226633Sdim const char *GlobalName, 2684226633Sdim unsigned Alignment) { 2685193326Sed // Get the default prefix if a name wasn't specified. 2686193326Sed if (!GlobalName) 2687198092Srdivacky GlobalName = ".str"; 2688193326Sed 2689251662Sdim if (Alignment == 0) 2690251662Sdim Alignment = getContext().getAlignOfGlobalVarInChars(getContext().CharTy) 2691251662Sdim .getQuantity(); 2692251662Sdim 2693193326Sed // Don't share any string literals if strings aren't constant. 2694234353Sdim if (LangOpts.WritableStrings) 2695226633Sdim return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment); 2696193326Sed 2697226633Sdim llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 2698221345Sdim ConstantStringMap.GetOrCreateValue(Str); 2699198092Srdivacky 2700226633Sdim if (llvm::GlobalVariable *GV = Entry.getValue()) { 2701226633Sdim if (Alignment > GV->getAlignment()) { 2702226633Sdim GV->setAlignment(Alignment); 2703226633Sdim } 2704226633Sdim return GV; 2705226633Sdim } 2706193326Sed 2707193326Sed // Create a global variable for this. 2708234353Sdim llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName, 2709234353Sdim Alignment); 2710226633Sdim Entry.setValue(GV); 2711226633Sdim return GV; 2712193326Sed} 2713193326Sed 2714193326Sed/// GetAddrOfConstantCString - Returns a pointer to a character 2715221345Sdim/// array containing the literal and a terminating '\0' 2716193326Sed/// character. The result has pointer to array type. 2717221345Sdimllvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str, 2718226633Sdim const char *GlobalName, 2719226633Sdim unsigned Alignment) { 2720226633Sdim StringRef StrWithNull(Str.c_str(), Str.size() + 1); 2721226633Sdim return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment); 2722193326Sed} 2723193326Sed 2724263508Sdimllvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary( 2725263508Sdim const MaterializeTemporaryExpr *E, const Expr *Init) { 2726263508Sdim assert((E->getStorageDuration() == SD_Static || 2727263508Sdim E->getStorageDuration() == SD_Thread) && "not a global temporary"); 2728263508Sdim const VarDecl *VD = cast<VarDecl>(E->getExtendingDecl()); 2729263508Sdim 2730263508Sdim // If we're not materializing a subobject of the temporary, keep the 2731263508Sdim // cv-qualifiers from the type of the MaterializeTemporaryExpr. 2732263508Sdim QualType MaterializedType = Init->getType(); 2733263508Sdim if (Init == E->GetTemporaryExpr()) 2734263508Sdim MaterializedType = E->getType(); 2735263508Sdim 2736263508Sdim llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E]; 2737263508Sdim if (Slot) 2738263508Sdim return Slot; 2739263508Sdim 2740263508Sdim // FIXME: If an externally-visible declaration extends multiple temporaries, 2741263508Sdim // we need to give each temporary the same name in every translation unit (and 2742263508Sdim // we also need to make the temporaries externally-visible). 2743263508Sdim SmallString<256> Name; 2744263508Sdim llvm::raw_svector_ostream Out(Name); 2745263508Sdim getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Out); 2746263508Sdim Out.flush(); 2747263508Sdim 2748263508Sdim APValue *Value = 0; 2749263508Sdim if (E->getStorageDuration() == SD_Static) { 2750263508Sdim // We might have a cached constant initializer for this temporary. Note 2751263508Sdim // that this might have a different value from the value computed by 2752263508Sdim // evaluating the initializer if the surrounding constant expression 2753263508Sdim // modifies the temporary. 2754263508Sdim Value = getContext().getMaterializedTemporaryValue(E, false); 2755263508Sdim if (Value && Value->isUninit()) 2756263508Sdim Value = 0; 2757263508Sdim } 2758263508Sdim 2759263508Sdim // Try evaluating it now, it might have a constant initializer. 2760263508Sdim Expr::EvalResult EvalResult; 2761263508Sdim if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 2762263508Sdim !EvalResult.hasSideEffects()) 2763263508Sdim Value = &EvalResult.Val; 2764263508Sdim 2765263508Sdim llvm::Constant *InitialValue = 0; 2766263508Sdim bool Constant = false; 2767263508Sdim llvm::Type *Type; 2768263508Sdim if (Value) { 2769263508Sdim // The temporary has a constant initializer, use it. 2770263508Sdim InitialValue = EmitConstantValue(*Value, MaterializedType, 0); 2771263508Sdim Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 2772263508Sdim Type = InitialValue->getType(); 2773263508Sdim } else { 2774263508Sdim // No initializer, the initialization will be provided when we 2775263508Sdim // initialize the declaration which performed lifetime extension. 2776263508Sdim Type = getTypes().ConvertTypeForMem(MaterializedType); 2777263508Sdim } 2778263508Sdim 2779263508Sdim // Create a global variable for this lifetime-extended temporary. 2780263508Sdim llvm::GlobalVariable *GV = 2781263508Sdim new llvm::GlobalVariable(getModule(), Type, Constant, 2782263508Sdim llvm::GlobalValue::PrivateLinkage, 2783263508Sdim InitialValue, Name.c_str()); 2784263508Sdim GV->setAlignment( 2785263508Sdim getContext().getTypeAlignInChars(MaterializedType).getQuantity()); 2786263508Sdim if (VD->getTLSKind()) 2787263508Sdim setTLSMode(GV, *VD); 2788263508Sdim Slot = GV; 2789263508Sdim return GV; 2790263508Sdim} 2791263508Sdim 2792193326Sed/// EmitObjCPropertyImplementations - Emit information for synthesized 2793193326Sed/// properties for an implementation. 2794198092Srdivackyvoid CodeGenModule::EmitObjCPropertyImplementations(const 2795193326Sed ObjCImplementationDecl *D) { 2796198092Srdivacky for (ObjCImplementationDecl::propimpl_iterator 2797195341Sed i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) { 2798193326Sed ObjCPropertyImplDecl *PID = *i; 2799198092Srdivacky 2800193326Sed // Dynamic is just for type-checking. 2801193326Sed if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 2802193326Sed ObjCPropertyDecl *PD = PID->getPropertyDecl(); 2803193326Sed 2804193326Sed // Determine which methods need to be implemented, some may have 2805243830Sdim // been overridden. Note that ::isPropertyAccessor is not the method 2806193326Sed // we want, that just indicates if the decl came from a 2807193326Sed // property. What we want to know is if the method is defined in 2808193326Sed // this implementation. 2809195341Sed if (!D->getInstanceMethod(PD->getGetterName())) 2810193326Sed CodeGenFunction(*this).GenerateObjCGetter( 2811193326Sed const_cast<ObjCImplementationDecl *>(D), PID); 2812193326Sed if (!PD->isReadOnly() && 2813195341Sed !D->getInstanceMethod(PD->getSetterName())) 2814193326Sed CodeGenFunction(*this).GenerateObjCSetter( 2815193326Sed const_cast<ObjCImplementationDecl *>(D), PID); 2816193326Sed } 2817193326Sed } 2818193326Sed} 2819193326Sed 2820221345Sdimstatic bool needsDestructMethod(ObjCImplementationDecl *impl) { 2821226633Sdim const ObjCInterfaceDecl *iface = impl->getClassInterface(); 2822226633Sdim for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 2823221345Sdim ivar; ivar = ivar->getNextIvar()) 2824221345Sdim if (ivar->getType().isDestructedType()) 2825221345Sdim return true; 2826221345Sdim 2827221345Sdim return false; 2828221345Sdim} 2829221345Sdim 2830207619Srdivacky/// EmitObjCIvarInitializations - Emit information for ivar initialization 2831207619Srdivacky/// for an implementation. 2832207619Srdivackyvoid CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 2833221345Sdim // We might need a .cxx_destruct even if we don't have any ivar initializers. 2834221345Sdim if (needsDestructMethod(D)) { 2835221345Sdim IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 2836221345Sdim Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 2837221345Sdim ObjCMethodDecl *DTORMethod = 2838221345Sdim ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(), 2839226633Sdim cxxSelector, getContext().VoidTy, 0, D, 2840226633Sdim /*isInstance=*/true, /*isVariadic=*/false, 2841243830Sdim /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true, 2842226633Sdim /*isDefined=*/false, ObjCMethodDecl::Required); 2843221345Sdim D->addInstanceMethod(DTORMethod); 2844221345Sdim CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 2845243830Sdim D->setHasDestructors(true); 2846221345Sdim } 2847221345Sdim 2848221345Sdim // If the implementation doesn't have any ivar initializers, we don't need 2849221345Sdim // a .cxx_construct. 2850221345Sdim if (D->getNumIvarInitializers() == 0) 2851207619Srdivacky return; 2852221345Sdim 2853221345Sdim IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 2854207619Srdivacky Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 2855207619Srdivacky // The constructor returns 'self'. 2856207619Srdivacky ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 2857207619Srdivacky D->getLocation(), 2858226633Sdim D->getLocation(), 2859226633Sdim cxxSelector, 2860207619Srdivacky getContext().getObjCIdType(), 0, 2861226633Sdim D, /*isInstance=*/true, 2862226633Sdim /*isVariadic=*/false, 2863243830Sdim /*isPropertyAccessor=*/true, 2864226633Sdim /*isImplicitlyDeclared=*/true, 2865226633Sdim /*isDefined=*/false, 2866207619Srdivacky ObjCMethodDecl::Required); 2867207619Srdivacky D->addInstanceMethod(CTORMethod); 2868207619Srdivacky CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 2869243830Sdim D->setHasNonZeroConstructors(true); 2870207619Srdivacky} 2871207619Srdivacky 2872193326Sed/// EmitNamespace - Emit all declarations in a namespace. 2873193326Sedvoid CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 2874195341Sed for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end(); 2875263508Sdim I != E; ++I) { 2876263508Sdim if (const VarDecl *VD = dyn_cast<VarDecl>(*I)) 2877263508Sdim if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization && 2878263508Sdim VD->getTemplateSpecializationKind() != TSK_Undeclared) 2879263508Sdim continue; 2880193326Sed EmitTopLevelDecl(*I); 2881263508Sdim } 2882193326Sed} 2883193326Sed 2884193326Sed// EmitLinkageSpec - Emit all declarations in a linkage spec. 2885193326Sedvoid CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 2886198092Srdivacky if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 2887198092Srdivacky LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 2888193326Sed ErrorUnsupported(LSD, "linkage spec"); 2889193326Sed return; 2890193326Sed } 2891193326Sed 2892195341Sed for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end(); 2893243830Sdim I != E; ++I) { 2894243830Sdim // Meta-data for ObjC class includes references to implemented methods. 2895243830Sdim // Generate class's method definitions first. 2896243830Sdim if (ObjCImplDecl *OID = dyn_cast<ObjCImplDecl>(*I)) { 2897243830Sdim for (ObjCContainerDecl::method_iterator M = OID->meth_begin(), 2898243830Sdim MEnd = OID->meth_end(); 2899243830Sdim M != MEnd; ++M) 2900243830Sdim EmitTopLevelDecl(*M); 2901243830Sdim } 2902193326Sed EmitTopLevelDecl(*I); 2903243830Sdim } 2904193326Sed} 2905193326Sed 2906193326Sed/// EmitTopLevelDecl - Emit code for a single top level declaration. 2907193326Sedvoid CodeGenModule::EmitTopLevelDecl(Decl *D) { 2908195341Sed // Ignore dependent declarations. 2909195341Sed if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 2910195341Sed return; 2911198092Srdivacky 2912193326Sed switch (D->getKind()) { 2913198092Srdivacky case Decl::CXXConversion: 2914193326Sed case Decl::CXXMethod: 2915193326Sed case Decl::Function: 2916195341Sed // Skip function templates 2917221345Sdim if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 2918221345Sdim cast<FunctionDecl>(D)->isLateTemplateParsed()) 2919195341Sed return; 2920198092Srdivacky 2921198092Srdivacky EmitGlobal(cast<FunctionDecl>(D)); 2922198092Srdivacky break; 2923263508Sdim 2924193326Sed case Decl::Var: 2925263508Sdim // Skip variable templates 2926263508Sdim if (cast<VarDecl>(D)->getDescribedVarTemplate()) 2927263508Sdim return; 2928263508Sdim case Decl::VarTemplateSpecialization: 2929198092Srdivacky EmitGlobal(cast<VarDecl>(D)); 2930193326Sed break; 2931193326Sed 2932221345Sdim // Indirect fields from global anonymous structs and unions can be 2933221345Sdim // ignored; only the actual variable requires IR gen support. 2934221345Sdim case Decl::IndirectField: 2935221345Sdim break; 2936221345Sdim 2937193326Sed // C++ Decls 2938193326Sed case Decl::Namespace: 2939193326Sed EmitNamespace(cast<NamespaceDecl>(D)); 2940193326Sed break; 2941194613Sed // No code generation needed. 2942199482Srdivacky case Decl::UsingShadow: 2943194613Sed case Decl::Using: 2944195341Sed case Decl::ClassTemplate: 2945263508Sdim case Decl::VarTemplate: 2946263508Sdim case Decl::VarTemplatePartialSpecialization: 2947195341Sed case Decl::FunctionTemplate: 2948223017Sdim case Decl::TypeAliasTemplate: 2949223017Sdim case Decl::Block: 2950249423Sdim case Decl::Empty: 2951194613Sed break; 2952263508Sdim case Decl::NamespaceAlias: 2953263508Sdim if (CGDebugInfo *DI = getModuleDebugInfo()) 2954263508Sdim DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 2955263508Sdim return; 2956251662Sdim case Decl::UsingDirective: // using namespace X; [C++] 2957251662Sdim if (CGDebugInfo *DI = getModuleDebugInfo()) 2958251662Sdim DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 2959251662Sdim return; 2960193326Sed case Decl::CXXConstructor: 2961199990Srdivacky // Skip function templates 2962221345Sdim if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 2963221345Sdim cast<FunctionDecl>(D)->isLateTemplateParsed()) 2964199990Srdivacky return; 2965199990Srdivacky 2966263508Sdim getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 2967193326Sed break; 2968193326Sed case Decl::CXXDestructor: 2969221345Sdim if (cast<FunctionDecl>(D)->isLateTemplateParsed()) 2970221345Sdim return; 2971263508Sdim getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 2972193326Sed break; 2973194179Sed 2974194179Sed case Decl::StaticAssert: 2975194179Sed // Nothing to do. 2976194179Sed break; 2977194179Sed 2978193326Sed // Objective-C Decls 2979198092Srdivacky 2980193326Sed // Forward declarations, no (immediate) code generation. 2981193326Sed case Decl::ObjCInterface: 2982239462Sdim case Decl::ObjCCategory: 2983193326Sed break; 2984193326Sed 2985234353Sdim case Decl::ObjCProtocol: { 2986234353Sdim ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D); 2987234353Sdim if (Proto->isThisDeclarationADefinition()) 2988234353Sdim ObjCRuntime->GenerateProtocol(Proto); 2989193326Sed break; 2990234353Sdim } 2991234353Sdim 2992193326Sed case Decl::ObjCCategoryImpl: 2993193326Sed // Categories have properties but don't support synthesize so we 2994193326Sed // can ignore them here. 2995226633Sdim ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 2996193326Sed break; 2997193326Sed 2998193326Sed case Decl::ObjCImplementation: { 2999193326Sed ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D); 3000193326Sed EmitObjCPropertyImplementations(OMD); 3001207619Srdivacky EmitObjCIvarInitializations(OMD); 3002226633Sdim ObjCRuntime->GenerateClass(OMD); 3003234353Sdim // Emit global variable debug information. 3004234353Sdim if (CGDebugInfo *DI = getModuleDebugInfo()) 3005249423Sdim if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 3006249423Sdim DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 3007249423Sdim OMD->getClassInterface()), OMD->getLocation()); 3008193326Sed break; 3009198092Srdivacky } 3010193326Sed case Decl::ObjCMethod: { 3011193326Sed ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D); 3012193326Sed // If this is not a prototype, emit the body. 3013195341Sed if (OMD->getBody()) 3014193326Sed CodeGenFunction(*this).GenerateObjCMethod(OMD); 3015193326Sed break; 3016193326Sed } 3017198092Srdivacky case Decl::ObjCCompatibleAlias: 3018234353Sdim ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 3019193326Sed break; 3020193326Sed 3021193326Sed case Decl::LinkageSpec: 3022193326Sed EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 3023193326Sed break; 3024193326Sed 3025193326Sed case Decl::FileScopeAsm: { 3026193326Sed FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D); 3027226633Sdim StringRef AsmString = AD->getAsmString()->getString(); 3028198092Srdivacky 3029193326Sed const std::string &S = getModule().getModuleInlineAsm(); 3030193326Sed if (S.empty()) 3031193326Sed getModule().setModuleInlineAsm(AsmString); 3032239462Sdim else if (S.end()[-1] == '\n') 3033226633Sdim getModule().setModuleInlineAsm(S + AsmString.str()); 3034193326Sed else 3035200583Srdivacky getModule().setModuleInlineAsm(S + '\n' + AsmString.str()); 3036193326Sed break; 3037193326Sed } 3038198092Srdivacky 3039249423Sdim case Decl::Import: { 3040249423Sdim ImportDecl *Import = cast<ImportDecl>(D); 3041249423Sdim 3042249423Sdim // Ignore import declarations that come from imported modules. 3043249423Sdim if (clang::Module *Owner = Import->getOwningModule()) { 3044249423Sdim if (getLangOpts().CurrentModule.empty() || 3045249423Sdim Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule) 3046249423Sdim break; 3047249423Sdim } 3048249423Sdim 3049249423Sdim ImportedModules.insert(Import->getImportedModule()); 3050249423Sdim break; 3051249423Sdim } 3052249423Sdim 3053198092Srdivacky default: 3054193326Sed // Make sure we handled everything we should, every other kind is a 3055193326Sed // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 3056193326Sed // function. Need to recode Decl::Kind to do that easily. 3057193326Sed assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 3058193326Sed } 3059193326Sed} 3060210299Sed 3061210299Sed/// Turns the given pointer into a constant. 3062210299Sedstatic llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 3063210299Sed const void *Ptr) { 3064210299Sed uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 3065226633Sdim llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 3066210299Sed return llvm::ConstantInt::get(i64, PtrInt); 3067210299Sed} 3068210299Sed 3069210299Sedstatic void EmitGlobalDeclMetadata(CodeGenModule &CGM, 3070210299Sed llvm::NamedMDNode *&GlobalMetadata, 3071210299Sed GlobalDecl D, 3072210299Sed llvm::GlobalValue *Addr) { 3073210299Sed if (!GlobalMetadata) 3074210299Sed GlobalMetadata = 3075210299Sed CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 3076210299Sed 3077210299Sed // TODO: should we report variant information for ctors/dtors? 3078210299Sed llvm::Value *Ops[] = { 3079210299Sed Addr, 3080210299Sed GetPointerConstant(CGM.getLLVMContext(), D.getDecl()) 3081210299Sed }; 3082221345Sdim GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 3083210299Sed} 3084210299Sed 3085251662Sdim/// For each function which is declared within an extern "C" region and marked 3086251662Sdim/// as 'used', but has internal linkage, create an alias from the unmangled 3087251662Sdim/// name to the mangled name if possible. People expect to be able to refer 3088251662Sdim/// to such functions with an unmangled name from inline assembly within the 3089251662Sdim/// same translation unit. 3090251662Sdimvoid CodeGenModule::EmitStaticExternCAliases() { 3091251662Sdim for (StaticExternCMap::iterator I = StaticExternCValues.begin(), 3092251662Sdim E = StaticExternCValues.end(); 3093251662Sdim I != E; ++I) { 3094251662Sdim IdentifierInfo *Name = I->first; 3095251662Sdim llvm::GlobalValue *Val = I->second; 3096251662Sdim if (Val && !getModule().getNamedValue(Name->getName())) 3097251662Sdim AddUsedGlobal(new llvm::GlobalAlias(Val->getType(), Val->getLinkage(), 3098251662Sdim Name->getName(), Val, &getModule())); 3099251662Sdim } 3100251662Sdim} 3101251662Sdim 3102210299Sed/// Emits metadata nodes associating all the global values in the 3103210299Sed/// current module with the Decls they came from. This is useful for 3104210299Sed/// projects using IR gen as a subroutine. 3105210299Sed/// 3106210299Sed/// Since there's currently no way to associate an MDNode directly 3107210299Sed/// with an llvm::GlobalValue, we create a global named metadata 3108210299Sed/// with the name 'clang.global.decl.ptrs'. 3109210299Sedvoid CodeGenModule::EmitDeclMetadata() { 3110210299Sed llvm::NamedMDNode *GlobalMetadata = 0; 3111210299Sed 3112210299Sed // StaticLocalDeclMap 3113226633Sdim for (llvm::DenseMap<GlobalDecl,StringRef>::iterator 3114210299Sed I = MangledDeclNames.begin(), E = MangledDeclNames.end(); 3115210299Sed I != E; ++I) { 3116210299Sed llvm::GlobalValue *Addr = getModule().getNamedValue(I->second); 3117210299Sed EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr); 3118210299Sed } 3119210299Sed} 3120210299Sed 3121210299Sed/// Emits metadata nodes for all the local variables in the current 3122210299Sed/// function. 3123210299Sedvoid CodeGenFunction::EmitDeclMetadata() { 3124210299Sed if (LocalDeclMap.empty()) return; 3125210299Sed 3126210299Sed llvm::LLVMContext &Context = getLLVMContext(); 3127210299Sed 3128210299Sed // Find the unique metadata ID for this name. 3129210299Sed unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 3130210299Sed 3131210299Sed llvm::NamedMDNode *GlobalMetadata = 0; 3132210299Sed 3133210299Sed for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator 3134210299Sed I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) { 3135210299Sed const Decl *D = I->first; 3136210299Sed llvm::Value *Addr = I->second; 3137210299Sed 3138210299Sed if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 3139210299Sed llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 3140221345Sdim Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr)); 3141210299Sed } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 3142210299Sed GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 3143210299Sed EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 3144210299Sed } 3145210299Sed } 3146210299Sed} 3147212904Sdim 3148263508Sdimvoid CodeGenModule::EmitVersionIdentMetadata() { 3149263508Sdim llvm::NamedMDNode *IdentMetadata = 3150263508Sdim TheModule.getOrInsertNamedMetadata("llvm.ident"); 3151263508Sdim std::string Version = getClangFullVersion(); 3152263508Sdim llvm::LLVMContext &Ctx = TheModule.getContext(); 3153263508Sdim 3154263508Sdim llvm::Value *IdentNode[] = { 3155263508Sdim llvm::MDString::get(Ctx, Version) 3156263508Sdim }; 3157263508Sdim IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 3158263508Sdim} 3159263508Sdim 3160223017Sdimvoid CodeGenModule::EmitCoverageFile() { 3161223017Sdim if (!getCodeGenOpts().CoverageFile.empty()) { 3162223017Sdim if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) { 3163223017Sdim llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 3164223017Sdim llvm::LLVMContext &Ctx = TheModule.getContext(); 3165223017Sdim llvm::MDString *CoverageFile = 3166223017Sdim llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile); 3167223017Sdim for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 3168223017Sdim llvm::MDNode *CU = CUNode->getOperand(i); 3169223017Sdim llvm::Value *node[] = { CoverageFile, CU }; 3170223017Sdim llvm::MDNode *N = llvm::MDNode::get(Ctx, node); 3171223017Sdim GCov->addOperand(N); 3172223017Sdim } 3173223017Sdim } 3174223017Sdim } 3175223017Sdim} 3176243830Sdim 3177243830Sdimllvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid, 3178243830Sdim QualType GuidType) { 3179243830Sdim // Sema has checked that all uuid strings are of the form 3180243830Sdim // "12345678-1234-1234-1234-1234567890ab". 3181243830Sdim assert(Uuid.size() == 36); 3182263508Sdim for (unsigned i = 0; i < 36; ++i) { 3183263508Sdim if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-'); 3184263508Sdim else assert(isHexDigit(Uuid[i])); 3185243830Sdim } 3186243830Sdim 3187263508Sdim const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 }; 3188243830Sdim 3189263508Sdim llvm::Constant *Field3[8]; 3190263508Sdim for (unsigned Idx = 0; Idx < 8; ++Idx) 3191263508Sdim Field3[Idx] = llvm::ConstantInt::get( 3192263508Sdim Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16); 3193263508Sdim 3194263508Sdim llvm::Constant *Fields[4] = { 3195263508Sdim llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16), 3196263508Sdim llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16), 3197263508Sdim llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16), 3198263508Sdim llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3) 3199263508Sdim }; 3200263508Sdim 3201263508Sdim return llvm::ConstantStruct::getAnon(Fields); 3202243830Sdim} 3203