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),
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) {
77 else if (!Features.NeXTRuntime)
78 Runtime = CreateGNUObjCRuntime(*this);
79 else if (Features.ObjCNonFragileABI)
80 Runtime = CreateMacNonFragileABIObjCRuntime(*this);
82 Runtime = CreateMacObjCRuntime(*this);
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 generation is enabled, create the CGDebugInfo object.
90 DebugInfo = CodeGenOpts.DebugInfo ? new CGDebugInfo(*this) : 0;
92 Block.GlobalUniqueCount = 0;
94 // Initialize the type cache.
95 llvm::LLVMContext &LLVMContext = M.getContext();
96 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
97 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
98 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
99 PointerWidthInBits = C.Target.getPointerWidth(0);
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);
116 else if (Features.ObjCNonFragileABI)
117 Runtime = CreateMacNonFragileABIObjCRuntime(*this);
119 Runtime = CreateMacObjCRuntime(*this);
122 void CodeGenModule::Release() {
124 EmitCXXGlobalInitFunc();
125 EmitCXXGlobalDtorFunc();
127 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
128 AddGlobalCtor(ObjCInitFunction);
129 EmitCtorList(GlobalCtors, "llvm.global_ctors");
130 EmitCtorList(GlobalDtors, "llvm.global_dtors");
134 SimplifyPersonality();
136 if (getCodeGenOpts().EmitDeclMetadata)
140 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
143 return TBAA->getTBAAInfo(QTy);
146 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
147 llvm::MDNode *TBAAInfo) {
148 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
151 bool CodeGenModule::isTargetDarwin() const {
152 return getContext().Target.getTriple().getOS() == llvm::Triple::Darwin;
155 /// ErrorUnsupported - Print out an error that codegen doesn't support the
156 /// specified stmt yet.
157 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
159 if (OmitOnError && getDiags().hasErrorOccurred())
161 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
162 "cannot compile this %0 yet");
163 std::string Msg = Type;
164 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
165 << Msg << S->getSourceRange();
168 /// ErrorUnsupported - Print out an error that codegen doesn't support the
169 /// specified decl yet.
170 void CodeGenModule::ErrorUnsupported(const Decl *D, 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(D->getLocation()), DiagID) << Msg;
180 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
181 const NamedDecl *D) const {
182 // Internal definitions always have default visibility.
183 if (GV->hasLocalLinkage()) {
184 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
188 // Set visibility for definitions.
189 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
190 if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
191 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
194 /// Set the symbol visibility of type information (vtable and RTTI)
195 /// associated with the given type.
196 void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
197 const CXXRecordDecl *RD,
198 TypeVisibilityKind TVK) const {
199 setGlobalVisibility(GV, RD);
201 if (!CodeGenOpts.HiddenWeakVTables)
204 // We never want to drop the visibility for RTTI names.
205 if (TVK == TVK_ForRTTIName)
208 // We want to drop the visibility to hidden for weak type symbols.
209 // This isn't possible if there might be unresolved references
210 // elsewhere that rely on this symbol being visible.
212 // This should be kept roughly in sync with setThunkVisibility
216 if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
217 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
220 // Don't override an explicit visibility attribute.
221 if (RD->hasAttr<VisibilityAttr>())
224 switch (RD->getTemplateSpecializationKind()) {
225 // We have to disable the optimization if this is an EI definition
226 // because there might be EI declarations in other shared objects.
227 case TSK_ExplicitInstantiationDefinition:
228 case TSK_ExplicitInstantiationDeclaration:
231 // Every use of a non-template class's type information has to emit it.
235 // In theory, implicit instantiations can ignore the possibility of
236 // an explicit instantiation declaration because there necessarily
237 // must be an EI definition somewhere with default visibility. In
238 // practice, it's possible to have an explicit instantiation for
239 // an arbitrary template class, and linkers aren't necessarily able
240 // to deal with mixed-visibility symbols.
241 case TSK_ExplicitSpecialization:
242 case TSK_ImplicitInstantiation:
243 if (!CodeGenOpts.HiddenWeakTemplateVTables)
248 // If there's a key function, there may be translation units
249 // that don't have the key function's definition. But ignore
250 // this if we're emitting RTTI under -fno-rtti.
251 if (!(TVK != TVK_ForRTTI) || Features.RTTI) {
252 if (Context.getKeyFunction(RD))
256 // Otherwise, drop the visibility to hidden.
257 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
258 GV->setUnnamedAddr(true);
261 llvm::StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
262 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
264 llvm::StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
268 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
269 IdentifierInfo *II = ND->getIdentifier();
270 assert(II && "Attempt to mangle unnamed decl.");
276 llvm::SmallString<256> Buffer;
277 llvm::raw_svector_ostream Out(Buffer);
278 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
279 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
280 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
281 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
282 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
283 getCXXABI().getMangleContext().mangleBlock(BD, Out);
285 getCXXABI().getMangleContext().mangleName(ND, Out);
287 // Allocate space for the mangled name.
289 size_t Length = Buffer.size();
290 char *Name = MangledNamesAllocator.Allocate<char>(Length);
291 std::copy(Buffer.begin(), Buffer.end(), Name);
293 Str = llvm::StringRef(Name, Length);
298 void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
299 const BlockDecl *BD) {
300 MangleContext &MangleCtx = getCXXABI().getMangleContext();
301 const Decl *D = GD.getDecl();
302 llvm::raw_svector_ostream Out(Buffer.getBuffer());
304 MangleCtx.mangleGlobalBlock(BD, Out);
305 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
306 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
307 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
308 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
310 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
313 llvm::GlobalValue *CodeGenModule::GetGlobalValue(llvm::StringRef Name) {
314 return getModule().getNamedValue(Name);
317 /// AddGlobalCtor - Add a function to the list that will be called before
319 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
320 // FIXME: Type coercion of void()* types.
321 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
324 /// AddGlobalDtor - Add a function to the list that will be called
325 /// when the module is unloaded.
326 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
327 // FIXME: Type coercion of void()* types.
328 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
331 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
332 // Ctor function type is void()*.
333 llvm::FunctionType* CtorFTy =
334 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false);
335 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
337 // Get the type of a ctor entry, { i32, void ()* }.
338 llvm::StructType* CtorStructTy =
339 llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext),
340 llvm::PointerType::getUnqual(CtorFTy), NULL);
342 // Construct the constructor and destructor arrays.
343 std::vector<llvm::Constant*> Ctors;
344 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
345 std::vector<llvm::Constant*> S;
346 S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
348 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
349 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
352 if (!Ctors.empty()) {
353 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
354 new llvm::GlobalVariable(TheModule, AT, false,
355 llvm::GlobalValue::AppendingLinkage,
356 llvm::ConstantArray::get(AT, Ctors),
361 void CodeGenModule::EmitAnnotations() {
362 if (Annotations.empty())
365 // Create a new global variable for the ConstantStruct in the Module.
366 llvm::Constant *Array =
367 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
370 llvm::GlobalValue *gv =
371 new llvm::GlobalVariable(TheModule, Array->getType(), false,
372 llvm::GlobalValue::AppendingLinkage, Array,
373 "llvm.global.annotations");
374 gv->setSection("llvm.metadata");
377 llvm::GlobalValue::LinkageTypes
378 CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
379 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
381 if (Linkage == GVA_Internal)
382 return llvm::Function::InternalLinkage;
384 if (D->hasAttr<DLLExportAttr>())
385 return llvm::Function::DLLExportLinkage;
387 if (D->hasAttr<WeakAttr>())
388 return llvm::Function::WeakAnyLinkage;
390 // In C99 mode, 'inline' functions are guaranteed to have a strong
391 // definition somewhere else, so we can use available_externally linkage.
392 if (Linkage == GVA_C99Inline)
393 return llvm::Function::AvailableExternallyLinkage;
395 // In C++, the compiler has to emit a definition in every translation unit
396 // that references the function. We should use linkonce_odr because
397 // a) if all references in this translation unit are optimized away, we
398 // don't need to codegen it. b) if the function persists, it needs to be
399 // merged with other definitions. c) C++ has the ODR, so we know the
400 // definition is dependable.
401 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
402 return !Context.getLangOptions().AppleKext
403 ? llvm::Function::LinkOnceODRLinkage
404 : llvm::Function::InternalLinkage;
406 // An explicit instantiation of a template has weak linkage, since
407 // explicit instantiations can occur in multiple translation units
408 // and must all be equivalent. However, we are not allowed to
409 // throw away these explicit instantiations.
410 if (Linkage == GVA_ExplicitTemplateInstantiation)
411 return !Context.getLangOptions().AppleKext
412 ? llvm::Function::WeakODRLinkage
413 : llvm::Function::InternalLinkage;
415 // Otherwise, we have strong external linkage.
416 assert(Linkage == GVA_StrongExternal);
417 return llvm::Function::ExternalLinkage;
421 /// SetFunctionDefinitionAttributes - Set attributes for a global.
423 /// FIXME: This is currently only done for aliases and functions, but not for
424 /// variables (these details are set in EmitGlobalVarDefinition for variables).
425 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
426 llvm::GlobalValue *GV) {
427 SetCommonAttributes(D, GV);
430 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
431 const CGFunctionInfo &Info,
433 unsigned CallingConv;
434 AttributeListType AttributeList;
435 ConstructAttributeList(Info, D, AttributeList, CallingConv);
436 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
437 AttributeList.size()));
438 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
441 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
443 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
444 F->addFnAttr(llvm::Attribute::NoUnwind);
446 if (D->hasAttr<AlwaysInlineAttr>())
447 F->addFnAttr(llvm::Attribute::AlwaysInline);
449 if (D->hasAttr<NakedAttr>())
450 F->addFnAttr(llvm::Attribute::Naked);
452 if (D->hasAttr<NoInlineAttr>())
453 F->addFnAttr(llvm::Attribute::NoInline);
455 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
456 F->setUnnamedAddr(true);
458 if (Features.getStackProtectorMode() == LangOptions::SSPOn)
459 F->addFnAttr(llvm::Attribute::StackProtect);
460 else if (Features.getStackProtectorMode() == LangOptions::SSPReq)
461 F->addFnAttr(llvm::Attribute::StackProtectReq);
463 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
465 F->setAlignment(alignment);
467 // C++ ABI requires 2-byte alignment for member functions.
468 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
472 void CodeGenModule::SetCommonAttributes(const Decl *D,
473 llvm::GlobalValue *GV) {
474 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
475 setGlobalVisibility(GV, ND);
477 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
479 if (D->hasAttr<UsedAttr>())
482 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
483 GV->setSection(SA->getName());
485 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
488 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
490 const CGFunctionInfo &FI) {
491 SetLLVMFunctionAttributes(D, FI, F);
492 SetLLVMFunctionAttributesForDefinition(D, F);
494 F->setLinkage(llvm::Function::InternalLinkage);
496 SetCommonAttributes(D, F);
499 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
501 bool IsIncompleteFunction) {
502 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
504 if (!IsIncompleteFunction)
505 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
507 // Only a few attributes are set on declarations; these may later be
508 // overridden by a definition.
510 if (FD->hasAttr<DLLImportAttr>()) {
511 F->setLinkage(llvm::Function::DLLImportLinkage);
512 } else if (FD->hasAttr<WeakAttr>() ||
513 FD->hasAttr<WeakImportAttr>()) {
514 // "extern_weak" is overloaded in LLVM; we probably should have
515 // separate linkage types for this.
516 F->setLinkage(llvm::Function::ExternalWeakLinkage);
518 F->setLinkage(llvm::Function::ExternalLinkage);
520 NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
521 if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
522 F->setVisibility(GetLLVMVisibility(LV.visibility()));
526 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
527 F->setSection(SA->getName());
530 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
531 assert(!GV->isDeclaration() &&
532 "Only globals with definition can force usage.");
533 LLVMUsed.push_back(GV);
536 void CodeGenModule::EmitLLVMUsed() {
537 // Don't create llvm.used if there is no need.
538 if (LLVMUsed.empty())
541 const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
543 // Convert LLVMUsed to what ConstantArray needs.
544 std::vector<llvm::Constant*> UsedArray;
545 UsedArray.resize(LLVMUsed.size());
546 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
548 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
552 if (UsedArray.empty())
554 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
556 llvm::GlobalVariable *GV =
557 new llvm::GlobalVariable(getModule(), ATy, false,
558 llvm::GlobalValue::AppendingLinkage,
559 llvm::ConstantArray::get(ATy, UsedArray),
562 GV->setSection("llvm.metadata");
565 void CodeGenModule::EmitDeferred() {
566 // Emit code for any potentially referenced deferred decls. Since a
567 // previously unused static decl may become used during the generation of code
568 // for a static function, iterate until no changes are made.
570 while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
571 if (!DeferredVTables.empty()) {
572 const CXXRecordDecl *RD = DeferredVTables.back();
573 DeferredVTables.pop_back();
574 getVTables().GenerateClassData(getVTableLinkage(RD), RD);
578 GlobalDecl D = DeferredDeclsToEmit.back();
579 DeferredDeclsToEmit.pop_back();
581 // Check to see if we've already emitted this. This is necessary
582 // for a couple of reasons: first, decls can end up in the
583 // deferred-decls queue multiple times, and second, decls can end
584 // up with definitions in unusual ways (e.g. by an extern inline
585 // function acquiring a strong function redefinition). Just
586 // ignore these cases.
588 // TODO: That said, looking this up multiple times is very wasteful.
589 llvm::StringRef Name = getMangledName(D);
590 llvm::GlobalValue *CGRef = GetGlobalValue(Name);
591 assert(CGRef && "Deferred decl wasn't referenced?");
593 if (!CGRef->isDeclaration())
596 // GlobalAlias::isDeclaration() defers to the aliasee, but for our
597 // purposes an alias counts as a definition.
598 if (isa<llvm::GlobalAlias>(CGRef))
601 // Otherwise, emit the definition and move on to the next one.
602 EmitGlobalDefinition(D);
606 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
607 /// annotation information for a given GlobalValue. The annotation struct is
608 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
609 /// GlobalValue being annotated. The second field is the constant string
610 /// created from the AnnotateAttr's annotation. The third field is a constant
611 /// string containing the name of the translation unit. The fourth field is
612 /// the line number in the file of the annotated value declaration.
614 /// FIXME: this does not unique the annotation string constants, as llvm-gcc
617 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
618 const AnnotateAttr *AA,
620 llvm::Module *M = &getModule();
622 // get [N x i8] constants for the annotation string, and the filename string
623 // which are the 2nd and 3rd elements of the global annotation structure.
624 const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext);
625 llvm::Constant *anno = llvm::ConstantArray::get(VMContext,
626 AA->getAnnotation(), true);
627 llvm::Constant *unit = llvm::ConstantArray::get(VMContext,
628 M->getModuleIdentifier(),
631 // Get the two global values corresponding to the ConstantArrays we just
632 // created to hold the bytes of the strings.
633 llvm::GlobalValue *annoGV =
634 new llvm::GlobalVariable(*M, anno->getType(), false,
635 llvm::GlobalValue::PrivateLinkage, anno,
637 // translation unit name string, emitted into the llvm.metadata section.
638 llvm::GlobalValue *unitGV =
639 new llvm::GlobalVariable(*M, unit->getType(), false,
640 llvm::GlobalValue::PrivateLinkage, unit,
642 unitGV->setUnnamedAddr(true);
644 // Create the ConstantStruct for the global annotation.
645 llvm::Constant *Fields[4] = {
646 llvm::ConstantExpr::getBitCast(GV, SBP),
647 llvm::ConstantExpr::getBitCast(annoGV, SBP),
648 llvm::ConstantExpr::getBitCast(unitGV, SBP),
649 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo)
651 return llvm::ConstantStruct::get(VMContext, Fields, 4, false);
654 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
655 // Never defer when EmitAllDecls is specified.
656 if (Features.EmitAllDecls)
659 return !getContext().DeclMustBeEmitted(Global);
662 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
663 const AliasAttr *AA = VD->getAttr<AliasAttr>();
664 assert(AA && "No alias?");
666 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
668 // See if there is already something with the target's name in the module.
669 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
671 llvm::Constant *Aliasee;
672 if (isa<llvm::FunctionType>(DeclTy))
673 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
674 /*ForVTable=*/false);
676 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
677 llvm::PointerType::getUnqual(DeclTy), 0);
679 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
680 F->setLinkage(llvm::Function::ExternalWeakLinkage);
681 WeakRefReferences.insert(F);
687 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
688 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
690 // Weak references don't produce any output by themselves.
691 if (Global->hasAttr<WeakRefAttr>())
694 // If this is an alias definition (which otherwise looks like a declaration)
696 if (Global->hasAttr<AliasAttr>())
697 return EmitAliasDefinition(GD);
699 // Ignore declarations, they will be emitted on their first use.
700 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
701 if (FD->getIdentifier()) {
702 llvm::StringRef Name = FD->getName();
703 if (Name == "_Block_object_assign") {
704 BlockObjectAssignDecl = FD;
705 } else if (Name == "_Block_object_dispose") {
706 BlockObjectDisposeDecl = FD;
710 // Forward declarations are emitted lazily on first use.
711 if (!FD->isThisDeclarationADefinition())
714 const VarDecl *VD = cast<VarDecl>(Global);
715 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
717 if (VD->getIdentifier()) {
718 llvm::StringRef Name = VD->getName();
719 if (Name == "_NSConcreteGlobalBlock") {
720 NSConcreteGlobalBlockDecl = VD;
721 } else if (Name == "_NSConcreteStackBlock") {
722 NSConcreteStackBlockDecl = VD;
727 if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
731 // Defer code generation when possible if this is a static definition, inline
732 // function etc. These we only want to emit if they are used.
733 if (!MayDeferGeneration(Global)) {
734 // Emit the definition if it can't be deferred.
735 EmitGlobalDefinition(GD);
739 // If we're deferring emission of a C++ variable with an
740 // initializer, remember the order in which it appeared in the file.
741 if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) &&
742 cast<VarDecl>(Global)->hasInit()) {
743 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
744 CXXGlobalInits.push_back(0);
747 // If the value has already been used, add it directly to the
748 // DeferredDeclsToEmit list.
749 llvm::StringRef MangledName = getMangledName(GD);
750 if (GetGlobalValue(MangledName))
751 DeferredDeclsToEmit.push_back(GD);
753 // Otherwise, remember that we saw a deferred decl with this name. The
754 // first use of the mangled name will cause it to move into
755 // DeferredDeclsToEmit.
756 DeferredDecls[MangledName] = GD;
760 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
761 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
763 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
764 Context.getSourceManager(),
765 "Generating code for declaration");
767 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
768 // At -O0, don't generate IR for functions with available_externally
770 if (CodeGenOpts.OptimizationLevel == 0 &&
771 !Function->hasAttr<AlwaysInlineAttr>() &&
772 getFunctionLinkage(Function)
773 == llvm::Function::AvailableExternallyLinkage)
776 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
777 if (Method->isVirtual())
778 getVTables().EmitThunks(GD);
780 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
781 return EmitCXXConstructor(CD, GD.getCtorType());
783 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(Method))
784 return EmitCXXDestructor(DD, GD.getDtorType());
787 return EmitGlobalFunctionDefinition(GD);
790 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
791 return EmitGlobalVarDefinition(VD);
793 assert(0 && "Invalid argument to EmitGlobalDefinition()");
796 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
797 /// module, create and return an llvm Function with the specified type. If there
798 /// is something in the module with the specified name, return it potentially
799 /// bitcasted to the right type.
801 /// If D is non-null, it specifies a decl that correspond to this. This is used
802 /// to set the attributes on the function when it is first created.
804 CodeGenModule::GetOrCreateLLVMFunction(llvm::StringRef MangledName,
805 const llvm::Type *Ty,
806 GlobalDecl D, bool ForVTable) {
807 // Lookup the entry, lazily creating it if necessary.
808 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
810 if (WeakRefReferences.count(Entry)) {
811 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
812 if (FD && !FD->hasAttr<WeakAttr>())
813 Entry->setLinkage(llvm::Function::ExternalLinkage);
815 WeakRefReferences.erase(Entry);
818 if (Entry->getType()->getElementType() == Ty)
821 // Make sure the result is of the correct type.
822 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
823 return llvm::ConstantExpr::getBitCast(Entry, PTy);
826 // This function doesn't have a complete type (for example, the return
827 // type is an incomplete struct). Use a fake type instead, and make
828 // sure not to try to set attributes.
829 bool IsIncompleteFunction = false;
831 const llvm::FunctionType *FTy;
832 if (isa<llvm::FunctionType>(Ty)) {
833 FTy = cast<llvm::FunctionType>(Ty);
835 FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false);
836 IsIncompleteFunction = true;
839 llvm::Function *F = llvm::Function::Create(FTy,
840 llvm::Function::ExternalLinkage,
841 MangledName, &getModule());
842 assert(F->getName() == MangledName && "name was uniqued!");
844 SetFunctionAttributes(D, F, IsIncompleteFunction);
846 // This is the first use or definition of a mangled name. If there is a
847 // deferred decl with this name, remember that we need to emit it at the end
849 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
850 if (DDI != DeferredDecls.end()) {
851 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
852 // list, and remove it from DeferredDecls (since we don't need it anymore).
853 DeferredDeclsToEmit.push_back(DDI->second);
854 DeferredDecls.erase(DDI);
856 // Otherwise, there are cases we have to worry about where we're
857 // using a declaration for which we must emit a definition but where
858 // we might not find a top-level definition:
859 // - member functions defined inline in their classes
860 // - friend functions defined inline in some class
861 // - special member functions with implicit definitions
862 // If we ever change our AST traversal to walk into class methods,
863 // this will be unnecessary.
865 // We also don't emit a definition for a function if it's going to be an entry
866 // in a vtable, unless it's already marked as used.
867 } else if (getLangOptions().CPlusPlus && D.getDecl()) {
868 // Look for a declaration that's lexically in a record.
869 const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
871 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
872 if (FD->isImplicit() && !ForVTable) {
873 assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
874 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
876 } else if (FD->isThisDeclarationADefinition()) {
877 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
881 FD = FD->getPreviousDeclaration();
885 // Make sure the result is of the requested type.
886 if (!IsIncompleteFunction) {
887 assert(F->getType()->getElementType() == Ty);
891 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
892 return llvm::ConstantExpr::getBitCast(F, PTy);
895 /// GetAddrOfFunction - Return the address of the given function. If Ty is
896 /// non-null, then this function will use the specified type if it has to
897 /// create it (this occurs when we see a definition of the function).
898 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
899 const llvm::Type *Ty,
901 // If there was no specific requested type, just convert it now.
903 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
905 llvm::StringRef MangledName = getMangledName(GD);
906 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
909 /// CreateRuntimeFunction - Create a new runtime function with the specified
912 CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
913 llvm::StringRef Name) {
914 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false);
917 static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) {
918 if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
920 if (Context.getLangOptions().CPlusPlus &&
921 Context.getBaseElementType(D->getType())->getAs<RecordType>()) {
922 // FIXME: We should do something fancier here!
928 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
929 /// create and return an llvm GlobalVariable with the specified type. If there
930 /// is something in the module with the specified name, return it potentially
931 /// bitcasted to the right type.
933 /// If D is non-null, it specifies a decl that correspond to this. This is used
934 /// to set the attributes on the global when it is first created.
936 CodeGenModule::GetOrCreateLLVMGlobal(llvm::StringRef MangledName,
937 const llvm::PointerType *Ty,
940 // Lookup the entry, lazily creating it if necessary.
941 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
943 if (WeakRefReferences.count(Entry)) {
944 if (D && !D->hasAttr<WeakAttr>())
945 Entry->setLinkage(llvm::Function::ExternalLinkage);
947 WeakRefReferences.erase(Entry);
951 Entry->setUnnamedAddr(true);
953 if (Entry->getType() == Ty)
956 // Make sure the result is of the correct type.
957 return llvm::ConstantExpr::getBitCast(Entry, Ty);
960 // This is the first use or definition of a mangled name. If there is a
961 // deferred decl with this name, remember that we need to emit it at the end
963 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
964 if (DDI != DeferredDecls.end()) {
965 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
966 // list, and remove it from DeferredDecls (since we don't need it anymore).
967 DeferredDeclsToEmit.push_back(DDI->second);
968 DeferredDecls.erase(DDI);
971 llvm::GlobalVariable *GV =
972 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
973 llvm::GlobalValue::ExternalLinkage,
975 false, Ty->getAddressSpace());
977 // Handle things which are present even on external declarations.
979 // FIXME: This code is overly simple and should be merged with other global
981 GV->setConstant(DeclIsConstantGlobal(Context, D));
983 // Set linkage and visibility in case we never see a definition.
984 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
985 if (LV.linkage() != ExternalLinkage) {
986 // Don't set internal linkage on declarations.
988 if (D->hasAttr<DLLImportAttr>())
989 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
990 else if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakImportAttr>())
991 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
993 // Set visibility on a declaration only if it's explicit.
994 if (LV.visibilityExplicit())
995 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
998 GV->setThreadLocal(D->isThreadSpecified());
1005 llvm::GlobalVariable *
1006 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(llvm::StringRef Name,
1007 const llvm::Type *Ty,
1008 llvm::GlobalValue::LinkageTypes Linkage) {
1009 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1010 llvm::GlobalVariable *OldGV = 0;
1014 // Check if the variable has the right type.
1015 if (GV->getType()->getElementType() == Ty)
1018 // Because C++ name mangling, the only way we can end up with an already
1019 // existing global with the same name is if it has been declared extern "C".
1020 assert(GV->isDeclaration() && "Declaration has wrong type!");
1024 // Create a new variable.
1025 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1029 // Replace occurrences of the old variable if needed.
1030 GV->takeName(OldGV);
1032 if (!OldGV->use_empty()) {
1033 llvm::Constant *NewPtrForOldDecl =
1034 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1035 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1038 OldGV->eraseFromParent();
1044 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1045 /// given global variable. If Ty is non-null and if the global doesn't exist,
1046 /// then it will be greated with the specified type instead of whatever the
1047 /// normal requested type would be.
1048 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1049 const llvm::Type *Ty) {
1050 assert(D->hasGlobalStorage() && "Not a global variable");
1051 QualType ASTTy = D->getType();
1053 Ty = getTypes().ConvertTypeForMem(ASTTy);
1055 const llvm::PointerType *PTy =
1056 llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
1058 llvm::StringRef MangledName = getMangledName(D);
1059 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
1062 /// CreateRuntimeVariable - Create a new runtime global variable with the
1063 /// specified type and name.
1065 CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
1066 llvm::StringRef Name) {
1067 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
1071 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1072 assert(!D->getInit() && "Cannot emit definite definitions here!");
1074 if (MayDeferGeneration(D)) {
1075 // If we have not seen a reference to this variable yet, place it
1076 // into the deferred declarations table to be emitted if needed
1078 llvm::StringRef MangledName = getMangledName(D);
1079 if (!GetGlobalValue(MangledName)) {
1080 DeferredDecls[MangledName] = D;
1085 // The tentative definition is the only definition.
1086 EmitGlobalVarDefinition(D);
1089 void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
1090 if (DefinitionRequired)
1091 getVTables().GenerateClassData(getVTableLinkage(Class), Class);
1094 llvm::GlobalVariable::LinkageTypes
1095 CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
1096 if (RD->isInAnonymousNamespace() || !RD->hasLinkage())
1097 return llvm::GlobalVariable::InternalLinkage;
1099 if (const CXXMethodDecl *KeyFunction
1100 = RD->getASTContext().getKeyFunction(RD)) {
1101 // If this class has a key function, use that to determine the linkage of
1103 const FunctionDecl *Def = 0;
1104 if (KeyFunction->hasBody(Def))
1105 KeyFunction = cast<CXXMethodDecl>(Def);
1107 switch (KeyFunction->getTemplateSpecializationKind()) {
1108 case TSK_Undeclared:
1109 case TSK_ExplicitSpecialization:
1110 // When compiling with optimizations turned on, we emit all vtables,
1111 // even if the key function is not defined in the current translation
1112 // unit. If this is the case, use available_externally linkage.
1113 if (!Def && CodeGenOpts.OptimizationLevel)
1114 return llvm::GlobalVariable::AvailableExternallyLinkage;
1116 if (KeyFunction->isInlined())
1117 return !Context.getLangOptions().AppleKext ?
1118 llvm::GlobalVariable::LinkOnceODRLinkage :
1119 llvm::Function::InternalLinkage;
1121 return llvm::GlobalVariable::ExternalLinkage;
1123 case TSK_ImplicitInstantiation:
1124 return !Context.getLangOptions().AppleKext ?
1125 llvm::GlobalVariable::LinkOnceODRLinkage :
1126 llvm::Function::InternalLinkage;
1128 case TSK_ExplicitInstantiationDefinition:
1129 return !Context.getLangOptions().AppleKext ?
1130 llvm::GlobalVariable::WeakODRLinkage :
1131 llvm::Function::InternalLinkage;
1133 case TSK_ExplicitInstantiationDeclaration:
1134 // FIXME: Use available_externally linkage. However, this currently
1135 // breaks LLVM's build due to undefined symbols.
1136 // return llvm::GlobalVariable::AvailableExternallyLinkage;
1137 return !Context.getLangOptions().AppleKext ?
1138 llvm::GlobalVariable::LinkOnceODRLinkage :
1139 llvm::Function::InternalLinkage;
1143 if (Context.getLangOptions().AppleKext)
1144 return llvm::Function::InternalLinkage;
1146 switch (RD->getTemplateSpecializationKind()) {
1147 case TSK_Undeclared:
1148 case TSK_ExplicitSpecialization:
1149 case TSK_ImplicitInstantiation:
1150 // FIXME: Use available_externally linkage. However, this currently
1151 // breaks LLVM's build due to undefined symbols.
1152 // return llvm::GlobalVariable::AvailableExternallyLinkage;
1153 case TSK_ExplicitInstantiationDeclaration:
1154 return llvm::GlobalVariable::LinkOnceODRLinkage;
1156 case TSK_ExplicitInstantiationDefinition:
1157 return llvm::GlobalVariable::WeakODRLinkage;
1160 // Silence GCC warning.
1161 return llvm::GlobalVariable::LinkOnceODRLinkage;
1164 CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const {
1165 return Context.toCharUnitsFromBits(
1166 TheTargetData.getTypeStoreSizeInBits(Ty));
1169 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1170 llvm::Constant *Init = 0;
1171 QualType ASTTy = D->getType();
1172 bool NonConstInit = false;
1174 const Expr *InitExpr = D->getAnyInitializer();
1177 // This is a tentative definition; tentative definitions are
1178 // implicitly initialized with { 0 }.
1180 // Note that tentative definitions are only emitted at the end of
1181 // a translation unit, so they should never have incomplete
1182 // type. In addition, EmitTentativeDefinition makes sure that we
1183 // never attempt to emit a tentative definition if a real one
1184 // exists. A use may still exists, however, so we still may need
1186 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1187 Init = EmitNullConstant(D->getType());
1189 Init = EmitConstantExpr(InitExpr, D->getType());
1191 QualType T = InitExpr->getType();
1192 if (D->getType()->isReferenceType())
1195 if (getLangOptions().CPlusPlus) {
1196 Init = EmitNullConstant(T);
1197 NonConstInit = true;
1199 ErrorUnsupported(D, "static initializer");
1200 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1203 // We don't need an initializer, so remove the entry for the delayed
1204 // initializer position (just in case this entry was delayed).
1205 if (getLangOptions().CPlusPlus)
1206 DelayedCXXInitPosition.erase(D);
1210 const llvm::Type* InitType = Init->getType();
1211 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1213 // Strip off a bitcast if we got one back.
1214 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1215 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1216 // all zero index gep.
1217 CE->getOpcode() == llvm::Instruction::GetElementPtr);
1218 Entry = CE->getOperand(0);
1221 // Entry is now either a Function or GlobalVariable.
1222 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1224 // We have a definition after a declaration with the wrong type.
1225 // We must make a new GlobalVariable* and update everything that used OldGV
1226 // (a declaration or tentative definition) with the new GlobalVariable*
1227 // (which will be a definition).
1229 // This happens if there is a prototype for a global (e.g.
1230 // "extern int x[];") and then a definition of a different type (e.g.
1231 // "int x[10];"). This also happens when an initializer has a different type
1232 // from the type of the global (this happens with unions).
1234 GV->getType()->getElementType() != InitType ||
1235 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
1237 // Move the old entry aside so that we'll create a new one.
1238 Entry->setName(llvm::StringRef());
1240 // Make a new global with the correct type, this is now guaranteed to work.
1241 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
1243 // Replace all uses of the old global with the new global
1244 llvm::Constant *NewPtrForOldDecl =
1245 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1246 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1248 // Erase the old global, since it is no longer used.
1249 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1252 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
1253 SourceManager &SM = Context.getSourceManager();
1254 AddAnnotation(EmitAnnotateAttr(GV, AA,
1255 SM.getInstantiationLineNumber(D->getLocation())));
1258 GV->setInitializer(Init);
1260 // If it is safe to mark the global 'constant', do so now.
1261 GV->setConstant(false);
1262 if (!NonConstInit && DeclIsConstantGlobal(Context, D))
1263 GV->setConstant(true);
1265 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1267 // Set the llvm linkage type as appropriate.
1268 llvm::GlobalValue::LinkageTypes Linkage =
1269 GetLLVMLinkageVarDefinition(D, GV);
1270 GV->setLinkage(Linkage);
1271 if (Linkage == llvm::GlobalVariable::CommonLinkage)
1272 // common vars aren't constant even if declared const.
1273 GV->setConstant(false);
1275 SetCommonAttributes(D, GV);
1277 // Emit the initializer function if necessary.
1279 EmitCXXGlobalVarDeclInitFunc(D, GV);
1281 // Emit global variable debug information.
1282 if (CGDebugInfo *DI = getDebugInfo()) {
1283 DI->setLocation(D->getLocation());
1284 DI->EmitGlobalVariable(GV, D);
1288 llvm::GlobalValue::LinkageTypes
1289 CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1290 llvm::GlobalVariable *GV) {
1291 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1292 if (Linkage == GVA_Internal)
1293 return llvm::Function::InternalLinkage;
1294 else if (D->hasAttr<DLLImportAttr>())
1295 return llvm::Function::DLLImportLinkage;
1296 else if (D->hasAttr<DLLExportAttr>())
1297 return llvm::Function::DLLExportLinkage;
1298 else if (D->hasAttr<WeakAttr>()) {
1299 if (GV->isConstant())
1300 return llvm::GlobalVariable::WeakODRLinkage;
1302 return llvm::GlobalVariable::WeakAnyLinkage;
1303 } else if (Linkage == GVA_TemplateInstantiation ||
1304 Linkage == GVA_ExplicitTemplateInstantiation)
1305 // FIXME: It seems like we can provide more specific linkage here
1306 // (LinkOnceODR, WeakODR).
1307 return llvm::GlobalVariable::WeakAnyLinkage;
1308 else if (!getLangOptions().CPlusPlus &&
1309 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1310 D->getAttr<CommonAttr>()) &&
1311 !D->hasExternalStorage() && !D->getInit() &&
1312 !D->getAttr<SectionAttr>() && !D->isThreadSpecified()) {
1313 // Thread local vars aren't considered common linkage.
1314 return llvm::GlobalVariable::CommonLinkage;
1316 return llvm::GlobalVariable::ExternalLinkage;
1319 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1320 /// implement a function with no prototype, e.g. "int foo() {}". If there are
1321 /// existing call uses of the old function in the module, this adjusts them to
1322 /// call the new function directly.
1324 /// This is not just a cleanup: the always_inline pass requires direct calls to
1325 /// functions to be able to inline them. If there is a bitcast in the way, it
1326 /// won't inline them. Instcombine normally deletes these calls, but it isn't
1328 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1329 llvm::Function *NewFn) {
1330 // If we're redefining a global as a function, don't transform it.
1331 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1332 if (OldFn == 0) return;
1334 const llvm::Type *NewRetTy = NewFn->getReturnType();
1335 llvm::SmallVector<llvm::Value*, 4> ArgList;
1337 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
1339 // TODO: Do invokes ever occur in C code? If so, we should handle them too.
1340 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1341 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
1342 if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
1343 llvm::CallSite CS(CI);
1344 if (!CI || !CS.isCallee(I)) continue;
1346 // If the return types don't match exactly, and if the call isn't dead, then
1347 // we can't transform this call.
1348 if (CI->getType() != NewRetTy && !CI->use_empty())
1351 // If the function was passed too few arguments, don't transform. If extra
1352 // arguments were passed, we silently drop them. If any of the types
1353 // mismatch, we don't transform.
1355 bool DontTransform = false;
1356 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1357 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
1358 if (CS.arg_size() == ArgNo ||
1359 CS.getArgument(ArgNo)->getType() != AI->getType()) {
1360 DontTransform = true;
1367 // Okay, we can transform this. Create the new call instruction and copy
1368 // over the required information.
1369 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
1370 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
1371 ArgList.end(), "", CI);
1373 if (!NewCall->getType()->isVoidTy())
1374 NewCall->takeName(CI);
1375 NewCall->setAttributes(CI->getAttributes());
1376 NewCall->setCallingConv(CI->getCallingConv());
1378 // Finally, remove the old call, replacing any uses with the new one.
1379 if (!CI->use_empty())
1380 CI->replaceAllUsesWith(NewCall);
1382 // Copy debug location attached to CI.
1383 if (!CI->getDebugLoc().isUnknown())
1384 NewCall->setDebugLoc(CI->getDebugLoc());
1385 CI->eraseFromParent();
1390 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
1391 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
1392 const llvm::FunctionType *Ty = getTypes().GetFunctionType(GD);
1393 // Get or create the prototype for the function.
1394 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
1396 // Strip off a bitcast if we got one back.
1397 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1398 assert(CE->getOpcode() == llvm::Instruction::BitCast);
1399 Entry = CE->getOperand(0);
1403 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
1404 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
1406 // If the types mismatch then we have to rewrite the definition.
1407 assert(OldFn->isDeclaration() &&
1408 "Shouldn't replace non-declaration");
1410 // F is the Function* for the one with the wrong type, we must make a new
1411 // Function* and update everything that used F (a declaration) with the new
1412 // Function* (which will be a definition).
1414 // This happens if there is a prototype for a function
1415 // (e.g. "int f()") and then a definition of a different type
1416 // (e.g. "int f(int x)"). Move the old function aside so that it
1417 // doesn't interfere with GetAddrOfFunction.
1418 OldFn->setName(llvm::StringRef());
1419 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
1421 // If this is an implementation of a function without a prototype, try to
1422 // replace any existing uses of the function (which may be calls) with uses
1423 // of the new function
1424 if (D->getType()->isFunctionNoProtoType()) {
1425 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
1426 OldFn->removeDeadConstantUsers();
1429 // Replace uses of F with the Function we will endow with a body.
1430 if (!Entry->use_empty()) {
1431 llvm::Constant *NewPtrForOldDecl =
1432 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
1433 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1436 // Ok, delete the old function now, which is dead.
1437 OldFn->eraseFromParent();
1442 // We need to set linkage and visibility on the function before
1443 // generating code for it because various parts of IR generation
1444 // want to propagate this information down (e.g. to local static
1446 llvm::Function *Fn = cast<llvm::Function>(Entry);
1447 setFunctionLinkage(D, Fn);
1449 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
1450 setGlobalVisibility(Fn, D);
1452 CodeGenFunction(*this).GenerateCode(D, Fn);
1454 SetFunctionDefinitionAttributes(D, Fn);
1455 SetLLVMFunctionAttributesForDefinition(D, Fn);
1457 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
1458 AddGlobalCtor(Fn, CA->getPriority());
1459 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
1460 AddGlobalDtor(Fn, DA->getPriority());
1463 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1464 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
1465 const AliasAttr *AA = D->getAttr<AliasAttr>();
1466 assert(AA && "Not an alias?");
1468 llvm::StringRef MangledName = getMangledName(GD);
1470 // If there is a definition in the module, then it wins over the alias.
1471 // This is dubious, but allow it to be safe. Just ignore the alias.
1472 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1473 if (Entry && !Entry->isDeclaration())
1476 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1478 // Create a reference to the named value. This ensures that it is emitted
1479 // if a deferred decl.
1480 llvm::Constant *Aliasee;
1481 if (isa<llvm::FunctionType>(DeclTy))
1482 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
1483 /*ForVTable=*/false);
1485 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1486 llvm::PointerType::getUnqual(DeclTy), 0);
1488 // Create the new alias itself, but don't set a name yet.
1489 llvm::GlobalValue *GA =
1490 new llvm::GlobalAlias(Aliasee->getType(),
1491 llvm::Function::ExternalLinkage,
1492 "", Aliasee, &getModule());
1495 assert(Entry->isDeclaration());
1497 // If there is a declaration in the module, then we had an extern followed
1498 // by the alias, as in:
1499 // extern int test6();
1501 // int test6() __attribute__((alias("test7")));
1503 // Remove it and replace uses of it with the alias.
1504 GA->takeName(Entry);
1506 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
1508 Entry->eraseFromParent();
1510 GA->setName(MangledName);
1513 // Set attributes which are particular to an alias; this is a
1514 // specialization of the attributes which may be set on a global
1515 // variable/function.
1516 if (D->hasAttr<DLLExportAttr>()) {
1517 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1518 // The dllexport attribute is ignored for undefined symbols.
1520 GA->setLinkage(llvm::Function::DLLExportLinkage);
1522 GA->setLinkage(llvm::Function::DLLExportLinkage);
1524 } else if (D->hasAttr<WeakAttr>() ||
1525 D->hasAttr<WeakRefAttr>() ||
1526 D->hasAttr<WeakImportAttr>()) {
1527 GA->setLinkage(llvm::Function::WeakAnyLinkage);
1530 SetCommonAttributes(D, GA);
1533 /// getBuiltinLibFunction - Given a builtin id for a function like
1534 /// "__builtin_fabsf", return a Function* for "fabsf".
1535 llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
1536 unsigned BuiltinID) {
1537 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
1538 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
1541 // Get the name, skip over the __builtin_ prefix (if necessary).
1542 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
1543 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
1546 const llvm::FunctionType *Ty =
1547 cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
1549 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD), /*ForVTable=*/false);
1552 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
1554 return llvm::Intrinsic::getDeclaration(&getModule(),
1555 (llvm::Intrinsic::ID)IID, Tys, NumTys);
1558 static llvm::StringMapEntry<llvm::Constant*> &
1559 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1560 const StringLiteral *Literal,
1563 unsigned &StringLength) {
1564 llvm::StringRef String = Literal->getString();
1565 unsigned NumBytes = String.size();
1567 // Check for simple case.
1568 if (!Literal->containsNonAsciiOrNull()) {
1569 StringLength = NumBytes;
1570 return Map.GetOrCreateValue(String);
1573 // Otherwise, convert the UTF8 literals into a byte string.
1574 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
1575 const UTF8 *FromPtr = (UTF8 *)String.data();
1576 UTF16 *ToPtr = &ToBuf[0];
1578 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1579 &ToPtr, ToPtr + NumBytes,
1582 // ConvertUTF8toUTF16 returns the length in ToPtr.
1583 StringLength = ToPtr - &ToBuf[0];
1585 // Render the UTF-16 string into a byte array and convert to the target byte
1588 // FIXME: This isn't something we should need to do here.
1589 llvm::SmallString<128> AsBytes;
1590 AsBytes.reserve(StringLength * 2);
1591 for (unsigned i = 0; i != StringLength; ++i) {
1592 unsigned short Val = ToBuf[i];
1594 AsBytes.push_back(Val & 0xFF);
1595 AsBytes.push_back(Val >> 8);
1597 AsBytes.push_back(Val >> 8);
1598 AsBytes.push_back(Val & 0xFF);
1601 // Append one extra null character, the second is automatically added by our
1603 AsBytes.push_back(0);
1606 return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size()));
1610 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1611 unsigned StringLength = 0;
1612 bool isUTF16 = false;
1613 llvm::StringMapEntry<llvm::Constant*> &Entry =
1614 GetConstantCFStringEntry(CFConstantStringMap, Literal,
1615 getTargetData().isLittleEndian(),
1616 isUTF16, StringLength);
1618 if (llvm::Constant *C = Entry.getValue())
1621 llvm::Constant *Zero =
1622 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1623 llvm::Constant *Zeros[] = { Zero, Zero };
1625 // If we don't already have it, get __CFConstantStringClassReference.
1626 if (!CFConstantStringClassRef) {
1627 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1628 Ty = llvm::ArrayType::get(Ty, 0);
1629 llvm::Constant *GV = CreateRuntimeVariable(Ty,
1630 "__CFConstantStringClassReference");
1631 // Decay array -> ptr
1632 CFConstantStringClassRef =
1633 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1636 QualType CFTy = getContext().getCFConstantStringType();
1638 const llvm::StructType *STy =
1639 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1641 std::vector<llvm::Constant*> Fields(4);
1644 Fields[0] = CFConstantStringClassRef;
1647 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1648 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
1649 llvm::ConstantInt::get(Ty, 0x07C8);
1652 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1654 llvm::GlobalValue::LinkageTypes Linkage;
1657 // FIXME: why do utf strings get "_" labels instead of "L" labels?
1658 Linkage = llvm::GlobalValue::InternalLinkage;
1659 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1660 // does make plain ascii ones writable.
1663 Linkage = llvm::GlobalValue::PrivateLinkage;
1664 isConstant = !Features.WritableStrings;
1667 llvm::GlobalVariable *GV =
1668 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1670 GV->setUnnamedAddr(true);
1672 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1673 GV->setAlignment(Align.getQuantity());
1675 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1678 Ty = getTypes().ConvertType(getContext().LongTy);
1679 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
1682 C = llvm::ConstantStruct::get(STy, Fields);
1683 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1684 llvm::GlobalVariable::PrivateLinkage, C,
1685 "_unnamed_cfstring_");
1686 if (const char *Sect = getContext().Target.getCFStringSection())
1687 GV->setSection(Sect);
1694 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
1695 unsigned StringLength = 0;
1696 bool isUTF16 = false;
1697 llvm::StringMapEntry<llvm::Constant*> &Entry =
1698 GetConstantCFStringEntry(CFConstantStringMap, Literal,
1699 getTargetData().isLittleEndian(),
1700 isUTF16, StringLength);
1702 if (llvm::Constant *C = Entry.getValue())
1705 llvm::Constant *Zero =
1706 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1707 llvm::Constant *Zeros[] = { Zero, Zero };
1709 // If we don't already have it, get _NSConstantStringClassReference.
1710 if (!ConstantStringClassRef) {
1711 std::string StringClass(getLangOptions().ObjCConstantStringClass);
1712 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1713 Ty = llvm::ArrayType::get(Ty, 0);
1715 if (StringClass.empty())
1716 GV = CreateRuntimeVariable(Ty,
1717 Features.ObjCNonFragileABI ?
1718 "OBJC_CLASS_$_NSConstantString" :
1719 "_NSConstantStringClassReference");
1722 if (Features.ObjCNonFragileABI)
1723 str = "OBJC_CLASS_$_" + StringClass;
1725 str = "_" + StringClass + "ClassReference";
1726 GV = CreateRuntimeVariable(Ty, str);
1728 // Decay array -> ptr
1729 ConstantStringClassRef =
1730 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1733 QualType NSTy = getContext().getNSConstantStringType();
1735 const llvm::StructType *STy =
1736 cast<llvm::StructType>(getTypes().ConvertType(NSTy));
1738 std::vector<llvm::Constant*> Fields(3);
1741 Fields[0] = ConstantStringClassRef;
1744 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1746 llvm::GlobalValue::LinkageTypes Linkage;
1749 // FIXME: why do utf strings get "_" labels instead of "L" labels?
1750 Linkage = llvm::GlobalValue::InternalLinkage;
1751 // Note: -fwritable-strings doesn't make unicode NSStrings writable, but
1752 // does make plain ascii ones writable.
1755 Linkage = llvm::GlobalValue::PrivateLinkage;
1756 isConstant = !Features.WritableStrings;
1759 llvm::GlobalVariable *GV =
1760 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1762 GV->setUnnamedAddr(true);
1764 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1765 GV->setAlignment(Align.getQuantity());
1767 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1770 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1771 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
1774 C = llvm::ConstantStruct::get(STy, Fields);
1775 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1776 llvm::GlobalVariable::PrivateLinkage, C,
1777 "_unnamed_nsstring_");
1778 // FIXME. Fix section.
1779 if (const char *Sect =
1780 Features.ObjCNonFragileABI
1781 ? getContext().Target.getNSStringNonFragileABISection()
1782 : getContext().Target.getNSStringSection())
1783 GV->setSection(Sect);
1789 /// GetStringForStringLiteral - Return the appropriate bytes for a
1790 /// string literal, properly padded to match the literal type.
1791 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
1792 const ASTContext &Context = getContext();
1793 const ConstantArrayType *CAT =
1794 Context.getAsConstantArrayType(E->getType());
1795 assert(CAT && "String isn't pointer or array!");
1797 // Resize the string to the right size.
1798 uint64_t RealLen = CAT->getSize().getZExtValue();
1801 RealLen *= Context.Target.getWCharWidth() / Context.getCharWidth();
1803 std::string Str = E->getString().str();
1804 Str.resize(RealLen, '\0');
1809 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1810 /// constant array for the given string literal.
1812 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1813 // FIXME: This can be more efficient.
1814 // FIXME: We shouldn't need to bitcast the constant in the wide string case.
1815 llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S));
1817 llvm::Type *DestTy =
1818 llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
1819 C = llvm::ConstantExpr::getBitCast(C, DestTy);
1824 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1825 /// array for the given ObjCEncodeExpr node.
1827 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1829 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1831 return GetAddrOfConstantCString(Str);
1835 /// GenerateWritableString -- Creates storage for a string literal.
1836 static llvm::Constant *GenerateStringLiteral(const std::string &str,
1839 const char *GlobalName) {
1840 // Create Constant for this string literal. Don't add a '\0'.
1842 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
1844 // Create a global variable for this string
1845 llvm::GlobalVariable *GV =
1846 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
1847 llvm::GlobalValue::PrivateLinkage,
1849 GV->setUnnamedAddr(true);
1853 /// GetAddrOfConstantString - Returns a pointer to a character array
1854 /// containing the literal. This contents are exactly that of the
1855 /// given string, i.e. it will not be null terminated automatically;
1856 /// see GetAddrOfConstantCString. Note that whether the result is
1857 /// actually a pointer to an LLVM constant depends on
1858 /// Feature.WriteableStrings.
1860 /// The result has pointer to array type.
1861 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1862 const char *GlobalName) {
1863 bool IsConstant = !Features.WritableStrings;
1865 // Get the default prefix if a name wasn't specified.
1867 GlobalName = ".str";
1869 // Don't share any string literals if strings aren't constant.
1871 return GenerateStringLiteral(str, false, *this, GlobalName);
1873 llvm::StringMapEntry<llvm::Constant *> &Entry =
1874 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1876 if (Entry.getValue())
1877 return Entry.getValue();
1879 // Create a global variable for this.
1880 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
1885 /// GetAddrOfConstantCString - Returns a pointer to a character
1886 /// array containing the literal and a terminating '\-'
1887 /// character. The result has pointer to array type.
1888 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1889 const char *GlobalName){
1890 return GetAddrOfConstantString(str + '\0', GlobalName);
1893 /// EmitObjCPropertyImplementations - Emit information for synthesized
1894 /// properties for an implementation.
1895 void CodeGenModule::EmitObjCPropertyImplementations(const
1896 ObjCImplementationDecl *D) {
1897 for (ObjCImplementationDecl::propimpl_iterator
1898 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
1899 ObjCPropertyImplDecl *PID = *i;
1901 // Dynamic is just for type-checking.
1902 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1903 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1905 // Determine which methods need to be implemented, some may have
1906 // been overridden. Note that ::isSynthesized is not the method
1907 // we want, that just indicates if the decl came from a
1908 // property. What we want to know is if the method is defined in
1909 // this implementation.
1910 if (!D->getInstanceMethod(PD->getGetterName()))
1911 CodeGenFunction(*this).GenerateObjCGetter(
1912 const_cast<ObjCImplementationDecl *>(D), PID);
1913 if (!PD->isReadOnly() &&
1914 !D->getInstanceMethod(PD->getSetterName()))
1915 CodeGenFunction(*this).GenerateObjCSetter(
1916 const_cast<ObjCImplementationDecl *>(D), PID);
1921 /// EmitObjCIvarInitializations - Emit information for ivar initialization
1922 /// for an implementation.
1923 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
1924 if (!Features.NeXTRuntime || D->getNumIvarInitializers() == 0)
1926 DeclContext* DC = const_cast<DeclContext*>(dyn_cast<DeclContext>(D));
1927 assert(DC && "EmitObjCIvarInitializations - null DeclContext");
1928 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
1929 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
1930 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(getContext(),
1932 D->getLocation(), cxxSelector,
1933 getContext().VoidTy, 0,
1934 DC, true, false, true, false,
1935 ObjCMethodDecl::Required);
1936 D->addInstanceMethod(DTORMethod);
1937 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
1939 II = &getContext().Idents.get(".cxx_construct");
1940 cxxSelector = getContext().Selectors.getSelector(0, &II);
1941 // The constructor returns 'self'.
1942 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
1944 D->getLocation(), cxxSelector,
1945 getContext().getObjCIdType(), 0,
1946 DC, true, false, true, false,
1947 ObjCMethodDecl::Required);
1948 D->addInstanceMethod(CTORMethod);
1949 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
1954 /// EmitNamespace - Emit all declarations in a namespace.
1955 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
1956 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
1958 EmitTopLevelDecl(*I);
1961 // EmitLinkageSpec - Emit all declarations in a linkage spec.
1962 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
1963 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
1964 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
1965 ErrorUnsupported(LSD, "linkage spec");
1969 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
1971 EmitTopLevelDecl(*I);
1974 /// EmitTopLevelDecl - Emit code for a single top level declaration.
1975 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1976 // If an error has occurred, stop code generation, but continue
1977 // parsing and semantic analysis (to ensure all warnings and errors
1979 if (Diags.hasErrorOccurred())
1982 // Ignore dependent declarations.
1983 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
1986 switch (D->getKind()) {
1987 case Decl::CXXConversion:
1988 case Decl::CXXMethod:
1989 case Decl::Function:
1990 // Skip function templates
1991 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1994 EmitGlobal(cast<FunctionDecl>(D));
1998 EmitGlobal(cast<VarDecl>(D));
2002 case Decl::Namespace:
2003 EmitNamespace(cast<NamespaceDecl>(D));
2005 // No code generation needed.
2006 case Decl::UsingShadow:
2008 case Decl::UsingDirective:
2009 case Decl::ClassTemplate:
2010 case Decl::FunctionTemplate:
2011 case Decl::NamespaceAlias:
2013 case Decl::CXXConstructor:
2014 // Skip function templates
2015 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
2018 EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2020 case Decl::CXXDestructor:
2021 EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2024 case Decl::StaticAssert:
2028 // Objective-C Decls
2030 // Forward declarations, no (immediate) code generation.
2031 case Decl::ObjCClass:
2032 case Decl::ObjCForwardProtocol:
2033 case Decl::ObjCInterface:
2036 case Decl::ObjCCategory: {
2037 ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
2038 if (CD->IsClassExtension() && CD->hasSynthBitfield())
2039 Context.ResetObjCLayout(CD->getClassInterface());
2044 case Decl::ObjCProtocol:
2045 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
2048 case Decl::ObjCCategoryImpl:
2049 // Categories have properties but don't support synthesize so we
2050 // can ignore them here.
2051 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2054 case Decl::ObjCImplementation: {
2055 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2056 if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
2057 Context.ResetObjCLayout(OMD->getClassInterface());
2058 EmitObjCPropertyImplementations(OMD);
2059 EmitObjCIvarInitializations(OMD);
2060 Runtime->GenerateClass(OMD);
2063 case Decl::ObjCMethod: {
2064 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2065 // If this is not a prototype, emit the body.
2067 CodeGenFunction(*this).GenerateObjCMethod(OMD);
2070 case Decl::ObjCCompatibleAlias:
2071 // compatibility-alias is a directive and has no code gen.
2074 case Decl::LinkageSpec:
2075 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
2078 case Decl::FileScopeAsm: {
2079 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
2080 llvm::StringRef AsmString = AD->getAsmString()->getString();
2082 const std::string &S = getModule().getModuleInlineAsm();
2084 getModule().setModuleInlineAsm(AsmString);
2086 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
2091 // Make sure we handled everything we should, every other kind is a
2092 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
2093 // function. Need to recode Decl::Kind to do that easily.
2094 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2098 /// Turns the given pointer into a constant.
2099 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2101 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2102 const llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2103 return llvm::ConstantInt::get(i64, PtrInt);
2106 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2107 llvm::NamedMDNode *&GlobalMetadata,
2109 llvm::GlobalValue *Addr) {
2110 if (!GlobalMetadata)
2112 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2114 // TODO: should we report variant information for ctors/dtors?
2115 llvm::Value *Ops[] = {
2117 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2119 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops, 2));
2122 /// Emits metadata nodes associating all the global values in the
2123 /// current module with the Decls they came from. This is useful for
2124 /// projects using IR gen as a subroutine.
2126 /// Since there's currently no way to associate an MDNode directly
2127 /// with an llvm::GlobalValue, we create a global named metadata
2128 /// with the name 'clang.global.decl.ptrs'.
2129 void CodeGenModule::EmitDeclMetadata() {
2130 llvm::NamedMDNode *GlobalMetadata = 0;
2132 // StaticLocalDeclMap
2133 for (llvm::DenseMap<GlobalDecl,llvm::StringRef>::iterator
2134 I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2136 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2137 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2141 /// Emits metadata nodes for all the local variables in the current
2143 void CodeGenFunction::EmitDeclMetadata() {
2144 if (LocalDeclMap.empty()) return;
2146 llvm::LLVMContext &Context = getLLVMContext();
2148 // Find the unique metadata ID for this name.
2149 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2151 llvm::NamedMDNode *GlobalMetadata = 0;
2153 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2154 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2155 const Decl *D = I->first;
2156 llvm::Value *Addr = I->second;
2158 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2159 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
2160 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, &DAddr, 1));
2161 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2162 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2163 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2168 ///@name Custom Runtime Function Interfaces
2171 // FIXME: These can be eliminated once we can have clients just get the required
2172 // AST nodes from the builtin tables.
2174 llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2175 if (BlockObjectDispose)
2176 return BlockObjectDispose;
2178 // If we saw an explicit decl, use that.
2179 if (BlockObjectDisposeDecl) {
2180 return BlockObjectDispose = GetAddrOfFunction(
2181 BlockObjectDisposeDecl,
2182 getTypes().GetFunctionType(BlockObjectDisposeDecl));
2185 // Otherwise construct the function by hand.
2186 const llvm::FunctionType *FTy;
2187 std::vector<const llvm::Type*> ArgTys;
2188 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
2189 ArgTys.push_back(Int8PtrTy);
2190 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
2191 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
2192 return BlockObjectDispose =
2193 CreateRuntimeFunction(FTy, "_Block_object_dispose");
2196 llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2197 if (BlockObjectAssign)
2198 return BlockObjectAssign;
2200 // If we saw an explicit decl, use that.
2201 if (BlockObjectAssignDecl) {
2202 return BlockObjectAssign = GetAddrOfFunction(
2203 BlockObjectAssignDecl,
2204 getTypes().GetFunctionType(BlockObjectAssignDecl));
2207 // Otherwise construct the function by hand.
2208 const llvm::FunctionType *FTy;
2209 std::vector<const llvm::Type*> ArgTys;
2210 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
2211 ArgTys.push_back(Int8PtrTy);
2212 ArgTys.push_back(Int8PtrTy);
2213 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
2214 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
2215 return BlockObjectAssign =
2216 CreateRuntimeFunction(FTy, "_Block_object_assign");
2219 llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2220 if (NSConcreteGlobalBlock)
2221 return NSConcreteGlobalBlock;
2223 // If we saw an explicit decl, use that.
2224 if (NSConcreteGlobalBlockDecl) {
2225 return NSConcreteGlobalBlock = GetAddrOfGlobalVar(
2226 NSConcreteGlobalBlockDecl,
2227 getTypes().ConvertType(NSConcreteGlobalBlockDecl->getType()));
2230 // Otherwise construct the variable by hand.
2231 return NSConcreteGlobalBlock =
2232 CreateRuntimeVariable(Int8PtrTy, "_NSConcreteGlobalBlock");
2235 llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2236 if (NSConcreteStackBlock)
2237 return NSConcreteStackBlock;
2239 // If we saw an explicit decl, use that.
2240 if (NSConcreteStackBlockDecl) {
2241 return NSConcreteStackBlock = GetAddrOfGlobalVar(
2242 NSConcreteStackBlockDecl,
2243 getTypes().ConvertType(NSConcreteStackBlockDecl->getType()));
2246 // Otherwise construct the variable by hand.
2247 return NSConcreteStackBlock =
2248 CreateRuntimeVariable(Int8PtrTy, "_NSConcreteStackBlock");