1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This coordinates the per-module state used while generating code.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenModule.h"
15 #include "CGDebugInfo.h"
16 #include "CodeGenFunction.h"
17 #include "CodeGenTBAA.h"
19 #include "CGCUDARuntime.h"
21 #include "CGObjCRuntime.h"
22 #include "CGOpenCLRuntime.h"
23 #include "TargetInfo.h"
24 #include "clang/Frontend/CodeGenOptions.h"
25 #include "clang/AST/ASTContext.h"
26 #include "clang/AST/CharUnits.h"
27 #include "clang/AST/DeclObjC.h"
28 #include "clang/AST/DeclCXX.h"
29 #include "clang/AST/DeclTemplate.h"
30 #include "clang/AST/Mangle.h"
31 #include "clang/AST/RecordLayout.h"
32 #include "clang/AST/RecursiveASTVisitor.h"
33 #include "clang/Basic/Builtins.h"
34 #include "clang/Basic/Diagnostic.h"
35 #include "clang/Basic/SourceManager.h"
36 #include "clang/Basic/TargetInfo.h"
37 #include "clang/Basic/ConvertUTF.h"
38 #include "llvm/CallingConv.h"
39 #include "llvm/Module.h"
40 #include "llvm/Intrinsics.h"
41 #include "llvm/LLVMContext.h"
42 #include "llvm/ADT/APSInt.h"
43 #include "llvm/ADT/Triple.h"
44 #include "llvm/Target/Mangler.h"
45 #include "llvm/Target/TargetData.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/ErrorHandling.h"
48 using namespace clang;
49 using namespace CodeGen;
51 static const char AnnotationSection[] = "llvm.metadata";
53 static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
54 switch (CGM.getContext().getTargetInfo().getCXXABI()) {
55 case CXXABI_ARM: return *CreateARMCXXABI(CGM);
56 case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
57 case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
60 llvm_unreachable("invalid C++ ABI kind");
64 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
65 llvm::Module &M, const llvm::TargetData &TD,
66 DiagnosticsEngine &diags)
67 : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
68 TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
69 ABI(createCXXABI(*this)),
72 VTables(*this), ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0),
73 DebugInfo(0), ARCData(0), NoObjCARCExceptionsMetadata(0),
74 RRData(0), CFConstantStringClassRef(0),
75 ConstantStringClassRef(0), NSConstantStringType(0),
76 VMContext(M.getContext()),
77 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
78 BlockObjectAssign(0), BlockObjectDispose(0),
79 BlockDescriptorType(0), GenericBlockLiteralType(0) {
81 // Initialize the type cache.
82 llvm::LLVMContext &LLVMContext = M.getContext();
83 VoidTy = llvm::Type::getVoidTy(LLVMContext);
84 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
85 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
86 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
87 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
88 FloatTy = llvm::Type::getFloatTy(LLVMContext);
89 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
90 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
92 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
93 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
94 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
95 Int8PtrTy = Int8Ty->getPointerTo(0);
96 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
101 createOpenCLRuntime();
105 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
106 if (LangOpts.ThreadSanitizer ||
107 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
108 TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
109 ABI.getMangleContext());
111 // If debug info or coverage generation is enabled, create the CGDebugInfo
113 if (CodeGenOpts.DebugInfo != CodeGenOptions::NoDebugInfo ||
114 CodeGenOpts.EmitGcovArcs ||
115 CodeGenOpts.EmitGcovNotes)
116 DebugInfo = new CGDebugInfo(*this);
118 Block.GlobalUniqueCount = 0;
120 if (C.getLangOpts().ObjCAutoRefCount)
121 ARCData = new ARCEntrypoints();
122 RRData = new RREntrypoints();
125 CodeGenModule::~CodeGenModule() {
127 delete OpenCLRuntime;
129 delete TheTargetCodeGenInfo;
137 void CodeGenModule::createObjCRuntime() {
138 // This is just isGNUFamily(), but we want to force implementors of
139 // new ABIs to decide how best to do this.
140 switch (LangOpts.ObjCRuntime.getKind()) {
141 case ObjCRuntime::GNUstep:
142 case ObjCRuntime::GCC:
143 case ObjCRuntime::ObjFW:
144 ObjCRuntime = CreateGNUObjCRuntime(*this);
147 case ObjCRuntime::FragileMacOSX:
148 case ObjCRuntime::MacOSX:
149 case ObjCRuntime::iOS:
150 ObjCRuntime = CreateMacObjCRuntime(*this);
153 llvm_unreachable("bad runtime kind");
156 void CodeGenModule::createOpenCLRuntime() {
157 OpenCLRuntime = new CGOpenCLRuntime(*this);
160 void CodeGenModule::createCUDARuntime() {
161 CUDARuntime = CreateNVCUDARuntime(*this);
164 void CodeGenModule::Release() {
166 EmitCXXGlobalInitFunc();
167 EmitCXXGlobalDtorFunc();
169 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
170 AddGlobalCtor(ObjCInitFunction);
171 EmitCtorList(GlobalCtors, "llvm.global_ctors");
172 EmitCtorList(GlobalDtors, "llvm.global_dtors");
173 EmitGlobalAnnotations();
176 SimplifyPersonality();
178 if (getCodeGenOpts().EmitDeclMetadata)
181 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
185 DebugInfo->finalize();
188 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
189 // Make sure that this type is translated.
190 Types.UpdateCompletedType(TD);
193 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
196 return TBAA->getTBAAInfo(QTy);
199 llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
202 return TBAA->getTBAAInfoForVTablePtr();
205 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
206 llvm::MDNode *TBAAInfo) {
207 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
210 bool CodeGenModule::isTargetDarwin() const {
211 return getContext().getTargetInfo().getTriple().isOSDarwin();
214 void CodeGenModule::Error(SourceLocation loc, StringRef error) {
215 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error);
216 getDiags().Report(Context.getFullLoc(loc), diagID);
219 /// ErrorUnsupported - Print out an error that codegen doesn't support the
220 /// specified stmt yet.
221 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
223 if (OmitOnError && getDiags().hasErrorOccurred())
225 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
226 "cannot compile this %0 yet");
227 std::string Msg = Type;
228 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
229 << Msg << S->getSourceRange();
232 /// ErrorUnsupported - Print out an error that codegen doesn't support the
233 /// specified decl yet.
234 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
236 if (OmitOnError && getDiags().hasErrorOccurred())
238 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
239 "cannot compile this %0 yet");
240 std::string Msg = Type;
241 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
244 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
245 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
248 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
249 const NamedDecl *D) const {
250 // Internal definitions always have default visibility.
251 if (GV->hasLocalLinkage()) {
252 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
256 // Set visibility for definitions.
257 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
258 if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
259 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
262 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
263 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
264 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
265 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
266 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
267 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
270 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
271 CodeGenOptions::TLSModel M) {
273 case CodeGenOptions::GeneralDynamicTLSModel:
274 return llvm::GlobalVariable::GeneralDynamicTLSModel;
275 case CodeGenOptions::LocalDynamicTLSModel:
276 return llvm::GlobalVariable::LocalDynamicTLSModel;
277 case CodeGenOptions::InitialExecTLSModel:
278 return llvm::GlobalVariable::InitialExecTLSModel;
279 case CodeGenOptions::LocalExecTLSModel:
280 return llvm::GlobalVariable::LocalExecTLSModel;
282 llvm_unreachable("Invalid TLS model!");
285 void CodeGenModule::setTLSMode(llvm::GlobalVariable *GV,
286 const VarDecl &D) const {
287 assert(D.isThreadSpecified() && "setting TLS mode on non-TLS var!");
289 llvm::GlobalVariable::ThreadLocalMode TLM;
290 TLM = GetLLVMTLSModel(CodeGenOpts.DefaultTLSModel);
292 // Override the TLS model if it is explicitly specified.
293 if (D.hasAttr<TLSModelAttr>()) {
294 const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>();
295 TLM = GetLLVMTLSModel(Attr->getModel());
298 GV->setThreadLocalMode(TLM);
301 /// Set the symbol visibility of type information (vtable and RTTI)
302 /// associated with the given type.
303 void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
304 const CXXRecordDecl *RD,
305 TypeVisibilityKind TVK) const {
306 setGlobalVisibility(GV, RD);
308 if (!CodeGenOpts.HiddenWeakVTables)
311 // We never want to drop the visibility for RTTI names.
312 if (TVK == TVK_ForRTTIName)
315 // We want to drop the visibility to hidden for weak type symbols.
316 // This isn't possible if there might be unresolved references
317 // elsewhere that rely on this symbol being visible.
319 // This should be kept roughly in sync with setThunkVisibility
323 if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
324 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
327 // Don't override an explicit visibility attribute.
328 if (RD->getExplicitVisibility())
331 switch (RD->getTemplateSpecializationKind()) {
332 // We have to disable the optimization if this is an EI definition
333 // because there might be EI declarations in other shared objects.
334 case TSK_ExplicitInstantiationDefinition:
335 case TSK_ExplicitInstantiationDeclaration:
338 // Every use of a non-template class's type information has to emit it.
342 // In theory, implicit instantiations can ignore the possibility of
343 // an explicit instantiation declaration because there necessarily
344 // must be an EI definition somewhere with default visibility. In
345 // practice, it's possible to have an explicit instantiation for
346 // an arbitrary template class, and linkers aren't necessarily able
347 // to deal with mixed-visibility symbols.
348 case TSK_ExplicitSpecialization:
349 case TSK_ImplicitInstantiation:
350 if (!CodeGenOpts.HiddenWeakTemplateVTables)
355 // If there's a key function, there may be translation units
356 // that don't have the key function's definition. But ignore
357 // this if we're emitting RTTI under -fno-rtti.
358 if (!(TVK != TVK_ForRTTI) || LangOpts.RTTI) {
359 if (Context.getKeyFunction(RD))
363 // Otherwise, drop the visibility to hidden.
364 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
365 GV->setUnnamedAddr(true);
368 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
369 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
371 StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
375 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
376 IdentifierInfo *II = ND->getIdentifier();
377 assert(II && "Attempt to mangle unnamed decl.");
383 SmallString<256> Buffer;
384 llvm::raw_svector_ostream Out(Buffer);
385 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
386 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
387 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
388 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
389 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
390 getCXXABI().getMangleContext().mangleBlock(BD, Out,
391 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()));
393 getCXXABI().getMangleContext().mangleName(ND, Out);
395 // Allocate space for the mangled name.
397 size_t Length = Buffer.size();
398 char *Name = MangledNamesAllocator.Allocate<char>(Length);
399 std::copy(Buffer.begin(), Buffer.end(), Name);
401 Str = StringRef(Name, Length);
406 void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
407 const BlockDecl *BD) {
408 MangleContext &MangleCtx = getCXXABI().getMangleContext();
409 const Decl *D = GD.getDecl();
410 llvm::raw_svector_ostream Out(Buffer.getBuffer());
412 MangleCtx.mangleGlobalBlock(BD,
413 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
414 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
415 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
416 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
417 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
419 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
422 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
423 return getModule().getNamedValue(Name);
426 /// AddGlobalCtor - Add a function to the list that will be called before
428 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
429 // FIXME: Type coercion of void()* types.
430 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
433 /// AddGlobalDtor - Add a function to the list that will be called
434 /// when the module is unloaded.
435 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
436 // FIXME: Type coercion of void()* types.
437 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
440 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
441 // Ctor function type is void()*.
442 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
443 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
445 // Get the type of a ctor entry, { i32, void ()* }.
446 llvm::StructType *CtorStructTy =
447 llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL);
449 // Construct the constructor and destructor arrays.
450 SmallVector<llvm::Constant*, 8> Ctors;
451 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
452 llvm::Constant *S[] = {
453 llvm::ConstantInt::get(Int32Ty, I->second, false),
454 llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)
456 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
459 if (!Ctors.empty()) {
460 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
461 new llvm::GlobalVariable(TheModule, AT, false,
462 llvm::GlobalValue::AppendingLinkage,
463 llvm::ConstantArray::get(AT, Ctors),
468 llvm::GlobalValue::LinkageTypes
469 CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
470 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
472 if (Linkage == GVA_Internal)
473 return llvm::Function::InternalLinkage;
475 if (D->hasAttr<DLLExportAttr>())
476 return llvm::Function::DLLExportLinkage;
478 if (D->hasAttr<WeakAttr>())
479 return llvm::Function::WeakAnyLinkage;
481 // In C99 mode, 'inline' functions are guaranteed to have a strong
482 // definition somewhere else, so we can use available_externally linkage.
483 if (Linkage == GVA_C99Inline)
484 return llvm::Function::AvailableExternallyLinkage;
486 // Note that Apple's kernel linker doesn't support symbol
487 // coalescing, so we need to avoid linkonce and weak linkages there.
488 // Normally, this means we just map to internal, but for explicit
489 // instantiations we'll map to external.
491 // In C++, the compiler has to emit a definition in every translation unit
492 // that references the function. We should use linkonce_odr because
493 // a) if all references in this translation unit are optimized away, we
494 // don't need to codegen it. b) if the function persists, it needs to be
495 // merged with other definitions. c) C++ has the ODR, so we know the
496 // definition is dependable.
497 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
498 return !Context.getLangOpts().AppleKext
499 ? llvm::Function::LinkOnceODRLinkage
500 : llvm::Function::InternalLinkage;
502 // An explicit instantiation of a template has weak linkage, since
503 // explicit instantiations can occur in multiple translation units
504 // and must all be equivalent. However, we are not allowed to
505 // throw away these explicit instantiations.
506 if (Linkage == GVA_ExplicitTemplateInstantiation)
507 return !Context.getLangOpts().AppleKext
508 ? llvm::Function::WeakODRLinkage
509 : llvm::Function::ExternalLinkage;
511 // Otherwise, we have strong external linkage.
512 assert(Linkage == GVA_StrongExternal);
513 return llvm::Function::ExternalLinkage;
517 /// SetFunctionDefinitionAttributes - Set attributes for a global.
519 /// FIXME: This is currently only done for aliases and functions, but not for
520 /// variables (these details are set in EmitGlobalVarDefinition for variables).
521 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
522 llvm::GlobalValue *GV) {
523 SetCommonAttributes(D, GV);
526 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
527 const CGFunctionInfo &Info,
529 unsigned CallingConv;
530 AttributeListType AttributeList;
531 ConstructAttributeList(Info, D, AttributeList, CallingConv);
532 F->setAttributes(llvm::AttrListPtr::get(AttributeList));
533 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
536 /// Determines whether the language options require us to model
537 /// unwind exceptions. We treat -fexceptions as mandating this
538 /// except under the fragile ObjC ABI with only ObjC exceptions
539 /// enabled. This means, for example, that C with -fexceptions
541 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
542 // If exceptions are completely disabled, obviously this is false.
543 if (!LangOpts.Exceptions) return false;
545 // If C++ exceptions are enabled, this is true.
546 if (LangOpts.CXXExceptions) return true;
548 // If ObjC exceptions are enabled, this depends on the ABI.
549 if (LangOpts.ObjCExceptions) {
550 return LangOpts.ObjCRuntime.hasUnwindExceptions();
556 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
558 if (CodeGenOpts.UnwindTables)
561 if (!hasUnwindExceptions(LangOpts))
562 F->addFnAttr(llvm::Attribute::NoUnwind);
564 if (D->hasAttr<NakedAttr>()) {
565 // Naked implies noinline: we should not be inlining such functions.
566 F->addFnAttr(llvm::Attribute::Naked);
567 F->addFnAttr(llvm::Attribute::NoInline);
570 if (D->hasAttr<NoInlineAttr>())
571 F->addFnAttr(llvm::Attribute::NoInline);
573 // (noinline wins over always_inline, and we can't specify both in IR)
574 if ((D->hasAttr<AlwaysInlineAttr>() || D->hasAttr<ForceInlineAttr>()) &&
575 !F->hasFnAttr(llvm::Attribute::NoInline))
576 F->addFnAttr(llvm::Attribute::AlwaysInline);
578 // FIXME: Communicate hot and cold attributes to LLVM more directly.
579 if (D->hasAttr<ColdAttr>())
580 F->addFnAttr(llvm::Attribute::OptimizeForSize);
582 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
583 F->setUnnamedAddr(true);
585 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
586 F->addFnAttr(llvm::Attribute::StackProtect);
587 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
588 F->addFnAttr(llvm::Attribute::StackProtectReq);
590 if (LangOpts.AddressSanitizer) {
591 // When AddressSanitizer is enabled, set AddressSafety attribute
592 // unless __attribute__((no_address_safety_analysis)) is used.
593 if (!D->hasAttr<NoAddressSafetyAnalysisAttr>())
594 F->addFnAttr(llvm::Attribute::AddressSafety);
597 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
599 F->setAlignment(alignment);
601 // C++ ABI requires 2-byte alignment for member functions.
602 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
606 void CodeGenModule::SetCommonAttributes(const Decl *D,
607 llvm::GlobalValue *GV) {
608 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
609 setGlobalVisibility(GV, ND);
611 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
613 if (D->hasAttr<UsedAttr>())
616 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
617 GV->setSection(SA->getName());
619 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
622 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
624 const CGFunctionInfo &FI) {
625 SetLLVMFunctionAttributes(D, FI, F);
626 SetLLVMFunctionAttributesForDefinition(D, F);
628 F->setLinkage(llvm::Function::InternalLinkage);
630 SetCommonAttributes(D, F);
633 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
635 bool IsIncompleteFunction) {
636 if (unsigned IID = F->getIntrinsicID()) {
637 // If this is an intrinsic function, set the function's attributes
638 // to the intrinsic's attributes.
639 F->setAttributes(llvm::Intrinsic::getAttributes((llvm::Intrinsic::ID)IID));
643 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
645 if (!IsIncompleteFunction)
646 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
648 // Only a few attributes are set on declarations; these may later be
649 // overridden by a definition.
651 if (FD->hasAttr<DLLImportAttr>()) {
652 F->setLinkage(llvm::Function::DLLImportLinkage);
653 } else if (FD->hasAttr<WeakAttr>() ||
654 FD->isWeakImported()) {
655 // "extern_weak" is overloaded in LLVM; we probably should have
656 // separate linkage types for this.
657 F->setLinkage(llvm::Function::ExternalWeakLinkage);
659 F->setLinkage(llvm::Function::ExternalLinkage);
661 NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
662 if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
663 F->setVisibility(GetLLVMVisibility(LV.visibility()));
667 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
668 F->setSection(SA->getName());
671 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
672 assert(!GV->isDeclaration() &&
673 "Only globals with definition can force usage.");
674 LLVMUsed.push_back(GV);
677 void CodeGenModule::EmitLLVMUsed() {
678 // Don't create llvm.used if there is no need.
679 if (LLVMUsed.empty())
682 // Convert LLVMUsed to what ConstantArray needs.
683 SmallVector<llvm::Constant*, 8> UsedArray;
684 UsedArray.resize(LLVMUsed.size());
685 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
687 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
691 if (UsedArray.empty())
693 llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
695 llvm::GlobalVariable *GV =
696 new llvm::GlobalVariable(getModule(), ATy, false,
697 llvm::GlobalValue::AppendingLinkage,
698 llvm::ConstantArray::get(ATy, UsedArray),
701 GV->setSection("llvm.metadata");
704 void CodeGenModule::EmitDeferred() {
705 // Emit code for any potentially referenced deferred decls. Since a
706 // previously unused static decl may become used during the generation of code
707 // for a static function, iterate until no changes are made.
709 while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
710 if (!DeferredVTables.empty()) {
711 const CXXRecordDecl *RD = DeferredVTables.back();
712 DeferredVTables.pop_back();
713 getCXXABI().EmitVTables(RD);
717 GlobalDecl D = DeferredDeclsToEmit.back();
718 DeferredDeclsToEmit.pop_back();
720 // Check to see if we've already emitted this. This is necessary
721 // for a couple of reasons: first, decls can end up in the
722 // deferred-decls queue multiple times, and second, decls can end
723 // up with definitions in unusual ways (e.g. by an extern inline
724 // function acquiring a strong function redefinition). Just
725 // ignore these cases.
727 // TODO: That said, looking this up multiple times is very wasteful.
728 StringRef Name = getMangledName(D);
729 llvm::GlobalValue *CGRef = GetGlobalValue(Name);
730 assert(CGRef && "Deferred decl wasn't referenced?");
732 if (!CGRef->isDeclaration())
735 // GlobalAlias::isDeclaration() defers to the aliasee, but for our
736 // purposes an alias counts as a definition.
737 if (isa<llvm::GlobalAlias>(CGRef))
740 // Otherwise, emit the definition and move on to the next one.
741 EmitGlobalDefinition(D);
745 void CodeGenModule::EmitGlobalAnnotations() {
746 if (Annotations.empty())
749 // Create a new global variable for the ConstantStruct in the Module.
750 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
751 Annotations[0]->getType(), Annotations.size()), Annotations);
752 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
753 Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
754 "llvm.global.annotations");
755 gv->setSection(AnnotationSection);
758 llvm::Constant *CodeGenModule::EmitAnnotationString(llvm::StringRef Str) {
759 llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str);
760 if (i != AnnotationStrings.end())
763 // Not found yet, create a new global.
764 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
765 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
766 true, llvm::GlobalValue::PrivateLinkage, s, ".str");
767 gv->setSection(AnnotationSection);
768 gv->setUnnamedAddr(true);
769 AnnotationStrings[Str] = gv;
773 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
774 SourceManager &SM = getContext().getSourceManager();
775 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
777 return EmitAnnotationString(PLoc.getFilename());
778 return EmitAnnotationString(SM.getBufferName(Loc));
781 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
782 SourceManager &SM = getContext().getSourceManager();
783 PresumedLoc PLoc = SM.getPresumedLoc(L);
784 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
785 SM.getExpansionLineNumber(L);
786 return llvm::ConstantInt::get(Int32Ty, LineNo);
789 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
790 const AnnotateAttr *AA,
792 // Get the globals for file name, annotation, and the line number.
793 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
794 *UnitGV = EmitAnnotationUnit(L),
795 *LineNoCst = EmitAnnotationLineNo(L);
797 // Create the ConstantStruct for the global annotation.
798 llvm::Constant *Fields[4] = {
799 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
800 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
801 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
804 return llvm::ConstantStruct::getAnon(Fields);
807 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
808 llvm::GlobalValue *GV) {
809 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
810 // Get the struct elements for these annotations.
811 for (specific_attr_iterator<AnnotateAttr>
812 ai = D->specific_attr_begin<AnnotateAttr>(),
813 ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
814 Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
817 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
818 // Never defer when EmitAllDecls is specified.
819 if (LangOpts.EmitAllDecls)
822 return !getContext().DeclMustBeEmitted(Global);
825 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
826 const AliasAttr *AA = VD->getAttr<AliasAttr>();
827 assert(AA && "No alias?");
829 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
831 // See if there is already something with the target's name in the module.
832 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
834 llvm::Constant *Aliasee;
835 if (isa<llvm::FunctionType>(DeclTy))
836 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
837 /*ForVTable=*/false);
839 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
840 llvm::PointerType::getUnqual(DeclTy), 0);
842 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
843 F->setLinkage(llvm::Function::ExternalWeakLinkage);
844 WeakRefReferences.insert(F);
850 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
851 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
853 // Weak references don't produce any output by themselves.
854 if (Global->hasAttr<WeakRefAttr>())
857 // If this is an alias definition (which otherwise looks like a declaration)
859 if (Global->hasAttr<AliasAttr>())
860 return EmitAliasDefinition(GD);
862 // If this is CUDA, be selective about which declarations we emit.
864 if (CodeGenOpts.CUDAIsDevice) {
865 if (!Global->hasAttr<CUDADeviceAttr>() &&
866 !Global->hasAttr<CUDAGlobalAttr>() &&
867 !Global->hasAttr<CUDAConstantAttr>() &&
868 !Global->hasAttr<CUDASharedAttr>())
871 if (!Global->hasAttr<CUDAHostAttr>() && (
872 Global->hasAttr<CUDADeviceAttr>() ||
873 Global->hasAttr<CUDAConstantAttr>() ||
874 Global->hasAttr<CUDASharedAttr>()))
879 // Ignore declarations, they will be emitted on their first use.
880 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
881 // Forward declarations are emitted lazily on first use.
882 if (!FD->doesThisDeclarationHaveABody()) {
883 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
886 const FunctionDecl *InlineDefinition = 0;
887 FD->getBody(InlineDefinition);
889 StringRef MangledName = getMangledName(GD);
890 DeferredDecls.erase(MangledName);
891 EmitGlobalDefinition(InlineDefinition);
895 const VarDecl *VD = cast<VarDecl>(Global);
896 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
898 if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
902 // Defer code generation when possible if this is a static definition, inline
903 // function etc. These we only want to emit if they are used.
904 if (!MayDeferGeneration(Global)) {
905 // Emit the definition if it can't be deferred.
906 EmitGlobalDefinition(GD);
910 // If we're deferring emission of a C++ variable with an
911 // initializer, remember the order in which it appeared in the file.
912 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
913 cast<VarDecl>(Global)->hasInit()) {
914 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
915 CXXGlobalInits.push_back(0);
918 // If the value has already been used, add it directly to the
919 // DeferredDeclsToEmit list.
920 StringRef MangledName = getMangledName(GD);
921 if (GetGlobalValue(MangledName))
922 DeferredDeclsToEmit.push_back(GD);
924 // Otherwise, remember that we saw a deferred decl with this name. The
925 // first use of the mangled name will cause it to move into
926 // DeferredDeclsToEmit.
927 DeferredDecls[MangledName] = GD;
932 struct FunctionIsDirectlyRecursive :
933 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
934 const StringRef Name;
935 const Builtin::Context &BI;
937 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
938 Name(N), BI(C), Result(false) {
940 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
942 bool TraverseCallExpr(CallExpr *E) {
943 const FunctionDecl *FD = E->getDirectCallee();
946 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
947 if (Attr && Name == Attr->getLabel()) {
951 unsigned BuiltinID = FD->getBuiltinID();
954 StringRef BuiltinName = BI.GetName(BuiltinID);
955 if (BuiltinName.startswith("__builtin_") &&
956 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
965 // isTriviallyRecursive - Check if this function calls another
966 // decl that, because of the asm attribute or the other decl being a builtin,
967 // ends up pointing to itself.
969 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
971 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
972 // asm labels are a special kind of mangling we have to support.
973 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
976 Name = Attr->getLabel();
978 Name = FD->getName();
981 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
982 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
983 return Walker.Result;
987 CodeGenModule::shouldEmitFunction(const FunctionDecl *F) {
988 if (getFunctionLinkage(F) != llvm::Function::AvailableExternallyLinkage)
990 if (CodeGenOpts.OptimizationLevel == 0 &&
991 !F->hasAttr<AlwaysInlineAttr>() && !F->hasAttr<ForceInlineAttr>())
993 // PR9614. Avoid cases where the source code is lying to us. An available
994 // externally function should have an equivalent function somewhere else,
995 // but a function that calls itself is clearly not equivalent to the real
997 // This happens in glibc's btowc and in some configure checks.
998 return !isTriviallyRecursive(F);
1001 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
1002 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
1004 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1005 Context.getSourceManager(),
1006 "Generating code for declaration");
1008 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1009 // At -O0, don't generate IR for functions with available_externally
1011 if (!shouldEmitFunction(Function))
1014 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
1015 // Make sure to emit the definition(s) before we emit the thunks.
1016 // This is necessary for the generation of certain thunks.
1017 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
1018 EmitCXXConstructor(CD, GD.getCtorType());
1019 else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
1020 EmitCXXDestructor(DD, GD.getDtorType());
1022 EmitGlobalFunctionDefinition(GD);
1024 if (Method->isVirtual())
1025 getVTables().EmitThunks(GD);
1030 return EmitGlobalFunctionDefinition(GD);
1033 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1034 return EmitGlobalVarDefinition(VD);
1036 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1039 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1040 /// module, create and return an llvm Function with the specified type. If there
1041 /// is something in the module with the specified name, return it potentially
1042 /// bitcasted to the right type.
1044 /// If D is non-null, it specifies a decl that correspond to this. This is used
1045 /// to set the attributes on the function when it is first created.
1047 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
1049 GlobalDecl D, bool ForVTable,
1050 llvm::Attributes ExtraAttrs) {
1051 // Lookup the entry, lazily creating it if necessary.
1052 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1054 if (WeakRefReferences.count(Entry)) {
1055 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
1056 if (FD && !FD->hasAttr<WeakAttr>())
1057 Entry->setLinkage(llvm::Function::ExternalLinkage);
1059 WeakRefReferences.erase(Entry);
1062 if (Entry->getType()->getElementType() == Ty)
1065 // Make sure the result is of the correct type.
1066 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1069 // This function doesn't have a complete type (for example, the return
1070 // type is an incomplete struct). Use a fake type instead, and make
1071 // sure not to try to set attributes.
1072 bool IsIncompleteFunction = false;
1074 llvm::FunctionType *FTy;
1075 if (isa<llvm::FunctionType>(Ty)) {
1076 FTy = cast<llvm::FunctionType>(Ty);
1078 FTy = llvm::FunctionType::get(VoidTy, false);
1079 IsIncompleteFunction = true;
1082 llvm::Function *F = llvm::Function::Create(FTy,
1083 llvm::Function::ExternalLinkage,
1084 MangledName, &getModule());
1085 assert(F->getName() == MangledName && "name was uniqued!");
1087 SetFunctionAttributes(D, F, IsIncompleteFunction);
1088 if (ExtraAttrs != llvm::Attribute::None)
1089 F->addFnAttr(ExtraAttrs);
1091 // This is the first use or definition of a mangled name. If there is a
1092 // deferred decl with this name, remember that we need to emit it at the end
1094 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1095 if (DDI != DeferredDecls.end()) {
1096 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1097 // list, and remove it from DeferredDecls (since we don't need it anymore).
1098 DeferredDeclsToEmit.push_back(DDI->second);
1099 DeferredDecls.erase(DDI);
1101 // Otherwise, there are cases we have to worry about where we're
1102 // using a declaration for which we must emit a definition but where
1103 // we might not find a top-level definition:
1104 // - member functions defined inline in their classes
1105 // - friend functions defined inline in some class
1106 // - special member functions with implicit definitions
1107 // If we ever change our AST traversal to walk into class methods,
1108 // this will be unnecessary.
1110 // We also don't emit a definition for a function if it's going to be an entry
1111 // in a vtable, unless it's already marked as used.
1112 } else if (getLangOpts().CPlusPlus && D.getDecl()) {
1113 // Look for a declaration that's lexically in a record.
1114 const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
1115 FD = FD->getMostRecentDecl();
1117 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
1118 if (FD->isImplicit() && !ForVTable) {
1119 assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
1120 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
1122 } else if (FD->doesThisDeclarationHaveABody()) {
1123 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
1127 FD = FD->getPreviousDecl();
1131 // Make sure the result is of the requested type.
1132 if (!IsIncompleteFunction) {
1133 assert(F->getType()->getElementType() == Ty);
1137 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1138 return llvm::ConstantExpr::getBitCast(F, PTy);
1141 /// GetAddrOfFunction - Return the address of the given function. If Ty is
1142 /// non-null, then this function will use the specified type if it has to
1143 /// create it (this occurs when we see a definition of the function).
1144 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
1147 // If there was no specific requested type, just convert it now.
1149 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
1151 StringRef MangledName = getMangledName(GD);
1152 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
1155 /// CreateRuntimeFunction - Create a new runtime function with the specified
1158 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
1160 llvm::Attributes ExtraAttrs) {
1161 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1165 /// isTypeConstant - Determine whether an object of this type can be emitted
1168 /// If ExcludeCtor is true, the duration when the object's constructor runs
1169 /// will not be considered. The caller will need to verify that the object is
1170 /// not written to during its construction.
1171 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1172 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
1175 if (Context.getLangOpts().CPlusPlus) {
1176 if (const CXXRecordDecl *Record
1177 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1178 return ExcludeCtor && !Record->hasMutableFields() &&
1179 Record->hasTrivialDestructor();
1185 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1186 /// create and return an llvm GlobalVariable with the specified type. If there
1187 /// is something in the module with the specified name, return it potentially
1188 /// bitcasted to the right type.
1190 /// If D is non-null, it specifies a decl that correspond to this. This is used
1191 /// to set the attributes on the global when it is first created.
1193 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
1194 llvm::PointerType *Ty,
1197 // Lookup the entry, lazily creating it if necessary.
1198 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1200 if (WeakRefReferences.count(Entry)) {
1201 if (D && !D->hasAttr<WeakAttr>())
1202 Entry->setLinkage(llvm::Function::ExternalLinkage);
1204 WeakRefReferences.erase(Entry);
1208 Entry->setUnnamedAddr(true);
1210 if (Entry->getType() == Ty)
1213 // Make sure the result is of the correct type.
1214 return llvm::ConstantExpr::getBitCast(Entry, Ty);
1217 // This is the first use or definition of a mangled name. If there is a
1218 // deferred decl with this name, remember that we need to emit it at the end
1220 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1221 if (DDI != DeferredDecls.end()) {
1222 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1223 // list, and remove it from DeferredDecls (since we don't need it anymore).
1224 DeferredDeclsToEmit.push_back(DDI->second);
1225 DeferredDecls.erase(DDI);
1228 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
1229 llvm::GlobalVariable *GV =
1230 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
1231 llvm::GlobalValue::ExternalLinkage,
1233 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
1235 // Handle things which are present even on external declarations.
1237 // FIXME: This code is overly simple and should be merged with other global
1239 GV->setConstant(isTypeConstant(D->getType(), false));
1241 // Set linkage and visibility in case we never see a definition.
1242 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
1243 if (LV.linkage() != ExternalLinkage) {
1244 // Don't set internal linkage on declarations.
1246 if (D->hasAttr<DLLImportAttr>())
1247 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
1248 else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
1249 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1251 // Set visibility on a declaration only if it's explicit.
1252 if (LV.visibilityExplicit())
1253 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
1256 if (D->isThreadSpecified())
1260 if (AddrSpace != Ty->getAddressSpace())
1261 return llvm::ConstantExpr::getBitCast(GV, Ty);
1267 llvm::GlobalVariable *
1268 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
1270 llvm::GlobalValue::LinkageTypes Linkage) {
1271 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1272 llvm::GlobalVariable *OldGV = 0;
1276 // Check if the variable has the right type.
1277 if (GV->getType()->getElementType() == Ty)
1280 // Because C++ name mangling, the only way we can end up with an already
1281 // existing global with the same name is if it has been declared extern "C".
1282 assert(GV->isDeclaration() && "Declaration has wrong type!");
1286 // Create a new variable.
1287 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1291 // Replace occurrences of the old variable if needed.
1292 GV->takeName(OldGV);
1294 if (!OldGV->use_empty()) {
1295 llvm::Constant *NewPtrForOldDecl =
1296 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1297 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1300 OldGV->eraseFromParent();
1306 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1307 /// given global variable. If Ty is non-null and if the global doesn't exist,
1308 /// then it will be created with the specified type instead of whatever the
1309 /// normal requested type would be.
1310 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1312 assert(D->hasGlobalStorage() && "Not a global variable");
1313 QualType ASTTy = D->getType();
1315 Ty = getTypes().ConvertTypeForMem(ASTTy);
1317 llvm::PointerType *PTy =
1318 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1320 StringRef MangledName = getMangledName(D);
1321 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
1324 /// CreateRuntimeVariable - Create a new runtime global variable with the
1325 /// specified type and name.
1327 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
1329 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
1333 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1334 assert(!D->getInit() && "Cannot emit definite definitions here!");
1336 if (MayDeferGeneration(D)) {
1337 // If we have not seen a reference to this variable yet, place it
1338 // into the deferred declarations table to be emitted if needed
1340 StringRef MangledName = getMangledName(D);
1341 if (!GetGlobalValue(MangledName)) {
1342 DeferredDecls[MangledName] = D;
1347 // The tentative definition is the only definition.
1348 EmitGlobalVarDefinition(D);
1351 void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
1352 if (DefinitionRequired)
1353 getCXXABI().EmitVTables(Class);
1356 llvm::GlobalVariable::LinkageTypes
1357 CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
1358 if (RD->getLinkage() != ExternalLinkage)
1359 return llvm::GlobalVariable::InternalLinkage;
1361 if (const CXXMethodDecl *KeyFunction
1362 = RD->getASTContext().getKeyFunction(RD)) {
1363 // If this class has a key function, use that to determine the linkage of
1365 const FunctionDecl *Def = 0;
1366 if (KeyFunction->hasBody(Def))
1367 KeyFunction = cast<CXXMethodDecl>(Def);
1369 switch (KeyFunction->getTemplateSpecializationKind()) {
1370 case TSK_Undeclared:
1371 case TSK_ExplicitSpecialization:
1372 // When compiling with optimizations turned on, we emit all vtables,
1373 // even if the key function is not defined in the current translation
1374 // unit. If this is the case, use available_externally linkage.
1375 if (!Def && CodeGenOpts.OptimizationLevel)
1376 return llvm::GlobalVariable::AvailableExternallyLinkage;
1378 if (KeyFunction->isInlined())
1379 return !Context.getLangOpts().AppleKext ?
1380 llvm::GlobalVariable::LinkOnceODRLinkage :
1381 llvm::Function::InternalLinkage;
1383 return llvm::GlobalVariable::ExternalLinkage;
1385 case TSK_ImplicitInstantiation:
1386 return !Context.getLangOpts().AppleKext ?
1387 llvm::GlobalVariable::LinkOnceODRLinkage :
1388 llvm::Function::InternalLinkage;
1390 case TSK_ExplicitInstantiationDefinition:
1391 return !Context.getLangOpts().AppleKext ?
1392 llvm::GlobalVariable::WeakODRLinkage :
1393 llvm::Function::InternalLinkage;
1395 case TSK_ExplicitInstantiationDeclaration:
1396 // FIXME: Use available_externally linkage. However, this currently
1397 // breaks LLVM's build due to undefined symbols.
1398 // return llvm::GlobalVariable::AvailableExternallyLinkage;
1399 return !Context.getLangOpts().AppleKext ?
1400 llvm::GlobalVariable::LinkOnceODRLinkage :
1401 llvm::Function::InternalLinkage;
1405 if (Context.getLangOpts().AppleKext)
1406 return llvm::Function::InternalLinkage;
1408 switch (RD->getTemplateSpecializationKind()) {
1409 case TSK_Undeclared:
1410 case TSK_ExplicitSpecialization:
1411 case TSK_ImplicitInstantiation:
1412 // FIXME: Use available_externally linkage. However, this currently
1413 // breaks LLVM's build due to undefined symbols.
1414 // return llvm::GlobalVariable::AvailableExternallyLinkage;
1415 case TSK_ExplicitInstantiationDeclaration:
1416 return llvm::GlobalVariable::LinkOnceODRLinkage;
1418 case TSK_ExplicitInstantiationDefinition:
1419 return llvm::GlobalVariable::WeakODRLinkage;
1422 llvm_unreachable("Invalid TemplateSpecializationKind!");
1425 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
1426 return Context.toCharUnitsFromBits(
1427 TheTargetData.getTypeStoreSizeInBits(Ty));
1431 CodeGenModule::MaybeEmitGlobalStdInitializerListInitializer(const VarDecl *D,
1432 const Expr *rawInit) {
1433 ArrayRef<ExprWithCleanups::CleanupObject> cleanups;
1434 if (const ExprWithCleanups *withCleanups =
1435 dyn_cast<ExprWithCleanups>(rawInit)) {
1436 cleanups = withCleanups->getObjects();
1437 rawInit = withCleanups->getSubExpr();
1440 const InitListExpr *init = dyn_cast<InitListExpr>(rawInit);
1441 if (!init || !init->initializesStdInitializerList() ||
1442 init->getNumInits() == 0)
1445 ASTContext &ctx = getContext();
1446 unsigned numInits = init->getNumInits();
1447 // FIXME: This check is here because we would otherwise silently miscompile
1448 // nested global std::initializer_lists. Better would be to have a real
1450 for (unsigned i = 0; i < numInits; ++i) {
1451 const InitListExpr *inner = dyn_cast<InitListExpr>(init->getInit(i));
1452 if (inner && inner->initializesStdInitializerList()) {
1453 ErrorUnsupported(inner, "nested global std::initializer_list");
1458 // Synthesize a fake VarDecl for the array and initialize that.
1459 QualType elementType = init->getInit(0)->getType();
1460 llvm::APInt numElements(ctx.getTypeSize(ctx.getSizeType()), numInits);
1461 QualType arrayType = ctx.getConstantArrayType(elementType, numElements,
1462 ArrayType::Normal, 0);
1464 IdentifierInfo *name = &ctx.Idents.get(D->getNameAsString() + "__initlist");
1465 TypeSourceInfo *sourceInfo = ctx.getTrivialTypeSourceInfo(
1466 arrayType, D->getLocation());
1467 VarDecl *backingArray = VarDecl::Create(ctx, const_cast<DeclContext*>(
1468 D->getDeclContext()),
1469 D->getLocStart(), D->getLocation(),
1470 name, arrayType, sourceInfo,
1471 SC_Static, SC_Static);
1473 // Now clone the InitListExpr to initialize the array instead.
1474 // Incredible hack: we want to use the existing InitListExpr here, so we need
1475 // to tell it that it no longer initializes a std::initializer_list.
1476 Expr *arrayInit = new (ctx) InitListExpr(ctx, init->getLBraceLoc(),
1477 const_cast<InitListExpr*>(init)->getInits(),
1478 init->getNumInits(),
1479 init->getRBraceLoc());
1480 arrayInit->setType(arrayType);
1482 if (!cleanups.empty())
1483 arrayInit = ExprWithCleanups::Create(ctx, arrayInit, cleanups);
1485 backingArray->setInit(arrayInit);
1487 // Emit the definition of the array.
1488 EmitGlobalVarDefinition(backingArray);
1490 // Inspect the initializer list to validate it and determine its type.
1491 // FIXME: doing this every time is probably inefficient; caching would be nice
1492 RecordDecl *record = init->getType()->castAs<RecordType>()->getDecl();
1493 RecordDecl::field_iterator field = record->field_begin();
1494 if (field == record->field_end()) {
1495 ErrorUnsupported(D, "weird std::initializer_list");
1498 QualType elementPtr = ctx.getPointerType(elementType.withConst());
1500 if (!ctx.hasSameType(field->getType(), elementPtr)) {
1501 ErrorUnsupported(D, "weird std::initializer_list");
1505 if (field == record->field_end()) {
1506 ErrorUnsupported(D, "weird std::initializer_list");
1509 bool isStartEnd = false;
1510 if (ctx.hasSameType(field->getType(), elementPtr)) {
1513 } else if(!ctx.hasSameType(field->getType(), ctx.getSizeType())) {
1514 ErrorUnsupported(D, "weird std::initializer_list");
1518 // Now build an APValue representing the std::initializer_list.
1519 APValue initListValue(APValue::UninitStruct(), 0, 2);
1520 APValue &startField = initListValue.getStructField(0);
1521 APValue::LValuePathEntry startOffsetPathEntry;
1522 startOffsetPathEntry.ArrayIndex = 0;
1523 startField = APValue(APValue::LValueBase(backingArray),
1524 CharUnits::fromQuantity(0),
1525 llvm::makeArrayRef(startOffsetPathEntry),
1526 /*IsOnePastTheEnd=*/false, 0);
1529 APValue &endField = initListValue.getStructField(1);
1530 APValue::LValuePathEntry endOffsetPathEntry;
1531 endOffsetPathEntry.ArrayIndex = numInits;
1532 endField = APValue(APValue::LValueBase(backingArray),
1533 ctx.getTypeSizeInChars(elementType) * numInits,
1534 llvm::makeArrayRef(endOffsetPathEntry),
1535 /*IsOnePastTheEnd=*/true, 0);
1537 APValue &sizeField = initListValue.getStructField(1);
1538 sizeField = APValue(llvm::APSInt(numElements));
1541 // Emit the constant for the initializer_list.
1542 llvm::Constant *llvmInit =
1543 EmitConstantValueForMemory(initListValue, D->getType());
1544 assert(llvmInit && "failed to initialize as constant");
1548 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
1549 unsigned AddrSpace) {
1550 if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
1551 if (D->hasAttr<CUDAConstantAttr>())
1552 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
1553 else if (D->hasAttr<CUDASharedAttr>())
1554 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
1556 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
1562 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1563 llvm::Constant *Init = 0;
1564 QualType ASTTy = D->getType();
1565 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1566 bool NeedsGlobalCtor = false;
1567 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
1569 const VarDecl *InitDecl;
1570 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
1573 // This is a tentative definition; tentative definitions are
1574 // implicitly initialized with { 0 }.
1576 // Note that tentative definitions are only emitted at the end of
1577 // a translation unit, so they should never have incomplete
1578 // type. In addition, EmitTentativeDefinition makes sure that we
1579 // never attempt to emit a tentative definition if a real one
1580 // exists. A use may still exists, however, so we still may need
1582 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1583 Init = EmitNullConstant(D->getType());
1585 // If this is a std::initializer_list, emit the special initializer.
1586 Init = MaybeEmitGlobalStdInitializerListInitializer(D, InitExpr);
1587 // An empty init list will perform zero-initialization, which happens
1588 // to be exactly what we want.
1589 // FIXME: It does so in a global constructor, which is *not* what we
1593 initializedGlobalDecl = GlobalDecl(D);
1594 Init = EmitConstantInit(*InitDecl);
1597 QualType T = InitExpr->getType();
1598 if (D->getType()->isReferenceType())
1601 if (getLangOpts().CPlusPlus) {
1602 Init = EmitNullConstant(T);
1603 NeedsGlobalCtor = true;
1605 ErrorUnsupported(D, "static initializer");
1606 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1609 // We don't need an initializer, so remove the entry for the delayed
1610 // initializer position (just in case this entry was delayed) if we
1611 // also don't need to register a destructor.
1612 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
1613 DelayedCXXInitPosition.erase(D);
1617 llvm::Type* InitType = Init->getType();
1618 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1620 // Strip off a bitcast if we got one back.
1621 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1622 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1623 // all zero index gep.
1624 CE->getOpcode() == llvm::Instruction::GetElementPtr);
1625 Entry = CE->getOperand(0);
1628 // Entry is now either a Function or GlobalVariable.
1629 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1631 // We have a definition after a declaration with the wrong type.
1632 // We must make a new GlobalVariable* and update everything that used OldGV
1633 // (a declaration or tentative definition) with the new GlobalVariable*
1634 // (which will be a definition).
1636 // This happens if there is a prototype for a global (e.g.
1637 // "extern int x[];") and then a definition of a different type (e.g.
1638 // "int x[10];"). This also happens when an initializer has a different type
1639 // from the type of the global (this happens with unions).
1641 GV->getType()->getElementType() != InitType ||
1642 GV->getType()->getAddressSpace() !=
1643 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
1645 // Move the old entry aside so that we'll create a new one.
1646 Entry->setName(StringRef());
1648 // Make a new global with the correct type, this is now guaranteed to work.
1649 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
1651 // Replace all uses of the old global with the new global
1652 llvm::Constant *NewPtrForOldDecl =
1653 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1654 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1656 // Erase the old global, since it is no longer used.
1657 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1660 if (D->hasAttr<AnnotateAttr>())
1661 AddGlobalAnnotations(D, GV);
1663 GV->setInitializer(Init);
1665 // If it is safe to mark the global 'constant', do so now.
1666 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
1667 isTypeConstant(D->getType(), true));
1669 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1671 // Set the llvm linkage type as appropriate.
1672 llvm::GlobalValue::LinkageTypes Linkage =
1673 GetLLVMLinkageVarDefinition(D, GV);
1674 GV->setLinkage(Linkage);
1675 if (Linkage == llvm::GlobalVariable::CommonLinkage)
1676 // common vars aren't constant even if declared const.
1677 GV->setConstant(false);
1679 SetCommonAttributes(D, GV);
1681 // Emit the initializer function if necessary.
1682 if (NeedsGlobalCtor || NeedsGlobalDtor)
1683 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
1685 // Emit global variable debug information.
1686 if (CGDebugInfo *DI = getModuleDebugInfo())
1687 if (getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo)
1688 DI->EmitGlobalVariable(GV, D);
1691 llvm::GlobalValue::LinkageTypes
1692 CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1693 llvm::GlobalVariable *GV) {
1694 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1695 if (Linkage == GVA_Internal)
1696 return llvm::Function::InternalLinkage;
1697 else if (D->hasAttr<DLLImportAttr>())
1698 return llvm::Function::DLLImportLinkage;
1699 else if (D->hasAttr<DLLExportAttr>())
1700 return llvm::Function::DLLExportLinkage;
1701 else if (D->hasAttr<WeakAttr>()) {
1702 if (GV->isConstant())
1703 return llvm::GlobalVariable::WeakODRLinkage;
1705 return llvm::GlobalVariable::WeakAnyLinkage;
1706 } else if (Linkage == GVA_TemplateInstantiation ||
1707 Linkage == GVA_ExplicitTemplateInstantiation)
1708 return llvm::GlobalVariable::WeakODRLinkage;
1709 else if (!getLangOpts().CPlusPlus &&
1710 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1711 D->getAttr<CommonAttr>()) &&
1712 !D->hasExternalStorage() && !D->getInit() &&
1713 !D->getAttr<SectionAttr>() && !D->isThreadSpecified() &&
1714 !D->getAttr<WeakImportAttr>()) {
1715 // Thread local vars aren't considered common linkage.
1716 return llvm::GlobalVariable::CommonLinkage;
1718 return llvm::GlobalVariable::ExternalLinkage;
1721 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1722 /// implement a function with no prototype, e.g. "int foo() {}". If there are
1723 /// existing call uses of the old function in the module, this adjusts them to
1724 /// call the new function directly.
1726 /// This is not just a cleanup: the always_inline pass requires direct calls to
1727 /// functions to be able to inline them. If there is a bitcast in the way, it
1728 /// won't inline them. Instcombine normally deletes these calls, but it isn't
1730 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1731 llvm::Function *NewFn) {
1732 // If we're redefining a global as a function, don't transform it.
1733 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1734 if (OldFn == 0) return;
1736 llvm::Type *NewRetTy = NewFn->getReturnType();
1737 SmallVector<llvm::Value*, 4> ArgList;
1739 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
1741 // TODO: Do invokes ever occur in C code? If so, we should handle them too.
1742 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1743 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
1744 if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
1745 llvm::CallSite CS(CI);
1746 if (!CI || !CS.isCallee(I)) continue;
1748 // If the return types don't match exactly, and if the call isn't dead, then
1749 // we can't transform this call.
1750 if (CI->getType() != NewRetTy && !CI->use_empty())
1753 // Get the attribute list.
1754 llvm::SmallVector<llvm::AttributeWithIndex, 8> AttrVec;
1755 llvm::AttrListPtr AttrList = CI->getAttributes();
1757 // Get any return attributes.
1758 llvm::Attributes RAttrs = AttrList.getRetAttributes();
1760 // Add the return attributes.
1762 AttrVec.push_back(llvm::AttributeWithIndex::get(0, RAttrs));
1764 // If the function was passed too few arguments, don't transform. If extra
1765 // arguments were passed, we silently drop them. If any of the types
1766 // mismatch, we don't transform.
1768 bool DontTransform = false;
1769 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1770 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
1771 if (CS.arg_size() == ArgNo ||
1772 CS.getArgument(ArgNo)->getType() != AI->getType()) {
1773 DontTransform = true;
1777 // Add any parameter attributes.
1778 if (llvm::Attributes PAttrs = AttrList.getParamAttributes(ArgNo + 1))
1779 AttrVec.push_back(llvm::AttributeWithIndex::get(ArgNo + 1, PAttrs));
1784 if (llvm::Attributes FnAttrs = AttrList.getFnAttributes())
1785 AttrVec.push_back(llvm::AttributeWithIndex::get(~0, FnAttrs));
1787 // Okay, we can transform this. Create the new call instruction and copy
1788 // over the required information.
1789 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
1790 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList, "", CI);
1792 if (!NewCall->getType()->isVoidTy())
1793 NewCall->takeName(CI);
1794 NewCall->setAttributes(llvm::AttrListPtr::get(AttrVec));
1795 NewCall->setCallingConv(CI->getCallingConv());
1797 // Finally, remove the old call, replacing any uses with the new one.
1798 if (!CI->use_empty())
1799 CI->replaceAllUsesWith(NewCall);
1801 // Copy debug location attached to CI.
1802 if (!CI->getDebugLoc().isUnknown())
1803 NewCall->setDebugLoc(CI->getDebugLoc());
1804 CI->eraseFromParent();
1808 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
1809 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
1810 // If we have a definition, this might be a deferred decl. If the
1811 // instantiation is explicit, make sure we emit it at the end.
1812 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
1813 GetAddrOfGlobalVar(VD);
1816 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
1817 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
1819 // Compute the function info and LLVM type.
1820 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1821 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
1823 // Get or create the prototype for the function.
1824 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
1826 // Strip off a bitcast if we got one back.
1827 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1828 assert(CE->getOpcode() == llvm::Instruction::BitCast);
1829 Entry = CE->getOperand(0);
1833 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
1834 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
1836 // If the types mismatch then we have to rewrite the definition.
1837 assert(OldFn->isDeclaration() &&
1838 "Shouldn't replace non-declaration");
1840 // F is the Function* for the one with the wrong type, we must make a new
1841 // Function* and update everything that used F (a declaration) with the new
1842 // Function* (which will be a definition).
1844 // This happens if there is a prototype for a function
1845 // (e.g. "int f()") and then a definition of a different type
1846 // (e.g. "int f(int x)"). Move the old function aside so that it
1847 // doesn't interfere with GetAddrOfFunction.
1848 OldFn->setName(StringRef());
1849 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
1851 // If this is an implementation of a function without a prototype, try to
1852 // replace any existing uses of the function (which may be calls) with uses
1853 // of the new function
1854 if (D->getType()->isFunctionNoProtoType()) {
1855 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
1856 OldFn->removeDeadConstantUsers();
1859 // Replace uses of F with the Function we will endow with a body.
1860 if (!Entry->use_empty()) {
1861 llvm::Constant *NewPtrForOldDecl =
1862 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
1863 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1866 // Ok, delete the old function now, which is dead.
1867 OldFn->eraseFromParent();
1872 // We need to set linkage and visibility on the function before
1873 // generating code for it because various parts of IR generation
1874 // want to propagate this information down (e.g. to local static
1876 llvm::Function *Fn = cast<llvm::Function>(Entry);
1877 setFunctionLinkage(D, Fn);
1879 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
1880 setGlobalVisibility(Fn, D);
1882 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
1884 SetFunctionDefinitionAttributes(D, Fn);
1885 SetLLVMFunctionAttributesForDefinition(D, Fn);
1887 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
1888 AddGlobalCtor(Fn, CA->getPriority());
1889 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
1890 AddGlobalDtor(Fn, DA->getPriority());
1891 if (D->hasAttr<AnnotateAttr>())
1892 AddGlobalAnnotations(D, Fn);
1895 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1896 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
1897 const AliasAttr *AA = D->getAttr<AliasAttr>();
1898 assert(AA && "Not an alias?");
1900 StringRef MangledName = getMangledName(GD);
1902 // If there is a definition in the module, then it wins over the alias.
1903 // This is dubious, but allow it to be safe. Just ignore the alias.
1904 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1905 if (Entry && !Entry->isDeclaration())
1908 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1910 // Create a reference to the named value. This ensures that it is emitted
1911 // if a deferred decl.
1912 llvm::Constant *Aliasee;
1913 if (isa<llvm::FunctionType>(DeclTy))
1914 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
1915 /*ForVTable=*/false);
1917 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1918 llvm::PointerType::getUnqual(DeclTy), 0);
1920 // Create the new alias itself, but don't set a name yet.
1921 llvm::GlobalValue *GA =
1922 new llvm::GlobalAlias(Aliasee->getType(),
1923 llvm::Function::ExternalLinkage,
1924 "", Aliasee, &getModule());
1927 assert(Entry->isDeclaration());
1929 // If there is a declaration in the module, then we had an extern followed
1930 // by the alias, as in:
1931 // extern int test6();
1933 // int test6() __attribute__((alias("test7")));
1935 // Remove it and replace uses of it with the alias.
1936 GA->takeName(Entry);
1938 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
1940 Entry->eraseFromParent();
1942 GA->setName(MangledName);
1945 // Set attributes which are particular to an alias; this is a
1946 // specialization of the attributes which may be set on a global
1947 // variable/function.
1948 if (D->hasAttr<DLLExportAttr>()) {
1949 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1950 // The dllexport attribute is ignored for undefined symbols.
1952 GA->setLinkage(llvm::Function::DLLExportLinkage);
1954 GA->setLinkage(llvm::Function::DLLExportLinkage);
1956 } else if (D->hasAttr<WeakAttr>() ||
1957 D->hasAttr<WeakRefAttr>() ||
1958 D->isWeakImported()) {
1959 GA->setLinkage(llvm::Function::WeakAnyLinkage);
1962 SetCommonAttributes(D, GA);
1965 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
1966 ArrayRef<llvm::Type*> Tys) {
1967 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
1971 static llvm::StringMapEntry<llvm::Constant*> &
1972 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1973 const StringLiteral *Literal,
1976 unsigned &StringLength) {
1977 StringRef String = Literal->getString();
1978 unsigned NumBytes = String.size();
1980 // Check for simple case.
1981 if (!Literal->containsNonAsciiOrNull()) {
1982 StringLength = NumBytes;
1983 return Map.GetOrCreateValue(String);
1986 // Otherwise, convert the UTF8 literals into a string of shorts.
1989 SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
1990 const UTF8 *FromPtr = (UTF8 *)String.data();
1991 UTF16 *ToPtr = &ToBuf[0];
1993 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1994 &ToPtr, ToPtr + NumBytes,
1997 // ConvertUTF8toUTF16 returns the length in ToPtr.
1998 StringLength = ToPtr - &ToBuf[0];
2000 // Add an explicit null.
2003 GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2004 (StringLength + 1) * 2));
2007 static llvm::StringMapEntry<llvm::Constant*> &
2008 GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2009 const StringLiteral *Literal,
2010 unsigned &StringLength) {
2011 StringRef String = Literal->getString();
2012 StringLength = String.size();
2013 return Map.GetOrCreateValue(String);
2017 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2018 unsigned StringLength = 0;
2019 bool isUTF16 = false;
2020 llvm::StringMapEntry<llvm::Constant*> &Entry =
2021 GetConstantCFStringEntry(CFConstantStringMap, Literal,
2022 getTargetData().isLittleEndian(),
2023 isUTF16, StringLength);
2025 if (llvm::Constant *C = Entry.getValue())
2028 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2029 llvm::Constant *Zeros[] = { Zero, Zero };
2031 // If we don't already have it, get __CFConstantStringClassReference.
2032 if (!CFConstantStringClassRef) {
2033 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2034 Ty = llvm::ArrayType::get(Ty, 0);
2035 llvm::Constant *GV = CreateRuntimeVariable(Ty,
2036 "__CFConstantStringClassReference");
2037 // Decay array -> ptr
2038 CFConstantStringClassRef =
2039 llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2042 QualType CFTy = getContext().getCFConstantStringType();
2044 llvm::StructType *STy =
2045 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2047 llvm::Constant *Fields[4];
2050 Fields[0] = CFConstantStringClassRef;
2053 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2054 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
2055 llvm::ConstantInt::get(Ty, 0x07C8);
2058 llvm::Constant *C = 0;
2060 ArrayRef<uint16_t> Arr =
2061 llvm::makeArrayRef<uint16_t>((uint16_t*)Entry.getKey().data(),
2062 Entry.getKey().size() / 2);
2063 C = llvm::ConstantDataArray::get(VMContext, Arr);
2065 C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2068 llvm::GlobalValue::LinkageTypes Linkage;
2070 // FIXME: why do utf strings get "_" labels instead of "L" labels?
2071 Linkage = llvm::GlobalValue::InternalLinkage;
2073 // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
2074 // when using private linkage. It is not clear if this is a bug in ld
2075 // or a reasonable new restriction.
2076 Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
2078 // Note: -fwritable-strings doesn't make the backing store strings of
2079 // CFStrings writable. (See <rdar://problem/10657500>)
2080 llvm::GlobalVariable *GV =
2081 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2082 Linkage, C, ".str");
2083 GV->setUnnamedAddr(true);
2085 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2086 GV->setAlignment(Align.getQuantity());
2088 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2089 GV->setAlignment(Align.getQuantity());
2093 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2096 // Cast the UTF16 string to the correct type.
2097 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2100 Ty = getTypes().ConvertType(getContext().LongTy);
2101 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
2104 C = llvm::ConstantStruct::get(STy, Fields);
2105 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2106 llvm::GlobalVariable::PrivateLinkage, C,
2107 "_unnamed_cfstring_");
2108 if (const char *Sect = getContext().getTargetInfo().getCFStringSection())
2109 GV->setSection(Sect);
2116 CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
2117 DeclContext *DC, IdentifierInfo *Id) {
2119 if (Ctx.getLangOpts().CPlusPlus)
2120 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2122 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2126 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
2127 unsigned StringLength = 0;
2128 llvm::StringMapEntry<llvm::Constant*> &Entry =
2129 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
2131 if (llvm::Constant *C = Entry.getValue())
2134 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2135 llvm::Constant *Zeros[] = { Zero, Zero };
2137 // If we don't already have it, get _NSConstantStringClassReference.
2138 if (!ConstantStringClassRef) {
2139 std::string StringClass(getLangOpts().ObjCConstantStringClass);
2140 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2142 if (LangOpts.ObjCRuntime.isNonFragile()) {
2144 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2145 : "OBJC_CLASS_$_" + StringClass;
2146 GV = getObjCRuntime().GetClassGlobal(str);
2147 // Make sure the result is of the correct type.
2148 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2149 ConstantStringClassRef =
2150 llvm::ConstantExpr::getBitCast(GV, PTy);
2153 StringClass.empty() ? "_NSConstantStringClassReference"
2154 : "_" + StringClass + "ClassReference";
2155 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
2156 GV = CreateRuntimeVariable(PTy, str);
2157 // Decay array -> ptr
2158 ConstantStringClassRef =
2159 llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2163 if (!NSConstantStringType) {
2164 // Construct the type for a constant NSString.
2165 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2166 Context.getTranslationUnitDecl(),
2167 &Context.Idents.get("__builtin_NSString"));
2168 D->startDefinition();
2170 QualType FieldTypes[3];
2173 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2175 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2176 // unsigned int length;
2177 FieldTypes[2] = Context.UnsignedIntTy;
2180 for (unsigned i = 0; i < 3; ++i) {
2181 FieldDecl *Field = FieldDecl::Create(Context, D,
2183 SourceLocation(), 0,
2184 FieldTypes[i], /*TInfo=*/0,
2188 Field->setAccess(AS_public);
2192 D->completeDefinition();
2193 QualType NSTy = Context.getTagDeclType(D);
2194 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2197 llvm::Constant *Fields[3];
2200 Fields[0] = ConstantStringClassRef;
2204 llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2206 llvm::GlobalValue::LinkageTypes Linkage;
2208 Linkage = llvm::GlobalValue::PrivateLinkage;
2209 isConstant = !LangOpts.WritableStrings;
2211 llvm::GlobalVariable *GV =
2212 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
2214 GV->setUnnamedAddr(true);
2215 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2216 GV->setAlignment(Align.getQuantity());
2217 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2220 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2221 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2224 C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
2225 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2226 llvm::GlobalVariable::PrivateLinkage, C,
2227 "_unnamed_nsstring_");
2228 // FIXME. Fix section.
2229 if (const char *Sect =
2230 LangOpts.ObjCRuntime.isNonFragile()
2231 ? getContext().getTargetInfo().getNSStringNonFragileABISection()
2232 : getContext().getTargetInfo().getNSStringSection())
2233 GV->setSection(Sect);
2239 QualType CodeGenModule::getObjCFastEnumerationStateType() {
2240 if (ObjCFastEnumerationStateType.isNull()) {
2241 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2242 Context.getTranslationUnitDecl(),
2243 &Context.Idents.get("__objcFastEnumerationState"));
2244 D->startDefinition();
2246 QualType FieldTypes[] = {
2247 Context.UnsignedLongTy,
2248 Context.getPointerType(Context.getObjCIdType()),
2249 Context.getPointerType(Context.UnsignedLongTy),
2250 Context.getConstantArrayType(Context.UnsignedLongTy,
2251 llvm::APInt(32, 5), ArrayType::Normal, 0)
2254 for (size_t i = 0; i < 4; ++i) {
2255 FieldDecl *Field = FieldDecl::Create(Context,
2258 SourceLocation(), 0,
2259 FieldTypes[i], /*TInfo=*/0,
2263 Field->setAccess(AS_public);
2267 D->completeDefinition();
2268 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2271 return ObjCFastEnumerationStateType;
2275 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2276 assert(!E->getType()->isPointerType() && "Strings are always arrays");
2278 // Don't emit it as the address of the string, emit the string data itself
2279 // as an inline array.
2280 if (E->getCharByteWidth() == 1) {
2281 SmallString<64> Str(E->getString());
2283 // Resize the string to the right size, which is indicated by its type.
2284 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2285 Str.resize(CAT->getSize().getZExtValue());
2286 return llvm::ConstantDataArray::getString(VMContext, Str, false);
2289 llvm::ArrayType *AType =
2290 cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
2291 llvm::Type *ElemTy = AType->getElementType();
2292 unsigned NumElements = AType->getNumElements();
2294 // Wide strings have either 2-byte or 4-byte elements.
2295 if (ElemTy->getPrimitiveSizeInBits() == 16) {
2296 SmallVector<uint16_t, 32> Elements;
2297 Elements.reserve(NumElements);
2299 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2300 Elements.push_back(E->getCodeUnit(i));
2301 Elements.resize(NumElements);
2302 return llvm::ConstantDataArray::get(VMContext, Elements);
2305 assert(ElemTy->getPrimitiveSizeInBits() == 32);
2306 SmallVector<uint32_t, 32> Elements;
2307 Elements.reserve(NumElements);
2309 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2310 Elements.push_back(E->getCodeUnit(i));
2311 Elements.resize(NumElements);
2312 return llvm::ConstantDataArray::get(VMContext, Elements);
2315 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2316 /// constant array for the given string literal.
2318 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
2319 CharUnits Align = getContext().getTypeAlignInChars(S->getType());
2320 if (S->isAscii() || S->isUTF8()) {
2321 SmallString<64> Str(S->getString());
2323 // Resize the string to the right size, which is indicated by its type.
2324 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
2325 Str.resize(CAT->getSize().getZExtValue());
2326 return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity());
2329 // FIXME: the following does not memoize wide strings.
2330 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2331 llvm::GlobalVariable *GV =
2332 new llvm::GlobalVariable(getModule(),C->getType(),
2333 !LangOpts.WritableStrings,
2334 llvm::GlobalValue::PrivateLinkage,
2337 GV->setAlignment(Align.getQuantity());
2338 GV->setUnnamedAddr(true);
2342 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2343 /// array for the given ObjCEncodeExpr node.
2345 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2347 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
2349 return GetAddrOfConstantCString(Str);
2353 /// GenerateWritableString -- Creates storage for a string literal.
2354 static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
2357 const char *GlobalName,
2358 unsigned Alignment) {
2359 // Create Constant for this string literal. Don't add a '\0'.
2361 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
2363 // Create a global variable for this string
2364 llvm::GlobalVariable *GV =
2365 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
2366 llvm::GlobalValue::PrivateLinkage,
2368 GV->setAlignment(Alignment);
2369 GV->setUnnamedAddr(true);
2373 /// GetAddrOfConstantString - Returns a pointer to a character array
2374 /// containing the literal. This contents are exactly that of the
2375 /// given string, i.e. it will not be null terminated automatically;
2376 /// see GetAddrOfConstantCString. Note that whether the result is
2377 /// actually a pointer to an LLVM constant depends on
2378 /// Feature.WriteableStrings.
2380 /// The result has pointer to array type.
2381 llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
2382 const char *GlobalName,
2383 unsigned Alignment) {
2384 // Get the default prefix if a name wasn't specified.
2386 GlobalName = ".str";
2388 // Don't share any string literals if strings aren't constant.
2389 if (LangOpts.WritableStrings)
2390 return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
2392 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2393 ConstantStringMap.GetOrCreateValue(Str);
2395 if (llvm::GlobalVariable *GV = Entry.getValue()) {
2396 if (Alignment > GV->getAlignment()) {
2397 GV->setAlignment(Alignment);
2402 // Create a global variable for this.
2403 llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
2409 /// GetAddrOfConstantCString - Returns a pointer to a character
2410 /// array containing the literal and a terminating '\0'
2411 /// character. The result has pointer to array type.
2412 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
2413 const char *GlobalName,
2414 unsigned Alignment) {
2415 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
2416 return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
2419 /// EmitObjCPropertyImplementations - Emit information for synthesized
2420 /// properties for an implementation.
2421 void CodeGenModule::EmitObjCPropertyImplementations(const
2422 ObjCImplementationDecl *D) {
2423 for (ObjCImplementationDecl::propimpl_iterator
2424 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
2425 ObjCPropertyImplDecl *PID = *i;
2427 // Dynamic is just for type-checking.
2428 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2429 ObjCPropertyDecl *PD = PID->getPropertyDecl();
2431 // Determine which methods need to be implemented, some may have
2432 // been overridden. Note that ::isSynthesized is not the method
2433 // we want, that just indicates if the decl came from a
2434 // property. What we want to know is if the method is defined in
2435 // this implementation.
2436 if (!D->getInstanceMethod(PD->getGetterName()))
2437 CodeGenFunction(*this).GenerateObjCGetter(
2438 const_cast<ObjCImplementationDecl *>(D), PID);
2439 if (!PD->isReadOnly() &&
2440 !D->getInstanceMethod(PD->getSetterName()))
2441 CodeGenFunction(*this).GenerateObjCSetter(
2442 const_cast<ObjCImplementationDecl *>(D), PID);
2447 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
2448 const ObjCInterfaceDecl *iface = impl->getClassInterface();
2449 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
2450 ivar; ivar = ivar->getNextIvar())
2451 if (ivar->getType().isDestructedType())
2457 /// EmitObjCIvarInitializations - Emit information for ivar initialization
2458 /// for an implementation.
2459 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
2460 // We might need a .cxx_destruct even if we don't have any ivar initializers.
2461 if (needsDestructMethod(D)) {
2462 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2463 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2464 ObjCMethodDecl *DTORMethod =
2465 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
2466 cxxSelector, getContext().VoidTy, 0, D,
2467 /*isInstance=*/true, /*isVariadic=*/false,
2468 /*isSynthesized=*/true, /*isImplicitlyDeclared=*/true,
2469 /*isDefined=*/false, ObjCMethodDecl::Required);
2470 D->addInstanceMethod(DTORMethod);
2471 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
2472 D->setHasCXXStructors(true);
2475 // If the implementation doesn't have any ivar initializers, we don't need
2476 // a .cxx_construct.
2477 if (D->getNumIvarInitializers() == 0)
2480 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2481 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2482 // The constructor returns 'self'.
2483 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2487 getContext().getObjCIdType(), 0,
2488 D, /*isInstance=*/true,
2489 /*isVariadic=*/false,
2490 /*isSynthesized=*/true,
2491 /*isImplicitlyDeclared=*/true,
2492 /*isDefined=*/false,
2493 ObjCMethodDecl::Required);
2494 D->addInstanceMethod(CTORMethod);
2495 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
2496 D->setHasCXXStructors(true);
2499 /// EmitNamespace - Emit all declarations in a namespace.
2500 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
2501 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
2503 EmitTopLevelDecl(*I);
2506 // EmitLinkageSpec - Emit all declarations in a linkage spec.
2507 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
2508 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2509 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
2510 ErrorUnsupported(LSD, "linkage spec");
2514 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
2516 EmitTopLevelDecl(*I);
2519 /// EmitTopLevelDecl - Emit code for a single top level declaration.
2520 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
2521 // If an error has occurred, stop code generation, but continue
2522 // parsing and semantic analysis (to ensure all warnings and errors
2524 if (Diags.hasErrorOccurred())
2527 // Ignore dependent declarations.
2528 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2531 switch (D->getKind()) {
2532 case Decl::CXXConversion:
2533 case Decl::CXXMethod:
2534 case Decl::Function:
2535 // Skip function templates
2536 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2537 cast<FunctionDecl>(D)->isLateTemplateParsed())
2540 EmitGlobal(cast<FunctionDecl>(D));
2544 EmitGlobal(cast<VarDecl>(D));
2547 // Indirect fields from global anonymous structs and unions can be
2548 // ignored; only the actual variable requires IR gen support.
2549 case Decl::IndirectField:
2553 case Decl::Namespace:
2554 EmitNamespace(cast<NamespaceDecl>(D));
2556 // No code generation needed.
2557 case Decl::UsingShadow:
2559 case Decl::UsingDirective:
2560 case Decl::ClassTemplate:
2561 case Decl::FunctionTemplate:
2562 case Decl::TypeAliasTemplate:
2563 case Decl::NamespaceAlias:
2567 case Decl::CXXConstructor:
2568 // Skip function templates
2569 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2570 cast<FunctionDecl>(D)->isLateTemplateParsed())
2573 EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2575 case Decl::CXXDestructor:
2576 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
2578 EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2581 case Decl::StaticAssert:
2585 // Objective-C Decls
2587 // Forward declarations, no (immediate) code generation.
2588 case Decl::ObjCInterface:
2589 case Decl::ObjCCategory:
2592 case Decl::ObjCProtocol: {
2593 ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
2594 if (Proto->isThisDeclarationADefinition())
2595 ObjCRuntime->GenerateProtocol(Proto);
2599 case Decl::ObjCCategoryImpl:
2600 // Categories have properties but don't support synthesize so we
2601 // can ignore them here.
2602 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2605 case Decl::ObjCImplementation: {
2606 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2607 EmitObjCPropertyImplementations(OMD);
2608 EmitObjCIvarInitializations(OMD);
2609 ObjCRuntime->GenerateClass(OMD);
2610 // Emit global variable debug information.
2611 if (CGDebugInfo *DI = getModuleDebugInfo())
2612 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(OMD->getClassInterface()),
2613 OMD->getLocation());
2617 case Decl::ObjCMethod: {
2618 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2619 // If this is not a prototype, emit the body.
2621 CodeGenFunction(*this).GenerateObjCMethod(OMD);
2624 case Decl::ObjCCompatibleAlias:
2625 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
2628 case Decl::LinkageSpec:
2629 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
2632 case Decl::FileScopeAsm: {
2633 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
2634 StringRef AsmString = AD->getAsmString()->getString();
2636 const std::string &S = getModule().getModuleInlineAsm();
2638 getModule().setModuleInlineAsm(AsmString);
2639 else if (S.end()[-1] == '\n')
2640 getModule().setModuleInlineAsm(S + AsmString.str());
2642 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
2647 // Make sure we handled everything we should, every other kind is a
2648 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
2649 // function. Need to recode Decl::Kind to do that easily.
2650 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2654 /// Turns the given pointer into a constant.
2655 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2657 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2658 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2659 return llvm::ConstantInt::get(i64, PtrInt);
2662 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2663 llvm::NamedMDNode *&GlobalMetadata,
2665 llvm::GlobalValue *Addr) {
2666 if (!GlobalMetadata)
2668 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2670 // TODO: should we report variant information for ctors/dtors?
2671 llvm::Value *Ops[] = {
2673 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2675 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2678 /// Emits metadata nodes associating all the global values in the
2679 /// current module with the Decls they came from. This is useful for
2680 /// projects using IR gen as a subroutine.
2682 /// Since there's currently no way to associate an MDNode directly
2683 /// with an llvm::GlobalValue, we create a global named metadata
2684 /// with the name 'clang.global.decl.ptrs'.
2685 void CodeGenModule::EmitDeclMetadata() {
2686 llvm::NamedMDNode *GlobalMetadata = 0;
2688 // StaticLocalDeclMap
2689 for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
2690 I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2692 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2693 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2697 /// Emits metadata nodes for all the local variables in the current
2699 void CodeGenFunction::EmitDeclMetadata() {
2700 if (LocalDeclMap.empty()) return;
2702 llvm::LLVMContext &Context = getLLVMContext();
2704 // Find the unique metadata ID for this name.
2705 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2707 llvm::NamedMDNode *GlobalMetadata = 0;
2709 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2710 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2711 const Decl *D = I->first;
2712 llvm::Value *Addr = I->second;
2714 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2715 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
2716 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
2717 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2718 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2719 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2724 void CodeGenModule::EmitCoverageFile() {
2725 if (!getCodeGenOpts().CoverageFile.empty()) {
2726 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
2727 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
2728 llvm::LLVMContext &Ctx = TheModule.getContext();
2729 llvm::MDString *CoverageFile =
2730 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
2731 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
2732 llvm::MDNode *CU = CUNode->getOperand(i);
2733 llvm::Value *node[] = { CoverageFile, CU };
2734 llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
2735 GCov->addOperand(N);