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"
20 #include "CGObjCRuntime.h"
21 #include "TargetInfo.h"
22 #include "clang/Frontend/CodeGenOptions.h"
23 #include "clang/AST/ASTContext.h"
24 #include "clang/AST/CharUnits.h"
25 #include "clang/AST/DeclObjC.h"
26 #include "clang/AST/DeclCXX.h"
27 #include "clang/AST/DeclTemplate.h"
28 #include "clang/AST/Mangle.h"
29 #include "clang/AST/RecordLayout.h"
30 #include "clang/Basic/Builtins.h"
31 #include "clang/Basic/Diagnostic.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Basic/ConvertUTF.h"
35 #include "llvm/CallingConv.h"
36 #include "llvm/Module.h"
37 #include "llvm/Intrinsics.h"
38 #include "llvm/LLVMContext.h"
39 #include "llvm/ADT/Triple.h"
40 #include "llvm/Target/Mangler.h"
41 #include "llvm/Target/TargetData.h"
42 #include "llvm/Support/CallSite.h"
43 #include "llvm/Support/ErrorHandling.h"
44 using namespace clang;
45 using namespace CodeGen;
47 static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
48 switch (CGM.getContext().Target.getCXXABI()) {
49 case CXXABI_ARM: return *CreateARMCXXABI(CGM);
50 case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
51 case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
54 llvm_unreachable("invalid C++ ABI kind");
55 return *CreateItaniumCXXABI(CGM);
59 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
60 llvm::Module &M, const llvm::TargetData &TD,
62 : Context(C), Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
63 TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
64 ABI(createCXXABI(*this)),
65 Types(C, M, TD, getTargetCodeGenInfo().getABIInfo(), ABI),
67 VTables(*this), Runtime(0), DebugInfo(0),
68 CFConstantStringClassRef(0), ConstantStringClassRef(0),
69 VMContext(M.getContext()),
70 NSConcreteGlobalBlockDecl(0), NSConcreteStackBlockDecl(0),
71 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
72 BlockObjectAssignDecl(0), BlockObjectDisposeDecl(0),
73 BlockObjectAssign(0), BlockObjectDispose(0),
74 BlockDescriptorType(0), GenericBlockLiteralType(0) {
78 // Enable TBAA unless it's suppressed.
79 if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)
80 TBAA = new CodeGenTBAA(Context, VMContext, getLangOptions(),
81 ABI.getMangleContext());
83 // If debug info or coverage generation is enabled, create the CGDebugInfo
85 if (CodeGenOpts.DebugInfo || CodeGenOpts.EmitGcovArcs ||
86 CodeGenOpts.EmitGcovNotes)
87 DebugInfo = new CGDebugInfo(*this);
89 Block.GlobalUniqueCount = 0;
91 // Initialize the type cache.
92 llvm::LLVMContext &LLVMContext = M.getContext();
93 VoidTy = llvm::Type::getVoidTy(LLVMContext);
94 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
95 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
96 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
97 PointerWidthInBits = C.Target.getPointerWidth(0);
99 C.toCharUnitsFromBits(C.Target.getPointerAlign(0)).getQuantity();
100 IntTy = llvm::IntegerType::get(LLVMContext, C.Target.getIntWidth());
101 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
102 Int8PtrTy = Int8Ty->getPointerTo(0);
103 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
106 CodeGenModule::~CodeGenModule() {
113 void CodeGenModule::createObjCRuntime() {
114 if (!Features.NeXTRuntime)
115 Runtime = CreateGNUObjCRuntime(*this);
117 Runtime = CreateMacObjCRuntime(*this);
120 void CodeGenModule::Release() {
122 EmitCXXGlobalInitFunc();
123 EmitCXXGlobalDtorFunc();
125 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
126 AddGlobalCtor(ObjCInitFunction);
127 EmitCtorList(GlobalCtors, "llvm.global_ctors");
128 EmitCtorList(GlobalDtors, "llvm.global_dtors");
132 SimplifyPersonality();
134 if (getCodeGenOpts().EmitDeclMetadata)
137 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
141 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
142 // Make sure that this type is translated.
143 Types.UpdateCompletedType(TD);
145 DebugInfo->UpdateCompletedType(TD);
148 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
151 return TBAA->getTBAAInfo(QTy);
154 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
155 llvm::MDNode *TBAAInfo) {
156 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
159 bool CodeGenModule::isTargetDarwin() const {
160 return getContext().Target.getTriple().isOSDarwin();
163 void CodeGenModule::Error(SourceLocation loc, llvm::StringRef error) {
164 unsigned diagID = getDiags().getCustomDiagID(Diagnostic::Error, error);
165 getDiags().Report(Context.getFullLoc(loc), diagID);
168 /// ErrorUnsupported - Print out an error that codegen doesn't support the
169 /// specified stmt yet.
170 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
172 if (OmitOnError && getDiags().hasErrorOccurred())
174 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
175 "cannot compile this %0 yet");
176 std::string Msg = Type;
177 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
178 << Msg << S->getSourceRange();
181 /// ErrorUnsupported - Print out an error that codegen doesn't support the
182 /// specified decl yet.
183 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
185 if (OmitOnError && getDiags().hasErrorOccurred())
187 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
188 "cannot compile this %0 yet");
189 std::string Msg = Type;
190 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
193 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
194 const NamedDecl *D) const {
195 // Internal definitions always have default visibility.
196 if (GV->hasLocalLinkage()) {
197 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
201 // Set visibility for definitions.
202 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
203 if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
204 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
207 /// Set the symbol visibility of type information (vtable and RTTI)
208 /// associated with the given type.
209 void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
210 const CXXRecordDecl *RD,
211 TypeVisibilityKind TVK) const {
212 setGlobalVisibility(GV, RD);
214 if (!CodeGenOpts.HiddenWeakVTables)
217 // We never want to drop the visibility for RTTI names.
218 if (TVK == TVK_ForRTTIName)
221 // We want to drop the visibility to hidden for weak type symbols.
222 // This isn't possible if there might be unresolved references
223 // elsewhere that rely on this symbol being visible.
225 // This should be kept roughly in sync with setThunkVisibility
229 if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
230 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
233 // Don't override an explicit visibility attribute.
234 if (RD->getExplicitVisibility())
237 switch (RD->getTemplateSpecializationKind()) {
238 // We have to disable the optimization if this is an EI definition
239 // because there might be EI declarations in other shared objects.
240 case TSK_ExplicitInstantiationDefinition:
241 case TSK_ExplicitInstantiationDeclaration:
244 // Every use of a non-template class's type information has to emit it.
248 // In theory, implicit instantiations can ignore the possibility of
249 // an explicit instantiation declaration because there necessarily
250 // must be an EI definition somewhere with default visibility. In
251 // practice, it's possible to have an explicit instantiation for
252 // an arbitrary template class, and linkers aren't necessarily able
253 // to deal with mixed-visibility symbols.
254 case TSK_ExplicitSpecialization:
255 case TSK_ImplicitInstantiation:
256 if (!CodeGenOpts.HiddenWeakTemplateVTables)
261 // If there's a key function, there may be translation units
262 // that don't have the key function's definition. But ignore
263 // this if we're emitting RTTI under -fno-rtti.
264 if (!(TVK != TVK_ForRTTI) || Features.RTTI) {
265 if (Context.getKeyFunction(RD))
269 // Otherwise, drop the visibility to hidden.
270 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
271 GV->setUnnamedAddr(true);
274 llvm::StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
275 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
277 llvm::StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
281 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
282 IdentifierInfo *II = ND->getIdentifier();
283 assert(II && "Attempt to mangle unnamed decl.");
289 llvm::SmallString<256> Buffer;
290 llvm::raw_svector_ostream Out(Buffer);
291 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
292 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
293 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
294 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
295 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
296 getCXXABI().getMangleContext().mangleBlock(BD, Out);
298 getCXXABI().getMangleContext().mangleName(ND, Out);
300 // Allocate space for the mangled name.
302 size_t Length = Buffer.size();
303 char *Name = MangledNamesAllocator.Allocate<char>(Length);
304 std::copy(Buffer.begin(), Buffer.end(), Name);
306 Str = llvm::StringRef(Name, Length);
311 void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
312 const BlockDecl *BD) {
313 MangleContext &MangleCtx = getCXXABI().getMangleContext();
314 const Decl *D = GD.getDecl();
315 llvm::raw_svector_ostream Out(Buffer.getBuffer());
317 MangleCtx.mangleGlobalBlock(BD, Out);
318 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
319 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
320 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
321 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
323 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
326 llvm::GlobalValue *CodeGenModule::GetGlobalValue(llvm::StringRef Name) {
327 return getModule().getNamedValue(Name);
330 /// AddGlobalCtor - Add a function to the list that will be called before
332 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
333 // FIXME: Type coercion of void()* types.
334 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
337 /// AddGlobalDtor - Add a function to the list that will be called
338 /// when the module is unloaded.
339 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
340 // FIXME: Type coercion of void()* types.
341 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
344 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
345 // Ctor function type is void()*.
346 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
347 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
349 // Get the type of a ctor entry, { i32, void ()* }.
350 llvm::StructType* CtorStructTy =
351 llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext),
352 llvm::PointerType::getUnqual(CtorFTy), NULL);
354 // Construct the constructor and destructor arrays.
355 std::vector<llvm::Constant*> Ctors;
356 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
357 std::vector<llvm::Constant*> S;
358 S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
360 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
361 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
364 if (!Ctors.empty()) {
365 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
366 new llvm::GlobalVariable(TheModule, AT, false,
367 llvm::GlobalValue::AppendingLinkage,
368 llvm::ConstantArray::get(AT, Ctors),
373 void CodeGenModule::EmitAnnotations() {
374 if (Annotations.empty())
377 // Create a new global variable for the ConstantStruct in the Module.
378 llvm::Constant *Array =
379 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
382 llvm::GlobalValue *gv =
383 new llvm::GlobalVariable(TheModule, Array->getType(), false,
384 llvm::GlobalValue::AppendingLinkage, Array,
385 "llvm.global.annotations");
386 gv->setSection("llvm.metadata");
389 llvm::GlobalValue::LinkageTypes
390 CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
391 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
393 if (Linkage == GVA_Internal)
394 return llvm::Function::InternalLinkage;
396 if (D->hasAttr<DLLExportAttr>())
397 return llvm::Function::DLLExportLinkage;
399 if (D->hasAttr<WeakAttr>())
400 return llvm::Function::WeakAnyLinkage;
402 // In C99 mode, 'inline' functions are guaranteed to have a strong
403 // definition somewhere else, so we can use available_externally linkage.
404 if (Linkage == GVA_C99Inline)
405 return llvm::Function::AvailableExternallyLinkage;
407 // In C++, the compiler has to emit a definition in every translation unit
408 // that references the function. We should use linkonce_odr because
409 // a) if all references in this translation unit are optimized away, we
410 // don't need to codegen it. b) if the function persists, it needs to be
411 // merged with other definitions. c) C++ has the ODR, so we know the
412 // definition is dependable.
413 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
414 return !Context.getLangOptions().AppleKext
415 ? llvm::Function::LinkOnceODRLinkage
416 : llvm::Function::InternalLinkage;
418 // An explicit instantiation of a template has weak linkage, since
419 // explicit instantiations can occur in multiple translation units
420 // and must all be equivalent. However, we are not allowed to
421 // throw away these explicit instantiations.
422 if (Linkage == GVA_ExplicitTemplateInstantiation)
423 return !Context.getLangOptions().AppleKext
424 ? llvm::Function::WeakODRLinkage
425 : llvm::Function::InternalLinkage;
427 // Otherwise, we have strong external linkage.
428 assert(Linkage == GVA_StrongExternal);
429 return llvm::Function::ExternalLinkage;
433 /// SetFunctionDefinitionAttributes - Set attributes for a global.
435 /// FIXME: This is currently only done for aliases and functions, but not for
436 /// variables (these details are set in EmitGlobalVarDefinition for variables).
437 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
438 llvm::GlobalValue *GV) {
439 SetCommonAttributes(D, GV);
442 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
443 const CGFunctionInfo &Info,
445 unsigned CallingConv;
446 AttributeListType AttributeList;
447 ConstructAttributeList(Info, D, AttributeList, CallingConv);
448 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
449 AttributeList.size()));
450 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
453 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
455 if (CodeGenOpts.UnwindTables)
458 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
459 F->addFnAttr(llvm::Attribute::NoUnwind);
461 if (D->hasAttr<AlwaysInlineAttr>())
462 F->addFnAttr(llvm::Attribute::AlwaysInline);
464 if (D->hasAttr<NakedAttr>())
465 F->addFnAttr(llvm::Attribute::Naked);
467 if (D->hasAttr<NoInlineAttr>())
468 F->addFnAttr(llvm::Attribute::NoInline);
470 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
471 F->setUnnamedAddr(true);
473 if (Features.getStackProtectorMode() == LangOptions::SSPOn)
474 F->addFnAttr(llvm::Attribute::StackProtect);
475 else if (Features.getStackProtectorMode() == LangOptions::SSPReq)
476 F->addFnAttr(llvm::Attribute::StackProtectReq);
478 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
480 F->setAlignment(alignment);
482 // C++ ABI requires 2-byte alignment for member functions.
483 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
487 void CodeGenModule::SetCommonAttributes(const Decl *D,
488 llvm::GlobalValue *GV) {
489 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
490 setGlobalVisibility(GV, ND);
492 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
494 if (D->hasAttr<UsedAttr>())
497 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
498 GV->setSection(SA->getName());
500 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
503 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
505 const CGFunctionInfo &FI) {
506 SetLLVMFunctionAttributes(D, FI, F);
507 SetLLVMFunctionAttributesForDefinition(D, F);
509 F->setLinkage(llvm::Function::InternalLinkage);
511 SetCommonAttributes(D, F);
514 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
516 bool IsIncompleteFunction) {
517 if (unsigned IID = F->getIntrinsicID()) {
518 // If this is an intrinsic function, set the function's attributes
519 // to the intrinsic's attributes.
520 F->setAttributes(llvm::Intrinsic::getAttributes((llvm::Intrinsic::ID)IID));
524 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
526 if (!IsIncompleteFunction)
527 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
529 // Only a few attributes are set on declarations; these may later be
530 // overridden by a definition.
532 if (FD->hasAttr<DLLImportAttr>()) {
533 F->setLinkage(llvm::Function::DLLImportLinkage);
534 } else if (FD->hasAttr<WeakAttr>() ||
535 FD->isWeakImported()) {
536 // "extern_weak" is overloaded in LLVM; we probably should have
537 // separate linkage types for this.
538 F->setLinkage(llvm::Function::ExternalWeakLinkage);
540 F->setLinkage(llvm::Function::ExternalLinkage);
542 NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
543 if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
544 F->setVisibility(GetLLVMVisibility(LV.visibility()));
548 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
549 F->setSection(SA->getName());
552 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
553 assert(!GV->isDeclaration() &&
554 "Only globals with definition can force usage.");
555 LLVMUsed.push_back(GV);
558 void CodeGenModule::EmitLLVMUsed() {
559 // Don't create llvm.used if there is no need.
560 if (LLVMUsed.empty())
563 const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
565 // Convert LLVMUsed to what ConstantArray needs.
566 std::vector<llvm::Constant*> UsedArray;
567 UsedArray.resize(LLVMUsed.size());
568 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
570 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
574 if (UsedArray.empty())
576 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
578 llvm::GlobalVariable *GV =
579 new llvm::GlobalVariable(getModule(), ATy, false,
580 llvm::GlobalValue::AppendingLinkage,
581 llvm::ConstantArray::get(ATy, UsedArray),
584 GV->setSection("llvm.metadata");
587 void CodeGenModule::EmitDeferred() {
588 // Emit code for any potentially referenced deferred decls. Since a
589 // previously unused static decl may become used during the generation of code
590 // for a static function, iterate until no changes are made.
592 while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
593 if (!DeferredVTables.empty()) {
594 const CXXRecordDecl *RD = DeferredVTables.back();
595 DeferredVTables.pop_back();
596 getVTables().GenerateClassData(getVTableLinkage(RD), RD);
600 GlobalDecl D = DeferredDeclsToEmit.back();
601 DeferredDeclsToEmit.pop_back();
603 // Check to see if we've already emitted this. This is necessary
604 // for a couple of reasons: first, decls can end up in the
605 // deferred-decls queue multiple times, and second, decls can end
606 // up with definitions in unusual ways (e.g. by an extern inline
607 // function acquiring a strong function redefinition). Just
608 // ignore these cases.
610 // TODO: That said, looking this up multiple times is very wasteful.
611 llvm::StringRef Name = getMangledName(D);
612 llvm::GlobalValue *CGRef = GetGlobalValue(Name);
613 assert(CGRef && "Deferred decl wasn't referenced?");
615 if (!CGRef->isDeclaration())
618 // GlobalAlias::isDeclaration() defers to the aliasee, but for our
619 // purposes an alias counts as a definition.
620 if (isa<llvm::GlobalAlias>(CGRef))
623 // Otherwise, emit the definition and move on to the next one.
624 EmitGlobalDefinition(D);
628 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
629 /// annotation information for a given GlobalValue. The annotation struct is
630 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
631 /// GlobalValue being annotated. The second field is the constant string
632 /// created from the AnnotateAttr's annotation. The third field is a constant
633 /// string containing the name of the translation unit. The fourth field is
634 /// the line number in the file of the annotated value declaration.
636 /// FIXME: this does not unique the annotation string constants, as llvm-gcc
639 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
640 const AnnotateAttr *AA,
642 llvm::Module *M = &getModule();
644 // get [N x i8] constants for the annotation string, and the filename string
645 // which are the 2nd and 3rd elements of the global annotation structure.
646 const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext);
647 llvm::Constant *anno = llvm::ConstantArray::get(VMContext,
648 AA->getAnnotation(), true);
649 llvm::Constant *unit = llvm::ConstantArray::get(VMContext,
650 M->getModuleIdentifier(),
653 // Get the two global values corresponding to the ConstantArrays we just
654 // created to hold the bytes of the strings.
655 llvm::GlobalValue *annoGV =
656 new llvm::GlobalVariable(*M, anno->getType(), false,
657 llvm::GlobalValue::PrivateLinkage, anno,
659 // translation unit name string, emitted into the llvm.metadata section.
660 llvm::GlobalValue *unitGV =
661 new llvm::GlobalVariable(*M, unit->getType(), false,
662 llvm::GlobalValue::PrivateLinkage, unit,
664 unitGV->setUnnamedAddr(true);
666 // Create the ConstantStruct for the global annotation.
667 llvm::Constant *Fields[4] = {
668 llvm::ConstantExpr::getBitCast(GV, SBP),
669 llvm::ConstantExpr::getBitCast(annoGV, SBP),
670 llvm::ConstantExpr::getBitCast(unitGV, SBP),
671 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo)
673 return llvm::ConstantStruct::get(VMContext, Fields, 4, false);
676 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
677 // Never defer when EmitAllDecls is specified.
678 if (Features.EmitAllDecls)
681 return !getContext().DeclMustBeEmitted(Global);
684 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
685 const AliasAttr *AA = VD->getAttr<AliasAttr>();
686 assert(AA && "No alias?");
688 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
690 // See if there is already something with the target's name in the module.
691 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
693 llvm::Constant *Aliasee;
694 if (isa<llvm::FunctionType>(DeclTy))
695 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
696 /*ForVTable=*/false);
698 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
699 llvm::PointerType::getUnqual(DeclTy), 0);
701 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
702 F->setLinkage(llvm::Function::ExternalWeakLinkage);
703 WeakRefReferences.insert(F);
709 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
710 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
712 // Weak references don't produce any output by themselves.
713 if (Global->hasAttr<WeakRefAttr>())
716 // If this is an alias definition (which otherwise looks like a declaration)
718 if (Global->hasAttr<AliasAttr>())
719 return EmitAliasDefinition(GD);
721 // Ignore declarations, they will be emitted on their first use.
722 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
723 if (FD->getIdentifier()) {
724 llvm::StringRef Name = FD->getName();
725 if (Name == "_Block_object_assign") {
726 BlockObjectAssignDecl = FD;
727 } else if (Name == "_Block_object_dispose") {
728 BlockObjectDisposeDecl = FD;
732 // Forward declarations are emitted lazily on first use.
733 if (!FD->doesThisDeclarationHaveABody())
736 const VarDecl *VD = cast<VarDecl>(Global);
737 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
739 if (VD->getIdentifier()) {
740 llvm::StringRef Name = VD->getName();
741 if (Name == "_NSConcreteGlobalBlock") {
742 NSConcreteGlobalBlockDecl = VD;
743 } else if (Name == "_NSConcreteStackBlock") {
744 NSConcreteStackBlockDecl = VD;
749 if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
753 // Defer code generation when possible if this is a static definition, inline
754 // function etc. These we only want to emit if they are used.
755 if (!MayDeferGeneration(Global)) {
756 // Emit the definition if it can't be deferred.
757 EmitGlobalDefinition(GD);
761 // If we're deferring emission of a C++ variable with an
762 // initializer, remember the order in which it appeared in the file.
763 if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) &&
764 cast<VarDecl>(Global)->hasInit()) {
765 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
766 CXXGlobalInits.push_back(0);
769 // If the value has already been used, add it directly to the
770 // DeferredDeclsToEmit list.
771 llvm::StringRef MangledName = getMangledName(GD);
772 if (GetGlobalValue(MangledName))
773 DeferredDeclsToEmit.push_back(GD);
775 // Otherwise, remember that we saw a deferred decl with this name. The
776 // first use of the mangled name will cause it to move into
777 // DeferredDeclsToEmit.
778 DeferredDecls[MangledName] = GD;
782 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
783 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
785 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
786 Context.getSourceManager(),
787 "Generating code for declaration");
789 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
790 // At -O0, don't generate IR for functions with available_externally
792 if (CodeGenOpts.OptimizationLevel == 0 &&
793 !Function->hasAttr<AlwaysInlineAttr>() &&
794 getFunctionLinkage(Function)
795 == llvm::Function::AvailableExternallyLinkage)
798 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
799 // Make sure to emit the definition(s) before we emit the thunks.
800 // This is necessary for the generation of certain thunks.
801 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
802 EmitCXXConstructor(CD, GD.getCtorType());
803 else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
804 EmitCXXDestructor(DD, GD.getDtorType());
806 EmitGlobalFunctionDefinition(GD);
808 if (Method->isVirtual())
809 getVTables().EmitThunks(GD);
814 return EmitGlobalFunctionDefinition(GD);
817 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
818 return EmitGlobalVarDefinition(VD);
820 assert(0 && "Invalid argument to EmitGlobalDefinition()");
823 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
824 /// module, create and return an llvm Function with the specified type. If there
825 /// is something in the module with the specified name, return it potentially
826 /// bitcasted to the right type.
828 /// If D is non-null, it specifies a decl that correspond to this. This is used
829 /// to set the attributes on the function when it is first created.
831 CodeGenModule::GetOrCreateLLVMFunction(llvm::StringRef MangledName,
832 const llvm::Type *Ty,
833 GlobalDecl D, bool ForVTable) {
834 // Lookup the entry, lazily creating it if necessary.
835 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
837 if (WeakRefReferences.count(Entry)) {
838 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
839 if (FD && !FD->hasAttr<WeakAttr>())
840 Entry->setLinkage(llvm::Function::ExternalLinkage);
842 WeakRefReferences.erase(Entry);
845 if (Entry->getType()->getElementType() == Ty)
848 // Make sure the result is of the correct type.
849 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
850 return llvm::ConstantExpr::getBitCast(Entry, PTy);
853 // This function doesn't have a complete type (for example, the return
854 // type is an incomplete struct). Use a fake type instead, and make
855 // sure not to try to set attributes.
856 bool IsIncompleteFunction = false;
858 const llvm::FunctionType *FTy;
859 if (isa<llvm::FunctionType>(Ty)) {
860 FTy = cast<llvm::FunctionType>(Ty);
862 FTy = llvm::FunctionType::get(VoidTy, false);
863 IsIncompleteFunction = true;
866 llvm::Function *F = llvm::Function::Create(FTy,
867 llvm::Function::ExternalLinkage,
868 MangledName, &getModule());
869 assert(F->getName() == MangledName && "name was uniqued!");
871 SetFunctionAttributes(D, F, IsIncompleteFunction);
873 // This is the first use or definition of a mangled name. If there is a
874 // deferred decl with this name, remember that we need to emit it at the end
876 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
877 if (DDI != DeferredDecls.end()) {
878 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
879 // list, and remove it from DeferredDecls (since we don't need it anymore).
880 DeferredDeclsToEmit.push_back(DDI->second);
881 DeferredDecls.erase(DDI);
883 // Otherwise, there are cases we have to worry about where we're
884 // using a declaration for which we must emit a definition but where
885 // we might not find a top-level definition:
886 // - member functions defined inline in their classes
887 // - friend functions defined inline in some class
888 // - special member functions with implicit definitions
889 // If we ever change our AST traversal to walk into class methods,
890 // this will be unnecessary.
892 // We also don't emit a definition for a function if it's going to be an entry
893 // in a vtable, unless it's already marked as used.
894 } else if (getLangOptions().CPlusPlus && D.getDecl()) {
895 // Look for a declaration that's lexically in a record.
896 const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
898 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
899 if (FD->isImplicit() && !ForVTable) {
900 assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
901 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
903 } else if (FD->doesThisDeclarationHaveABody()) {
904 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
908 FD = FD->getPreviousDeclaration();
912 // Make sure the result is of the requested type.
913 if (!IsIncompleteFunction) {
914 assert(F->getType()->getElementType() == Ty);
918 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
919 return llvm::ConstantExpr::getBitCast(F, PTy);
922 /// GetAddrOfFunction - Return the address of the given function. If Ty is
923 /// non-null, then this function will use the specified type if it has to
924 /// create it (this occurs when we see a definition of the function).
925 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
926 const llvm::Type *Ty,
928 // If there was no specific requested type, just convert it now.
930 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
932 llvm::StringRef MangledName = getMangledName(GD);
933 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
936 /// CreateRuntimeFunction - Create a new runtime function with the specified
939 CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
940 llvm::StringRef Name) {
941 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false);
944 static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D,
946 if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
949 if (Context.getLangOptions().CPlusPlus) {
950 if (const RecordType *Record
951 = Context.getBaseElementType(D->getType())->getAs<RecordType>())
952 return ConstantInit &&
953 cast<CXXRecordDecl>(Record->getDecl())->isPOD() &&
954 !cast<CXXRecordDecl>(Record->getDecl())->hasMutableFields();
960 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
961 /// create and return an llvm GlobalVariable with the specified type. If there
962 /// is something in the module with the specified name, return it potentially
963 /// bitcasted to the right type.
965 /// If D is non-null, it specifies a decl that correspond to this. This is used
966 /// to set the attributes on the global when it is first created.
968 CodeGenModule::GetOrCreateLLVMGlobal(llvm::StringRef MangledName,
969 const llvm::PointerType *Ty,
972 // Lookup the entry, lazily creating it if necessary.
973 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
975 if (WeakRefReferences.count(Entry)) {
976 if (D && !D->hasAttr<WeakAttr>())
977 Entry->setLinkage(llvm::Function::ExternalLinkage);
979 WeakRefReferences.erase(Entry);
983 Entry->setUnnamedAddr(true);
985 if (Entry->getType() == Ty)
988 // Make sure the result is of the correct type.
989 return llvm::ConstantExpr::getBitCast(Entry, Ty);
992 // This is the first use or definition of a mangled name. If there is a
993 // deferred decl with this name, remember that we need to emit it at the end
995 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
996 if (DDI != DeferredDecls.end()) {
997 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
998 // list, and remove it from DeferredDecls (since we don't need it anymore).
999 DeferredDeclsToEmit.push_back(DDI->second);
1000 DeferredDecls.erase(DDI);
1003 llvm::GlobalVariable *GV =
1004 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
1005 llvm::GlobalValue::ExternalLinkage,
1007 false, Ty->getAddressSpace());
1009 // Handle things which are present even on external declarations.
1011 // FIXME: This code is overly simple and should be merged with other global
1013 GV->setConstant(DeclIsConstantGlobal(Context, D, false));
1015 // Set linkage and visibility in case we never see a definition.
1016 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
1017 if (LV.linkage() != ExternalLinkage) {
1018 // Don't set internal linkage on declarations.
1020 if (D->hasAttr<DLLImportAttr>())
1021 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
1022 else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
1023 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1025 // Set visibility on a declaration only if it's explicit.
1026 if (LV.visibilityExplicit())
1027 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
1030 GV->setThreadLocal(D->isThreadSpecified());
1037 llvm::GlobalVariable *
1038 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(llvm::StringRef Name,
1039 const llvm::Type *Ty,
1040 llvm::GlobalValue::LinkageTypes Linkage) {
1041 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1042 llvm::GlobalVariable *OldGV = 0;
1046 // Check if the variable has the right type.
1047 if (GV->getType()->getElementType() == Ty)
1050 // Because C++ name mangling, the only way we can end up with an already
1051 // existing global with the same name is if it has been declared extern "C".
1052 assert(GV->isDeclaration() && "Declaration has wrong type!");
1056 // Create a new variable.
1057 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1061 // Replace occurrences of the old variable if needed.
1062 GV->takeName(OldGV);
1064 if (!OldGV->use_empty()) {
1065 llvm::Constant *NewPtrForOldDecl =
1066 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1067 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1070 OldGV->eraseFromParent();
1076 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1077 /// given global variable. If Ty is non-null and if the global doesn't exist,
1078 /// then it will be greated with the specified type instead of whatever the
1079 /// normal requested type would be.
1080 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1081 const llvm::Type *Ty) {
1082 assert(D->hasGlobalStorage() && "Not a global variable");
1083 QualType ASTTy = D->getType();
1085 Ty = getTypes().ConvertTypeForMem(ASTTy);
1087 const llvm::PointerType *PTy =
1088 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1090 llvm::StringRef MangledName = getMangledName(D);
1091 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
1094 /// CreateRuntimeVariable - Create a new runtime global variable with the
1095 /// specified type and name.
1097 CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
1098 llvm::StringRef Name) {
1099 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
1103 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1104 assert(!D->getInit() && "Cannot emit definite definitions here!");
1106 if (MayDeferGeneration(D)) {
1107 // If we have not seen a reference to this variable yet, place it
1108 // into the deferred declarations table to be emitted if needed
1110 llvm::StringRef MangledName = getMangledName(D);
1111 if (!GetGlobalValue(MangledName)) {
1112 DeferredDecls[MangledName] = D;
1117 // The tentative definition is the only definition.
1118 EmitGlobalVarDefinition(D);
1121 void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
1122 if (DefinitionRequired)
1123 getVTables().GenerateClassData(getVTableLinkage(Class), Class);
1126 llvm::GlobalVariable::LinkageTypes
1127 CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
1128 if (RD->getLinkage() != ExternalLinkage)
1129 return llvm::GlobalVariable::InternalLinkage;
1131 if (const CXXMethodDecl *KeyFunction
1132 = RD->getASTContext().getKeyFunction(RD)) {
1133 // If this class has a key function, use that to determine the linkage of
1135 const FunctionDecl *Def = 0;
1136 if (KeyFunction->hasBody(Def))
1137 KeyFunction = cast<CXXMethodDecl>(Def);
1139 switch (KeyFunction->getTemplateSpecializationKind()) {
1140 case TSK_Undeclared:
1141 case TSK_ExplicitSpecialization:
1142 // When compiling with optimizations turned on, we emit all vtables,
1143 // even if the key function is not defined in the current translation
1144 // unit. If this is the case, use available_externally linkage.
1145 if (!Def && CodeGenOpts.OptimizationLevel)
1146 return llvm::GlobalVariable::AvailableExternallyLinkage;
1148 if (KeyFunction->isInlined())
1149 return !Context.getLangOptions().AppleKext ?
1150 llvm::GlobalVariable::LinkOnceODRLinkage :
1151 llvm::Function::InternalLinkage;
1153 return llvm::GlobalVariable::ExternalLinkage;
1155 case TSK_ImplicitInstantiation:
1156 return !Context.getLangOptions().AppleKext ?
1157 llvm::GlobalVariable::LinkOnceODRLinkage :
1158 llvm::Function::InternalLinkage;
1160 case TSK_ExplicitInstantiationDefinition:
1161 return !Context.getLangOptions().AppleKext ?
1162 llvm::GlobalVariable::WeakODRLinkage :
1163 llvm::Function::InternalLinkage;
1165 case TSK_ExplicitInstantiationDeclaration:
1166 // FIXME: Use available_externally linkage. However, this currently
1167 // breaks LLVM's build due to undefined symbols.
1168 // return llvm::GlobalVariable::AvailableExternallyLinkage;
1169 return !Context.getLangOptions().AppleKext ?
1170 llvm::GlobalVariable::LinkOnceODRLinkage :
1171 llvm::Function::InternalLinkage;
1175 if (Context.getLangOptions().AppleKext)
1176 return llvm::Function::InternalLinkage;
1178 switch (RD->getTemplateSpecializationKind()) {
1179 case TSK_Undeclared:
1180 case TSK_ExplicitSpecialization:
1181 case TSK_ImplicitInstantiation:
1182 // FIXME: Use available_externally linkage. However, this currently
1183 // breaks LLVM's build due to undefined symbols.
1184 // return llvm::GlobalVariable::AvailableExternallyLinkage;
1185 case TSK_ExplicitInstantiationDeclaration:
1186 return llvm::GlobalVariable::LinkOnceODRLinkage;
1188 case TSK_ExplicitInstantiationDefinition:
1189 return llvm::GlobalVariable::WeakODRLinkage;
1192 // Silence GCC warning.
1193 return llvm::GlobalVariable::LinkOnceODRLinkage;
1196 CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const {
1197 return Context.toCharUnitsFromBits(
1198 TheTargetData.getTypeStoreSizeInBits(Ty));
1201 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1202 llvm::Constant *Init = 0;
1203 QualType ASTTy = D->getType();
1204 bool NonConstInit = false;
1206 const Expr *InitExpr = D->getAnyInitializer();
1209 // This is a tentative definition; tentative definitions are
1210 // implicitly initialized with { 0 }.
1212 // Note that tentative definitions are only emitted at the end of
1213 // a translation unit, so they should never have incomplete
1214 // type. In addition, EmitTentativeDefinition makes sure that we
1215 // never attempt to emit a tentative definition if a real one
1216 // exists. A use may still exists, however, so we still may need
1218 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1219 Init = EmitNullConstant(D->getType());
1221 Init = EmitConstantExpr(InitExpr, D->getType());
1223 QualType T = InitExpr->getType();
1224 if (D->getType()->isReferenceType())
1227 if (getLangOptions().CPlusPlus) {
1228 Init = EmitNullConstant(T);
1229 NonConstInit = true;
1231 ErrorUnsupported(D, "static initializer");
1232 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1235 // We don't need an initializer, so remove the entry for the delayed
1236 // initializer position (just in case this entry was delayed).
1237 if (getLangOptions().CPlusPlus)
1238 DelayedCXXInitPosition.erase(D);
1242 const llvm::Type* InitType = Init->getType();
1243 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1245 // Strip off a bitcast if we got one back.
1246 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1247 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1248 // all zero index gep.
1249 CE->getOpcode() == llvm::Instruction::GetElementPtr);
1250 Entry = CE->getOperand(0);
1253 // Entry is now either a Function or GlobalVariable.
1254 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1256 // We have a definition after a declaration with the wrong type.
1257 // We must make a new GlobalVariable* and update everything that used OldGV
1258 // (a declaration or tentative definition) with the new GlobalVariable*
1259 // (which will be a definition).
1261 // This happens if there is a prototype for a global (e.g.
1262 // "extern int x[];") and then a definition of a different type (e.g.
1263 // "int x[10];"). This also happens when an initializer has a different type
1264 // from the type of the global (this happens with unions).
1266 GV->getType()->getElementType() != InitType ||
1267 GV->getType()->getAddressSpace() !=
1268 getContext().getTargetAddressSpace(ASTTy)) {
1270 // Move the old entry aside so that we'll create a new one.
1271 Entry->setName(llvm::StringRef());
1273 // Make a new global with the correct type, this is now guaranteed to work.
1274 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
1276 // Replace all uses of the old global with the new global
1277 llvm::Constant *NewPtrForOldDecl =
1278 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1279 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1281 // Erase the old global, since it is no longer used.
1282 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1285 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
1286 SourceManager &SM = Context.getSourceManager();
1287 AddAnnotation(EmitAnnotateAttr(GV, AA,
1288 SM.getInstantiationLineNumber(D->getLocation())));
1291 GV->setInitializer(Init);
1293 // If it is safe to mark the global 'constant', do so now.
1294 GV->setConstant(false);
1295 if (!NonConstInit && DeclIsConstantGlobal(Context, D, true))
1296 GV->setConstant(true);
1298 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1300 // Set the llvm linkage type as appropriate.
1301 llvm::GlobalValue::LinkageTypes Linkage =
1302 GetLLVMLinkageVarDefinition(D, GV);
1303 GV->setLinkage(Linkage);
1304 if (Linkage == llvm::GlobalVariable::CommonLinkage)
1305 // common vars aren't constant even if declared const.
1306 GV->setConstant(false);
1308 SetCommonAttributes(D, GV);
1310 // Emit the initializer function if necessary.
1312 EmitCXXGlobalVarDeclInitFunc(D, GV);
1314 // Emit global variable debug information.
1315 if (CGDebugInfo *DI = getModuleDebugInfo()) {
1316 DI->setLocation(D->getLocation());
1317 DI->EmitGlobalVariable(GV, D);
1321 llvm::GlobalValue::LinkageTypes
1322 CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1323 llvm::GlobalVariable *GV) {
1324 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1325 if (Linkage == GVA_Internal)
1326 return llvm::Function::InternalLinkage;
1327 else if (D->hasAttr<DLLImportAttr>())
1328 return llvm::Function::DLLImportLinkage;
1329 else if (D->hasAttr<DLLExportAttr>())
1330 return llvm::Function::DLLExportLinkage;
1331 else if (D->hasAttr<WeakAttr>()) {
1332 if (GV->isConstant())
1333 return llvm::GlobalVariable::WeakODRLinkage;
1335 return llvm::GlobalVariable::WeakAnyLinkage;
1336 } else if (Linkage == GVA_TemplateInstantiation ||
1337 Linkage == GVA_ExplicitTemplateInstantiation)
1338 return llvm::GlobalVariable::WeakODRLinkage;
1339 else if (!getLangOptions().CPlusPlus &&
1340 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1341 D->getAttr<CommonAttr>()) &&
1342 !D->hasExternalStorage() && !D->getInit() &&
1343 !D->getAttr<SectionAttr>() && !D->isThreadSpecified()) {
1344 // Thread local vars aren't considered common linkage.
1345 return llvm::GlobalVariable::CommonLinkage;
1347 return llvm::GlobalVariable::ExternalLinkage;
1350 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1351 /// implement a function with no prototype, e.g. "int foo() {}". If there are
1352 /// existing call uses of the old function in the module, this adjusts them to
1353 /// call the new function directly.
1355 /// This is not just a cleanup: the always_inline pass requires direct calls to
1356 /// functions to be able to inline them. If there is a bitcast in the way, it
1357 /// won't inline them. Instcombine normally deletes these calls, but it isn't
1359 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1360 llvm::Function *NewFn) {
1361 // If we're redefining a global as a function, don't transform it.
1362 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1363 if (OldFn == 0) return;
1365 const llvm::Type *NewRetTy = NewFn->getReturnType();
1366 llvm::SmallVector<llvm::Value*, 4> ArgList;
1368 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
1370 // TODO: Do invokes ever occur in C code? If so, we should handle them too.
1371 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1372 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
1373 if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
1374 llvm::CallSite CS(CI);
1375 if (!CI || !CS.isCallee(I)) continue;
1377 // If the return types don't match exactly, and if the call isn't dead, then
1378 // we can't transform this call.
1379 if (CI->getType() != NewRetTy && !CI->use_empty())
1382 // If the function was passed too few arguments, don't transform. If extra
1383 // arguments were passed, we silently drop them. If any of the types
1384 // mismatch, we don't transform.
1386 bool DontTransform = false;
1387 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1388 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
1389 if (CS.arg_size() == ArgNo ||
1390 CS.getArgument(ArgNo)->getType() != AI->getType()) {
1391 DontTransform = true;
1398 // Okay, we can transform this. Create the new call instruction and copy
1399 // over the required information.
1400 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
1401 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
1402 ArgList.end(), "", CI);
1404 if (!NewCall->getType()->isVoidTy())
1405 NewCall->takeName(CI);
1406 NewCall->setAttributes(CI->getAttributes());
1407 NewCall->setCallingConv(CI->getCallingConv());
1409 // Finally, remove the old call, replacing any uses with the new one.
1410 if (!CI->use_empty())
1411 CI->replaceAllUsesWith(NewCall);
1413 // Copy debug location attached to CI.
1414 if (!CI->getDebugLoc().isUnknown())
1415 NewCall->setDebugLoc(CI->getDebugLoc());
1416 CI->eraseFromParent();
1421 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
1422 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
1424 // Compute the function info and LLVM type.
1425 const CGFunctionInfo &FI = getTypes().getFunctionInfo(GD);
1426 bool variadic = false;
1427 if (const FunctionProtoType *fpt = D->getType()->getAs<FunctionProtoType>())
1428 variadic = fpt->isVariadic();
1429 const llvm::FunctionType *Ty = getTypes().GetFunctionType(FI, variadic, false);
1431 // Get or create the prototype for the function.
1432 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
1434 // Strip off a bitcast if we got one back.
1435 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1436 assert(CE->getOpcode() == llvm::Instruction::BitCast);
1437 Entry = CE->getOperand(0);
1441 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
1442 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
1444 // If the types mismatch then we have to rewrite the definition.
1445 assert(OldFn->isDeclaration() &&
1446 "Shouldn't replace non-declaration");
1448 // F is the Function* for the one with the wrong type, we must make a new
1449 // Function* and update everything that used F (a declaration) with the new
1450 // Function* (which will be a definition).
1452 // This happens if there is a prototype for a function
1453 // (e.g. "int f()") and then a definition of a different type
1454 // (e.g. "int f(int x)"). Move the old function aside so that it
1455 // doesn't interfere with GetAddrOfFunction.
1456 OldFn->setName(llvm::StringRef());
1457 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
1459 // If this is an implementation of a function without a prototype, try to
1460 // replace any existing uses of the function (which may be calls) with uses
1461 // of the new function
1462 if (D->getType()->isFunctionNoProtoType()) {
1463 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
1464 OldFn->removeDeadConstantUsers();
1467 // Replace uses of F with the Function we will endow with a body.
1468 if (!Entry->use_empty()) {
1469 llvm::Constant *NewPtrForOldDecl =
1470 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
1471 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1474 // Ok, delete the old function now, which is dead.
1475 OldFn->eraseFromParent();
1480 // We need to set linkage and visibility on the function before
1481 // generating code for it because various parts of IR generation
1482 // want to propagate this information down (e.g. to local static
1484 llvm::Function *Fn = cast<llvm::Function>(Entry);
1485 setFunctionLinkage(D, Fn);
1487 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
1488 setGlobalVisibility(Fn, D);
1490 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
1492 SetFunctionDefinitionAttributes(D, Fn);
1493 SetLLVMFunctionAttributesForDefinition(D, Fn);
1495 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
1496 AddGlobalCtor(Fn, CA->getPriority());
1497 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
1498 AddGlobalDtor(Fn, DA->getPriority());
1501 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1502 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
1503 const AliasAttr *AA = D->getAttr<AliasAttr>();
1504 assert(AA && "Not an alias?");
1506 llvm::StringRef MangledName = getMangledName(GD);
1508 // If there is a definition in the module, then it wins over the alias.
1509 // This is dubious, but allow it to be safe. Just ignore the alias.
1510 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1511 if (Entry && !Entry->isDeclaration())
1514 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1516 // Create a reference to the named value. This ensures that it is emitted
1517 // if a deferred decl.
1518 llvm::Constant *Aliasee;
1519 if (isa<llvm::FunctionType>(DeclTy))
1520 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
1521 /*ForVTable=*/false);
1523 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1524 llvm::PointerType::getUnqual(DeclTy), 0);
1526 // Create the new alias itself, but don't set a name yet.
1527 llvm::GlobalValue *GA =
1528 new llvm::GlobalAlias(Aliasee->getType(),
1529 llvm::Function::ExternalLinkage,
1530 "", Aliasee, &getModule());
1533 assert(Entry->isDeclaration());
1535 // If there is a declaration in the module, then we had an extern followed
1536 // by the alias, as in:
1537 // extern int test6();
1539 // int test6() __attribute__((alias("test7")));
1541 // Remove it and replace uses of it with the alias.
1542 GA->takeName(Entry);
1544 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
1546 Entry->eraseFromParent();
1548 GA->setName(MangledName);
1551 // Set attributes which are particular to an alias; this is a
1552 // specialization of the attributes which may be set on a global
1553 // variable/function.
1554 if (D->hasAttr<DLLExportAttr>()) {
1555 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1556 // The dllexport attribute is ignored for undefined symbols.
1558 GA->setLinkage(llvm::Function::DLLExportLinkage);
1560 GA->setLinkage(llvm::Function::DLLExportLinkage);
1562 } else if (D->hasAttr<WeakAttr>() ||
1563 D->hasAttr<WeakRefAttr>() ||
1564 D->isWeakImported()) {
1565 GA->setLinkage(llvm::Function::WeakAnyLinkage);
1568 SetCommonAttributes(D, GA);
1571 /// getBuiltinLibFunction - Given a builtin id for a function like
1572 /// "__builtin_fabsf", return a Function* for "fabsf".
1573 llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
1574 unsigned BuiltinID) {
1575 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
1576 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
1579 // Get the name, skip over the __builtin_ prefix (if necessary).
1580 llvm::StringRef Name;
1583 // If the builtin has been declared explicitly with an assembler label,
1584 // use the mangled name. This differs from the plain label on platforms
1585 // that prefix labels.
1586 if (FD->hasAttr<AsmLabelAttr>())
1587 Name = getMangledName(D);
1588 else if (Context.BuiltinInfo.isLibFunction(BuiltinID))
1589 Name = Context.BuiltinInfo.GetName(BuiltinID) + 10;
1591 Name = Context.BuiltinInfo.GetName(BuiltinID);
1594 const llvm::FunctionType *Ty =
1595 cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
1597 return GetOrCreateLLVMFunction(Name, Ty, D, /*ForVTable=*/false);
1600 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
1602 return llvm::Intrinsic::getDeclaration(&getModule(),
1603 (llvm::Intrinsic::ID)IID, Tys, NumTys);
1606 static llvm::StringMapEntry<llvm::Constant*> &
1607 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1608 const StringLiteral *Literal,
1611 unsigned &StringLength) {
1612 llvm::StringRef String = Literal->getString();
1613 unsigned NumBytes = String.size();
1615 // Check for simple case.
1616 if (!Literal->containsNonAsciiOrNull()) {
1617 StringLength = NumBytes;
1618 return Map.GetOrCreateValue(String);
1621 // Otherwise, convert the UTF8 literals into a byte string.
1622 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
1623 const UTF8 *FromPtr = (UTF8 *)String.data();
1624 UTF16 *ToPtr = &ToBuf[0];
1626 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1627 &ToPtr, ToPtr + NumBytes,
1630 // ConvertUTF8toUTF16 returns the length in ToPtr.
1631 StringLength = ToPtr - &ToBuf[0];
1633 // Render the UTF-16 string into a byte array and convert to the target byte
1636 // FIXME: This isn't something we should need to do here.
1637 llvm::SmallString<128> AsBytes;
1638 AsBytes.reserve(StringLength * 2);
1639 for (unsigned i = 0; i != StringLength; ++i) {
1640 unsigned short Val = ToBuf[i];
1642 AsBytes.push_back(Val & 0xFF);
1643 AsBytes.push_back(Val >> 8);
1645 AsBytes.push_back(Val >> 8);
1646 AsBytes.push_back(Val & 0xFF);
1649 // Append one extra null character, the second is automatically added by our
1651 AsBytes.push_back(0);
1654 return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size()));
1657 static llvm::StringMapEntry<llvm::Constant*> &
1658 GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1659 const StringLiteral *Literal,
1660 unsigned &StringLength)
1662 llvm::StringRef String = Literal->getString();
1663 StringLength = String.size();
1664 return Map.GetOrCreateValue(String);
1668 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1669 unsigned StringLength = 0;
1670 bool isUTF16 = false;
1671 llvm::StringMapEntry<llvm::Constant*> &Entry =
1672 GetConstantCFStringEntry(CFConstantStringMap, Literal,
1673 getTargetData().isLittleEndian(),
1674 isUTF16, StringLength);
1676 if (llvm::Constant *C = Entry.getValue())
1679 llvm::Constant *Zero =
1680 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1681 llvm::Constant *Zeros[] = { Zero, Zero };
1683 // If we don't already have it, get __CFConstantStringClassReference.
1684 if (!CFConstantStringClassRef) {
1685 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1686 Ty = llvm::ArrayType::get(Ty, 0);
1687 llvm::Constant *GV = CreateRuntimeVariable(Ty,
1688 "__CFConstantStringClassReference");
1689 // Decay array -> ptr
1690 CFConstantStringClassRef =
1691 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1694 QualType CFTy = getContext().getCFConstantStringType();
1696 const llvm::StructType *STy =
1697 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1699 std::vector<llvm::Constant*> Fields(4);
1702 Fields[0] = CFConstantStringClassRef;
1705 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1706 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
1707 llvm::ConstantInt::get(Ty, 0x07C8);
1710 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1712 llvm::GlobalValue::LinkageTypes Linkage;
1715 // FIXME: why do utf strings get "_" labels instead of "L" labels?
1716 Linkage = llvm::GlobalValue::InternalLinkage;
1717 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1718 // does make plain ascii ones writable.
1721 // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
1722 // when using private linkage. It is not clear if this is a bug in ld
1723 // or a reasonable new restriction.
1724 Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
1725 isConstant = !Features.WritableStrings;
1728 llvm::GlobalVariable *GV =
1729 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1731 GV->setUnnamedAddr(true);
1733 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1734 GV->setAlignment(Align.getQuantity());
1736 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
1737 GV->setAlignment(Align.getQuantity());
1739 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1742 Ty = getTypes().ConvertType(getContext().LongTy);
1743 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
1746 C = llvm::ConstantStruct::get(STy, Fields);
1747 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1748 llvm::GlobalVariable::PrivateLinkage, C,
1749 "_unnamed_cfstring_");
1750 if (const char *Sect = getContext().Target.getCFStringSection())
1751 GV->setSection(Sect);
1758 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
1759 unsigned StringLength = 0;
1760 llvm::StringMapEntry<llvm::Constant*> &Entry =
1761 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
1763 if (llvm::Constant *C = Entry.getValue())
1766 llvm::Constant *Zero =
1767 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1768 llvm::Constant *Zeros[] = { Zero, Zero };
1770 // If we don't already have it, get _NSConstantStringClassReference.
1771 if (!ConstantStringClassRef) {
1772 std::string StringClass(getLangOptions().ObjCConstantStringClass);
1773 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1775 if (Features.ObjCNonFragileABI) {
1777 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
1778 : "OBJC_CLASS_$_" + StringClass;
1779 GV = getObjCRuntime().GetClassGlobal(str);
1780 // Make sure the result is of the correct type.
1781 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1782 ConstantStringClassRef =
1783 llvm::ConstantExpr::getBitCast(GV, PTy);
1786 StringClass.empty() ? "_NSConstantStringClassReference"
1787 : "_" + StringClass + "ClassReference";
1788 const llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
1789 GV = CreateRuntimeVariable(PTy, str);
1790 // Decay array -> ptr
1791 ConstantStringClassRef =
1792 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1796 QualType NSTy = getContext().getNSConstantStringType();
1798 const llvm::StructType *STy =
1799 cast<llvm::StructType>(getTypes().ConvertType(NSTy));
1801 std::vector<llvm::Constant*> Fields(3);
1804 Fields[0] = ConstantStringClassRef;
1807 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1809 llvm::GlobalValue::LinkageTypes Linkage;
1811 Linkage = llvm::GlobalValue::PrivateLinkage;
1812 isConstant = !Features.WritableStrings;
1814 llvm::GlobalVariable *GV =
1815 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1817 GV->setUnnamedAddr(true);
1818 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
1819 GV->setAlignment(Align.getQuantity());
1820 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1823 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1824 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
1827 C = llvm::ConstantStruct::get(STy, Fields);
1828 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1829 llvm::GlobalVariable::PrivateLinkage, C,
1830 "_unnamed_nsstring_");
1831 // FIXME. Fix section.
1832 if (const char *Sect =
1833 Features.ObjCNonFragileABI
1834 ? getContext().Target.getNSStringNonFragileABISection()
1835 : getContext().Target.getNSStringSection())
1836 GV->setSection(Sect);
1842 /// GetStringForStringLiteral - Return the appropriate bytes for a
1843 /// string literal, properly padded to match the literal type.
1844 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
1845 const ASTContext &Context = getContext();
1846 const ConstantArrayType *CAT =
1847 Context.getAsConstantArrayType(E->getType());
1848 assert(CAT && "String isn't pointer or array!");
1850 // Resize the string to the right size.
1851 uint64_t RealLen = CAT->getSize().getZExtValue();
1854 RealLen *= Context.Target.getWCharWidth() / Context.getCharWidth();
1856 std::string Str = E->getString().str();
1857 Str.resize(RealLen, '\0');
1862 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1863 /// constant array for the given string literal.
1865 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1866 // FIXME: This can be more efficient.
1867 // FIXME: We shouldn't need to bitcast the constant in the wide string case.
1868 llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S));
1870 llvm::Type *DestTy =
1871 llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
1872 C = llvm::ConstantExpr::getBitCast(C, DestTy);
1877 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1878 /// array for the given ObjCEncodeExpr node.
1880 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1882 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1884 return GetAddrOfConstantCString(Str);
1888 /// GenerateWritableString -- Creates storage for a string literal.
1889 static llvm::Constant *GenerateStringLiteral(llvm::StringRef str,
1892 const char *GlobalName) {
1893 // Create Constant for this string literal. Don't add a '\0'.
1895 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
1897 // Create a global variable for this string
1898 llvm::GlobalVariable *GV =
1899 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
1900 llvm::GlobalValue::PrivateLinkage,
1902 GV->setAlignment(1);
1903 GV->setUnnamedAddr(true);
1907 /// GetAddrOfConstantString - Returns a pointer to a character array
1908 /// containing the literal. This contents are exactly that of the
1909 /// given string, i.e. it will not be null terminated automatically;
1910 /// see GetAddrOfConstantCString. Note that whether the result is
1911 /// actually a pointer to an LLVM constant depends on
1912 /// Feature.WriteableStrings.
1914 /// The result has pointer to array type.
1915 llvm::Constant *CodeGenModule::GetAddrOfConstantString(llvm::StringRef Str,
1916 const char *GlobalName) {
1917 bool IsConstant = !Features.WritableStrings;
1919 // Get the default prefix if a name wasn't specified.
1921 GlobalName = ".str";
1923 // Don't share any string literals if strings aren't constant.
1925 return GenerateStringLiteral(Str, false, *this, GlobalName);
1927 llvm::StringMapEntry<llvm::Constant *> &Entry =
1928 ConstantStringMap.GetOrCreateValue(Str);
1930 if (Entry.getValue())
1931 return Entry.getValue();
1933 // Create a global variable for this.
1934 llvm::Constant *C = GenerateStringLiteral(Str, true, *this, GlobalName);
1939 /// GetAddrOfConstantCString - Returns a pointer to a character
1940 /// array containing the literal and a terminating '\0'
1941 /// character. The result has pointer to array type.
1942 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
1943 const char *GlobalName){
1944 llvm::StringRef StrWithNull(Str.c_str(), Str.size() + 1);
1945 return GetAddrOfConstantString(StrWithNull, GlobalName);
1948 /// EmitObjCPropertyImplementations - Emit information for synthesized
1949 /// properties for an implementation.
1950 void CodeGenModule::EmitObjCPropertyImplementations(const
1951 ObjCImplementationDecl *D) {
1952 for (ObjCImplementationDecl::propimpl_iterator
1953 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
1954 ObjCPropertyImplDecl *PID = *i;
1956 // Dynamic is just for type-checking.
1957 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1958 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1960 // Determine which methods need to be implemented, some may have
1961 // been overridden. Note that ::isSynthesized is not the method
1962 // we want, that just indicates if the decl came from a
1963 // property. What we want to know is if the method is defined in
1964 // this implementation.
1965 if (!D->getInstanceMethod(PD->getGetterName()))
1966 CodeGenFunction(*this).GenerateObjCGetter(
1967 const_cast<ObjCImplementationDecl *>(D), PID);
1968 if (!PD->isReadOnly() &&
1969 !D->getInstanceMethod(PD->getSetterName()))
1970 CodeGenFunction(*this).GenerateObjCSetter(
1971 const_cast<ObjCImplementationDecl *>(D), PID);
1976 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
1977 ObjCInterfaceDecl *iface
1978 = const_cast<ObjCInterfaceDecl*>(impl->getClassInterface());
1979 for (ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
1980 ivar; ivar = ivar->getNextIvar())
1981 if (ivar->getType().isDestructedType())
1987 /// EmitObjCIvarInitializations - Emit information for ivar initialization
1988 /// for an implementation.
1989 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
1990 // We might need a .cxx_destruct even if we don't have any ivar initializers.
1991 if (needsDestructMethod(D)) {
1992 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
1993 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
1994 ObjCMethodDecl *DTORMethod =
1995 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
1996 cxxSelector, getContext().VoidTy, 0, D, true,
1997 false, true, false, ObjCMethodDecl::Required);
1998 D->addInstanceMethod(DTORMethod);
1999 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
2002 // If the implementation doesn't have any ivar initializers, we don't need
2003 // a .cxx_construct.
2004 if (D->getNumIvarInitializers() == 0)
2007 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2008 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2009 // The constructor returns 'self'.
2010 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2012 D->getLocation(), cxxSelector,
2013 getContext().getObjCIdType(), 0,
2014 D, true, false, true, false,
2015 ObjCMethodDecl::Required);
2016 D->addInstanceMethod(CTORMethod);
2017 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
2020 /// EmitNamespace - Emit all declarations in a namespace.
2021 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
2022 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
2024 EmitTopLevelDecl(*I);
2027 // EmitLinkageSpec - Emit all declarations in a linkage spec.
2028 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
2029 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2030 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
2031 ErrorUnsupported(LSD, "linkage spec");
2035 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
2037 EmitTopLevelDecl(*I);
2040 /// EmitTopLevelDecl - Emit code for a single top level declaration.
2041 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
2042 // If an error has occurred, stop code generation, but continue
2043 // parsing and semantic analysis (to ensure all warnings and errors
2045 if (Diags.hasErrorOccurred())
2048 // Ignore dependent declarations.
2049 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2052 switch (D->getKind()) {
2053 case Decl::CXXConversion:
2054 case Decl::CXXMethod:
2055 case Decl::Function:
2056 // Skip function templates
2057 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2058 cast<FunctionDecl>(D)->isLateTemplateParsed())
2061 EmitGlobal(cast<FunctionDecl>(D));
2065 EmitGlobal(cast<VarDecl>(D));
2068 // Indirect fields from global anonymous structs and unions can be
2069 // ignored; only the actual variable requires IR gen support.
2070 case Decl::IndirectField:
2074 case Decl::Namespace:
2075 EmitNamespace(cast<NamespaceDecl>(D));
2077 // No code generation needed.
2078 case Decl::UsingShadow:
2080 case Decl::UsingDirective:
2081 case Decl::ClassTemplate:
2082 case Decl::FunctionTemplate:
2083 case Decl::TypeAliasTemplate:
2084 case Decl::NamespaceAlias:
2087 case Decl::CXXConstructor:
2088 // Skip function templates
2089 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2090 cast<FunctionDecl>(D)->isLateTemplateParsed())
2093 EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2095 case Decl::CXXDestructor:
2096 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
2098 EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2101 case Decl::StaticAssert:
2105 // Objective-C Decls
2107 // Forward declarations, no (immediate) code generation.
2108 case Decl::ObjCClass:
2109 case Decl::ObjCForwardProtocol:
2110 case Decl::ObjCInterface:
2113 case Decl::ObjCCategory: {
2114 ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
2115 if (CD->IsClassExtension() && CD->hasSynthBitfield())
2116 Context.ResetObjCLayout(CD->getClassInterface());
2120 case Decl::ObjCProtocol:
2121 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
2124 case Decl::ObjCCategoryImpl:
2125 // Categories have properties but don't support synthesize so we
2126 // can ignore them here.
2127 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2130 case Decl::ObjCImplementation: {
2131 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2132 if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
2133 Context.ResetObjCLayout(OMD->getClassInterface());
2134 EmitObjCPropertyImplementations(OMD);
2135 EmitObjCIvarInitializations(OMD);
2136 Runtime->GenerateClass(OMD);
2139 case Decl::ObjCMethod: {
2140 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2141 // If this is not a prototype, emit the body.
2143 CodeGenFunction(*this).GenerateObjCMethod(OMD);
2146 case Decl::ObjCCompatibleAlias:
2147 // compatibility-alias is a directive and has no code gen.
2150 case Decl::LinkageSpec:
2151 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
2154 case Decl::FileScopeAsm: {
2155 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
2156 llvm::StringRef AsmString = AD->getAsmString()->getString();
2158 const std::string &S = getModule().getModuleInlineAsm();
2160 getModule().setModuleInlineAsm(AsmString);
2162 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
2167 // Make sure we handled everything we should, every other kind is a
2168 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
2169 // function. Need to recode Decl::Kind to do that easily.
2170 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2174 /// Turns the given pointer into a constant.
2175 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2177 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2178 const llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2179 return llvm::ConstantInt::get(i64, PtrInt);
2182 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2183 llvm::NamedMDNode *&GlobalMetadata,
2185 llvm::GlobalValue *Addr) {
2186 if (!GlobalMetadata)
2188 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2190 // TODO: should we report variant information for ctors/dtors?
2191 llvm::Value *Ops[] = {
2193 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2195 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2198 /// Emits metadata nodes associating all the global values in the
2199 /// current module with the Decls they came from. This is useful for
2200 /// projects using IR gen as a subroutine.
2202 /// Since there's currently no way to associate an MDNode directly
2203 /// with an llvm::GlobalValue, we create a global named metadata
2204 /// with the name 'clang.global.decl.ptrs'.
2205 void CodeGenModule::EmitDeclMetadata() {
2206 llvm::NamedMDNode *GlobalMetadata = 0;
2208 // StaticLocalDeclMap
2209 for (llvm::DenseMap<GlobalDecl,llvm::StringRef>::iterator
2210 I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2212 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2213 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2217 /// Emits metadata nodes for all the local variables in the current
2219 void CodeGenFunction::EmitDeclMetadata() {
2220 if (LocalDeclMap.empty()) return;
2222 llvm::LLVMContext &Context = getLLVMContext();
2224 // Find the unique metadata ID for this name.
2225 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2227 llvm::NamedMDNode *GlobalMetadata = 0;
2229 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2230 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2231 const Decl *D = I->first;
2232 llvm::Value *Addr = I->second;
2234 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2235 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
2236 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
2237 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2238 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2239 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2244 void CodeGenModule::EmitCoverageFile() {
2245 if (!getCodeGenOpts().CoverageFile.empty()) {
2246 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
2247 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
2248 llvm::LLVMContext &Ctx = TheModule.getContext();
2249 llvm::MDString *CoverageFile =
2250 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
2251 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
2252 llvm::MDNode *CU = CUNode->getOperand(i);
2253 llvm::Value *node[] = { CoverageFile, CU };
2254 llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
2255 GCov->addOperand(N);
2261 ///@name Custom Runtime Function Interfaces
2264 // FIXME: These can be eliminated once we can have clients just get the required
2265 // AST nodes from the builtin tables.
2267 llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2268 if (BlockObjectDispose)
2269 return BlockObjectDispose;
2271 // If we saw an explicit decl, use that.
2272 if (BlockObjectDisposeDecl) {
2273 return BlockObjectDispose = GetAddrOfFunction(
2274 BlockObjectDisposeDecl,
2275 getTypes().GetFunctionType(BlockObjectDisposeDecl));
2278 // Otherwise construct the function by hand.
2279 const llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2280 const llvm::FunctionType *fty
2281 = llvm::FunctionType::get(VoidTy, args, false);
2282 return BlockObjectDispose =
2283 CreateRuntimeFunction(fty, "_Block_object_dispose");
2286 llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2287 if (BlockObjectAssign)
2288 return BlockObjectAssign;
2290 // If we saw an explicit decl, use that.
2291 if (BlockObjectAssignDecl) {
2292 return BlockObjectAssign = GetAddrOfFunction(
2293 BlockObjectAssignDecl,
2294 getTypes().GetFunctionType(BlockObjectAssignDecl));
2297 // Otherwise construct the function by hand.
2298 const llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2299 const llvm::FunctionType *fty
2300 = llvm::FunctionType::get(VoidTy, args, false);
2301 return BlockObjectAssign =
2302 CreateRuntimeFunction(fty, "_Block_object_assign");
2305 llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2306 if (NSConcreteGlobalBlock)
2307 return NSConcreteGlobalBlock;
2309 // If we saw an explicit decl, use that.
2310 if (NSConcreteGlobalBlockDecl) {
2311 return NSConcreteGlobalBlock = GetAddrOfGlobalVar(
2312 NSConcreteGlobalBlockDecl,
2313 getTypes().ConvertType(NSConcreteGlobalBlockDecl->getType()));
2316 // Otherwise construct the variable by hand.
2317 return NSConcreteGlobalBlock =
2318 CreateRuntimeVariable(Int8PtrTy, "_NSConcreteGlobalBlock");
2321 llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2322 if (NSConcreteStackBlock)
2323 return NSConcreteStackBlock;
2325 // If we saw an explicit decl, use that.
2326 if (NSConcreteStackBlockDecl) {
2327 return NSConcreteStackBlock = GetAddrOfGlobalVar(
2328 NSConcreteStackBlockDecl,
2329 getTypes().ConvertType(NSConcreteStackBlockDecl->getType()));
2332 // Otherwise construct the variable by hand.
2333 return NSConcreteStackBlock =
2334 CreateRuntimeVariable(Int8PtrTy, "_NSConcreteStackBlock");