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/Basic/Diagnostic.h"
33 #include "clang/Basic/SourceManager.h"
34 #include "clang/Basic/TargetInfo.h"
35 #include "clang/Basic/ConvertUTF.h"
36 #include "llvm/CallingConv.h"
37 #include "llvm/Module.h"
38 #include "llvm/Intrinsics.h"
39 #include "llvm/LLVMContext.h"
40 #include "llvm/ADT/Triple.h"
41 #include "llvm/Target/Mangler.h"
42 #include "llvm/Target/TargetData.h"
43 #include "llvm/Support/CallSite.h"
44 #include "llvm/Support/ErrorHandling.h"
45 using namespace clang;
46 using namespace CodeGen;
48 static const char AnnotationSection[] = "llvm.metadata";
50 static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
51 switch (CGM.getContext().getTargetInfo().getCXXABI()) {
52 case CXXABI_ARM: return *CreateARMCXXABI(CGM);
53 case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
54 case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
57 llvm_unreachable("invalid C++ ABI kind");
58 return *CreateItaniumCXXABI(CGM);
62 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
63 llvm::Module &M, const llvm::TargetData &TD,
64 DiagnosticsEngine &diags)
65 : Context(C), Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
66 TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
67 ABI(createCXXABI(*this)),
68 Types(C, M, TD, getTargetCodeGenInfo().getABIInfo(), ABI, CGO),
70 VTables(*this), ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0),
71 DebugInfo(0), ARCData(0), RRData(0), CFConstantStringClassRef(0),
72 ConstantStringClassRef(0), NSConstantStringType(0),
73 VMContext(M.getContext()),
74 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
75 BlockObjectAssign(0), BlockObjectDispose(0),
76 BlockDescriptorType(0), GenericBlockLiteralType(0) {
80 createOpenCLRuntime();
84 // Enable TBAA unless it's suppressed.
85 if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)
86 TBAA = new CodeGenTBAA(Context, VMContext, getLangOptions(),
87 ABI.getMangleContext());
89 // If debug info or coverage generation is enabled, create the CGDebugInfo
91 if (CodeGenOpts.DebugInfo || CodeGenOpts.EmitGcovArcs ||
92 CodeGenOpts.EmitGcovNotes)
93 DebugInfo = new CGDebugInfo(*this);
95 Block.GlobalUniqueCount = 0;
97 if (C.getLangOptions().ObjCAutoRefCount)
98 ARCData = new ARCEntrypoints();
99 RRData = new RREntrypoints();
101 // Initialize the type cache.
102 llvm::LLVMContext &LLVMContext = M.getContext();
103 VoidTy = llvm::Type::getVoidTy(LLVMContext);
104 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
105 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
106 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
107 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
108 PointerAlignInBytes =
109 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
110 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
111 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
112 Int8PtrTy = Int8Ty->getPointerTo(0);
113 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
116 CodeGenModule::~CodeGenModule() {
118 delete OpenCLRuntime;
120 delete TheTargetCodeGenInfo;
128 void CodeGenModule::createObjCRuntime() {
129 if (!Features.NeXTRuntime)
130 ObjCRuntime = CreateGNUObjCRuntime(*this);
132 ObjCRuntime = CreateMacObjCRuntime(*this);
135 void CodeGenModule::createOpenCLRuntime() {
136 OpenCLRuntime = new CGOpenCLRuntime(*this);
139 void CodeGenModule::createCUDARuntime() {
140 CUDARuntime = CreateNVCUDARuntime(*this);
143 void CodeGenModule::Release() {
145 EmitCXXGlobalInitFunc();
146 EmitCXXGlobalDtorFunc();
148 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
149 AddGlobalCtor(ObjCInitFunction);
150 EmitCtorList(GlobalCtors, "llvm.global_ctors");
151 EmitCtorList(GlobalDtors, "llvm.global_dtors");
152 EmitGlobalAnnotations();
155 SimplifyPersonality();
157 if (getCodeGenOpts().EmitDeclMetadata)
160 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
164 DebugInfo->finalize();
167 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
168 // Make sure that this type is translated.
169 Types.UpdateCompletedType(TD);
171 DebugInfo->UpdateCompletedType(TD);
174 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
177 return TBAA->getTBAAInfo(QTy);
180 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
181 llvm::MDNode *TBAAInfo) {
182 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
185 bool CodeGenModule::isTargetDarwin() const {
186 return getContext().getTargetInfo().getTriple().isOSDarwin();
189 void CodeGenModule::Error(SourceLocation loc, StringRef error) {
190 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error);
191 getDiags().Report(Context.getFullLoc(loc), diagID);
194 /// ErrorUnsupported - Print out an error that codegen doesn't support the
195 /// specified stmt yet.
196 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
198 if (OmitOnError && getDiags().hasErrorOccurred())
200 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
201 "cannot compile this %0 yet");
202 std::string Msg = Type;
203 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
204 << Msg << S->getSourceRange();
207 /// ErrorUnsupported - Print out an error that codegen doesn't support the
208 /// specified decl yet.
209 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
211 if (OmitOnError && getDiags().hasErrorOccurred())
213 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
214 "cannot compile this %0 yet");
215 std::string Msg = Type;
216 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
219 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
220 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
223 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
224 const NamedDecl *D) const {
225 // Internal definitions always have default visibility.
226 if (GV->hasLocalLinkage()) {
227 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
231 // Set visibility for definitions.
232 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
233 if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
234 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
237 /// Set the symbol visibility of type information (vtable and RTTI)
238 /// associated with the given type.
239 void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
240 const CXXRecordDecl *RD,
241 TypeVisibilityKind TVK) const {
242 setGlobalVisibility(GV, RD);
244 if (!CodeGenOpts.HiddenWeakVTables)
247 // We never want to drop the visibility for RTTI names.
248 if (TVK == TVK_ForRTTIName)
251 // We want to drop the visibility to hidden for weak type symbols.
252 // This isn't possible if there might be unresolved references
253 // elsewhere that rely on this symbol being visible.
255 // This should be kept roughly in sync with setThunkVisibility
259 if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
260 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
263 // Don't override an explicit visibility attribute.
264 if (RD->getExplicitVisibility())
267 switch (RD->getTemplateSpecializationKind()) {
268 // We have to disable the optimization if this is an EI definition
269 // because there might be EI declarations in other shared objects.
270 case TSK_ExplicitInstantiationDefinition:
271 case TSK_ExplicitInstantiationDeclaration:
274 // Every use of a non-template class's type information has to emit it.
278 // In theory, implicit instantiations can ignore the possibility of
279 // an explicit instantiation declaration because there necessarily
280 // must be an EI definition somewhere with default visibility. In
281 // practice, it's possible to have an explicit instantiation for
282 // an arbitrary template class, and linkers aren't necessarily able
283 // to deal with mixed-visibility symbols.
284 case TSK_ExplicitSpecialization:
285 case TSK_ImplicitInstantiation:
286 if (!CodeGenOpts.HiddenWeakTemplateVTables)
291 // If there's a key function, there may be translation units
292 // that don't have the key function's definition. But ignore
293 // this if we're emitting RTTI under -fno-rtti.
294 if (!(TVK != TVK_ForRTTI) || Features.RTTI) {
295 if (Context.getKeyFunction(RD))
299 // Otherwise, drop the visibility to hidden.
300 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
301 GV->setUnnamedAddr(true);
304 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
305 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
307 StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
311 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
312 IdentifierInfo *II = ND->getIdentifier();
313 assert(II && "Attempt to mangle unnamed decl.");
319 llvm::SmallString<256> Buffer;
320 llvm::raw_svector_ostream Out(Buffer);
321 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
322 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
323 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
324 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
325 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
326 getCXXABI().getMangleContext().mangleBlock(BD, Out);
328 getCXXABI().getMangleContext().mangleName(ND, Out);
330 // Allocate space for the mangled name.
332 size_t Length = Buffer.size();
333 char *Name = MangledNamesAllocator.Allocate<char>(Length);
334 std::copy(Buffer.begin(), Buffer.end(), Name);
336 Str = StringRef(Name, Length);
341 void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
342 const BlockDecl *BD) {
343 MangleContext &MangleCtx = getCXXABI().getMangleContext();
344 const Decl *D = GD.getDecl();
345 llvm::raw_svector_ostream Out(Buffer.getBuffer());
347 MangleCtx.mangleGlobalBlock(BD, Out);
348 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
349 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
350 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
351 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
353 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
356 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
357 return getModule().getNamedValue(Name);
360 /// AddGlobalCtor - Add a function to the list that will be called before
362 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
363 // FIXME: Type coercion of void()* types.
364 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
367 /// AddGlobalDtor - Add a function to the list that will be called
368 /// when the module is unloaded.
369 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
370 // FIXME: Type coercion of void()* types.
371 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
374 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
375 // Ctor function type is void()*.
376 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
377 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
379 // Get the type of a ctor entry, { i32, void ()* }.
380 llvm::StructType *CtorStructTy =
381 llvm::StructType::get(llvm::Type::getInt32Ty(VMContext),
382 llvm::PointerType::getUnqual(CtorFTy), NULL);
384 // Construct the constructor and destructor arrays.
385 std::vector<llvm::Constant*> Ctors;
386 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
387 std::vector<llvm::Constant*> S;
388 S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
390 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
391 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
394 if (!Ctors.empty()) {
395 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
396 new llvm::GlobalVariable(TheModule, AT, false,
397 llvm::GlobalValue::AppendingLinkage,
398 llvm::ConstantArray::get(AT, Ctors),
403 llvm::GlobalValue::LinkageTypes
404 CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
405 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
407 if (Linkage == GVA_Internal)
408 return llvm::Function::InternalLinkage;
410 if (D->hasAttr<DLLExportAttr>())
411 return llvm::Function::DLLExportLinkage;
413 if (D->hasAttr<WeakAttr>())
414 return llvm::Function::WeakAnyLinkage;
416 // In C99 mode, 'inline' functions are guaranteed to have a strong
417 // definition somewhere else, so we can use available_externally linkage.
418 if (Linkage == GVA_C99Inline)
419 return llvm::Function::AvailableExternallyLinkage;
421 // Note that Apple's kernel linker doesn't support symbol
422 // coalescing, so we need to avoid linkonce and weak linkages there.
423 // Normally, this means we just map to internal, but for explicit
424 // instantiations we'll map to external.
426 // In C++, the compiler has to emit a definition in every translation unit
427 // that references the function. We should use linkonce_odr because
428 // a) if all references in this translation unit are optimized away, we
429 // don't need to codegen it. b) if the function persists, it needs to be
430 // merged with other definitions. c) C++ has the ODR, so we know the
431 // definition is dependable.
432 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
433 return !Context.getLangOptions().AppleKext
434 ? llvm::Function::LinkOnceODRLinkage
435 : llvm::Function::InternalLinkage;
437 // An explicit instantiation of a template has weak linkage, since
438 // explicit instantiations can occur in multiple translation units
439 // and must all be equivalent. However, we are not allowed to
440 // throw away these explicit instantiations.
441 if (Linkage == GVA_ExplicitTemplateInstantiation)
442 return !Context.getLangOptions().AppleKext
443 ? llvm::Function::WeakODRLinkage
444 : llvm::Function::ExternalLinkage;
446 // Otherwise, we have strong external linkage.
447 assert(Linkage == GVA_StrongExternal);
448 return llvm::Function::ExternalLinkage;
452 /// SetFunctionDefinitionAttributes - Set attributes for a global.
454 /// FIXME: This is currently only done for aliases and functions, but not for
455 /// variables (these details are set in EmitGlobalVarDefinition for variables).
456 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
457 llvm::GlobalValue *GV) {
458 SetCommonAttributes(D, GV);
461 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
462 const CGFunctionInfo &Info,
464 unsigned CallingConv;
465 AttributeListType AttributeList;
466 ConstructAttributeList(Info, D, AttributeList, CallingConv);
467 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
468 AttributeList.size()));
469 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
472 /// Determines whether the language options require us to model
473 /// unwind exceptions. We treat -fexceptions as mandating this
474 /// except under the fragile ObjC ABI with only ObjC exceptions
475 /// enabled. This means, for example, that C with -fexceptions
477 static bool hasUnwindExceptions(const LangOptions &Features) {
478 // If exceptions are completely disabled, obviously this is false.
479 if (!Features.Exceptions) return false;
481 // If C++ exceptions are enabled, this is true.
482 if (Features.CXXExceptions) return true;
484 // If ObjC exceptions are enabled, this depends on the ABI.
485 if (Features.ObjCExceptions) {
486 if (!Features.ObjCNonFragileABI) return false;
492 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
494 if (CodeGenOpts.UnwindTables)
497 if (!hasUnwindExceptions(Features))
498 F->addFnAttr(llvm::Attribute::NoUnwind);
500 if (D->hasAttr<NakedAttr>()) {
501 // Naked implies noinline: we should not be inlining such functions.
502 F->addFnAttr(llvm::Attribute::Naked);
503 F->addFnAttr(llvm::Attribute::NoInline);
506 if (D->hasAttr<NoInlineAttr>())
507 F->addFnAttr(llvm::Attribute::NoInline);
509 // (noinline wins over always_inline, and we can't specify both in IR)
510 if (D->hasAttr<AlwaysInlineAttr>() &&
511 !F->hasFnAttr(llvm::Attribute::NoInline))
512 F->addFnAttr(llvm::Attribute::AlwaysInline);
514 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
515 F->setUnnamedAddr(true);
517 if (Features.getStackProtector() == LangOptions::SSPOn)
518 F->addFnAttr(llvm::Attribute::StackProtect);
519 else if (Features.getStackProtector() == LangOptions::SSPReq)
520 F->addFnAttr(llvm::Attribute::StackProtectReq);
522 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
524 F->setAlignment(alignment);
526 // C++ ABI requires 2-byte alignment for member functions.
527 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
531 void CodeGenModule::SetCommonAttributes(const Decl *D,
532 llvm::GlobalValue *GV) {
533 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
534 setGlobalVisibility(GV, ND);
536 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
538 if (D->hasAttr<UsedAttr>())
541 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
542 GV->setSection(SA->getName());
544 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
547 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
549 const CGFunctionInfo &FI) {
550 SetLLVMFunctionAttributes(D, FI, F);
551 SetLLVMFunctionAttributesForDefinition(D, F);
553 F->setLinkage(llvm::Function::InternalLinkage);
555 SetCommonAttributes(D, F);
558 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
560 bool IsIncompleteFunction) {
561 if (unsigned IID = F->getIntrinsicID()) {
562 // If this is an intrinsic function, set the function's attributes
563 // to the intrinsic's attributes.
564 F->setAttributes(llvm::Intrinsic::getAttributes((llvm::Intrinsic::ID)IID));
568 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
570 if (!IsIncompleteFunction)
571 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
573 // Only a few attributes are set on declarations; these may later be
574 // overridden by a definition.
576 if (FD->hasAttr<DLLImportAttr>()) {
577 F->setLinkage(llvm::Function::DLLImportLinkage);
578 } else if (FD->hasAttr<WeakAttr>() ||
579 FD->isWeakImported()) {
580 // "extern_weak" is overloaded in LLVM; we probably should have
581 // separate linkage types for this.
582 F->setLinkage(llvm::Function::ExternalWeakLinkage);
584 F->setLinkage(llvm::Function::ExternalLinkage);
586 NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
587 if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
588 F->setVisibility(GetLLVMVisibility(LV.visibility()));
592 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
593 F->setSection(SA->getName());
596 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
597 assert(!GV->isDeclaration() &&
598 "Only globals with definition can force usage.");
599 LLVMUsed.push_back(GV);
602 void CodeGenModule::EmitLLVMUsed() {
603 // Don't create llvm.used if there is no need.
604 if (LLVMUsed.empty())
607 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
609 // Convert LLVMUsed to what ConstantArray needs.
610 std::vector<llvm::Constant*> UsedArray;
611 UsedArray.resize(LLVMUsed.size());
612 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
614 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
618 if (UsedArray.empty())
620 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
622 llvm::GlobalVariable *GV =
623 new llvm::GlobalVariable(getModule(), ATy, false,
624 llvm::GlobalValue::AppendingLinkage,
625 llvm::ConstantArray::get(ATy, UsedArray),
628 GV->setSection("llvm.metadata");
631 void CodeGenModule::EmitDeferred() {
632 // Emit code for any potentially referenced deferred decls. Since a
633 // previously unused static decl may become used during the generation of code
634 // for a static function, iterate until no changes are made.
636 while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
637 if (!DeferredVTables.empty()) {
638 const CXXRecordDecl *RD = DeferredVTables.back();
639 DeferredVTables.pop_back();
640 getVTables().GenerateClassData(getVTableLinkage(RD), RD);
644 GlobalDecl D = DeferredDeclsToEmit.back();
645 DeferredDeclsToEmit.pop_back();
647 // Check to see if we've already emitted this. This is necessary
648 // for a couple of reasons: first, decls can end up in the
649 // deferred-decls queue multiple times, and second, decls can end
650 // up with definitions in unusual ways (e.g. by an extern inline
651 // function acquiring a strong function redefinition). Just
652 // ignore these cases.
654 // TODO: That said, looking this up multiple times is very wasteful.
655 StringRef Name = getMangledName(D);
656 llvm::GlobalValue *CGRef = GetGlobalValue(Name);
657 assert(CGRef && "Deferred decl wasn't referenced?");
659 if (!CGRef->isDeclaration())
662 // GlobalAlias::isDeclaration() defers to the aliasee, but for our
663 // purposes an alias counts as a definition.
664 if (isa<llvm::GlobalAlias>(CGRef))
667 // Otherwise, emit the definition and move on to the next one.
668 EmitGlobalDefinition(D);
672 void CodeGenModule::EmitGlobalAnnotations() {
673 if (Annotations.empty())
676 // Create a new global variable for the ConstantStruct in the Module.
677 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
678 Annotations[0]->getType(), Annotations.size()), Annotations);
679 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
680 Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
681 "llvm.global.annotations");
682 gv->setSection(AnnotationSection);
685 llvm::Constant *CodeGenModule::EmitAnnotationString(llvm::StringRef Str) {
686 llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str);
687 if (i != AnnotationStrings.end())
690 // Not found yet, create a new global.
691 llvm::Constant *s = llvm::ConstantArray::get(getLLVMContext(), Str, true);
692 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
693 true, llvm::GlobalValue::PrivateLinkage, s, ".str");
694 gv->setSection(AnnotationSection);
695 gv->setUnnamedAddr(true);
696 AnnotationStrings[Str] = gv;
700 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
701 SourceManager &SM = getContext().getSourceManager();
702 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
704 return EmitAnnotationString(PLoc.getFilename());
705 return EmitAnnotationString(SM.getBufferName(Loc));
708 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
709 SourceManager &SM = getContext().getSourceManager();
710 PresumedLoc PLoc = SM.getPresumedLoc(L);
711 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
712 SM.getExpansionLineNumber(L);
713 return llvm::ConstantInt::get(Int32Ty, LineNo);
716 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
717 const AnnotateAttr *AA,
719 // Get the globals for file name, annotation, and the line number.
720 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
721 *UnitGV = EmitAnnotationUnit(L),
722 *LineNoCst = EmitAnnotationLineNo(L);
724 // Create the ConstantStruct for the global annotation.
725 llvm::Constant *Fields[4] = {
726 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
727 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
728 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
731 return llvm::ConstantStruct::getAnon(Fields);
734 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
735 llvm::GlobalValue *GV) {
736 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
737 // Get the struct elements for these annotations.
738 for (specific_attr_iterator<AnnotateAttr>
739 ai = D->specific_attr_begin<AnnotateAttr>(),
740 ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
741 Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
744 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
745 // Never defer when EmitAllDecls is specified.
746 if (Features.EmitAllDecls)
749 return !getContext().DeclMustBeEmitted(Global);
752 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
753 const AliasAttr *AA = VD->getAttr<AliasAttr>();
754 assert(AA && "No alias?");
756 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
758 // See if there is already something with the target's name in the module.
759 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
761 llvm::Constant *Aliasee;
762 if (isa<llvm::FunctionType>(DeclTy))
763 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
764 /*ForVTable=*/false);
766 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
767 llvm::PointerType::getUnqual(DeclTy), 0);
769 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
770 F->setLinkage(llvm::Function::ExternalWeakLinkage);
771 WeakRefReferences.insert(F);
777 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
778 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
780 // Weak references don't produce any output by themselves.
781 if (Global->hasAttr<WeakRefAttr>())
784 // If this is an alias definition (which otherwise looks like a declaration)
786 if (Global->hasAttr<AliasAttr>())
787 return EmitAliasDefinition(GD);
789 // If this is CUDA, be selective about which declarations we emit.
791 if (CodeGenOpts.CUDAIsDevice) {
792 if (!Global->hasAttr<CUDADeviceAttr>() &&
793 !Global->hasAttr<CUDAGlobalAttr>() &&
794 !Global->hasAttr<CUDAConstantAttr>() &&
795 !Global->hasAttr<CUDASharedAttr>())
798 if (!Global->hasAttr<CUDAHostAttr>() && (
799 Global->hasAttr<CUDADeviceAttr>() ||
800 Global->hasAttr<CUDAConstantAttr>() ||
801 Global->hasAttr<CUDASharedAttr>()))
806 // Ignore declarations, they will be emitted on their first use.
807 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
808 // Forward declarations are emitted lazily on first use.
809 if (!FD->doesThisDeclarationHaveABody()) {
810 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
813 const FunctionDecl *InlineDefinition = 0;
814 FD->getBody(InlineDefinition);
816 StringRef MangledName = getMangledName(GD);
817 llvm::StringMap<GlobalDecl>::iterator DDI =
818 DeferredDecls.find(MangledName);
819 if (DDI != DeferredDecls.end())
820 DeferredDecls.erase(DDI);
821 EmitGlobalDefinition(InlineDefinition);
825 const VarDecl *VD = cast<VarDecl>(Global);
826 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
828 if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
832 // Defer code generation when possible if this is a static definition, inline
833 // function etc. These we only want to emit if they are used.
834 if (!MayDeferGeneration(Global)) {
835 // Emit the definition if it can't be deferred.
836 EmitGlobalDefinition(GD);
840 // If we're deferring emission of a C++ variable with an
841 // initializer, remember the order in which it appeared in the file.
842 if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) &&
843 cast<VarDecl>(Global)->hasInit()) {
844 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
845 CXXGlobalInits.push_back(0);
848 // If the value has already been used, add it directly to the
849 // DeferredDeclsToEmit list.
850 StringRef MangledName = getMangledName(GD);
851 if (GetGlobalValue(MangledName))
852 DeferredDeclsToEmit.push_back(GD);
854 // Otherwise, remember that we saw a deferred decl with this name. The
855 // first use of the mangled name will cause it to move into
856 // DeferredDeclsToEmit.
857 DeferredDecls[MangledName] = GD;
861 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
862 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
864 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
865 Context.getSourceManager(),
866 "Generating code for declaration");
868 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
869 // At -O0, don't generate IR for functions with available_externally
871 if (CodeGenOpts.OptimizationLevel == 0 &&
872 !Function->hasAttr<AlwaysInlineAttr>() &&
873 getFunctionLinkage(Function)
874 == llvm::Function::AvailableExternallyLinkage)
877 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
878 // Make sure to emit the definition(s) before we emit the thunks.
879 // This is necessary for the generation of certain thunks.
880 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
881 EmitCXXConstructor(CD, GD.getCtorType());
882 else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
883 EmitCXXDestructor(DD, GD.getDtorType());
885 EmitGlobalFunctionDefinition(GD);
887 if (Method->isVirtual())
888 getVTables().EmitThunks(GD);
893 return EmitGlobalFunctionDefinition(GD);
896 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
897 return EmitGlobalVarDefinition(VD);
899 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
902 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
903 /// module, create and return an llvm Function with the specified type. If there
904 /// is something in the module with the specified name, return it potentially
905 /// bitcasted to the right type.
907 /// If D is non-null, it specifies a decl that correspond to this. This is used
908 /// to set the attributes on the function when it is first created.
910 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
912 GlobalDecl D, bool ForVTable,
913 llvm::Attributes ExtraAttrs) {
914 // Lookup the entry, lazily creating it if necessary.
915 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
917 if (WeakRefReferences.count(Entry)) {
918 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
919 if (FD && !FD->hasAttr<WeakAttr>())
920 Entry->setLinkage(llvm::Function::ExternalLinkage);
922 WeakRefReferences.erase(Entry);
925 if (Entry->getType()->getElementType() == Ty)
928 // Make sure the result is of the correct type.
929 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
932 // This function doesn't have a complete type (for example, the return
933 // type is an incomplete struct). Use a fake type instead, and make
934 // sure not to try to set attributes.
935 bool IsIncompleteFunction = false;
937 llvm::FunctionType *FTy;
938 if (isa<llvm::FunctionType>(Ty)) {
939 FTy = cast<llvm::FunctionType>(Ty);
941 FTy = llvm::FunctionType::get(VoidTy, false);
942 IsIncompleteFunction = true;
945 llvm::Function *F = llvm::Function::Create(FTy,
946 llvm::Function::ExternalLinkage,
947 MangledName, &getModule());
948 assert(F->getName() == MangledName && "name was uniqued!");
950 SetFunctionAttributes(D, F, IsIncompleteFunction);
951 if (ExtraAttrs != llvm::Attribute::None)
952 F->addFnAttr(ExtraAttrs);
954 // This is the first use or definition of a mangled name. If there is a
955 // deferred decl with this name, remember that we need to emit it at the end
957 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
958 if (DDI != DeferredDecls.end()) {
959 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
960 // list, and remove it from DeferredDecls (since we don't need it anymore).
961 DeferredDeclsToEmit.push_back(DDI->second);
962 DeferredDecls.erase(DDI);
964 // Otherwise, there are cases we have to worry about where we're
965 // using a declaration for which we must emit a definition but where
966 // we might not find a top-level definition:
967 // - member functions defined inline in their classes
968 // - friend functions defined inline in some class
969 // - special member functions with implicit definitions
970 // If we ever change our AST traversal to walk into class methods,
971 // this will be unnecessary.
973 // We also don't emit a definition for a function if it's going to be an entry
974 // in a vtable, unless it's already marked as used.
975 } else if (getLangOptions().CPlusPlus && D.getDecl()) {
976 // Look for a declaration that's lexically in a record.
977 const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
979 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
980 if (FD->isImplicit() && !ForVTable) {
981 assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
982 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
984 } else if (FD->doesThisDeclarationHaveABody()) {
985 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
989 FD = FD->getPreviousDeclaration();
993 // Make sure the result is of the requested type.
994 if (!IsIncompleteFunction) {
995 assert(F->getType()->getElementType() == Ty);
999 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1000 return llvm::ConstantExpr::getBitCast(F, PTy);
1003 /// GetAddrOfFunction - Return the address of the given function. If Ty is
1004 /// non-null, then this function will use the specified type if it has to
1005 /// create it (this occurs when we see a definition of the function).
1006 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
1009 // If there was no specific requested type, just convert it now.
1011 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
1013 StringRef MangledName = getMangledName(GD);
1014 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
1017 /// CreateRuntimeFunction - Create a new runtime function with the specified
1020 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
1022 llvm::Attributes ExtraAttrs) {
1023 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1027 static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D,
1028 bool ConstantInit) {
1029 if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
1032 if (Context.getLangOptions().CPlusPlus) {
1033 if (const RecordType *Record
1034 = Context.getBaseElementType(D->getType())->getAs<RecordType>())
1035 return ConstantInit &&
1036 cast<CXXRecordDecl>(Record->getDecl())->isPOD() &&
1037 !cast<CXXRecordDecl>(Record->getDecl())->hasMutableFields();
1043 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1044 /// create and return an llvm GlobalVariable with the specified type. If there
1045 /// is something in the module with the specified name, return it potentially
1046 /// bitcasted to the right type.
1048 /// If D is non-null, it specifies a decl that correspond to this. This is used
1049 /// to set the attributes on the global when it is first created.
1051 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
1052 llvm::PointerType *Ty,
1055 // Lookup the entry, lazily creating it if necessary.
1056 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1058 if (WeakRefReferences.count(Entry)) {
1059 if (D && !D->hasAttr<WeakAttr>())
1060 Entry->setLinkage(llvm::Function::ExternalLinkage);
1062 WeakRefReferences.erase(Entry);
1066 Entry->setUnnamedAddr(true);
1068 if (Entry->getType() == Ty)
1071 // Make sure the result is of the correct type.
1072 return llvm::ConstantExpr::getBitCast(Entry, Ty);
1075 // This is the first use or definition of a mangled name. If there is a
1076 // deferred decl with this name, remember that we need to emit it at the end
1078 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1079 if (DDI != DeferredDecls.end()) {
1080 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1081 // list, and remove it from DeferredDecls (since we don't need it anymore).
1082 DeferredDeclsToEmit.push_back(DDI->second);
1083 DeferredDecls.erase(DDI);
1086 llvm::GlobalVariable *GV =
1087 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
1088 llvm::GlobalValue::ExternalLinkage,
1090 false, Ty->getAddressSpace());
1092 // Handle things which are present even on external declarations.
1094 // FIXME: This code is overly simple and should be merged with other global
1096 GV->setConstant(DeclIsConstantGlobal(Context, D, false));
1098 // Set linkage and visibility in case we never see a definition.
1099 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
1100 if (LV.linkage() != ExternalLinkage) {
1101 // Don't set internal linkage on declarations.
1103 if (D->hasAttr<DLLImportAttr>())
1104 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
1105 else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
1106 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1108 // Set visibility on a declaration only if it's explicit.
1109 if (LV.visibilityExplicit())
1110 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
1113 GV->setThreadLocal(D->isThreadSpecified());
1120 llvm::GlobalVariable *
1121 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
1123 llvm::GlobalValue::LinkageTypes Linkage) {
1124 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1125 llvm::GlobalVariable *OldGV = 0;
1129 // Check if the variable has the right type.
1130 if (GV->getType()->getElementType() == Ty)
1133 // Because C++ name mangling, the only way we can end up with an already
1134 // existing global with the same name is if it has been declared extern "C".
1135 assert(GV->isDeclaration() && "Declaration has wrong type!");
1139 // Create a new variable.
1140 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1144 // Replace occurrences of the old variable if needed.
1145 GV->takeName(OldGV);
1147 if (!OldGV->use_empty()) {
1148 llvm::Constant *NewPtrForOldDecl =
1149 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1150 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1153 OldGV->eraseFromParent();
1159 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1160 /// given global variable. If Ty is non-null and if the global doesn't exist,
1161 /// then it will be greated with the specified type instead of whatever the
1162 /// normal requested type would be.
1163 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1165 assert(D->hasGlobalStorage() && "Not a global variable");
1166 QualType ASTTy = D->getType();
1168 Ty = getTypes().ConvertTypeForMem(ASTTy);
1170 llvm::PointerType *PTy =
1171 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1173 StringRef MangledName = getMangledName(D);
1174 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
1177 /// CreateRuntimeVariable - Create a new runtime global variable with the
1178 /// specified type and name.
1180 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
1182 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
1186 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1187 assert(!D->getInit() && "Cannot emit definite definitions here!");
1189 if (MayDeferGeneration(D)) {
1190 // If we have not seen a reference to this variable yet, place it
1191 // into the deferred declarations table to be emitted if needed
1193 StringRef MangledName = getMangledName(D);
1194 if (!GetGlobalValue(MangledName)) {
1195 DeferredDecls[MangledName] = D;
1200 // The tentative definition is the only definition.
1201 EmitGlobalVarDefinition(D);
1204 void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
1205 if (DefinitionRequired)
1206 getVTables().GenerateClassData(getVTableLinkage(Class), Class);
1209 llvm::GlobalVariable::LinkageTypes
1210 CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
1211 if (RD->getLinkage() != ExternalLinkage)
1212 return llvm::GlobalVariable::InternalLinkage;
1214 if (const CXXMethodDecl *KeyFunction
1215 = RD->getASTContext().getKeyFunction(RD)) {
1216 // If this class has a key function, use that to determine the linkage of
1218 const FunctionDecl *Def = 0;
1219 if (KeyFunction->hasBody(Def))
1220 KeyFunction = cast<CXXMethodDecl>(Def);
1222 switch (KeyFunction->getTemplateSpecializationKind()) {
1223 case TSK_Undeclared:
1224 case TSK_ExplicitSpecialization:
1225 // When compiling with optimizations turned on, we emit all vtables,
1226 // even if the key function is not defined in the current translation
1227 // unit. If this is the case, use available_externally linkage.
1228 if (!Def && CodeGenOpts.OptimizationLevel)
1229 return llvm::GlobalVariable::AvailableExternallyLinkage;
1231 if (KeyFunction->isInlined())
1232 return !Context.getLangOptions().AppleKext ?
1233 llvm::GlobalVariable::LinkOnceODRLinkage :
1234 llvm::Function::InternalLinkage;
1236 return llvm::GlobalVariable::ExternalLinkage;
1238 case TSK_ImplicitInstantiation:
1239 return !Context.getLangOptions().AppleKext ?
1240 llvm::GlobalVariable::LinkOnceODRLinkage :
1241 llvm::Function::InternalLinkage;
1243 case TSK_ExplicitInstantiationDefinition:
1244 return !Context.getLangOptions().AppleKext ?
1245 llvm::GlobalVariable::WeakODRLinkage :
1246 llvm::Function::InternalLinkage;
1248 case TSK_ExplicitInstantiationDeclaration:
1249 // FIXME: Use available_externally linkage. However, this currently
1250 // breaks LLVM's build due to undefined symbols.
1251 // return llvm::GlobalVariable::AvailableExternallyLinkage;
1252 return !Context.getLangOptions().AppleKext ?
1253 llvm::GlobalVariable::LinkOnceODRLinkage :
1254 llvm::Function::InternalLinkage;
1258 if (Context.getLangOptions().AppleKext)
1259 return llvm::Function::InternalLinkage;
1261 switch (RD->getTemplateSpecializationKind()) {
1262 case TSK_Undeclared:
1263 case TSK_ExplicitSpecialization:
1264 case TSK_ImplicitInstantiation:
1265 // FIXME: Use available_externally linkage. However, this currently
1266 // breaks LLVM's build due to undefined symbols.
1267 // return llvm::GlobalVariable::AvailableExternallyLinkage;
1268 case TSK_ExplicitInstantiationDeclaration:
1269 return llvm::GlobalVariable::LinkOnceODRLinkage;
1271 case TSK_ExplicitInstantiationDefinition:
1272 return llvm::GlobalVariable::WeakODRLinkage;
1275 // Silence GCC warning.
1276 return llvm::GlobalVariable::LinkOnceODRLinkage;
1279 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
1280 return Context.toCharUnitsFromBits(
1281 TheTargetData.getTypeStoreSizeInBits(Ty));
1284 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1285 llvm::Constant *Init = 0;
1286 QualType ASTTy = D->getType();
1287 bool NonConstInit = false;
1289 const Expr *InitExpr = D->getAnyInitializer();
1292 // This is a tentative definition; tentative definitions are
1293 // implicitly initialized with { 0 }.
1295 // Note that tentative definitions are only emitted at the end of
1296 // a translation unit, so they should never have incomplete
1297 // type. In addition, EmitTentativeDefinition makes sure that we
1298 // never attempt to emit a tentative definition if a real one
1299 // exists. A use may still exists, however, so we still may need
1301 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1302 Init = EmitNullConstant(D->getType());
1304 Init = EmitConstantExpr(InitExpr, D->getType());
1306 QualType T = InitExpr->getType();
1307 if (D->getType()->isReferenceType())
1310 if (getLangOptions().CPlusPlus) {
1311 Init = EmitNullConstant(T);
1312 NonConstInit = true;
1314 ErrorUnsupported(D, "static initializer");
1315 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1318 // We don't need an initializer, so remove the entry for the delayed
1319 // initializer position (just in case this entry was delayed).
1320 if (getLangOptions().CPlusPlus)
1321 DelayedCXXInitPosition.erase(D);
1325 llvm::Type* InitType = Init->getType();
1326 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1328 // Strip off a bitcast if we got one back.
1329 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1330 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1331 // all zero index gep.
1332 CE->getOpcode() == llvm::Instruction::GetElementPtr);
1333 Entry = CE->getOperand(0);
1336 // Entry is now either a Function or GlobalVariable.
1337 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1339 // We have a definition after a declaration with the wrong type.
1340 // We must make a new GlobalVariable* and update everything that used OldGV
1341 // (a declaration or tentative definition) with the new GlobalVariable*
1342 // (which will be a definition).
1344 // This happens if there is a prototype for a global (e.g.
1345 // "extern int x[];") and then a definition of a different type (e.g.
1346 // "int x[10];"). This also happens when an initializer has a different type
1347 // from the type of the global (this happens with unions).
1349 GV->getType()->getElementType() != InitType ||
1350 GV->getType()->getAddressSpace() !=
1351 getContext().getTargetAddressSpace(ASTTy)) {
1353 // Move the old entry aside so that we'll create a new one.
1354 Entry->setName(StringRef());
1356 // Make a new global with the correct type, this is now guaranteed to work.
1357 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
1359 // Replace all uses of the old global with the new global
1360 llvm::Constant *NewPtrForOldDecl =
1361 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1362 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1364 // Erase the old global, since it is no longer used.
1365 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1368 if (D->hasAttr<AnnotateAttr>())
1369 AddGlobalAnnotations(D, GV);
1371 GV->setInitializer(Init);
1373 // If it is safe to mark the global 'constant', do so now.
1374 GV->setConstant(false);
1375 if (!NonConstInit && DeclIsConstantGlobal(Context, D, true))
1376 GV->setConstant(true);
1378 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1380 // Set the llvm linkage type as appropriate.
1381 llvm::GlobalValue::LinkageTypes Linkage =
1382 GetLLVMLinkageVarDefinition(D, GV);
1383 GV->setLinkage(Linkage);
1384 if (Linkage == llvm::GlobalVariable::CommonLinkage)
1385 // common vars aren't constant even if declared const.
1386 GV->setConstant(false);
1388 SetCommonAttributes(D, GV);
1390 // Emit the initializer function if necessary.
1392 EmitCXXGlobalVarDeclInitFunc(D, GV);
1394 // Emit global variable debug information.
1395 if (CGDebugInfo *DI = getModuleDebugInfo())
1396 DI->EmitGlobalVariable(GV, D);
1399 llvm::GlobalValue::LinkageTypes
1400 CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1401 llvm::GlobalVariable *GV) {
1402 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1403 if (Linkage == GVA_Internal)
1404 return llvm::Function::InternalLinkage;
1405 else if (D->hasAttr<DLLImportAttr>())
1406 return llvm::Function::DLLImportLinkage;
1407 else if (D->hasAttr<DLLExportAttr>())
1408 return llvm::Function::DLLExportLinkage;
1409 else if (D->hasAttr<WeakAttr>()) {
1410 if (GV->isConstant())
1411 return llvm::GlobalVariable::WeakODRLinkage;
1413 return llvm::GlobalVariable::WeakAnyLinkage;
1414 } else if (Linkage == GVA_TemplateInstantiation ||
1415 Linkage == GVA_ExplicitTemplateInstantiation)
1416 return llvm::GlobalVariable::WeakODRLinkage;
1417 else if (!getLangOptions().CPlusPlus &&
1418 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1419 D->getAttr<CommonAttr>()) &&
1420 !D->hasExternalStorage() && !D->getInit() &&
1421 !D->getAttr<SectionAttr>() && !D->isThreadSpecified() &&
1422 !D->getAttr<WeakImportAttr>()) {
1423 // Thread local vars aren't considered common linkage.
1424 return llvm::GlobalVariable::CommonLinkage;
1426 return llvm::GlobalVariable::ExternalLinkage;
1429 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1430 /// implement a function with no prototype, e.g. "int foo() {}". If there are
1431 /// existing call uses of the old function in the module, this adjusts them to
1432 /// call the new function directly.
1434 /// This is not just a cleanup: the always_inline pass requires direct calls to
1435 /// functions to be able to inline them. If there is a bitcast in the way, it
1436 /// won't inline them. Instcombine normally deletes these calls, but it isn't
1438 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1439 llvm::Function *NewFn) {
1440 // If we're redefining a global as a function, don't transform it.
1441 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1442 if (OldFn == 0) return;
1444 llvm::Type *NewRetTy = NewFn->getReturnType();
1445 SmallVector<llvm::Value*, 4> ArgList;
1447 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
1449 // TODO: Do invokes ever occur in C code? If so, we should handle them too.
1450 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1451 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
1452 if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
1453 llvm::CallSite CS(CI);
1454 if (!CI || !CS.isCallee(I)) continue;
1456 // If the return types don't match exactly, and if the call isn't dead, then
1457 // we can't transform this call.
1458 if (CI->getType() != NewRetTy && !CI->use_empty())
1461 // Get the attribute list.
1462 llvm::SmallVector<llvm::AttributeWithIndex, 8> AttrVec;
1463 llvm::AttrListPtr AttrList = CI->getAttributes();
1465 // Get any return attributes.
1466 llvm::Attributes RAttrs = AttrList.getRetAttributes();
1468 // Add the return attributes.
1470 AttrVec.push_back(llvm::AttributeWithIndex::get(0, RAttrs));
1472 // If the function was passed too few arguments, don't transform. If extra
1473 // arguments were passed, we silently drop them. If any of the types
1474 // mismatch, we don't transform.
1476 bool DontTransform = false;
1477 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1478 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
1479 if (CS.arg_size() == ArgNo ||
1480 CS.getArgument(ArgNo)->getType() != AI->getType()) {
1481 DontTransform = true;
1485 // Add any parameter attributes.
1486 if (llvm::Attributes PAttrs = AttrList.getParamAttributes(ArgNo + 1))
1487 AttrVec.push_back(llvm::AttributeWithIndex::get(ArgNo + 1, PAttrs));
1492 if (llvm::Attributes FnAttrs = AttrList.getFnAttributes())
1493 AttrVec.push_back(llvm::AttributeWithIndex::get(~0, FnAttrs));
1495 // Okay, we can transform this. Create the new call instruction and copy
1496 // over the required information.
1497 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
1498 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList, "", CI);
1500 if (!NewCall->getType()->isVoidTy())
1501 NewCall->takeName(CI);
1502 NewCall->setAttributes(llvm::AttrListPtr::get(AttrVec.begin(),
1504 NewCall->setCallingConv(CI->getCallingConv());
1506 // Finally, remove the old call, replacing any uses with the new one.
1507 if (!CI->use_empty())
1508 CI->replaceAllUsesWith(NewCall);
1510 // Copy debug location attached to CI.
1511 if (!CI->getDebugLoc().isUnknown())
1512 NewCall->setDebugLoc(CI->getDebugLoc());
1513 CI->eraseFromParent();
1518 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
1519 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
1521 // Compute the function info and LLVM type.
1522 const CGFunctionInfo &FI = getTypes().getFunctionInfo(GD);
1523 bool variadic = false;
1524 if (const FunctionProtoType *fpt = D->getType()->getAs<FunctionProtoType>())
1525 variadic = fpt->isVariadic();
1526 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI, variadic);
1528 // Get or create the prototype for the function.
1529 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
1531 // Strip off a bitcast if we got one back.
1532 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1533 assert(CE->getOpcode() == llvm::Instruction::BitCast);
1534 Entry = CE->getOperand(0);
1538 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
1539 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
1541 // If the types mismatch then we have to rewrite the definition.
1542 assert(OldFn->isDeclaration() &&
1543 "Shouldn't replace non-declaration");
1545 // F is the Function* for the one with the wrong type, we must make a new
1546 // Function* and update everything that used F (a declaration) with the new
1547 // Function* (which will be a definition).
1549 // This happens if there is a prototype for a function
1550 // (e.g. "int f()") and then a definition of a different type
1551 // (e.g. "int f(int x)"). Move the old function aside so that it
1552 // doesn't interfere with GetAddrOfFunction.
1553 OldFn->setName(StringRef());
1554 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
1556 // If this is an implementation of a function without a prototype, try to
1557 // replace any existing uses of the function (which may be calls) with uses
1558 // of the new function
1559 if (D->getType()->isFunctionNoProtoType()) {
1560 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
1561 OldFn->removeDeadConstantUsers();
1564 // Replace uses of F with the Function we will endow with a body.
1565 if (!Entry->use_empty()) {
1566 llvm::Constant *NewPtrForOldDecl =
1567 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
1568 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1571 // Ok, delete the old function now, which is dead.
1572 OldFn->eraseFromParent();
1577 // We need to set linkage and visibility on the function before
1578 // generating code for it because various parts of IR generation
1579 // want to propagate this information down (e.g. to local static
1581 llvm::Function *Fn = cast<llvm::Function>(Entry);
1582 setFunctionLinkage(D, Fn);
1584 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
1585 setGlobalVisibility(Fn, D);
1587 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
1589 SetFunctionDefinitionAttributes(D, Fn);
1590 SetLLVMFunctionAttributesForDefinition(D, Fn);
1592 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
1593 AddGlobalCtor(Fn, CA->getPriority());
1594 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
1595 AddGlobalDtor(Fn, DA->getPriority());
1596 if (D->hasAttr<AnnotateAttr>())
1597 AddGlobalAnnotations(D, Fn);
1600 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1601 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
1602 const AliasAttr *AA = D->getAttr<AliasAttr>();
1603 assert(AA && "Not an alias?");
1605 StringRef MangledName = getMangledName(GD);
1607 // If there is a definition in the module, then it wins over the alias.
1608 // This is dubious, but allow it to be safe. Just ignore the alias.
1609 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1610 if (Entry && !Entry->isDeclaration())
1613 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1615 // Create a reference to the named value. This ensures that it is emitted
1616 // if a deferred decl.
1617 llvm::Constant *Aliasee;
1618 if (isa<llvm::FunctionType>(DeclTy))
1619 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
1620 /*ForVTable=*/false);
1622 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1623 llvm::PointerType::getUnqual(DeclTy), 0);
1625 // Create the new alias itself, but don't set a name yet.
1626 llvm::GlobalValue *GA =
1627 new llvm::GlobalAlias(Aliasee->getType(),
1628 llvm::Function::ExternalLinkage,
1629 "", Aliasee, &getModule());
1632 assert(Entry->isDeclaration());
1634 // If there is a declaration in the module, then we had an extern followed
1635 // by the alias, as in:
1636 // extern int test6();
1638 // int test6() __attribute__((alias("test7")));
1640 // Remove it and replace uses of it with the alias.
1641 GA->takeName(Entry);
1643 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
1645 Entry->eraseFromParent();
1647 GA->setName(MangledName);
1650 // Set attributes which are particular to an alias; this is a
1651 // specialization of the attributes which may be set on a global
1652 // variable/function.
1653 if (D->hasAttr<DLLExportAttr>()) {
1654 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1655 // The dllexport attribute is ignored for undefined symbols.
1657 GA->setLinkage(llvm::Function::DLLExportLinkage);
1659 GA->setLinkage(llvm::Function::DLLExportLinkage);
1661 } else if (D->hasAttr<WeakAttr>() ||
1662 D->hasAttr<WeakRefAttr>() ||
1663 D->isWeakImported()) {
1664 GA->setLinkage(llvm::Function::WeakAnyLinkage);
1667 SetCommonAttributes(D, GA);
1670 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
1671 ArrayRef<llvm::Type*> Tys) {
1672 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
1676 static llvm::StringMapEntry<llvm::Constant*> &
1677 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1678 const StringLiteral *Literal,
1681 unsigned &StringLength) {
1682 StringRef String = Literal->getString();
1683 unsigned NumBytes = String.size();
1685 // Check for simple case.
1686 if (!Literal->containsNonAsciiOrNull()) {
1687 StringLength = NumBytes;
1688 return Map.GetOrCreateValue(String);
1691 // Otherwise, convert the UTF8 literals into a byte string.
1692 SmallVector<UTF16, 128> ToBuf(NumBytes);
1693 const UTF8 *FromPtr = (UTF8 *)String.data();
1694 UTF16 *ToPtr = &ToBuf[0];
1696 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1697 &ToPtr, ToPtr + NumBytes,
1700 // ConvertUTF8toUTF16 returns the length in ToPtr.
1701 StringLength = ToPtr - &ToBuf[0];
1703 // Render the UTF-16 string into a byte array and convert to the target byte
1706 // FIXME: This isn't something we should need to do here.
1707 llvm::SmallString<128> AsBytes;
1708 AsBytes.reserve(StringLength * 2);
1709 for (unsigned i = 0; i != StringLength; ++i) {
1710 unsigned short Val = ToBuf[i];
1712 AsBytes.push_back(Val & 0xFF);
1713 AsBytes.push_back(Val >> 8);
1715 AsBytes.push_back(Val >> 8);
1716 AsBytes.push_back(Val & 0xFF);
1719 // Append one extra null character, the second is automatically added by our
1721 AsBytes.push_back(0);
1724 return Map.GetOrCreateValue(StringRef(AsBytes.data(), AsBytes.size()));
1727 static llvm::StringMapEntry<llvm::Constant*> &
1728 GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1729 const StringLiteral *Literal,
1730 unsigned &StringLength)
1732 StringRef String = Literal->getString();
1733 StringLength = String.size();
1734 return Map.GetOrCreateValue(String);
1738 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1739 unsigned StringLength = 0;
1740 bool isUTF16 = false;
1741 llvm::StringMapEntry<llvm::Constant*> &Entry =
1742 GetConstantCFStringEntry(CFConstantStringMap, Literal,
1743 getTargetData().isLittleEndian(),
1744 isUTF16, StringLength);
1746 if (llvm::Constant *C = Entry.getValue())
1749 llvm::Constant *Zero =
1750 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1751 llvm::Constant *Zeros[] = { Zero, Zero };
1753 // If we don't already have it, get __CFConstantStringClassReference.
1754 if (!CFConstantStringClassRef) {
1755 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1756 Ty = llvm::ArrayType::get(Ty, 0);
1757 llvm::Constant *GV = CreateRuntimeVariable(Ty,
1758 "__CFConstantStringClassReference");
1759 // Decay array -> ptr
1760 CFConstantStringClassRef =
1761 llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
1764 QualType CFTy = getContext().getCFConstantStringType();
1766 llvm::StructType *STy =
1767 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1769 std::vector<llvm::Constant*> Fields(4);
1772 Fields[0] = CFConstantStringClassRef;
1775 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1776 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
1777 llvm::ConstantInt::get(Ty, 0x07C8);
1780 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1782 llvm::GlobalValue::LinkageTypes Linkage;
1785 // FIXME: why do utf strings get "_" labels instead of "L" labels?
1786 Linkage = llvm::GlobalValue::InternalLinkage;
1787 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1788 // does make plain ascii ones writable.
1791 // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
1792 // when using private linkage. It is not clear if this is a bug in ld
1793 // or a reasonable new restriction.
1794 Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
1795 isConstant = !Features.WritableStrings;
1798 llvm::GlobalVariable *GV =
1799 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1801 GV->setUnnamedAddr(true);
1803 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1804 GV->setAlignment(Align.getQuantity());
1806 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
1807 GV->setAlignment(Align.getQuantity());
1809 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
1812 Ty = getTypes().ConvertType(getContext().LongTy);
1813 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
1816 C = llvm::ConstantStruct::get(STy, Fields);
1817 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1818 llvm::GlobalVariable::PrivateLinkage, C,
1819 "_unnamed_cfstring_");
1820 if (const char *Sect = getContext().getTargetInfo().getCFStringSection())
1821 GV->setSection(Sect);
1828 CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
1829 DeclContext *DC, IdentifierInfo *Id) {
1831 if (Ctx.getLangOptions().CPlusPlus)
1832 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
1834 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
1838 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
1839 unsigned StringLength = 0;
1840 llvm::StringMapEntry<llvm::Constant*> &Entry =
1841 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
1843 if (llvm::Constant *C = Entry.getValue())
1846 llvm::Constant *Zero =
1847 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1848 llvm::Constant *Zeros[] = { Zero, Zero };
1850 // If we don't already have it, get _NSConstantStringClassReference.
1851 if (!ConstantStringClassRef) {
1852 std::string StringClass(getLangOptions().ObjCConstantStringClass);
1853 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1855 if (Features.ObjCNonFragileABI) {
1857 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
1858 : "OBJC_CLASS_$_" + StringClass;
1859 GV = getObjCRuntime().GetClassGlobal(str);
1860 // Make sure the result is of the correct type.
1861 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1862 ConstantStringClassRef =
1863 llvm::ConstantExpr::getBitCast(GV, PTy);
1866 StringClass.empty() ? "_NSConstantStringClassReference"
1867 : "_" + StringClass + "ClassReference";
1868 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
1869 GV = CreateRuntimeVariable(PTy, str);
1870 // Decay array -> ptr
1871 ConstantStringClassRef =
1872 llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
1876 if (!NSConstantStringType) {
1877 // Construct the type for a constant NSString.
1878 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
1879 Context.getTranslationUnitDecl(),
1880 &Context.Idents.get("__builtin_NSString"));
1881 D->startDefinition();
1883 QualType FieldTypes[3];
1886 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
1888 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
1889 // unsigned int length;
1890 FieldTypes[2] = Context.UnsignedIntTy;
1893 for (unsigned i = 0; i < 3; ++i) {
1894 FieldDecl *Field = FieldDecl::Create(Context, D,
1896 SourceLocation(), 0,
1897 FieldTypes[i], /*TInfo=*/0,
1901 Field->setAccess(AS_public);
1905 D->completeDefinition();
1906 QualType NSTy = Context.getTagDeclType(D);
1907 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
1910 std::vector<llvm::Constant*> Fields(3);
1913 Fields[0] = ConstantStringClassRef;
1916 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1918 llvm::GlobalValue::LinkageTypes Linkage;
1920 Linkage = llvm::GlobalValue::PrivateLinkage;
1921 isConstant = !Features.WritableStrings;
1923 llvm::GlobalVariable *GV =
1924 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1926 GV->setUnnamedAddr(true);
1927 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
1928 GV->setAlignment(Align.getQuantity());
1929 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
1932 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1933 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
1936 C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
1937 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1938 llvm::GlobalVariable::PrivateLinkage, C,
1939 "_unnamed_nsstring_");
1940 // FIXME. Fix section.
1941 if (const char *Sect =
1942 Features.ObjCNonFragileABI
1943 ? getContext().getTargetInfo().getNSStringNonFragileABISection()
1944 : getContext().getTargetInfo().getNSStringSection())
1945 GV->setSection(Sect);
1951 QualType CodeGenModule::getObjCFastEnumerationStateType() {
1952 if (ObjCFastEnumerationStateType.isNull()) {
1953 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
1954 Context.getTranslationUnitDecl(),
1955 &Context.Idents.get("__objcFastEnumerationState"));
1956 D->startDefinition();
1958 QualType FieldTypes[] = {
1959 Context.UnsignedLongTy,
1960 Context.getPointerType(Context.getObjCIdType()),
1961 Context.getPointerType(Context.UnsignedLongTy),
1962 Context.getConstantArrayType(Context.UnsignedLongTy,
1963 llvm::APInt(32, 5), ArrayType::Normal, 0)
1966 for (size_t i = 0; i < 4; ++i) {
1967 FieldDecl *Field = FieldDecl::Create(Context,
1970 SourceLocation(), 0,
1971 FieldTypes[i], /*TInfo=*/0,
1975 Field->setAccess(AS_public);
1979 D->completeDefinition();
1980 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
1983 return ObjCFastEnumerationStateType;
1986 /// GetStringForStringLiteral - Return the appropriate bytes for a
1987 /// string literal, properly padded to match the literal type.
1988 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
1989 const ASTContext &Context = getContext();
1990 const ConstantArrayType *CAT =
1991 Context.getAsConstantArrayType(E->getType());
1992 assert(CAT && "String isn't pointer or array!");
1994 // Resize the string to the right size.
1995 uint64_t RealLen = CAT->getSize().getZExtValue();
1997 switch (E->getKind()) {
1998 case StringLiteral::Ascii:
1999 case StringLiteral::UTF8:
2001 case StringLiteral::Wide:
2002 RealLen *= Context.getTargetInfo().getWCharWidth() / Context.getCharWidth();
2004 case StringLiteral::UTF16:
2005 RealLen *= Context.getTargetInfo().getChar16Width() / Context.getCharWidth();
2007 case StringLiteral::UTF32:
2008 RealLen *= Context.getTargetInfo().getChar32Width() / Context.getCharWidth();
2012 std::string Str = E->getString().str();
2013 Str.resize(RealLen, '\0');
2018 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2019 /// constant array for the given string literal.
2021 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
2022 // FIXME: This can be more efficient.
2023 // FIXME: We shouldn't need to bitcast the constant in the wide string case.
2024 CharUnits Align = getContext().getTypeAlignInChars(S->getType());
2025 llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S),
2027 Align.getQuantity());
2028 if (S->isWide() || S->isUTF16() || S->isUTF32()) {
2029 llvm::Type *DestTy =
2030 llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
2031 C = llvm::ConstantExpr::getBitCast(C, DestTy);
2036 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2037 /// array for the given ObjCEncodeExpr node.
2039 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2041 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
2043 return GetAddrOfConstantCString(Str);
2047 /// GenerateWritableString -- Creates storage for a string literal.
2048 static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
2051 const char *GlobalName,
2052 unsigned Alignment) {
2053 // Create Constant for this string literal. Don't add a '\0'.
2055 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
2057 // Create a global variable for this string
2058 llvm::GlobalVariable *GV =
2059 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
2060 llvm::GlobalValue::PrivateLinkage,
2062 GV->setAlignment(Alignment);
2063 GV->setUnnamedAddr(true);
2067 /// GetAddrOfConstantString - Returns a pointer to a character array
2068 /// containing the literal. This contents are exactly that of the
2069 /// given string, i.e. it will not be null terminated automatically;
2070 /// see GetAddrOfConstantCString. Note that whether the result is
2071 /// actually a pointer to an LLVM constant depends on
2072 /// Feature.WriteableStrings.
2074 /// The result has pointer to array type.
2075 llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
2076 const char *GlobalName,
2077 unsigned Alignment) {
2078 bool IsConstant = !Features.WritableStrings;
2080 // Get the default prefix if a name wasn't specified.
2082 GlobalName = ".str";
2084 // Don't share any string literals if strings aren't constant.
2086 return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
2088 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2089 ConstantStringMap.GetOrCreateValue(Str);
2091 if (llvm::GlobalVariable *GV = Entry.getValue()) {
2092 if (Alignment > GV->getAlignment()) {
2093 GV->setAlignment(Alignment);
2098 // Create a global variable for this.
2099 llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName, Alignment);
2104 /// GetAddrOfConstantCString - Returns a pointer to a character
2105 /// array containing the literal and a terminating '\0'
2106 /// character. The result has pointer to array type.
2107 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
2108 const char *GlobalName,
2109 unsigned Alignment) {
2110 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
2111 return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
2114 /// EmitObjCPropertyImplementations - Emit information for synthesized
2115 /// properties for an implementation.
2116 void CodeGenModule::EmitObjCPropertyImplementations(const
2117 ObjCImplementationDecl *D) {
2118 for (ObjCImplementationDecl::propimpl_iterator
2119 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
2120 ObjCPropertyImplDecl *PID = *i;
2122 // Dynamic is just for type-checking.
2123 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2124 ObjCPropertyDecl *PD = PID->getPropertyDecl();
2126 // Determine which methods need to be implemented, some may have
2127 // been overridden. Note that ::isSynthesized is not the method
2128 // we want, that just indicates if the decl came from a
2129 // property. What we want to know is if the method is defined in
2130 // this implementation.
2131 if (!D->getInstanceMethod(PD->getGetterName()))
2132 CodeGenFunction(*this).GenerateObjCGetter(
2133 const_cast<ObjCImplementationDecl *>(D), PID);
2134 if (!PD->isReadOnly() &&
2135 !D->getInstanceMethod(PD->getSetterName()))
2136 CodeGenFunction(*this).GenerateObjCSetter(
2137 const_cast<ObjCImplementationDecl *>(D), PID);
2142 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
2143 const ObjCInterfaceDecl *iface = impl->getClassInterface();
2144 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
2145 ivar; ivar = ivar->getNextIvar())
2146 if (ivar->getType().isDestructedType())
2152 /// EmitObjCIvarInitializations - Emit information for ivar initialization
2153 /// for an implementation.
2154 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
2155 // We might need a .cxx_destruct even if we don't have any ivar initializers.
2156 if (needsDestructMethod(D)) {
2157 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2158 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2159 ObjCMethodDecl *DTORMethod =
2160 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
2161 cxxSelector, getContext().VoidTy, 0, D,
2162 /*isInstance=*/true, /*isVariadic=*/false,
2163 /*isSynthesized=*/true, /*isImplicitlyDeclared=*/true,
2164 /*isDefined=*/false, ObjCMethodDecl::Required);
2165 D->addInstanceMethod(DTORMethod);
2166 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
2167 D->setHasCXXStructors(true);
2170 // If the implementation doesn't have any ivar initializers, we don't need
2171 // a .cxx_construct.
2172 if (D->getNumIvarInitializers() == 0)
2175 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2176 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2177 // The constructor returns 'self'.
2178 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2182 getContext().getObjCIdType(), 0,
2183 D, /*isInstance=*/true,
2184 /*isVariadic=*/false,
2185 /*isSynthesized=*/true,
2186 /*isImplicitlyDeclared=*/true,
2187 /*isDefined=*/false,
2188 ObjCMethodDecl::Required);
2189 D->addInstanceMethod(CTORMethod);
2190 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
2191 D->setHasCXXStructors(true);
2194 /// EmitNamespace - Emit all declarations in a namespace.
2195 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
2196 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
2198 EmitTopLevelDecl(*I);
2201 // EmitLinkageSpec - Emit all declarations in a linkage spec.
2202 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
2203 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2204 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
2205 ErrorUnsupported(LSD, "linkage spec");
2209 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
2211 EmitTopLevelDecl(*I);
2214 /// EmitTopLevelDecl - Emit code for a single top level declaration.
2215 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
2216 // If an error has occurred, stop code generation, but continue
2217 // parsing and semantic analysis (to ensure all warnings and errors
2219 if (Diags.hasErrorOccurred())
2222 // Ignore dependent declarations.
2223 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2226 switch (D->getKind()) {
2227 case Decl::CXXConversion:
2228 case Decl::CXXMethod:
2229 case Decl::Function:
2230 // Skip function templates
2231 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2232 cast<FunctionDecl>(D)->isLateTemplateParsed())
2235 EmitGlobal(cast<FunctionDecl>(D));
2239 EmitGlobal(cast<VarDecl>(D));
2242 // Indirect fields from global anonymous structs and unions can be
2243 // ignored; only the actual variable requires IR gen support.
2244 case Decl::IndirectField:
2248 case Decl::Namespace:
2249 EmitNamespace(cast<NamespaceDecl>(D));
2251 // No code generation needed.
2252 case Decl::UsingShadow:
2254 case Decl::UsingDirective:
2255 case Decl::ClassTemplate:
2256 case Decl::FunctionTemplate:
2257 case Decl::TypeAliasTemplate:
2258 case Decl::NamespaceAlias:
2261 case Decl::CXXConstructor:
2262 // Skip function templates
2263 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2264 cast<FunctionDecl>(D)->isLateTemplateParsed())
2267 EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2269 case Decl::CXXDestructor:
2270 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
2272 EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2275 case Decl::StaticAssert:
2279 // Objective-C Decls
2281 // Forward declarations, no (immediate) code generation.
2282 case Decl::ObjCClass:
2283 case Decl::ObjCForwardProtocol:
2284 case Decl::ObjCInterface:
2287 case Decl::ObjCCategory: {
2288 ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
2289 if (CD->IsClassExtension() && CD->hasSynthBitfield())
2290 Context.ResetObjCLayout(CD->getClassInterface());
2294 case Decl::ObjCProtocol:
2295 ObjCRuntime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
2298 case Decl::ObjCCategoryImpl:
2299 // Categories have properties but don't support synthesize so we
2300 // can ignore them here.
2301 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2304 case Decl::ObjCImplementation: {
2305 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2306 if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
2307 Context.ResetObjCLayout(OMD->getClassInterface());
2308 EmitObjCPropertyImplementations(OMD);
2309 EmitObjCIvarInitializations(OMD);
2310 ObjCRuntime->GenerateClass(OMD);
2313 case Decl::ObjCMethod: {
2314 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2315 // If this is not a prototype, emit the body.
2317 CodeGenFunction(*this).GenerateObjCMethod(OMD);
2320 case Decl::ObjCCompatibleAlias:
2321 // compatibility-alias is a directive and has no code gen.
2324 case Decl::LinkageSpec:
2325 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
2328 case Decl::FileScopeAsm: {
2329 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
2330 StringRef AsmString = AD->getAsmString()->getString();
2332 const std::string &S = getModule().getModuleInlineAsm();
2334 getModule().setModuleInlineAsm(AsmString);
2335 else if (*--S.end() == '\n')
2336 getModule().setModuleInlineAsm(S + AsmString.str());
2338 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
2343 // Make sure we handled everything we should, every other kind is a
2344 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
2345 // function. Need to recode Decl::Kind to do that easily.
2346 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2350 /// Turns the given pointer into a constant.
2351 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2353 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2354 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2355 return llvm::ConstantInt::get(i64, PtrInt);
2358 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2359 llvm::NamedMDNode *&GlobalMetadata,
2361 llvm::GlobalValue *Addr) {
2362 if (!GlobalMetadata)
2364 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2366 // TODO: should we report variant information for ctors/dtors?
2367 llvm::Value *Ops[] = {
2369 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2371 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2374 /// Emits metadata nodes associating all the global values in the
2375 /// current module with the Decls they came from. This is useful for
2376 /// projects using IR gen as a subroutine.
2378 /// Since there's currently no way to associate an MDNode directly
2379 /// with an llvm::GlobalValue, we create a global named metadata
2380 /// with the name 'clang.global.decl.ptrs'.
2381 void CodeGenModule::EmitDeclMetadata() {
2382 llvm::NamedMDNode *GlobalMetadata = 0;
2384 // StaticLocalDeclMap
2385 for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
2386 I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2388 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2389 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2393 /// Emits metadata nodes for all the local variables in the current
2395 void CodeGenFunction::EmitDeclMetadata() {
2396 if (LocalDeclMap.empty()) return;
2398 llvm::LLVMContext &Context = getLLVMContext();
2400 // Find the unique metadata ID for this name.
2401 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2403 llvm::NamedMDNode *GlobalMetadata = 0;
2405 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2406 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2407 const Decl *D = I->first;
2408 llvm::Value *Addr = I->second;
2410 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2411 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
2412 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
2413 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2414 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2415 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2420 void CodeGenModule::EmitCoverageFile() {
2421 if (!getCodeGenOpts().CoverageFile.empty()) {
2422 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
2423 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
2424 llvm::LLVMContext &Ctx = TheModule.getContext();
2425 llvm::MDString *CoverageFile =
2426 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
2427 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
2428 llvm::MDNode *CU = CUNode->getOperand(i);
2429 llvm::Value *node[] = { CoverageFile, CU };
2430 llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
2431 GCov->addOperand(N);