CodeGenModule.cpp revision 198112
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" 15193326Sed#include "CGDebugInfo.h" 16193326Sed#include "CodeGenFunction.h" 17193326Sed#include "CGCall.h" 18193326Sed#include "CGObjCRuntime.h" 19193326Sed#include "Mangle.h" 20193326Sed#include "clang/Frontend/CompileOptions.h" 21193326Sed#include "clang/AST/ASTContext.h" 22193326Sed#include "clang/AST/DeclObjC.h" 23193326Sed#include "clang/AST/DeclCXX.h" 24194179Sed#include "clang/Basic/Builtins.h" 25193326Sed#include "clang/Basic/Diagnostic.h" 26193326Sed#include "clang/Basic/SourceManager.h" 27193326Sed#include "clang/Basic/TargetInfo.h" 28193326Sed#include "clang/Basic/ConvertUTF.h" 29193326Sed#include "llvm/CallingConv.h" 30193326Sed#include "llvm/Module.h" 31193326Sed#include "llvm/Intrinsics.h" 32193326Sed#include "llvm/Target/TargetData.h" 33193326Sedusing namespace clang; 34193326Sedusing namespace CodeGen; 35193326Sed 36193326Sed 37193326SedCodeGenModule::CodeGenModule(ASTContext &C, const CompileOptions &compileOpts, 38193326Sed llvm::Module &M, const llvm::TargetData &TD, 39193326Sed Diagnostic &diags) 40193326Sed : BlockModule(C, M, TD, Types, *this), Context(C), 41193326Sed Features(C.getLangOptions()), CompileOpts(compileOpts), TheModule(M), 42198092Srdivacky TheTargetData(TD), Diags(diags), Types(C, M, TD), MangleCtx(C), 43198092Srdivacky VtableInfo(*this), Runtime(0), 44198092Srdivacky MemCpyFn(0), MemMoveFn(0), MemSetFn(0), CFConstantStringClassRef(0), 45198092Srdivacky VMContext(M.getContext()) { 46193326Sed 47193326Sed if (!Features.ObjC1) 48193326Sed Runtime = 0; 49193326Sed else if (!Features.NeXTRuntime) 50193326Sed Runtime = CreateGNUObjCRuntime(*this); 51193326Sed else if (Features.ObjCNonFragileABI) 52193326Sed Runtime = CreateMacNonFragileABIObjCRuntime(*this); 53193326Sed else 54193326Sed Runtime = CreateMacObjCRuntime(*this); 55193326Sed 56193326Sed // If debug info generation is enabled, create the CGDebugInfo object. 57193326Sed DebugInfo = CompileOpts.DebugInfo ? new CGDebugInfo(this) : 0; 58193326Sed} 59193326Sed 60193326SedCodeGenModule::~CodeGenModule() { 61193326Sed delete Runtime; 62193326Sed delete DebugInfo; 63193326Sed} 64193326Sed 65193326Sedvoid CodeGenModule::Release() { 66198092Srdivacky // We need to call this first because it can add deferred declarations. 67198092Srdivacky EmitCXXGlobalInitFunc(); 68198092Srdivacky 69193326Sed EmitDeferred(); 70193326Sed if (Runtime) 71193326Sed if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction()) 72193326Sed AddGlobalCtor(ObjCInitFunction); 73193326Sed EmitCtorList(GlobalCtors, "llvm.global_ctors"); 74193326Sed EmitCtorList(GlobalDtors, "llvm.global_dtors"); 75193326Sed EmitAnnotations(); 76193326Sed EmitLLVMUsed(); 77193326Sed} 78193326Sed 79193326Sed/// ErrorUnsupported - Print out an error that codegen doesn't support the 80193326Sed/// specified stmt yet. 81193326Sedvoid CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type, 82193326Sed bool OmitOnError) { 83193326Sed if (OmitOnError && getDiags().hasErrorOccurred()) 84193326Sed return; 85198092Srdivacky unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 86193326Sed "cannot compile this %0 yet"); 87193326Sed std::string Msg = Type; 88193326Sed getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 89193326Sed << Msg << S->getSourceRange(); 90193326Sed} 91193326Sed 92193326Sed/// ErrorUnsupported - Print out an error that codegen doesn't support the 93193326Sed/// specified decl yet. 94193326Sedvoid CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type, 95193326Sed bool OmitOnError) { 96193326Sed if (OmitOnError && getDiags().hasErrorOccurred()) 97193326Sed return; 98198092Srdivacky unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 99193326Sed "cannot compile this %0 yet"); 100193326Sed std::string Msg = Type; 101193326Sed getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 102193326Sed} 103193326Sed 104198092SrdivackyLangOptions::VisibilityMode 105193326SedCodeGenModule::getDeclVisibilityMode(const Decl *D) const { 106193326Sed if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 107193326Sed if (VD->getStorageClass() == VarDecl::PrivateExtern) 108193326Sed return LangOptions::Hidden; 109193326Sed 110195341Sed if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) { 111193326Sed switch (attr->getVisibility()) { 112193326Sed default: assert(0 && "Unknown visibility!"); 113198092Srdivacky case VisibilityAttr::DefaultVisibility: 114193326Sed return LangOptions::Default; 115193326Sed case VisibilityAttr::HiddenVisibility: 116193326Sed return LangOptions::Hidden; 117193326Sed case VisibilityAttr::ProtectedVisibility: 118193326Sed return LangOptions::Protected; 119193326Sed } 120193326Sed } 121193326Sed 122193326Sed return getLangOptions().getVisibilityMode(); 123193326Sed} 124193326Sed 125198092Srdivackyvoid CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 126193326Sed const Decl *D) const { 127193326Sed // Internal definitions always have default visibility. 128193326Sed if (GV->hasLocalLinkage()) { 129193326Sed GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 130193326Sed return; 131193326Sed } 132193326Sed 133193326Sed switch (getDeclVisibilityMode(D)) { 134193326Sed default: assert(0 && "Unknown visibility!"); 135193326Sed case LangOptions::Default: 136193326Sed return GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 137193326Sed case LangOptions::Hidden: 138193326Sed return GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 139193326Sed case LangOptions::Protected: 140193326Sed return GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 141193326Sed } 142193326Sed} 143193326Sed 144193326Sedconst char *CodeGenModule::getMangledName(const GlobalDecl &GD) { 145198092Srdivacky const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 146198092Srdivacky 147193326Sed if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND)) 148193326Sed return getMangledCXXCtorName(D, GD.getCtorType()); 149193326Sed if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND)) 150193326Sed return getMangledCXXDtorName(D, GD.getDtorType()); 151198092Srdivacky 152193326Sed return getMangledName(ND); 153193326Sed} 154193326Sed 155193326Sed/// \brief Retrieves the mangled name for the given declaration. 156193326Sed/// 157193326Sed/// If the given declaration requires a mangled name, returns an 158193326Sed/// const char* containing the mangled name. Otherwise, returns 159193326Sed/// the unmangled name. 160193326Sed/// 161193326Sedconst char *CodeGenModule::getMangledName(const NamedDecl *ND) { 162193326Sed // In C, functions with no attributes never need to be mangled. Fastpath them. 163193326Sed if (!getLangOptions().CPlusPlus && !ND->hasAttrs()) { 164193326Sed assert(ND->getIdentifier() && "Attempt to mangle unnamed decl."); 165193326Sed return ND->getNameAsCString(); 166193326Sed } 167198092Srdivacky 168193326Sed llvm::SmallString<256> Name; 169193326Sed llvm::raw_svector_ostream Out(Name); 170198092Srdivacky if (!mangleName(getMangleContext(), ND, Out)) { 171193326Sed assert(ND->getIdentifier() && "Attempt to mangle unnamed decl."); 172193326Sed return ND->getNameAsCString(); 173193326Sed } 174193326Sed 175193326Sed Name += '\0'; 176193326Sed return UniqueMangledName(Name.begin(), Name.end()); 177193326Sed} 178193326Sed 179193326Sedconst char *CodeGenModule::UniqueMangledName(const char *NameStart, 180193326Sed const char *NameEnd) { 181193326Sed assert(*(NameEnd - 1) == '\0' && "Mangled name must be null terminated!"); 182198092Srdivacky 183193326Sed return MangledNames.GetOrCreateValue(NameStart, NameEnd).getKeyData(); 184193326Sed} 185193326Sed 186193326Sed/// AddGlobalCtor - Add a function to the list that will be called before 187193326Sed/// main() runs. 188193326Sedvoid CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) { 189193326Sed // FIXME: Type coercion of void()* types. 190193326Sed GlobalCtors.push_back(std::make_pair(Ctor, Priority)); 191193326Sed} 192193326Sed 193193326Sed/// AddGlobalDtor - Add a function to the list that will be called 194193326Sed/// when the module is unloaded. 195193326Sedvoid CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) { 196193326Sed // FIXME: Type coercion of void()* types. 197193326Sed GlobalDtors.push_back(std::make_pair(Dtor, Priority)); 198193326Sed} 199193326Sed 200193326Sedvoid CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 201193326Sed // Ctor function type is void()*. 202193326Sed llvm::FunctionType* CtorFTy = 203198092Srdivacky llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), 204193326Sed std::vector<const llvm::Type*>(), 205193326Sed false); 206193326Sed llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 207193326Sed 208193326Sed // Get the type of a ctor entry, { i32, void ()* }. 209198092Srdivacky llvm::StructType* CtorStructTy = 210198092Srdivacky llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext), 211193326Sed llvm::PointerType::getUnqual(CtorFTy), NULL); 212193326Sed 213193326Sed // Construct the constructor and destructor arrays. 214193326Sed std::vector<llvm::Constant*> Ctors; 215193326Sed for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 216193326Sed std::vector<llvm::Constant*> S; 217198092Srdivacky S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 218198092Srdivacky I->second, false)); 219193326Sed S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)); 220193326Sed Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 221193326Sed } 222193326Sed 223193326Sed if (!Ctors.empty()) { 224193326Sed llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 225198092Srdivacky new llvm::GlobalVariable(TheModule, AT, false, 226193326Sed llvm::GlobalValue::AppendingLinkage, 227193326Sed llvm::ConstantArray::get(AT, Ctors), 228198092Srdivacky GlobalName); 229193326Sed } 230193326Sed} 231193326Sed 232193326Sedvoid CodeGenModule::EmitAnnotations() { 233193326Sed if (Annotations.empty()) 234193326Sed return; 235193326Sed 236193326Sed // Create a new global variable for the ConstantStruct in the Module. 237193326Sed llvm::Constant *Array = 238193326Sed llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(), 239193326Sed Annotations.size()), 240193326Sed Annotations); 241198092Srdivacky llvm::GlobalValue *gv = 242198092Srdivacky new llvm::GlobalVariable(TheModule, Array->getType(), false, 243198092Srdivacky llvm::GlobalValue::AppendingLinkage, Array, 244198092Srdivacky "llvm.global.annotations"); 245193326Sed gv->setSection("llvm.metadata"); 246193326Sed} 247193326Sed 248193326Sedstatic CodeGenModule::GVALinkage 249198092SrdivackyGetLinkageForFunction(ASTContext &Context, const FunctionDecl *FD, 250194613Sed const LangOptions &Features) { 251198092Srdivacky // Everything located semantically within an anonymous namespace is 252198092Srdivacky // always internal. 253198092Srdivacky if (FD->isInAnonymousNamespace()) 254198092Srdivacky return CodeGenModule::GVA_Internal; 255198092Srdivacky 256195341Sed // The kind of external linkage this function will have, if it is not 257195341Sed // inline or static. 258195341Sed CodeGenModule::GVALinkage External = CodeGenModule::GVA_StrongExternal; 259195341Sed if (Context.getLangOptions().CPlusPlus && 260198092Srdivacky FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 261195341Sed External = CodeGenModule::GVA_TemplateInstantiation; 262198092Srdivacky 263193326Sed if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 264193326Sed // C++ member functions defined inside the class are always inline. 265194613Sed if (MD->isInline() || !MD->isOutOfLine()) 266193326Sed return CodeGenModule::GVA_CXXInline; 267198092Srdivacky 268195341Sed return External; 269193326Sed } 270198092Srdivacky 271193326Sed // "static" functions get internal linkage. 272193326Sed if (FD->getStorageClass() == FunctionDecl::Static) 273193326Sed return CodeGenModule::GVA_Internal; 274193326Sed 275193326Sed if (!FD->isInline()) 276195341Sed return External; 277193326Sed 278198092Srdivacky if (!Features.CPlusPlus || FD->hasAttr<GNUInlineAttr>()) { 279198092Srdivacky // GNU or C99 inline semantics. Determine whether this symbol should be 280198092Srdivacky // externally visible. 281198092Srdivacky if (FD->isInlineDefinitionExternallyVisible()) 282198092Srdivacky return External; 283198092Srdivacky 284198092Srdivacky // C99 inline semantics, where the symbol is not externally visible. 285193326Sed return CodeGenModule::GVA_C99Inline; 286198092Srdivacky } 287193326Sed 288198092Srdivacky // C++ inline semantics 289198092Srdivacky assert(Features.CPlusPlus && "Must be in C++ mode"); 290198092Srdivacky return CodeGenModule::GVA_CXXInline; 291193326Sed} 292193326Sed 293193326Sed/// SetFunctionDefinitionAttributes - Set attributes for a global. 294193326Sed/// 295193326Sed/// FIXME: This is currently only done for aliases and functions, but not for 296193326Sed/// variables (these details are set in EmitGlobalVarDefinition for variables). 297193326Sedvoid CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D, 298193326Sed llvm::GlobalValue *GV) { 299194613Sed GVALinkage Linkage = GetLinkageForFunction(getContext(), D, Features); 300193326Sed 301193326Sed if (Linkage == GVA_Internal) { 302193326Sed GV->setLinkage(llvm::Function::InternalLinkage); 303195341Sed } else if (D->hasAttr<DLLExportAttr>()) { 304193326Sed GV->setLinkage(llvm::Function::DLLExportLinkage); 305195341Sed } else if (D->hasAttr<WeakAttr>()) { 306193326Sed GV->setLinkage(llvm::Function::WeakAnyLinkage); 307193326Sed } else if (Linkage == GVA_C99Inline) { 308193326Sed // In C99 mode, 'inline' functions are guaranteed to have a strong 309193326Sed // definition somewhere else, so we can use available_externally linkage. 310193326Sed GV->setLinkage(llvm::Function::AvailableExternallyLinkage); 311195341Sed } else if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) { 312193326Sed // In C++, the compiler has to emit a definition in every translation unit 313193326Sed // that references the function. We should use linkonce_odr because 314193326Sed // a) if all references in this translation unit are optimized away, we 315193326Sed // don't need to codegen it. b) if the function persists, it needs to be 316193326Sed // merged with other definitions. c) C++ has the ODR, so we know the 317193326Sed // definition is dependable. 318193326Sed GV->setLinkage(llvm::Function::LinkOnceODRLinkage); 319193326Sed } else { 320193326Sed assert(Linkage == GVA_StrongExternal); 321193326Sed // Otherwise, we have strong external linkage. 322193326Sed GV->setLinkage(llvm::Function::ExternalLinkage); 323193326Sed } 324193326Sed 325193326Sed SetCommonAttributes(D, GV); 326193326Sed} 327193326Sed 328193326Sedvoid CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 329198092Srdivacky const CGFunctionInfo &Info, 330193326Sed llvm::Function *F) { 331198092Srdivacky unsigned CallingConv; 332193326Sed AttributeListType AttributeList; 333198092Srdivacky ConstructAttributeList(Info, D, AttributeList, CallingConv); 334193326Sed F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(), 335198092Srdivacky AttributeList.size())); 336198092Srdivacky F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 337193326Sed} 338193326Sed 339193326Sedvoid CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 340193326Sed llvm::Function *F) { 341193326Sed if (!Features.Exceptions && !Features.ObjCNonFragileABI) 342198092Srdivacky F->addFnAttr(llvm::Attribute::NoUnwind); 343193326Sed 344195341Sed if (D->hasAttr<AlwaysInlineAttr>()) 345193326Sed F->addFnAttr(llvm::Attribute::AlwaysInline); 346198092Srdivacky 347198092Srdivacky if (D->hasAttr<NoInlineAttr>()) 348193326Sed F->addFnAttr(llvm::Attribute::NoInline); 349198092Srdivacky 350198092Srdivacky if (const AlignedAttr *AA = D->getAttr<AlignedAttr>()) 351198092Srdivacky F->setAlignment(AA->getAlignment()/8); 352198092Srdivacky // C++ ABI requires 2-byte alignment for member functions. 353198092Srdivacky if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 354198092Srdivacky F->setAlignment(2); 355193326Sed} 356193326Sed 357198092Srdivackyvoid CodeGenModule::SetCommonAttributes(const Decl *D, 358193326Sed llvm::GlobalValue *GV) { 359193326Sed setGlobalVisibility(GV, D); 360193326Sed 361195341Sed if (D->hasAttr<UsedAttr>()) 362193326Sed AddUsedGlobal(GV); 363193326Sed 364195341Sed if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 365193326Sed GV->setSection(SA->getName()); 366193326Sed} 367193326Sed 368193326Sedvoid CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 369193326Sed llvm::Function *F, 370193326Sed const CGFunctionInfo &FI) { 371193326Sed SetLLVMFunctionAttributes(D, FI, F); 372193326Sed SetLLVMFunctionAttributesForDefinition(D, F); 373193326Sed 374193326Sed F->setLinkage(llvm::Function::InternalLinkage); 375193326Sed 376193326Sed SetCommonAttributes(D, F); 377193326Sed} 378193326Sed 379193326Sedvoid CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD, 380193326Sed llvm::Function *F, 381193326Sed bool IsIncompleteFunction) { 382193326Sed if (!IsIncompleteFunction) 383193326Sed SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F); 384198092Srdivacky 385193326Sed // Only a few attributes are set on declarations; these may later be 386193326Sed // overridden by a definition. 387198092Srdivacky 388195341Sed if (FD->hasAttr<DLLImportAttr>()) { 389193326Sed F->setLinkage(llvm::Function::DLLImportLinkage); 390198092Srdivacky } else if (FD->hasAttr<WeakAttr>() || 391195341Sed FD->hasAttr<WeakImportAttr>()) { 392193326Sed // "extern_weak" is overloaded in LLVM; we probably should have 393198092Srdivacky // separate linkage types for this. 394193326Sed F->setLinkage(llvm::Function::ExternalWeakLinkage); 395193326Sed } else { 396198092Srdivacky F->setLinkage(llvm::Function::ExternalLinkage); 397193326Sed } 398193326Sed 399195341Sed if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 400193326Sed F->setSection(SA->getName()); 401193326Sed} 402193326Sed 403193326Sedvoid CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) { 404198092Srdivacky assert(!GV->isDeclaration() && 405193326Sed "Only globals with definition can force usage."); 406193326Sed LLVMUsed.push_back(GV); 407193326Sed} 408193326Sed 409193326Sedvoid CodeGenModule::EmitLLVMUsed() { 410193326Sed // Don't create llvm.used if there is no need. 411198092Srdivacky if (LLVMUsed.empty()) 412193326Sed return; 413193326Sed 414198092Srdivacky const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext); 415198092Srdivacky 416193326Sed // Convert LLVMUsed to what ConstantArray needs. 417193326Sed std::vector<llvm::Constant*> UsedArray; 418193326Sed UsedArray.resize(LLVMUsed.size()); 419193326Sed for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) { 420198092Srdivacky UsedArray[i] = 421198092Srdivacky llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]), 422198092Srdivacky i8PTy); 423193326Sed } 424198092Srdivacky 425195099Sed if (UsedArray.empty()) 426195099Sed return; 427195099Sed llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size()); 428198092Srdivacky 429198092Srdivacky llvm::GlobalVariable *GV = 430198092Srdivacky new llvm::GlobalVariable(getModule(), ATy, false, 431193326Sed llvm::GlobalValue::AppendingLinkage, 432193326Sed llvm::ConstantArray::get(ATy, UsedArray), 433198092Srdivacky "llvm.used"); 434193326Sed 435193326Sed GV->setSection("llvm.metadata"); 436193326Sed} 437193326Sed 438193326Sedvoid CodeGenModule::EmitDeferred() { 439193326Sed // Emit code for any potentially referenced deferred decls. Since a 440193326Sed // previously unused static decl may become used during the generation of code 441193326Sed // for a static function, iterate until no changes are made. 442193326Sed while (!DeferredDeclsToEmit.empty()) { 443193326Sed GlobalDecl D = DeferredDeclsToEmit.back(); 444193326Sed DeferredDeclsToEmit.pop_back(); 445193326Sed 446193326Sed // The mangled name for the decl must have been emitted in GlobalDeclMap. 447193326Sed // Look it up to see if it was defined with a stronger definition (e.g. an 448193326Sed // extern inline function with a strong function redefinition). If so, 449193326Sed // just ignore the deferred decl. 450193326Sed llvm::GlobalValue *CGRef = GlobalDeclMap[getMangledName(D)]; 451193326Sed assert(CGRef && "Deferred decl wasn't referenced?"); 452198092Srdivacky 453193326Sed if (!CGRef->isDeclaration()) 454193326Sed continue; 455198092Srdivacky 456193326Sed // Otherwise, emit the definition and move on to the next one. 457193326Sed EmitGlobalDefinition(D); 458193326Sed } 459193326Sed} 460193326Sed 461198092Srdivacky/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the 462193326Sed/// annotation information for a given GlobalValue. The annotation struct is 463198092Srdivacky/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the 464198092Srdivacky/// GlobalValue being annotated. The second field is the constant string 465198092Srdivacky/// created from the AnnotateAttr's annotation. The third field is a constant 466193326Sed/// string containing the name of the translation unit. The fourth field is 467193326Sed/// the line number in the file of the annotated value declaration. 468193326Sed/// 469193326Sed/// FIXME: this does not unique the annotation string constants, as llvm-gcc 470193326Sed/// appears to. 471193326Sed/// 472198092Srdivackyllvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 473193326Sed const AnnotateAttr *AA, 474193326Sed unsigned LineNo) { 475193326Sed llvm::Module *M = &getModule(); 476193326Sed 477193326Sed // get [N x i8] constants for the annotation string, and the filename string 478193326Sed // which are the 2nd and 3rd elements of the global annotation structure. 479198092Srdivacky const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext); 480198092Srdivacky llvm::Constant *anno = llvm::ConstantArray::get(VMContext, 481198092Srdivacky AA->getAnnotation(), true); 482198092Srdivacky llvm::Constant *unit = llvm::ConstantArray::get(VMContext, 483198092Srdivacky M->getModuleIdentifier(), 484193326Sed true); 485193326Sed 486193326Sed // Get the two global values corresponding to the ConstantArrays we just 487193326Sed // created to hold the bytes of the strings. 488198092Srdivacky llvm::GlobalValue *annoGV = 489198092Srdivacky new llvm::GlobalVariable(*M, anno->getType(), false, 490198092Srdivacky llvm::GlobalValue::PrivateLinkage, anno, 491198092Srdivacky GV->getName()); 492193326Sed // translation unit name string, emitted into the llvm.metadata section. 493193326Sed llvm::GlobalValue *unitGV = 494198092Srdivacky new llvm::GlobalVariable(*M, unit->getType(), false, 495198092Srdivacky llvm::GlobalValue::PrivateLinkage, unit, 496198092Srdivacky ".str"); 497193326Sed 498193326Sed // Create the ConstantStruct for the global annotation. 499193326Sed llvm::Constant *Fields[4] = { 500193326Sed llvm::ConstantExpr::getBitCast(GV, SBP), 501193326Sed llvm::ConstantExpr::getBitCast(annoGV, SBP), 502193326Sed llvm::ConstantExpr::getBitCast(unitGV, SBP), 503198092Srdivacky llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo) 504193326Sed }; 505198092Srdivacky return llvm::ConstantStruct::get(VMContext, Fields, 4, false); 506193326Sed} 507193326Sed 508193326Sedbool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) { 509193326Sed // Never defer when EmitAllDecls is specified or the decl has 510193326Sed // attribute used. 511195341Sed if (Features.EmitAllDecls || Global->hasAttr<UsedAttr>()) 512193326Sed return false; 513193326Sed 514193326Sed if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 515193326Sed // Constructors and destructors should never be deferred. 516198092Srdivacky if (FD->hasAttr<ConstructorAttr>() || 517195341Sed FD->hasAttr<DestructorAttr>()) 518193326Sed return false; 519193326Sed 520194613Sed GVALinkage Linkage = GetLinkageForFunction(getContext(), FD, Features); 521198092Srdivacky 522193326Sed // static, static inline, always_inline, and extern inline functions can 523193326Sed // always be deferred. Normal inline functions can be deferred in C99/C++. 524193326Sed if (Linkage == GVA_Internal || Linkage == GVA_C99Inline || 525193326Sed Linkage == GVA_CXXInline) 526193326Sed return true; 527193326Sed return false; 528193326Sed } 529198092Srdivacky 530193326Sed const VarDecl *VD = cast<VarDecl>(Global); 531193326Sed assert(VD->isFileVarDecl() && "Invalid decl"); 532193326Sed 533198092Srdivacky // We never want to defer structs that have non-trivial constructors or 534198092Srdivacky // destructors. 535198092Srdivacky 536198092Srdivacky // FIXME: Handle references. 537198092Srdivacky if (const RecordType *RT = VD->getType()->getAs<RecordType>()) { 538198092Srdivacky if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 539198092Srdivacky if (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()) 540198092Srdivacky return false; 541198092Srdivacky } 542198092Srdivacky } 543198092Srdivacky 544198112Srdivacky // Static data may be deferred, but out-of-line static data members 545198112Srdivacky // cannot be. 546198112Srdivacky // FIXME: What if the initializer has side effects? 547198112Srdivacky return VD->isInAnonymousNamespace() || 548198112Srdivacky (VD->getStorageClass() == VarDecl::Static && 549198112Srdivacky !(VD->isStaticDataMember() && VD->isOutOfLine())); 550193326Sed} 551193326Sed 552193326Sedvoid CodeGenModule::EmitGlobal(GlobalDecl GD) { 553198092Srdivacky const ValueDecl *Global = cast<ValueDecl>(GD.getDecl()); 554198092Srdivacky 555193326Sed // If this is an alias definition (which otherwise looks like a declaration) 556193326Sed // emit it now. 557195341Sed if (Global->hasAttr<AliasAttr>()) 558193326Sed return EmitAliasDefinition(Global); 559193326Sed 560193326Sed // Ignore declarations, they will be emitted on their first use. 561193326Sed if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 562193326Sed // Forward declarations are emitted lazily on first use. 563193326Sed if (!FD->isThisDeclarationADefinition()) 564193326Sed return; 565193326Sed } else { 566193326Sed const VarDecl *VD = cast<VarDecl>(Global); 567193326Sed assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 568193326Sed 569193326Sed // In C++, if this is marked "extern", defer code generation. 570193326Sed if (getLangOptions().CPlusPlus && !VD->getInit() && 571198092Srdivacky (VD->getStorageClass() == VarDecl::Extern || 572198092Srdivacky VD->isExternC())) 573193326Sed return; 574193326Sed 575193326Sed // In C, if this isn't a definition, defer code generation. 576193326Sed if (!getLangOptions().CPlusPlus && !VD->getInit()) 577193326Sed return; 578193326Sed } 579193326Sed 580193326Sed // Defer code generation when possible if this is a static definition, inline 581193326Sed // function etc. These we only want to emit if they are used. 582193326Sed if (MayDeferGeneration(Global)) { 583193326Sed // If the value has already been used, add it directly to the 584193326Sed // DeferredDeclsToEmit list. 585193326Sed const char *MangledName = getMangledName(GD); 586193326Sed if (GlobalDeclMap.count(MangledName)) 587193326Sed DeferredDeclsToEmit.push_back(GD); 588193326Sed else { 589193326Sed // Otherwise, remember that we saw a deferred decl with this name. The 590193326Sed // first use of the mangled name will cause it to move into 591193326Sed // DeferredDeclsToEmit. 592193326Sed DeferredDecls[MangledName] = GD; 593193326Sed } 594193326Sed return; 595193326Sed } 596193326Sed 597193326Sed // Otherwise emit the definition. 598193326Sed EmitGlobalDefinition(GD); 599193326Sed} 600193326Sed 601193326Sedvoid CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) { 602198092Srdivacky const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 603198092Srdivacky 604193326Sed if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 605193326Sed EmitCXXConstructor(CD, GD.getCtorType()); 606193326Sed else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D)) 607193326Sed EmitCXXDestructor(DD, GD.getDtorType()); 608193326Sed else if (isa<FunctionDecl>(D)) 609193326Sed EmitGlobalFunctionDefinition(GD); 610193326Sed else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 611193326Sed EmitGlobalVarDefinition(VD); 612193326Sed else { 613193326Sed assert(0 && "Invalid argument to EmitGlobalDefinition()"); 614193326Sed } 615193326Sed} 616193326Sed 617193326Sed/// GetOrCreateLLVMFunction - If the specified mangled name is not in the 618193326Sed/// module, create and return an llvm Function with the specified type. If there 619193326Sed/// is something in the module with the specified name, return it potentially 620193326Sed/// bitcasted to the right type. 621193326Sed/// 622193326Sed/// If D is non-null, it specifies a decl that correspond to this. This is used 623193326Sed/// to set the attributes on the function when it is first created. 624193326Sedllvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(const char *MangledName, 625193326Sed const llvm::Type *Ty, 626193326Sed GlobalDecl D) { 627193326Sed // Lookup the entry, lazily creating it if necessary. 628193326Sed llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName]; 629193326Sed if (Entry) { 630193326Sed if (Entry->getType()->getElementType() == Ty) 631193326Sed return Entry; 632198092Srdivacky 633193326Sed // Make sure the result is of the correct type. 634193326Sed const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 635193326Sed return llvm::ConstantExpr::getBitCast(Entry, PTy); 636193326Sed } 637198092Srdivacky 638193326Sed // This is the first use or definition of a mangled name. If there is a 639193326Sed // deferred decl with this name, remember that we need to emit it at the end 640193326Sed // of the file. 641198092Srdivacky llvm::DenseMap<const char*, GlobalDecl>::iterator DDI = 642193326Sed DeferredDecls.find(MangledName); 643193326Sed if (DDI != DeferredDecls.end()) { 644193326Sed // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 645193326Sed // list, and remove it from DeferredDecls (since we don't need it anymore). 646193326Sed DeferredDeclsToEmit.push_back(DDI->second); 647193326Sed DeferredDecls.erase(DDI); 648193326Sed } else if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl())) { 649193326Sed // If this the first reference to a C++ inline function in a class, queue up 650193326Sed // the deferred function body for emission. These are not seen as 651193326Sed // top-level declarations. 652193326Sed if (FD->isThisDeclarationADefinition() && MayDeferGeneration(FD)) 653193326Sed DeferredDeclsToEmit.push_back(D); 654198092Srdivacky // A called constructor which has no definition or declaration need be 655198092Srdivacky // synthesized. 656198092Srdivacky else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 657198092Srdivacky const CXXRecordDecl *ClassDecl = 658198092Srdivacky cast<CXXRecordDecl>(CD->getDeclContext()); 659198092Srdivacky if (CD->isCopyConstructor(getContext())) 660198092Srdivacky DeferredCopyConstructorToEmit(D); 661198092Srdivacky else if (!ClassDecl->hasUserDeclaredConstructor()) 662198092Srdivacky DeferredDeclsToEmit.push_back(D); 663198092Srdivacky } 664198092Srdivacky else if (isa<CXXDestructorDecl>(FD)) 665198092Srdivacky DeferredDestructorToEmit(D); 666198092Srdivacky else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 667198092Srdivacky if (MD->isCopyAssignment()) 668198092Srdivacky DeferredCopyAssignmentToEmit(D); 669193326Sed } 670198092Srdivacky 671193326Sed // This function doesn't have a complete type (for example, the return 672193326Sed // type is an incomplete struct). Use a fake type instead, and make 673193326Sed // sure not to try to set attributes. 674193326Sed bool IsIncompleteFunction = false; 675193326Sed if (!isa<llvm::FunctionType>(Ty)) { 676198092Srdivacky Ty = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), 677193326Sed std::vector<const llvm::Type*>(), false); 678193326Sed IsIncompleteFunction = true; 679193326Sed } 680198092Srdivacky llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty), 681193326Sed llvm::Function::ExternalLinkage, 682193326Sed "", &getModule()); 683193326Sed F->setName(MangledName); 684193326Sed if (D.getDecl()) 685193326Sed SetFunctionAttributes(cast<FunctionDecl>(D.getDecl()), F, 686193326Sed IsIncompleteFunction); 687193326Sed Entry = F; 688193326Sed return F; 689193326Sed} 690193326Sed 691198092Srdivacky/// Defer definition of copy constructor(s) which need be implicitly defined. 692198092Srdivackyvoid CodeGenModule::DeferredCopyConstructorToEmit(GlobalDecl CopyCtorDecl) { 693198092Srdivacky const CXXConstructorDecl *CD = 694198092Srdivacky cast<CXXConstructorDecl>(CopyCtorDecl.getDecl()); 695198092Srdivacky const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext()); 696198092Srdivacky if (ClassDecl->hasTrivialCopyConstructor() || 697198092Srdivacky ClassDecl->hasUserDeclaredCopyConstructor()) 698198092Srdivacky return; 699198092Srdivacky 700198092Srdivacky // First make sure all direct base classes and virtual bases and non-static 701198092Srdivacky // data mebers which need to have their copy constructors implicitly defined 702198092Srdivacky // are defined. 12.8.p7 703198092Srdivacky for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(); 704198092Srdivacky Base != ClassDecl->bases_end(); ++Base) { 705198092Srdivacky CXXRecordDecl *BaseClassDecl 706198092Srdivacky = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 707198092Srdivacky if (CXXConstructorDecl *BaseCopyCtor = 708198092Srdivacky BaseClassDecl->getCopyConstructor(Context, 0)) 709198092Srdivacky GetAddrOfCXXConstructor(BaseCopyCtor, Ctor_Complete); 710198092Srdivacky } 711198092Srdivacky 712198092Srdivacky for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 713198092Srdivacky FieldEnd = ClassDecl->field_end(); 714198092Srdivacky Field != FieldEnd; ++Field) { 715198092Srdivacky QualType FieldType = Context.getCanonicalType((*Field)->getType()); 716198092Srdivacky if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 717198092Srdivacky FieldType = Array->getElementType(); 718198092Srdivacky if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 719198092Srdivacky if ((*Field)->isAnonymousStructOrUnion()) 720198092Srdivacky continue; 721198092Srdivacky CXXRecordDecl *FieldClassDecl 722198092Srdivacky = cast<CXXRecordDecl>(FieldClassType->getDecl()); 723198092Srdivacky if (CXXConstructorDecl *FieldCopyCtor = 724198092Srdivacky FieldClassDecl->getCopyConstructor(Context, 0)) 725198092Srdivacky GetAddrOfCXXConstructor(FieldCopyCtor, Ctor_Complete); 726198092Srdivacky } 727198092Srdivacky } 728198092Srdivacky DeferredDeclsToEmit.push_back(CopyCtorDecl); 729198092Srdivacky} 730198092Srdivacky 731198092Srdivacky/// Defer definition of copy assignments which need be implicitly defined. 732198092Srdivackyvoid CodeGenModule::DeferredCopyAssignmentToEmit(GlobalDecl CopyAssignDecl) { 733198092Srdivacky const CXXMethodDecl *CD = cast<CXXMethodDecl>(CopyAssignDecl.getDecl()); 734198092Srdivacky const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext()); 735198092Srdivacky 736198092Srdivacky if (ClassDecl->hasTrivialCopyAssignment() || 737198092Srdivacky ClassDecl->hasUserDeclaredCopyAssignment()) 738198092Srdivacky return; 739198092Srdivacky 740198092Srdivacky // First make sure all direct base classes and virtual bases and non-static 741198092Srdivacky // data mebers which need to have their copy assignments implicitly defined 742198092Srdivacky // are defined. 12.8.p12 743198092Srdivacky for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(); 744198092Srdivacky Base != ClassDecl->bases_end(); ++Base) { 745198092Srdivacky CXXRecordDecl *BaseClassDecl 746198092Srdivacky = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 747198092Srdivacky const CXXMethodDecl *MD = 0; 748198092Srdivacky if (!BaseClassDecl->hasTrivialCopyAssignment() && 749198092Srdivacky !BaseClassDecl->hasUserDeclaredCopyAssignment() && 750198092Srdivacky BaseClassDecl->hasConstCopyAssignment(getContext(), MD)) 751198092Srdivacky GetAddrOfFunction(MD, 0); 752198092Srdivacky } 753198092Srdivacky 754198092Srdivacky for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 755198092Srdivacky FieldEnd = ClassDecl->field_end(); 756198092Srdivacky Field != FieldEnd; ++Field) { 757198092Srdivacky QualType FieldType = Context.getCanonicalType((*Field)->getType()); 758198092Srdivacky if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 759198092Srdivacky FieldType = Array->getElementType(); 760198092Srdivacky if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 761198092Srdivacky if ((*Field)->isAnonymousStructOrUnion()) 762198092Srdivacky continue; 763198092Srdivacky CXXRecordDecl *FieldClassDecl 764198092Srdivacky = cast<CXXRecordDecl>(FieldClassType->getDecl()); 765198092Srdivacky const CXXMethodDecl *MD = 0; 766198092Srdivacky if (!FieldClassDecl->hasTrivialCopyAssignment() && 767198092Srdivacky !FieldClassDecl->hasUserDeclaredCopyAssignment() && 768198092Srdivacky FieldClassDecl->hasConstCopyAssignment(getContext(), MD)) 769198092Srdivacky GetAddrOfFunction(MD, 0); 770198092Srdivacky } 771198092Srdivacky } 772198092Srdivacky DeferredDeclsToEmit.push_back(CopyAssignDecl); 773198092Srdivacky} 774198092Srdivacky 775198092Srdivackyvoid CodeGenModule::DeferredDestructorToEmit(GlobalDecl DtorDecl) { 776198092Srdivacky const CXXDestructorDecl *DD = cast<CXXDestructorDecl>(DtorDecl.getDecl()); 777198092Srdivacky const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(DD->getDeclContext()); 778198092Srdivacky if (ClassDecl->hasTrivialDestructor() || 779198092Srdivacky ClassDecl->hasUserDeclaredDestructor()) 780198092Srdivacky return; 781198092Srdivacky 782198092Srdivacky for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(); 783198092Srdivacky Base != ClassDecl->bases_end(); ++Base) { 784198092Srdivacky CXXRecordDecl *BaseClassDecl 785198092Srdivacky = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 786198092Srdivacky if (const CXXDestructorDecl *BaseDtor = 787198092Srdivacky BaseClassDecl->getDestructor(Context)) 788198092Srdivacky GetAddrOfCXXDestructor(BaseDtor, Dtor_Complete); 789198092Srdivacky } 790198092Srdivacky 791198092Srdivacky for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 792198092Srdivacky FieldEnd = ClassDecl->field_end(); 793198092Srdivacky Field != FieldEnd; ++Field) { 794198092Srdivacky QualType FieldType = Context.getCanonicalType((*Field)->getType()); 795198092Srdivacky if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 796198092Srdivacky FieldType = Array->getElementType(); 797198092Srdivacky if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 798198092Srdivacky if ((*Field)->isAnonymousStructOrUnion()) 799198092Srdivacky continue; 800198092Srdivacky CXXRecordDecl *FieldClassDecl 801198092Srdivacky = cast<CXXRecordDecl>(FieldClassType->getDecl()); 802198092Srdivacky if (const CXXDestructorDecl *FieldDtor = 803198092Srdivacky FieldClassDecl->getDestructor(Context)) 804198092Srdivacky GetAddrOfCXXDestructor(FieldDtor, Dtor_Complete); 805198092Srdivacky } 806198092Srdivacky } 807198092Srdivacky DeferredDeclsToEmit.push_back(DtorDecl); 808198092Srdivacky} 809198092Srdivacky 810198092Srdivacky 811193326Sed/// GetAddrOfFunction - Return the address of the given function. If Ty is 812193326Sed/// non-null, then this function will use the specified type if it has to 813193326Sed/// create it (this occurs when we see a definition of the function). 814193326Sedllvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 815193326Sed const llvm::Type *Ty) { 816193326Sed // If there was no specific requested type, just convert it now. 817193326Sed if (!Ty) 818198092Srdivacky Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType()); 819198092Srdivacky return GetOrCreateLLVMFunction(getMangledName(GD), Ty, GD); 820193326Sed} 821193326Sed 822193326Sed/// CreateRuntimeFunction - Create a new runtime function with the specified 823193326Sed/// type and name. 824193326Sedllvm::Constant * 825193326SedCodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy, 826193326Sed const char *Name) { 827193326Sed // Convert Name to be a uniqued string from the IdentifierInfo table. 828193326Sed Name = getContext().Idents.get(Name).getName(); 829193326Sed return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl()); 830193326Sed} 831193326Sed 832193326Sed/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 833193326Sed/// create and return an llvm GlobalVariable with the specified type. If there 834193326Sed/// is something in the module with the specified name, return it potentially 835193326Sed/// bitcasted to the right type. 836193326Sed/// 837193326Sed/// If D is non-null, it specifies a decl that correspond to this. This is used 838193326Sed/// to set the attributes on the global when it is first created. 839193326Sedllvm::Constant *CodeGenModule::GetOrCreateLLVMGlobal(const char *MangledName, 840193326Sed const llvm::PointerType*Ty, 841193326Sed const VarDecl *D) { 842193326Sed // Lookup the entry, lazily creating it if necessary. 843193326Sed llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName]; 844193326Sed if (Entry) { 845193326Sed if (Entry->getType() == Ty) 846193326Sed return Entry; 847198092Srdivacky 848193326Sed // Make sure the result is of the correct type. 849193326Sed return llvm::ConstantExpr::getBitCast(Entry, Ty); 850193326Sed } 851198092Srdivacky 852193326Sed // This is the first use or definition of a mangled name. If there is a 853193326Sed // deferred decl with this name, remember that we need to emit it at the end 854193326Sed // of the file. 855198092Srdivacky llvm::DenseMap<const char*, GlobalDecl>::iterator DDI = 856193326Sed DeferredDecls.find(MangledName); 857193326Sed if (DDI != DeferredDecls.end()) { 858193326Sed // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 859193326Sed // list, and remove it from DeferredDecls (since we don't need it anymore). 860193326Sed DeferredDeclsToEmit.push_back(DDI->second); 861193326Sed DeferredDecls.erase(DDI); 862193326Sed } 863198092Srdivacky 864198092Srdivacky llvm::GlobalVariable *GV = 865198092Srdivacky new llvm::GlobalVariable(getModule(), Ty->getElementType(), false, 866193326Sed llvm::GlobalValue::ExternalLinkage, 867198092Srdivacky 0, "", 0, 868193326Sed false, Ty->getAddressSpace()); 869193326Sed GV->setName(MangledName); 870193326Sed 871193326Sed // Handle things which are present even on external declarations. 872193326Sed if (D) { 873193326Sed // FIXME: This code is overly simple and should be merged with other global 874193326Sed // handling. 875193326Sed GV->setConstant(D->getType().isConstant(Context)); 876193326Sed 877193326Sed // FIXME: Merge with other attribute handling code. 878193326Sed if (D->getStorageClass() == VarDecl::PrivateExtern) 879193326Sed GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 880193326Sed 881198092Srdivacky if (D->hasAttr<WeakAttr>() || 882195341Sed D->hasAttr<WeakImportAttr>()) 883193326Sed GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 884193326Sed 885193326Sed GV->setThreadLocal(D->isThreadSpecified()); 886193326Sed } 887198092Srdivacky 888193326Sed return Entry = GV; 889193326Sed} 890193326Sed 891193326Sed 892193326Sed/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 893193326Sed/// given global variable. If Ty is non-null and if the global doesn't exist, 894193326Sed/// then it will be greated with the specified type instead of whatever the 895193326Sed/// normal requested type would be. 896193326Sedllvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 897193326Sed const llvm::Type *Ty) { 898193326Sed assert(D->hasGlobalStorage() && "Not a global variable"); 899193326Sed QualType ASTTy = D->getType(); 900193326Sed if (Ty == 0) 901193326Sed Ty = getTypes().ConvertTypeForMem(ASTTy); 902198092Srdivacky 903198092Srdivacky const llvm::PointerType *PTy = 904193326Sed llvm::PointerType::get(Ty, ASTTy.getAddressSpace()); 905193326Sed return GetOrCreateLLVMGlobal(getMangledName(D), PTy, D); 906193326Sed} 907193326Sed 908193326Sed/// CreateRuntimeVariable - Create a new runtime global variable with the 909193326Sed/// specified type and name. 910193326Sedllvm::Constant * 911193326SedCodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty, 912193326Sed const char *Name) { 913193326Sed // Convert Name to be a uniqued string from the IdentifierInfo table. 914193326Sed Name = getContext().Idents.get(Name).getName(); 915193326Sed return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0); 916193326Sed} 917193326Sed 918193326Sedvoid CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 919193326Sed assert(!D->getInit() && "Cannot emit definite definitions here!"); 920193326Sed 921193326Sed if (MayDeferGeneration(D)) { 922193326Sed // If we have not seen a reference to this variable yet, place it 923193326Sed // into the deferred declarations table to be emitted if needed 924193326Sed // later. 925193326Sed const char *MangledName = getMangledName(D); 926193326Sed if (GlobalDeclMap.count(MangledName) == 0) { 927198092Srdivacky DeferredDecls[MangledName] = D; 928193326Sed return; 929193326Sed } 930193326Sed } 931193326Sed 932193326Sed // The tentative definition is the only definition. 933193326Sed EmitGlobalVarDefinition(D); 934193326Sed} 935193326Sed 936198112Srdivackystatic CodeGenModule::GVALinkage 937198112SrdivackyGetLinkageForVariable(ASTContext &Context, const VarDecl *VD) { 938198112Srdivacky // Everything located semantically within an anonymous namespace is 939198112Srdivacky // always internal. 940198112Srdivacky if (VD->isInAnonymousNamespace()) 941198112Srdivacky return CodeGenModule::GVA_Internal; 942198112Srdivacky 943198112Srdivacky // Handle linkage for static data members. 944198112Srdivacky if (VD->isStaticDataMember()) { 945198112Srdivacky switch (VD->getTemplateSpecializationKind()) { 946198112Srdivacky case TSK_Undeclared: 947198112Srdivacky case TSK_ExplicitSpecialization: 948198112Srdivacky case TSK_ExplicitInstantiationDefinition: 949198112Srdivacky return CodeGenModule::GVA_StrongExternal; 950198112Srdivacky 951198112Srdivacky case TSK_ExplicitInstantiationDeclaration: 952198112Srdivacky assert(false && "Variable should not be instantiated"); 953198112Srdivacky // Fall through to treat this like any other instantiation. 954198112Srdivacky 955198112Srdivacky case TSK_ImplicitInstantiation: 956198112Srdivacky return CodeGenModule::GVA_TemplateInstantiation; 957198112Srdivacky } 958198112Srdivacky } 959198112Srdivacky 960198112Srdivacky // Static variables get internal linkage. 961198112Srdivacky if (VD->getStorageClass() == VarDecl::Static) 962198112Srdivacky return CodeGenModule::GVA_Internal; 963198112Srdivacky 964198112Srdivacky return CodeGenModule::GVA_StrongExternal; 965198112Srdivacky} 966198112Srdivacky 967193326Sedvoid CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 968193326Sed llvm::Constant *Init = 0; 969193326Sed QualType ASTTy = D->getType(); 970198092Srdivacky 971193326Sed if (D->getInit() == 0) { 972193326Sed // This is a tentative definition; tentative definitions are 973193326Sed // implicitly initialized with { 0 }. 974193326Sed // 975193326Sed // Note that tentative definitions are only emitted at the end of 976193326Sed // a translation unit, so they should never have incomplete 977193326Sed // type. In addition, EmitTentativeDefinition makes sure that we 978193326Sed // never attempt to emit a tentative definition if a real one 979193326Sed // exists. A use may still exists, however, so we still may need 980193326Sed // to do a RAUW. 981193326Sed assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 982198092Srdivacky Init = EmitNullConstant(D->getType()); 983193326Sed } else { 984193326Sed Init = EmitConstantExpr(D->getInit(), D->getType()); 985198092Srdivacky 986193326Sed if (!Init) { 987193326Sed QualType T = D->getInit()->getType(); 988198092Srdivacky if (getLangOptions().CPlusPlus) { 989198092Srdivacky CXXGlobalInits.push_back(D); 990198092Srdivacky Init = EmitNullConstant(T); 991198092Srdivacky } else { 992198092Srdivacky ErrorUnsupported(D, "static initializer"); 993198092Srdivacky Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 994198092Srdivacky } 995193326Sed } 996193326Sed } 997193326Sed 998193326Sed const llvm::Type* InitType = Init->getType(); 999193326Sed llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 1000198092Srdivacky 1001193326Sed // Strip off a bitcast if we got one back. 1002193326Sed if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1003198092Srdivacky assert(CE->getOpcode() == llvm::Instruction::BitCast || 1004198092Srdivacky // all zero index gep. 1005198092Srdivacky CE->getOpcode() == llvm::Instruction::GetElementPtr); 1006193326Sed Entry = CE->getOperand(0); 1007193326Sed } 1008198092Srdivacky 1009193326Sed // Entry is now either a Function or GlobalVariable. 1010193326Sed llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry); 1011198092Srdivacky 1012193326Sed // We have a definition after a declaration with the wrong type. 1013193326Sed // We must make a new GlobalVariable* and update everything that used OldGV 1014193326Sed // (a declaration or tentative definition) with the new GlobalVariable* 1015193326Sed // (which will be a definition). 1016193326Sed // 1017193326Sed // This happens if there is a prototype for a global (e.g. 1018193326Sed // "extern int x[];") and then a definition of a different type (e.g. 1019193326Sed // "int x[10];"). This also happens when an initializer has a different type 1020193326Sed // from the type of the global (this happens with unions). 1021193326Sed if (GV == 0 || 1022193326Sed GV->getType()->getElementType() != InitType || 1023193326Sed GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) { 1024198092Srdivacky 1025193326Sed // Remove the old entry from GlobalDeclMap so that we'll create a new one. 1026193326Sed GlobalDeclMap.erase(getMangledName(D)); 1027193326Sed 1028193326Sed // Make a new global with the correct type, this is now guaranteed to work. 1029193326Sed GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 1030193326Sed GV->takeName(cast<llvm::GlobalValue>(Entry)); 1031193326Sed 1032193326Sed // Replace all uses of the old global with the new global 1033198092Srdivacky llvm::Constant *NewPtrForOldDecl = 1034193326Sed llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 1035193326Sed Entry->replaceAllUsesWith(NewPtrForOldDecl); 1036193326Sed 1037193326Sed // Erase the old global, since it is no longer used. 1038193326Sed cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 1039193326Sed } 1040193326Sed 1041195341Sed if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) { 1042193326Sed SourceManager &SM = Context.getSourceManager(); 1043193326Sed AddAnnotation(EmitAnnotateAttr(GV, AA, 1044193326Sed SM.getInstantiationLineNumber(D->getLocation()))); 1045193326Sed } 1046193326Sed 1047193326Sed GV->setInitializer(Init); 1048198092Srdivacky 1049198092Srdivacky // If it is safe to mark the global 'constant', do so now. 1050198092Srdivacky GV->setConstant(false); 1051198092Srdivacky if (D->getType().isConstant(Context)) { 1052198092Srdivacky // FIXME: In C++, if the variable has a non-trivial ctor/dtor or any mutable 1053198092Srdivacky // members, it cannot be declared "LLVM const". 1054198092Srdivacky GV->setConstant(true); 1055198092Srdivacky } 1056198092Srdivacky 1057193326Sed GV->setAlignment(getContext().getDeclAlignInBytes(D)); 1058193326Sed 1059193326Sed // Set the llvm linkage type as appropriate. 1060198112Srdivacky GVALinkage Linkage = GetLinkageForVariable(getContext(), D); 1061198112Srdivacky if (Linkage == GVA_Internal) 1062193326Sed GV->setLinkage(llvm::Function::InternalLinkage); 1063195341Sed else if (D->hasAttr<DLLImportAttr>()) 1064193326Sed GV->setLinkage(llvm::Function::DLLImportLinkage); 1065195341Sed else if (D->hasAttr<DLLExportAttr>()) 1066193326Sed GV->setLinkage(llvm::Function::DLLExportLinkage); 1067198092Srdivacky else if (D->hasAttr<WeakAttr>()) { 1068198092Srdivacky if (GV->isConstant()) 1069198092Srdivacky GV->setLinkage(llvm::GlobalVariable::WeakODRLinkage); 1070198092Srdivacky else 1071198092Srdivacky GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 1072198112Srdivacky } else if (Linkage == GVA_TemplateInstantiation) 1073198112Srdivacky GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 1074198112Srdivacky else if (!CompileOpts.NoCommon && 1075198092Srdivacky !D->hasExternalStorage() && !D->getInit() && 1076198092Srdivacky !D->getAttr<SectionAttr>()) { 1077193326Sed GV->setLinkage(llvm::GlobalVariable::CommonLinkage); 1078198092Srdivacky // common vars aren't constant even if declared const. 1079198092Srdivacky GV->setConstant(false); 1080198092Srdivacky } else 1081193326Sed GV->setLinkage(llvm::GlobalVariable::ExternalLinkage); 1082193326Sed 1083193326Sed SetCommonAttributes(D, GV); 1084193326Sed 1085193326Sed // Emit global variable debug information. 1086193326Sed if (CGDebugInfo *DI = getDebugInfo()) { 1087193326Sed DI->setLocation(D->getLocation()); 1088193326Sed DI->EmitGlobalVariable(GV, D); 1089193326Sed } 1090193326Sed} 1091193326Sed 1092193326Sed/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 1093193326Sed/// implement a function with no prototype, e.g. "int foo() {}". If there are 1094193326Sed/// existing call uses of the old function in the module, this adjusts them to 1095193326Sed/// call the new function directly. 1096193326Sed/// 1097193326Sed/// This is not just a cleanup: the always_inline pass requires direct calls to 1098193326Sed/// functions to be able to inline them. If there is a bitcast in the way, it 1099193326Sed/// won't inline them. Instcombine normally deletes these calls, but it isn't 1100193326Sed/// run at -O0. 1101193326Sedstatic void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 1102193326Sed llvm::Function *NewFn) { 1103193326Sed // If we're redefining a global as a function, don't transform it. 1104193326Sed llvm::Function *OldFn = dyn_cast<llvm::Function>(Old); 1105193326Sed if (OldFn == 0) return; 1106198092Srdivacky 1107193326Sed const llvm::Type *NewRetTy = NewFn->getReturnType(); 1108193326Sed llvm::SmallVector<llvm::Value*, 4> ArgList; 1109193326Sed 1110193326Sed for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end(); 1111193326Sed UI != E; ) { 1112193326Sed // TODO: Do invokes ever occur in C code? If so, we should handle them too. 1113193576Sed unsigned OpNo = UI.getOperandNo(); 1114193326Sed llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*UI++); 1115193576Sed if (!CI || OpNo != 0) continue; 1116198092Srdivacky 1117193326Sed // If the return types don't match exactly, and if the call isn't dead, then 1118193326Sed // we can't transform this call. 1119193326Sed if (CI->getType() != NewRetTy && !CI->use_empty()) 1120193326Sed continue; 1121193326Sed 1122193326Sed // If the function was passed too few arguments, don't transform. If extra 1123193326Sed // arguments were passed, we silently drop them. If any of the types 1124193326Sed // mismatch, we don't transform. 1125193326Sed unsigned ArgNo = 0; 1126193326Sed bool DontTransform = false; 1127193326Sed for (llvm::Function::arg_iterator AI = NewFn->arg_begin(), 1128193326Sed E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) { 1129193326Sed if (CI->getNumOperands()-1 == ArgNo || 1130193326Sed CI->getOperand(ArgNo+1)->getType() != AI->getType()) { 1131193326Sed DontTransform = true; 1132193326Sed break; 1133193326Sed } 1134193326Sed } 1135193326Sed if (DontTransform) 1136193326Sed continue; 1137198092Srdivacky 1138193326Sed // Okay, we can transform this. Create the new call instruction and copy 1139193326Sed // over the required information. 1140193326Sed ArgList.append(CI->op_begin()+1, CI->op_begin()+1+ArgNo); 1141193326Sed llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(), 1142193326Sed ArgList.end(), "", CI); 1143193326Sed ArgList.clear(); 1144198092Srdivacky if (!NewCall->getType()->isVoidTy()) 1145193326Sed NewCall->takeName(CI); 1146198092Srdivacky NewCall->setAttributes(CI->getAttributes()); 1147193326Sed NewCall->setCallingConv(CI->getCallingConv()); 1148193326Sed 1149193326Sed // Finally, remove the old call, replacing any uses with the new one. 1150193326Sed if (!CI->use_empty()) 1151193326Sed CI->replaceAllUsesWith(NewCall); 1152198092Srdivacky 1153198092Srdivacky // Copy any custom metadata attached with CI. 1154198092Srdivacky llvm::MetadataContext &TheMetadata = CI->getContext().getMetadata(); 1155198092Srdivacky TheMetadata.copyMD(CI, NewCall); 1156198092Srdivacky 1157193326Sed CI->eraseFromParent(); 1158193326Sed } 1159193326Sed} 1160193326Sed 1161193326Sed 1162193326Sedvoid CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) { 1163193326Sed const llvm::FunctionType *Ty; 1164193326Sed const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl()); 1165198092Srdivacky 1166193326Sed if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 1167198092Srdivacky bool isVariadic = D->getType()->getAs<FunctionProtoType>()->isVariadic(); 1168198092Srdivacky 1169193326Sed Ty = getTypes().GetFunctionType(getTypes().getFunctionInfo(MD), isVariadic); 1170193326Sed } else { 1171193326Sed Ty = cast<llvm::FunctionType>(getTypes().ConvertType(D->getType())); 1172198092Srdivacky 1173193326Sed // As a special case, make sure that definitions of K&R function 1174193326Sed // "type foo()" aren't declared as varargs (which forces the backend 1175193326Sed // to do unnecessary work). 1176193326Sed if (D->getType()->isFunctionNoProtoType()) { 1177193326Sed assert(Ty->isVarArg() && "Didn't lower type as expected"); 1178198092Srdivacky // Due to stret, the lowered function could have arguments. 1179198092Srdivacky // Just create the same type as was lowered by ConvertType 1180193326Sed // but strip off the varargs bit. 1181193326Sed std::vector<const llvm::Type*> Args(Ty->param_begin(), Ty->param_end()); 1182193326Sed Ty = llvm::FunctionType::get(Ty->getReturnType(), Args, false); 1183193326Sed } 1184193326Sed } 1185193326Sed 1186193326Sed // Get or create the prototype for the function. 1187193326Sed llvm::Constant *Entry = GetAddrOfFunction(GD, Ty); 1188198092Srdivacky 1189193326Sed // Strip off a bitcast if we got one back. 1190193326Sed if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1191193326Sed assert(CE->getOpcode() == llvm::Instruction::BitCast); 1192193326Sed Entry = CE->getOperand(0); 1193193326Sed } 1194198092Srdivacky 1195198092Srdivacky 1196193326Sed if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) { 1197193326Sed llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry); 1198198092Srdivacky 1199193326Sed // If the types mismatch then we have to rewrite the definition. 1200193326Sed assert(OldFn->isDeclaration() && 1201193326Sed "Shouldn't replace non-declaration"); 1202193326Sed 1203193326Sed // F is the Function* for the one with the wrong type, we must make a new 1204193326Sed // Function* and update everything that used F (a declaration) with the new 1205193326Sed // Function* (which will be a definition). 1206193326Sed // 1207193326Sed // This happens if there is a prototype for a function 1208193326Sed // (e.g. "int f()") and then a definition of a different type 1209193326Sed // (e.g. "int f(int x)"). Start by making a new function of the 1210193326Sed // correct type, RAUW, then steal the name. 1211193326Sed GlobalDeclMap.erase(getMangledName(D)); 1212193326Sed llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty)); 1213193326Sed NewFn->takeName(OldFn); 1214198092Srdivacky 1215193326Sed // If this is an implementation of a function without a prototype, try to 1216193326Sed // replace any existing uses of the function (which may be calls) with uses 1217193326Sed // of the new function 1218193326Sed if (D->getType()->isFunctionNoProtoType()) { 1219193326Sed ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn); 1220193326Sed OldFn->removeDeadConstantUsers(); 1221193326Sed } 1222198092Srdivacky 1223193326Sed // Replace uses of F with the Function we will endow with a body. 1224193326Sed if (!Entry->use_empty()) { 1225198092Srdivacky llvm::Constant *NewPtrForOldDecl = 1226193326Sed llvm::ConstantExpr::getBitCast(NewFn, Entry->getType()); 1227193326Sed Entry->replaceAllUsesWith(NewPtrForOldDecl); 1228193326Sed } 1229198092Srdivacky 1230193326Sed // Ok, delete the old function now, which is dead. 1231193326Sed OldFn->eraseFromParent(); 1232198092Srdivacky 1233193326Sed Entry = NewFn; 1234193326Sed } 1235198092Srdivacky 1236193326Sed llvm::Function *Fn = cast<llvm::Function>(Entry); 1237193326Sed 1238193326Sed CodeGenFunction(*this).GenerateCode(D, Fn); 1239193326Sed 1240193326Sed SetFunctionDefinitionAttributes(D, Fn); 1241193326Sed SetLLVMFunctionAttributesForDefinition(D, Fn); 1242198092Srdivacky 1243195341Sed if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 1244193326Sed AddGlobalCtor(Fn, CA->getPriority()); 1245195341Sed if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 1246193326Sed AddGlobalDtor(Fn, DA->getPriority()); 1247193326Sed} 1248193326Sed 1249193326Sedvoid CodeGenModule::EmitAliasDefinition(const ValueDecl *D) { 1250195341Sed const AliasAttr *AA = D->getAttr<AliasAttr>(); 1251193326Sed assert(AA && "Not an alias?"); 1252193326Sed 1253193326Sed const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 1254198092Srdivacky 1255193326Sed // Unique the name through the identifier table. 1256193326Sed const char *AliaseeName = AA->getAliasee().c_str(); 1257193326Sed AliaseeName = getContext().Idents.get(AliaseeName).getName(); 1258193326Sed 1259193326Sed // Create a reference to the named value. This ensures that it is emitted 1260193326Sed // if a deferred decl. 1261193326Sed llvm::Constant *Aliasee; 1262193326Sed if (isa<llvm::FunctionType>(DeclTy)) 1263193326Sed Aliasee = GetOrCreateLLVMFunction(AliaseeName, DeclTy, GlobalDecl()); 1264193326Sed else 1265193326Sed Aliasee = GetOrCreateLLVMGlobal(AliaseeName, 1266193326Sed llvm::PointerType::getUnqual(DeclTy), 0); 1267193326Sed 1268193326Sed // Create the new alias itself, but don't set a name yet. 1269198092Srdivacky llvm::GlobalValue *GA = 1270193326Sed new llvm::GlobalAlias(Aliasee->getType(), 1271193326Sed llvm::Function::ExternalLinkage, 1272193326Sed "", Aliasee, &getModule()); 1273198092Srdivacky 1274193326Sed // See if there is already something with the alias' name in the module. 1275193326Sed const char *MangledName = getMangledName(D); 1276193326Sed llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName]; 1277198092Srdivacky 1278193326Sed if (Entry && !Entry->isDeclaration()) { 1279193326Sed // If there is a definition in the module, then it wins over the alias. 1280193326Sed // This is dubious, but allow it to be safe. Just ignore the alias. 1281193326Sed GA->eraseFromParent(); 1282193326Sed return; 1283193326Sed } 1284198092Srdivacky 1285193326Sed if (Entry) { 1286193326Sed // If there is a declaration in the module, then we had an extern followed 1287193326Sed // by the alias, as in: 1288193326Sed // extern int test6(); 1289193326Sed // ... 1290193326Sed // int test6() __attribute__((alias("test7"))); 1291193326Sed // 1292193326Sed // Remove it and replace uses of it with the alias. 1293198092Srdivacky 1294193326Sed Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 1295193326Sed Entry->getType())); 1296193326Sed Entry->eraseFromParent(); 1297193326Sed } 1298198092Srdivacky 1299193326Sed // Now we know that there is no conflict, set the name. 1300193326Sed Entry = GA; 1301193326Sed GA->setName(MangledName); 1302193326Sed 1303193326Sed // Set attributes which are particular to an alias; this is a 1304193326Sed // specialization of the attributes which may be set on a global 1305193326Sed // variable/function. 1306195341Sed if (D->hasAttr<DLLExportAttr>()) { 1307193326Sed if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1308193326Sed // The dllexport attribute is ignored for undefined symbols. 1309195341Sed if (FD->getBody()) 1310193326Sed GA->setLinkage(llvm::Function::DLLExportLinkage); 1311193326Sed } else { 1312193326Sed GA->setLinkage(llvm::Function::DLLExportLinkage); 1313193326Sed } 1314198092Srdivacky } else if (D->hasAttr<WeakAttr>() || 1315195341Sed D->hasAttr<WeakImportAttr>()) { 1316193326Sed GA->setLinkage(llvm::Function::WeakAnyLinkage); 1317193326Sed } 1318193326Sed 1319193326Sed SetCommonAttributes(D, GA); 1320193326Sed} 1321193326Sed 1322193326Sed/// getBuiltinLibFunction - Given a builtin id for a function like 1323193326Sed/// "__builtin_fabsf", return a Function* for "fabsf". 1324198092Srdivackyllvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD, 1325198092Srdivacky unsigned BuiltinID) { 1326193326Sed assert((Context.BuiltinInfo.isLibFunction(BuiltinID) || 1327198092Srdivacky Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) && 1328193326Sed "isn't a lib fn"); 1329198092Srdivacky 1330193326Sed // Get the name, skip over the __builtin_ prefix (if necessary). 1331193326Sed const char *Name = Context.BuiltinInfo.GetName(BuiltinID); 1332193326Sed if (Context.BuiltinInfo.isLibFunction(BuiltinID)) 1333193326Sed Name += 10; 1334198092Srdivacky 1335193326Sed // Get the type for the builtin. 1336194179Sed ASTContext::GetBuiltinTypeError Error; 1337194179Sed QualType Type = Context.GetBuiltinType(BuiltinID, Error); 1338194179Sed assert(Error == ASTContext::GE_None && "Can't get builtin type"); 1339193326Sed 1340198092Srdivacky const llvm::FunctionType *Ty = 1341193326Sed cast<llvm::FunctionType>(getTypes().ConvertType(Type)); 1342193326Sed 1343193326Sed // Unique the name through the identifier table. 1344193326Sed Name = getContext().Idents.get(Name).getName(); 1345198092Srdivacky return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD)); 1346193326Sed} 1347193326Sed 1348193326Sedllvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys, 1349193326Sed unsigned NumTys) { 1350193326Sed return llvm::Intrinsic::getDeclaration(&getModule(), 1351193326Sed (llvm::Intrinsic::ID)IID, Tys, NumTys); 1352193326Sed} 1353193326Sed 1354193326Sedllvm::Function *CodeGenModule::getMemCpyFn() { 1355193326Sed if (MemCpyFn) return MemCpyFn; 1356198092Srdivacky const llvm::Type *IntPtr = TheTargetData.getIntPtrType(VMContext); 1357193326Sed return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1); 1358193326Sed} 1359193326Sed 1360193326Sedllvm::Function *CodeGenModule::getMemMoveFn() { 1361193326Sed if (MemMoveFn) return MemMoveFn; 1362198092Srdivacky const llvm::Type *IntPtr = TheTargetData.getIntPtrType(VMContext); 1363193326Sed return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1); 1364193326Sed} 1365193326Sed 1366193326Sedllvm::Function *CodeGenModule::getMemSetFn() { 1367193326Sed if (MemSetFn) return MemSetFn; 1368198092Srdivacky const llvm::Type *IntPtr = TheTargetData.getIntPtrType(VMContext); 1369193326Sed return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1); 1370193326Sed} 1371193326Sed 1372198092Srdivackystatic llvm::StringMapEntry<llvm::Constant*> & 1373198092SrdivackyGetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map, 1374198092Srdivacky const StringLiteral *Literal, 1375198092Srdivacky bool TargetIsLSB, 1376198092Srdivacky bool &IsUTF16, 1377198092Srdivacky unsigned &StringLength) { 1378198092Srdivacky unsigned NumBytes = Literal->getByteLength(); 1379198092Srdivacky 1380198092Srdivacky // Check for simple case. 1381198092Srdivacky if (!Literal->containsNonAsciiOrNull()) { 1382198092Srdivacky StringLength = NumBytes; 1383198092Srdivacky return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(), 1384198092Srdivacky StringLength)); 1385193326Sed } 1386198092Srdivacky 1387198092Srdivacky // Otherwise, convert the UTF8 literals into a byte string. 1388198092Srdivacky llvm::SmallVector<UTF16, 128> ToBuf(NumBytes); 1389198092Srdivacky const UTF8 *FromPtr = (UTF8 *)Literal->getStrData(); 1390198092Srdivacky UTF16 *ToPtr = &ToBuf[0]; 1391198092Srdivacky 1392198092Srdivacky ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 1393198092Srdivacky &ToPtr, ToPtr + NumBytes, 1394198092Srdivacky strictConversion); 1395198092Srdivacky 1396198092Srdivacky // Check for conversion failure. 1397198092Srdivacky if (Result != conversionOK) { 1398198092Srdivacky // FIXME: Have Sema::CheckObjCString() validate the UTF-8 string and remove 1399198092Srdivacky // this duplicate code. 1400198092Srdivacky assert(Result == sourceIllegal && "UTF-8 to UTF-16 conversion failed"); 1401198092Srdivacky StringLength = NumBytes; 1402198092Srdivacky return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(), 1403198092Srdivacky StringLength)); 1404193326Sed } 1405198092Srdivacky 1406198092Srdivacky // ConvertUTF8toUTF16 returns the length in ToPtr. 1407198092Srdivacky StringLength = ToPtr - &ToBuf[0]; 1408198092Srdivacky 1409198092Srdivacky // Render the UTF-16 string into a byte array and convert to the target byte 1410198092Srdivacky // order. 1411198092Srdivacky // 1412198092Srdivacky // FIXME: This isn't something we should need to do here. 1413198092Srdivacky llvm::SmallString<128> AsBytes; 1414198092Srdivacky AsBytes.reserve(StringLength * 2); 1415198092Srdivacky for (unsigned i = 0; i != StringLength; ++i) { 1416198092Srdivacky unsigned short Val = ToBuf[i]; 1417198092Srdivacky if (TargetIsLSB) { 1418198092Srdivacky AsBytes.push_back(Val & 0xFF); 1419198092Srdivacky AsBytes.push_back(Val >> 8); 1420198092Srdivacky } else { 1421198092Srdivacky AsBytes.push_back(Val >> 8); 1422198092Srdivacky AsBytes.push_back(Val & 0xFF); 1423198092Srdivacky } 1424198092Srdivacky } 1425198092Srdivacky // Append one extra null character, the second is automatically added by our 1426198092Srdivacky // caller. 1427198092Srdivacky AsBytes.push_back(0); 1428198092Srdivacky 1429198092Srdivacky IsUTF16 = true; 1430198092Srdivacky return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size())); 1431193326Sed} 1432193326Sed 1433198092Srdivackyllvm::Constant * 1434198092SrdivackyCodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 1435193326Sed unsigned StringLength = 0; 1436193326Sed bool isUTF16 = false; 1437198092Srdivacky llvm::StringMapEntry<llvm::Constant*> &Entry = 1438198092Srdivacky GetConstantCFStringEntry(CFConstantStringMap, Literal, 1439198092Srdivacky getTargetData().isLittleEndian(), 1440198092Srdivacky isUTF16, StringLength); 1441198092Srdivacky 1442193326Sed if (llvm::Constant *C = Entry.getValue()) 1443193326Sed return C; 1444198092Srdivacky 1445198092Srdivacky llvm::Constant *Zero = 1446198092Srdivacky llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)); 1447193326Sed llvm::Constant *Zeros[] = { Zero, Zero }; 1448198092Srdivacky 1449198092Srdivacky // If we don't already have it, get __CFConstantStringClassReference. 1450193326Sed if (!CFConstantStringClassRef) { 1451193326Sed const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 1452193326Sed Ty = llvm::ArrayType::get(Ty, 0); 1453198092Srdivacky llvm::Constant *GV = CreateRuntimeVariable(Ty, 1454198092Srdivacky "__CFConstantStringClassReference"); 1455193326Sed // Decay array -> ptr 1456193326Sed CFConstantStringClassRef = 1457193326Sed llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1458193326Sed } 1459198092Srdivacky 1460193326Sed QualType CFTy = getContext().getCFConstantStringType(); 1461193326Sed 1462198092Srdivacky const llvm::StructType *STy = 1463193326Sed cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 1464193326Sed 1465198092Srdivacky std::vector<llvm::Constant*> Fields(4); 1466193326Sed 1467193326Sed // Class pointer. 1468198092Srdivacky Fields[0] = CFConstantStringClassRef; 1469198092Srdivacky 1470193326Sed // Flags. 1471193326Sed const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 1472198092Srdivacky Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 1473198092Srdivacky llvm::ConstantInt::get(Ty, 0x07C8); 1474198092Srdivacky 1475193326Sed // String pointer. 1476198092Srdivacky llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str()); 1477193326Sed 1478198092Srdivacky const char *Sect = 0; 1479198092Srdivacky llvm::GlobalValue::LinkageTypes Linkage; 1480193326Sed bool isConstant; 1481193326Sed if (isUTF16) { 1482193326Sed Sect = getContext().Target.getUnicodeStringSection(); 1483198092Srdivacky // FIXME: why do utf strings get "_" labels instead of "L" labels? 1484198092Srdivacky Linkage = llvm::GlobalValue::InternalLinkage; 1485198092Srdivacky // Note: -fwritable-strings doesn't make unicode CFStrings writable, but 1486198092Srdivacky // does make plain ascii ones writable. 1487198092Srdivacky isConstant = true; 1488193326Sed } else { 1489198092Srdivacky Linkage = llvm::GlobalValue::PrivateLinkage; 1490198092Srdivacky isConstant = !Features.WritableStrings; 1491193326Sed } 1492198092Srdivacky 1493198092Srdivacky llvm::GlobalVariable *GV = 1494198092Srdivacky new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 1495198092Srdivacky ".str"); 1496193326Sed if (Sect) 1497193326Sed GV->setSection(Sect); 1498193326Sed if (isUTF16) { 1499193326Sed unsigned Align = getContext().getTypeAlign(getContext().ShortTy)/8; 1500198092Srdivacky GV->setAlignment(Align); 1501193326Sed } 1502198092Srdivacky Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1503198092Srdivacky 1504193326Sed // String length. 1505193326Sed Ty = getTypes().ConvertType(getContext().LongTy); 1506198092Srdivacky Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 1507198092Srdivacky 1508193326Sed // The struct. 1509193326Sed C = llvm::ConstantStruct::get(STy, Fields); 1510198092Srdivacky GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 1511198092Srdivacky llvm::GlobalVariable::PrivateLinkage, C, 1512198092Srdivacky "_unnamed_cfstring_"); 1513193326Sed if (const char *Sect = getContext().Target.getCFStringSection()) 1514193326Sed GV->setSection(Sect); 1515193326Sed Entry.setValue(GV); 1516198092Srdivacky 1517193326Sed return GV; 1518193326Sed} 1519193326Sed 1520193326Sed/// GetStringForStringLiteral - Return the appropriate bytes for a 1521193326Sed/// string literal, properly padded to match the literal type. 1522193326Sedstd::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) { 1523193326Sed const char *StrData = E->getStrData(); 1524193326Sed unsigned Len = E->getByteLength(); 1525193326Sed 1526193326Sed const ConstantArrayType *CAT = 1527193326Sed getContext().getAsConstantArrayType(E->getType()); 1528193326Sed assert(CAT && "String isn't pointer or array!"); 1529198092Srdivacky 1530193326Sed // Resize the string to the right size. 1531193326Sed std::string Str(StrData, StrData+Len); 1532193326Sed uint64_t RealLen = CAT->getSize().getZExtValue(); 1533198092Srdivacky 1534193326Sed if (E->isWide()) 1535193326Sed RealLen *= getContext().Target.getWCharWidth()/8; 1536198092Srdivacky 1537193326Sed Str.resize(RealLen, '\0'); 1538198092Srdivacky 1539193326Sed return Str; 1540193326Sed} 1541193326Sed 1542193326Sed/// GetAddrOfConstantStringFromLiteral - Return a pointer to a 1543193326Sed/// constant array for the given string literal. 1544193326Sedllvm::Constant * 1545193326SedCodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 1546193326Sed // FIXME: This can be more efficient. 1547193326Sed return GetAddrOfConstantString(GetStringForStringLiteral(S)); 1548193326Sed} 1549193326Sed 1550193326Sed/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 1551193326Sed/// array for the given ObjCEncodeExpr node. 1552193326Sedllvm::Constant * 1553193326SedCodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 1554193326Sed std::string Str; 1555193326Sed getContext().getObjCEncodingForType(E->getEncodedType(), Str); 1556193326Sed 1557193326Sed return GetAddrOfConstantCString(Str); 1558193326Sed} 1559193326Sed 1560193326Sed 1561193326Sed/// GenerateWritableString -- Creates storage for a string literal. 1562198092Srdivackystatic llvm::Constant *GenerateStringLiteral(const std::string &str, 1563193326Sed bool constant, 1564193326Sed CodeGenModule &CGM, 1565193326Sed const char *GlobalName) { 1566193326Sed // Create Constant for this string literal. Don't add a '\0'. 1567198092Srdivacky llvm::Constant *C = 1568198092Srdivacky llvm::ConstantArray::get(CGM.getLLVMContext(), str, false); 1569198092Srdivacky 1570193326Sed // Create a global variable for this string 1571198092Srdivacky return new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant, 1572198092Srdivacky llvm::GlobalValue::PrivateLinkage, 1573198092Srdivacky C, GlobalName); 1574193326Sed} 1575193326Sed 1576193326Sed/// GetAddrOfConstantString - Returns a pointer to a character array 1577193326Sed/// containing the literal. This contents are exactly that of the 1578193326Sed/// given string, i.e. it will not be null terminated automatically; 1579193326Sed/// see GetAddrOfConstantCString. Note that whether the result is 1580193326Sed/// actually a pointer to an LLVM constant depends on 1581193326Sed/// Feature.WriteableStrings. 1582193326Sed/// 1583193326Sed/// The result has pointer to array type. 1584193326Sedllvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str, 1585193326Sed const char *GlobalName) { 1586193326Sed bool IsConstant = !Features.WritableStrings; 1587193326Sed 1588193326Sed // Get the default prefix if a name wasn't specified. 1589193326Sed if (!GlobalName) 1590198092Srdivacky GlobalName = ".str"; 1591193326Sed 1592193326Sed // Don't share any string literals if strings aren't constant. 1593193326Sed if (!IsConstant) 1594193326Sed return GenerateStringLiteral(str, false, *this, GlobalName); 1595193326Sed 1596198092Srdivacky llvm::StringMapEntry<llvm::Constant *> &Entry = 1597198092Srdivacky ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 1598198092Srdivacky 1599193326Sed if (Entry.getValue()) 1600193326Sed return Entry.getValue(); 1601193326Sed 1602193326Sed // Create a global variable for this. 1603193326Sed llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName); 1604193326Sed Entry.setValue(C); 1605193326Sed return C; 1606193326Sed} 1607193326Sed 1608193326Sed/// GetAddrOfConstantCString - Returns a pointer to a character 1609193326Sed/// array containing the literal and a terminating '\-' 1610193326Sed/// character. The result has pointer to array type. 1611193326Sedllvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str, 1612193326Sed const char *GlobalName){ 1613193326Sed return GetAddrOfConstantString(str + '\0', GlobalName); 1614193326Sed} 1615193326Sed 1616193326Sed/// EmitObjCPropertyImplementations - Emit information for synthesized 1617193326Sed/// properties for an implementation. 1618198092Srdivackyvoid CodeGenModule::EmitObjCPropertyImplementations(const 1619193326Sed ObjCImplementationDecl *D) { 1620198092Srdivacky for (ObjCImplementationDecl::propimpl_iterator 1621195341Sed i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) { 1622193326Sed ObjCPropertyImplDecl *PID = *i; 1623198092Srdivacky 1624193326Sed // Dynamic is just for type-checking. 1625193326Sed if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 1626193326Sed ObjCPropertyDecl *PD = PID->getPropertyDecl(); 1627193326Sed 1628193326Sed // Determine which methods need to be implemented, some may have 1629193326Sed // been overridden. Note that ::isSynthesized is not the method 1630193326Sed // we want, that just indicates if the decl came from a 1631193326Sed // property. What we want to know is if the method is defined in 1632193326Sed // this implementation. 1633195341Sed if (!D->getInstanceMethod(PD->getGetterName())) 1634193326Sed CodeGenFunction(*this).GenerateObjCGetter( 1635193326Sed const_cast<ObjCImplementationDecl *>(D), PID); 1636193326Sed if (!PD->isReadOnly() && 1637195341Sed !D->getInstanceMethod(PD->getSetterName())) 1638193326Sed CodeGenFunction(*this).GenerateObjCSetter( 1639193326Sed const_cast<ObjCImplementationDecl *>(D), PID); 1640193326Sed } 1641193326Sed } 1642193326Sed} 1643193326Sed 1644193326Sed/// EmitNamespace - Emit all declarations in a namespace. 1645193326Sedvoid CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 1646195341Sed for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end(); 1647193326Sed I != E; ++I) 1648193326Sed EmitTopLevelDecl(*I); 1649193326Sed} 1650193326Sed 1651193326Sed// EmitLinkageSpec - Emit all declarations in a linkage spec. 1652193326Sedvoid CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 1653198092Srdivacky if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 1654198092Srdivacky LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 1655193326Sed ErrorUnsupported(LSD, "linkage spec"); 1656193326Sed return; 1657193326Sed } 1658193326Sed 1659195341Sed for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end(); 1660193326Sed I != E; ++I) 1661193326Sed EmitTopLevelDecl(*I); 1662193326Sed} 1663193326Sed 1664193326Sed/// EmitTopLevelDecl - Emit code for a single top level declaration. 1665193326Sedvoid CodeGenModule::EmitTopLevelDecl(Decl *D) { 1666193326Sed // If an error has occurred, stop code generation, but continue 1667193326Sed // parsing and semantic analysis (to ensure all warnings and errors 1668193326Sed // are emitted). 1669193326Sed if (Diags.hasErrorOccurred()) 1670193326Sed return; 1671193326Sed 1672195341Sed // Ignore dependent declarations. 1673195341Sed if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 1674195341Sed return; 1675198092Srdivacky 1676193326Sed switch (D->getKind()) { 1677198092Srdivacky case Decl::CXXConversion: 1678193326Sed case Decl::CXXMethod: 1679193326Sed case Decl::Function: 1680195341Sed // Skip function templates 1681195341Sed if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate()) 1682195341Sed return; 1683198092Srdivacky 1684198092Srdivacky EmitGlobal(cast<FunctionDecl>(D)); 1685198092Srdivacky break; 1686195341Sed 1687193326Sed case Decl::Var: 1688198092Srdivacky EmitGlobal(cast<VarDecl>(D)); 1689193326Sed break; 1690193326Sed 1691193326Sed // C++ Decls 1692193326Sed case Decl::Namespace: 1693193326Sed EmitNamespace(cast<NamespaceDecl>(D)); 1694193326Sed break; 1695194613Sed // No code generation needed. 1696194613Sed case Decl::Using: 1697198092Srdivacky case Decl::UsingDirective: 1698195341Sed case Decl::ClassTemplate: 1699195341Sed case Decl::FunctionTemplate: 1700198092Srdivacky case Decl::NamespaceAlias: 1701194613Sed break; 1702193326Sed case Decl::CXXConstructor: 1703193326Sed EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 1704193326Sed break; 1705193326Sed case Decl::CXXDestructor: 1706193326Sed EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 1707193326Sed break; 1708194179Sed 1709194179Sed case Decl::StaticAssert: 1710194179Sed // Nothing to do. 1711194179Sed break; 1712194179Sed 1713193326Sed // Objective-C Decls 1714198092Srdivacky 1715193326Sed // Forward declarations, no (immediate) code generation. 1716193326Sed case Decl::ObjCClass: 1717193326Sed case Decl::ObjCForwardProtocol: 1718193326Sed case Decl::ObjCCategory: 1719193326Sed case Decl::ObjCInterface: 1720193326Sed break; 1721193326Sed 1722193326Sed case Decl::ObjCProtocol: 1723193326Sed Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D)); 1724193326Sed break; 1725193326Sed 1726193326Sed case Decl::ObjCCategoryImpl: 1727193326Sed // Categories have properties but don't support synthesize so we 1728193326Sed // can ignore them here. 1729193326Sed Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 1730193326Sed break; 1731193326Sed 1732193326Sed case Decl::ObjCImplementation: { 1733193326Sed ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D); 1734193326Sed EmitObjCPropertyImplementations(OMD); 1735193326Sed Runtime->GenerateClass(OMD); 1736193326Sed break; 1737198092Srdivacky } 1738193326Sed case Decl::ObjCMethod: { 1739193326Sed ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D); 1740193326Sed // If this is not a prototype, emit the body. 1741195341Sed if (OMD->getBody()) 1742193326Sed CodeGenFunction(*this).GenerateObjCMethod(OMD); 1743193326Sed break; 1744193326Sed } 1745198092Srdivacky case Decl::ObjCCompatibleAlias: 1746193326Sed // compatibility-alias is a directive and has no code gen. 1747193326Sed break; 1748193326Sed 1749193326Sed case Decl::LinkageSpec: 1750193326Sed EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 1751193326Sed break; 1752193326Sed 1753193326Sed case Decl::FileScopeAsm: { 1754193326Sed FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D); 1755193326Sed std::string AsmString(AD->getAsmString()->getStrData(), 1756193326Sed AD->getAsmString()->getByteLength()); 1757198092Srdivacky 1758193326Sed const std::string &S = getModule().getModuleInlineAsm(); 1759193326Sed if (S.empty()) 1760193326Sed getModule().setModuleInlineAsm(AsmString); 1761193326Sed else 1762193326Sed getModule().setModuleInlineAsm(S + '\n' + AsmString); 1763193326Sed break; 1764193326Sed } 1765198092Srdivacky 1766198092Srdivacky default: 1767193326Sed // Make sure we handled everything we should, every other kind is a 1768193326Sed // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 1769193326Sed // function. Need to recode Decl::Kind to do that easily. 1770193326Sed assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 1771193326Sed } 1772193326Sed} 1773