1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This coordinates the per-module state used while generating code.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenModule.h"
15 #include "CGDebugInfo.h"
16 #include "CodeGenFunction.h"
17 #include "CodeGenTBAA.h"
19 #include "CGCUDARuntime.h"
21 #include "CGObjCRuntime.h"
22 #include "CGOpenCLRuntime.h"
23 #include "TargetInfo.h"
24 #include "clang/Frontend/CodeGenOptions.h"
25 #include "clang/AST/ASTContext.h"
26 #include "clang/AST/CharUnits.h"
27 #include "clang/AST/DeclObjC.h"
28 #include "clang/AST/DeclCXX.h"
29 #include "clang/AST/DeclTemplate.h"
30 #include "clang/AST/Mangle.h"
31 #include "clang/AST/RecordLayout.h"
32 #include "clang/AST/RecursiveASTVisitor.h"
33 #include "clang/Basic/Builtins.h"
34 #include "clang/Basic/Diagnostic.h"
35 #include "clang/Basic/SourceManager.h"
36 #include "clang/Basic/TargetInfo.h"
37 #include "clang/Basic/ConvertUTF.h"
38 #include "llvm/CallingConv.h"
39 #include "llvm/Module.h"
40 #include "llvm/Intrinsics.h"
41 #include "llvm/LLVMContext.h"
42 #include "llvm/ADT/APSInt.h"
43 #include "llvm/ADT/Triple.h"
44 #include "llvm/Target/Mangler.h"
45 #include "llvm/DataLayout.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/ErrorHandling.h"
48 using namespace clang;
49 using namespace CodeGen;
51 static const char AnnotationSection[] = "llvm.metadata";
53 static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
54 switch (CGM.getContext().getTargetInfo().getCXXABI()) {
55 case CXXABI_ARM: return *CreateARMCXXABI(CGM);
56 case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
57 case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
60 llvm_unreachable("invalid C++ ABI kind");
64 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
65 llvm::Module &M, const llvm::DataLayout &TD,
66 DiagnosticsEngine &diags)
67 : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
68 TheDataLayout(TD), TheTargetCodeGenInfo(0), Diags(diags),
69 ABI(createCXXABI(*this)),
72 VTables(*this), ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0),
73 DebugInfo(0), ARCData(0), NoObjCARCExceptionsMetadata(0),
74 RRData(0), CFConstantStringClassRef(0),
75 ConstantStringClassRef(0), NSConstantStringType(0),
76 VMContext(M.getContext()),
77 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
78 BlockObjectAssign(0), BlockObjectDispose(0),
79 BlockDescriptorType(0), GenericBlockLiteralType(0) {
81 // Initialize the type cache.
82 llvm::LLVMContext &LLVMContext = M.getContext();
83 VoidTy = llvm::Type::getVoidTy(LLVMContext);
84 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
85 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
86 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
87 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
88 FloatTy = llvm::Type::getFloatTy(LLVMContext);
89 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
90 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
92 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
93 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
94 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
95 Int8PtrTy = Int8Ty->getPointerTo(0);
96 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
101 createOpenCLRuntime();
105 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
106 if (LangOpts.SanitizeThread ||
107 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
108 TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
109 ABI.getMangleContext());
111 // If debug info or coverage generation is enabled, create the CGDebugInfo
113 if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
114 CodeGenOpts.EmitGcovArcs ||
115 CodeGenOpts.EmitGcovNotes)
116 DebugInfo = new CGDebugInfo(*this);
118 Block.GlobalUniqueCount = 0;
120 if (C.getLangOpts().ObjCAutoRefCount)
121 ARCData = new ARCEntrypoints();
122 RRData = new RREntrypoints();
125 CodeGenModule::~CodeGenModule() {
127 delete OpenCLRuntime;
129 delete TheTargetCodeGenInfo;
137 void CodeGenModule::createObjCRuntime() {
138 // This is just isGNUFamily(), but we want to force implementors of
139 // new ABIs to decide how best to do this.
140 switch (LangOpts.ObjCRuntime.getKind()) {
141 case ObjCRuntime::GNUstep:
142 case ObjCRuntime::GCC:
143 case ObjCRuntime::ObjFW:
144 ObjCRuntime = CreateGNUObjCRuntime(*this);
147 case ObjCRuntime::FragileMacOSX:
148 case ObjCRuntime::MacOSX:
149 case ObjCRuntime::iOS:
150 ObjCRuntime = CreateMacObjCRuntime(*this);
153 llvm_unreachable("bad runtime kind");
156 void CodeGenModule::createOpenCLRuntime() {
157 OpenCLRuntime = new CGOpenCLRuntime(*this);
160 void CodeGenModule::createCUDARuntime() {
161 CUDARuntime = CreateNVCUDARuntime(*this);
164 void CodeGenModule::Release() {
166 EmitCXXGlobalInitFunc();
167 EmitCXXGlobalDtorFunc();
169 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
170 AddGlobalCtor(ObjCInitFunction);
171 EmitCtorList(GlobalCtors, "llvm.global_ctors");
172 EmitCtorList(GlobalDtors, "llvm.global_dtors");
173 EmitGlobalAnnotations();
176 SimplifyPersonality();
178 if (getCodeGenOpts().EmitDeclMetadata)
181 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
185 DebugInfo->finalize();
188 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
189 // Make sure that this type is translated.
190 Types.UpdateCompletedType(TD);
193 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
196 return TBAA->getTBAAInfo(QTy);
199 llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
202 return TBAA->getTBAAInfoForVTablePtr();
205 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
208 return TBAA->getTBAAStructInfo(QTy);
211 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
212 llvm::MDNode *TBAAInfo) {
213 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
216 bool CodeGenModule::isTargetDarwin() const {
217 return getContext().getTargetInfo().getTriple().isOSDarwin();
220 void CodeGenModule::Error(SourceLocation loc, StringRef error) {
221 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error);
222 getDiags().Report(Context.getFullLoc(loc), diagID);
225 /// ErrorUnsupported - Print out an error that codegen doesn't support the
226 /// specified stmt yet.
227 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
229 if (OmitOnError && getDiags().hasErrorOccurred())
231 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
232 "cannot compile this %0 yet");
233 std::string Msg = Type;
234 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
235 << Msg << S->getSourceRange();
238 /// ErrorUnsupported - Print out an error that codegen doesn't support the
239 /// specified decl yet.
240 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
242 if (OmitOnError && getDiags().hasErrorOccurred())
244 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
245 "cannot compile this %0 yet");
246 std::string Msg = Type;
247 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
250 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
251 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
254 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
255 const NamedDecl *D) const {
256 // Internal definitions always have default visibility.
257 if (GV->hasLocalLinkage()) {
258 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
262 // Set visibility for definitions.
263 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
264 if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
265 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
268 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
269 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
270 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
271 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
272 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
273 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
276 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
277 CodeGenOptions::TLSModel M) {
279 case CodeGenOptions::GeneralDynamicTLSModel:
280 return llvm::GlobalVariable::GeneralDynamicTLSModel;
281 case CodeGenOptions::LocalDynamicTLSModel:
282 return llvm::GlobalVariable::LocalDynamicTLSModel;
283 case CodeGenOptions::InitialExecTLSModel:
284 return llvm::GlobalVariable::InitialExecTLSModel;
285 case CodeGenOptions::LocalExecTLSModel:
286 return llvm::GlobalVariable::LocalExecTLSModel;
288 llvm_unreachable("Invalid TLS model!");
291 void CodeGenModule::setTLSMode(llvm::GlobalVariable *GV,
292 const VarDecl &D) const {
293 assert(D.isThreadSpecified() && "setting TLS mode on non-TLS var!");
295 llvm::GlobalVariable::ThreadLocalMode TLM;
296 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
298 // Override the TLS model if it is explicitly specified.
299 if (D.hasAttr<TLSModelAttr>()) {
300 const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>();
301 TLM = GetLLVMTLSModel(Attr->getModel());
304 GV->setThreadLocalMode(TLM);
307 /// Set the symbol visibility of type information (vtable and RTTI)
308 /// associated with the given type.
309 void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
310 const CXXRecordDecl *RD,
311 TypeVisibilityKind TVK) const {
312 setGlobalVisibility(GV, RD);
314 if (!CodeGenOpts.HiddenWeakVTables)
317 // We never want to drop the visibility for RTTI names.
318 if (TVK == TVK_ForRTTIName)
321 // We want to drop the visibility to hidden for weak type symbols.
322 // This isn't possible if there might be unresolved references
323 // elsewhere that rely on this symbol being visible.
325 // This should be kept roughly in sync with setThunkVisibility
329 if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
330 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
333 // Don't override an explicit visibility attribute.
334 if (RD->getExplicitVisibility())
337 switch (RD->getTemplateSpecializationKind()) {
338 // We have to disable the optimization if this is an EI definition
339 // because there might be EI declarations in other shared objects.
340 case TSK_ExplicitInstantiationDefinition:
341 case TSK_ExplicitInstantiationDeclaration:
344 // Every use of a non-template class's type information has to emit it.
348 // In theory, implicit instantiations can ignore the possibility of
349 // an explicit instantiation declaration because there necessarily
350 // must be an EI definition somewhere with default visibility. In
351 // practice, it's possible to have an explicit instantiation for
352 // an arbitrary template class, and linkers aren't necessarily able
353 // to deal with mixed-visibility symbols.
354 case TSK_ExplicitSpecialization:
355 case TSK_ImplicitInstantiation:
359 // If there's a key function, there may be translation units
360 // that don't have the key function's definition. But ignore
361 // this if we're emitting RTTI under -fno-rtti.
362 if (!(TVK != TVK_ForRTTI) || LangOpts.RTTI) {
363 if (Context.getKeyFunction(RD))
367 // Otherwise, drop the visibility to hidden.
368 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
369 GV->setUnnamedAddr(true);
372 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
373 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
375 StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
379 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
380 IdentifierInfo *II = ND->getIdentifier();
381 assert(II && "Attempt to mangle unnamed decl.");
387 SmallString<256> Buffer;
388 llvm::raw_svector_ostream Out(Buffer);
389 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
390 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
391 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
392 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
393 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
394 getCXXABI().getMangleContext().mangleBlock(BD, Out,
395 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()));
397 getCXXABI().getMangleContext().mangleName(ND, Out);
399 // Allocate space for the mangled name.
401 size_t Length = Buffer.size();
402 char *Name = MangledNamesAllocator.Allocate<char>(Length);
403 std::copy(Buffer.begin(), Buffer.end(), Name);
405 Str = StringRef(Name, Length);
410 void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
411 const BlockDecl *BD) {
412 MangleContext &MangleCtx = getCXXABI().getMangleContext();
413 const Decl *D = GD.getDecl();
414 llvm::raw_svector_ostream Out(Buffer.getBuffer());
416 MangleCtx.mangleGlobalBlock(BD,
417 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
418 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
419 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
420 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
421 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
423 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
426 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
427 return getModule().getNamedValue(Name);
430 /// AddGlobalCtor - Add a function to the list that will be called before
432 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
433 // FIXME: Type coercion of void()* types.
434 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
437 /// AddGlobalDtor - Add a function to the list that will be called
438 /// when the module is unloaded.
439 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
440 // FIXME: Type coercion of void()* types.
441 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
444 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
445 // Ctor function type is void()*.
446 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
447 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
449 // Get the type of a ctor entry, { i32, void ()* }.
450 llvm::StructType *CtorStructTy =
451 llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL);
453 // Construct the constructor and destructor arrays.
454 SmallVector<llvm::Constant*, 8> Ctors;
455 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
456 llvm::Constant *S[] = {
457 llvm::ConstantInt::get(Int32Ty, I->second, false),
458 llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)
460 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
463 if (!Ctors.empty()) {
464 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
465 new llvm::GlobalVariable(TheModule, AT, false,
466 llvm::GlobalValue::AppendingLinkage,
467 llvm::ConstantArray::get(AT, Ctors),
472 llvm::GlobalValue::LinkageTypes
473 CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
474 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
476 if (Linkage == GVA_Internal)
477 return llvm::Function::InternalLinkage;
479 if (D->hasAttr<DLLExportAttr>())
480 return llvm::Function::DLLExportLinkage;
482 if (D->hasAttr<WeakAttr>())
483 return llvm::Function::WeakAnyLinkage;
485 // In C99 mode, 'inline' functions are guaranteed to have a strong
486 // definition somewhere else, so we can use available_externally linkage.
487 if (Linkage == GVA_C99Inline)
488 return llvm::Function::AvailableExternallyLinkage;
490 // Note that Apple's kernel linker doesn't support symbol
491 // coalescing, so we need to avoid linkonce and weak linkages there.
492 // Normally, this means we just map to internal, but for explicit
493 // instantiations we'll map to external.
495 // In C++, the compiler has to emit a definition in every translation unit
496 // that references the function. We should use linkonce_odr because
497 // a) if all references in this translation unit are optimized away, we
498 // don't need to codegen it. b) if the function persists, it needs to be
499 // merged with other definitions. c) C++ has the ODR, so we know the
500 // definition is dependable.
501 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
502 return !Context.getLangOpts().AppleKext
503 ? llvm::Function::LinkOnceODRLinkage
504 : llvm::Function::InternalLinkage;
506 // An explicit instantiation of a template has weak linkage, since
507 // explicit instantiations can occur in multiple translation units
508 // and must all be equivalent. However, we are not allowed to
509 // throw away these explicit instantiations.
510 if (Linkage == GVA_ExplicitTemplateInstantiation)
511 return !Context.getLangOpts().AppleKext
512 ? llvm::Function::WeakODRLinkage
513 : llvm::Function::ExternalLinkage;
515 // Otherwise, we have strong external linkage.
516 assert(Linkage == GVA_StrongExternal);
517 return llvm::Function::ExternalLinkage;
521 /// SetFunctionDefinitionAttributes - Set attributes for a global.
523 /// FIXME: This is currently only done for aliases and functions, but not for
524 /// variables (these details are set in EmitGlobalVarDefinition for variables).
525 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
526 llvm::GlobalValue *GV) {
527 SetCommonAttributes(D, GV);
530 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
531 const CGFunctionInfo &Info,
533 unsigned CallingConv;
534 AttributeListType AttributeList;
535 ConstructAttributeList(Info, D, AttributeList, CallingConv);
536 F->setAttributes(llvm::AttrListPtr::get(getLLVMContext(), AttributeList));
537 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
540 /// Determines whether the language options require us to model
541 /// unwind exceptions. We treat -fexceptions as mandating this
542 /// except under the fragile ObjC ABI with only ObjC exceptions
543 /// enabled. This means, for example, that C with -fexceptions
545 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
546 // If exceptions are completely disabled, obviously this is false.
547 if (!LangOpts.Exceptions) return false;
549 // If C++ exceptions are enabled, this is true.
550 if (LangOpts.CXXExceptions) return true;
552 // If ObjC exceptions are enabled, this depends on the ABI.
553 if (LangOpts.ObjCExceptions) {
554 return LangOpts.ObjCRuntime.hasUnwindExceptions();
560 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
562 if (CodeGenOpts.UnwindTables)
565 if (!hasUnwindExceptions(LangOpts))
566 F->addFnAttr(llvm::Attributes::NoUnwind);
568 if (D->hasAttr<NakedAttr>()) {
569 // Naked implies noinline: we should not be inlining such functions.
570 F->addFnAttr(llvm::Attributes::Naked);
571 F->addFnAttr(llvm::Attributes::NoInline);
574 if (D->hasAttr<NoInlineAttr>())
575 F->addFnAttr(llvm::Attributes::NoInline);
577 // (noinline wins over always_inline, and we can't specify both in IR)
578 if ((D->hasAttr<AlwaysInlineAttr>() || D->hasAttr<ForceInlineAttr>()) &&
579 !F->getFnAttributes().hasAttribute(llvm::Attributes::NoInline))
580 F->addFnAttr(llvm::Attributes::AlwaysInline);
582 // FIXME: Communicate hot and cold attributes to LLVM more directly.
583 if (D->hasAttr<ColdAttr>())
584 F->addFnAttr(llvm::Attributes::OptimizeForSize);
586 if (D->hasAttr<MinSizeAttr>())
587 F->addFnAttr(llvm::Attributes::MinSize);
589 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
590 F->setUnnamedAddr(true);
592 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
594 F->setUnnamedAddr(true);
596 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
597 F->addFnAttr(llvm::Attributes::StackProtect);
598 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
599 F->addFnAttr(llvm::Attributes::StackProtectReq);
601 if (LangOpts.SanitizeAddress) {
602 // When AddressSanitizer is enabled, set AddressSafety attribute
603 // unless __attribute__((no_address_safety_analysis)) is used.
604 if (!D->hasAttr<NoAddressSafetyAnalysisAttr>())
605 F->addFnAttr(llvm::Attributes::AddressSafety);
608 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
610 F->setAlignment(alignment);
612 // C++ ABI requires 2-byte alignment for member functions.
613 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
617 void CodeGenModule::SetCommonAttributes(const Decl *D,
618 llvm::GlobalValue *GV) {
619 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
620 setGlobalVisibility(GV, ND);
622 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
624 if (D->hasAttr<UsedAttr>())
627 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
628 GV->setSection(SA->getName());
630 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
633 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
635 const CGFunctionInfo &FI) {
636 SetLLVMFunctionAttributes(D, FI, F);
637 SetLLVMFunctionAttributesForDefinition(D, F);
639 F->setLinkage(llvm::Function::InternalLinkage);
641 SetCommonAttributes(D, F);
644 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
646 bool IsIncompleteFunction) {
647 if (unsigned IID = F->getIntrinsicID()) {
648 // If this is an intrinsic function, set the function's attributes
649 // to the intrinsic's attributes.
650 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(),
651 (llvm::Intrinsic::ID)IID));
655 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
657 if (!IsIncompleteFunction)
658 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
660 // Only a few attributes are set on declarations; these may later be
661 // overridden by a definition.
663 if (FD->hasAttr<DLLImportAttr>()) {
664 F->setLinkage(llvm::Function::DLLImportLinkage);
665 } else if (FD->hasAttr<WeakAttr>() ||
666 FD->isWeakImported()) {
667 // "extern_weak" is overloaded in LLVM; we probably should have
668 // separate linkage types for this.
669 F->setLinkage(llvm::Function::ExternalWeakLinkage);
671 F->setLinkage(llvm::Function::ExternalLinkage);
673 NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
674 if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
675 F->setVisibility(GetLLVMVisibility(LV.visibility()));
679 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
680 F->setSection(SA->getName());
683 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
684 assert(!GV->isDeclaration() &&
685 "Only globals with definition can force usage.");
686 LLVMUsed.push_back(GV);
689 void CodeGenModule::EmitLLVMUsed() {
690 // Don't create llvm.used if there is no need.
691 if (LLVMUsed.empty())
694 // Convert LLVMUsed to what ConstantArray needs.
695 SmallVector<llvm::Constant*, 8> UsedArray;
696 UsedArray.resize(LLVMUsed.size());
697 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
699 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
703 if (UsedArray.empty())
705 llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
707 llvm::GlobalVariable *GV =
708 new llvm::GlobalVariable(getModule(), ATy, false,
709 llvm::GlobalValue::AppendingLinkage,
710 llvm::ConstantArray::get(ATy, UsedArray),
713 GV->setSection("llvm.metadata");
716 void CodeGenModule::EmitDeferred() {
717 // Emit code for any potentially referenced deferred decls. Since a
718 // previously unused static decl may become used during the generation of code
719 // for a static function, iterate until no changes are made.
721 while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
722 if (!DeferredVTables.empty()) {
723 const CXXRecordDecl *RD = DeferredVTables.back();
724 DeferredVTables.pop_back();
725 getCXXABI().EmitVTables(RD);
729 GlobalDecl D = DeferredDeclsToEmit.back();
730 DeferredDeclsToEmit.pop_back();
732 // Check to see if we've already emitted this. This is necessary
733 // for a couple of reasons: first, decls can end up in the
734 // deferred-decls queue multiple times, and second, decls can end
735 // up with definitions in unusual ways (e.g. by an extern inline
736 // function acquiring a strong function redefinition). Just
737 // ignore these cases.
739 // TODO: That said, looking this up multiple times is very wasteful.
740 StringRef Name = getMangledName(D);
741 llvm::GlobalValue *CGRef = GetGlobalValue(Name);
742 assert(CGRef && "Deferred decl wasn't referenced?");
744 if (!CGRef->isDeclaration())
747 // GlobalAlias::isDeclaration() defers to the aliasee, but for our
748 // purposes an alias counts as a definition.
749 if (isa<llvm::GlobalAlias>(CGRef))
752 // Otherwise, emit the definition and move on to the next one.
753 EmitGlobalDefinition(D);
757 void CodeGenModule::EmitGlobalAnnotations() {
758 if (Annotations.empty())
761 // Create a new global variable for the ConstantStruct in the Module.
762 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
763 Annotations[0]->getType(), Annotations.size()), Annotations);
764 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
765 Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
766 "llvm.global.annotations");
767 gv->setSection(AnnotationSection);
770 llvm::Constant *CodeGenModule::EmitAnnotationString(llvm::StringRef Str) {
771 llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str);
772 if (i != AnnotationStrings.end())
775 // Not found yet, create a new global.
776 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
777 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
778 true, llvm::GlobalValue::PrivateLinkage, s, ".str");
779 gv->setSection(AnnotationSection);
780 gv->setUnnamedAddr(true);
781 AnnotationStrings[Str] = gv;
785 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
786 SourceManager &SM = getContext().getSourceManager();
787 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
789 return EmitAnnotationString(PLoc.getFilename());
790 return EmitAnnotationString(SM.getBufferName(Loc));
793 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
794 SourceManager &SM = getContext().getSourceManager();
795 PresumedLoc PLoc = SM.getPresumedLoc(L);
796 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
797 SM.getExpansionLineNumber(L);
798 return llvm::ConstantInt::get(Int32Ty, LineNo);
801 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
802 const AnnotateAttr *AA,
804 // Get the globals for file name, annotation, and the line number.
805 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
806 *UnitGV = EmitAnnotationUnit(L),
807 *LineNoCst = EmitAnnotationLineNo(L);
809 // Create the ConstantStruct for the global annotation.
810 llvm::Constant *Fields[4] = {
811 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
812 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
813 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
816 return llvm::ConstantStruct::getAnon(Fields);
819 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
820 llvm::GlobalValue *GV) {
821 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
822 // Get the struct elements for these annotations.
823 for (specific_attr_iterator<AnnotateAttr>
824 ai = D->specific_attr_begin<AnnotateAttr>(),
825 ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
826 Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
829 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
830 // Never defer when EmitAllDecls is specified.
831 if (LangOpts.EmitAllDecls)
834 return !getContext().DeclMustBeEmitted(Global);
837 llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
838 const CXXUuidofExpr* E) {
839 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
842 if (E->isTypeOperand())
843 Uuid = CXXUuidofExpr::GetUuidAttrOfType(E->getTypeOperand())->getGuid();
845 // Special case: __uuidof(0) means an all-zero GUID.
846 Expr *Op = E->getExprOperand();
847 if (!Op->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
848 Uuid = CXXUuidofExpr::GetUuidAttrOfType(Op->getType())->getGuid();
850 Uuid = "00000000-0000-0000-0000-000000000000";
852 std::string Name = "__uuid_" + Uuid.str();
854 // Look for an existing global.
855 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
858 llvm::Constant *Init = EmitUuidofInitializer(Uuid, E->getType());
859 assert(Init && "failed to initialize as constant");
861 // GUIDs are assumed to be 16 bytes, spread over 4-2-2-8 bytes. However, the
862 // first field is declared as "long", which for many targets is 8 bytes.
863 // Those architectures are not supported. (With the MS abi, long is always 4
865 llvm::Type *GuidType = getTypes().ConvertType(E->getType());
866 if (Init->getType() != GuidType) {
867 DiagnosticsEngine &Diags = getDiags();
868 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
869 "__uuidof codegen is not supported on this architecture");
870 Diags.Report(E->getExprLoc(), DiagID) << E->getSourceRange();
871 Init = llvm::UndefValue::get(GuidType);
874 llvm::GlobalVariable *GV = new llvm::GlobalVariable(getModule(), GuidType,
875 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, Init, Name);
876 GV->setUnnamedAddr(true);
880 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
881 const AliasAttr *AA = VD->getAttr<AliasAttr>();
882 assert(AA && "No alias?");
884 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
886 // See if there is already something with the target's name in the module.
887 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
889 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
890 return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
893 llvm::Constant *Aliasee;
894 if (isa<llvm::FunctionType>(DeclTy))
895 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
896 GlobalDecl(cast<FunctionDecl>(VD)),
897 /*ForVTable=*/false);
899 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
900 llvm::PointerType::getUnqual(DeclTy), 0);
902 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
903 F->setLinkage(llvm::Function::ExternalWeakLinkage);
904 WeakRefReferences.insert(F);
909 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
910 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
912 // Weak references don't produce any output by themselves.
913 if (Global->hasAttr<WeakRefAttr>())
916 // If this is an alias definition (which otherwise looks like a declaration)
918 if (Global->hasAttr<AliasAttr>())
919 return EmitAliasDefinition(GD);
921 // If this is CUDA, be selective about which declarations we emit.
923 if (CodeGenOpts.CUDAIsDevice) {
924 if (!Global->hasAttr<CUDADeviceAttr>() &&
925 !Global->hasAttr<CUDAGlobalAttr>() &&
926 !Global->hasAttr<CUDAConstantAttr>() &&
927 !Global->hasAttr<CUDASharedAttr>())
930 if (!Global->hasAttr<CUDAHostAttr>() && (
931 Global->hasAttr<CUDADeviceAttr>() ||
932 Global->hasAttr<CUDAConstantAttr>() ||
933 Global->hasAttr<CUDASharedAttr>()))
938 // Ignore declarations, they will be emitted on their first use.
939 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
940 // Forward declarations are emitted lazily on first use.
941 if (!FD->doesThisDeclarationHaveABody()) {
942 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
945 const FunctionDecl *InlineDefinition = 0;
946 FD->getBody(InlineDefinition);
948 StringRef MangledName = getMangledName(GD);
949 DeferredDecls.erase(MangledName);
950 EmitGlobalDefinition(InlineDefinition);
954 const VarDecl *VD = cast<VarDecl>(Global);
955 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
957 if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
961 // Defer code generation when possible if this is a static definition, inline
962 // function etc. These we only want to emit if they are used.
963 if (!MayDeferGeneration(Global)) {
964 // Emit the definition if it can't be deferred.
965 EmitGlobalDefinition(GD);
969 // If we're deferring emission of a C++ variable with an
970 // initializer, remember the order in which it appeared in the file.
971 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
972 cast<VarDecl>(Global)->hasInit()) {
973 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
974 CXXGlobalInits.push_back(0);
977 // If the value has already been used, add it directly to the
978 // DeferredDeclsToEmit list.
979 StringRef MangledName = getMangledName(GD);
980 if (GetGlobalValue(MangledName))
981 DeferredDeclsToEmit.push_back(GD);
983 // Otherwise, remember that we saw a deferred decl with this name. The
984 // first use of the mangled name will cause it to move into
985 // DeferredDeclsToEmit.
986 DeferredDecls[MangledName] = GD;
991 struct FunctionIsDirectlyRecursive :
992 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
993 const StringRef Name;
994 const Builtin::Context &BI;
996 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
997 Name(N), BI(C), Result(false) {
999 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1001 bool TraverseCallExpr(CallExpr *E) {
1002 const FunctionDecl *FD = E->getDirectCallee();
1005 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1006 if (Attr && Name == Attr->getLabel()) {
1010 unsigned BuiltinID = FD->getBuiltinID();
1013 StringRef BuiltinName = BI.GetName(BuiltinID);
1014 if (BuiltinName.startswith("__builtin_") &&
1015 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1024 // isTriviallyRecursive - Check if this function calls another
1025 // decl that, because of the asm attribute or the other decl being a builtin,
1026 // ends up pointing to itself.
1028 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1030 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1031 // asm labels are a special kind of mangling we have to support.
1032 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1035 Name = Attr->getLabel();
1037 Name = FD->getName();
1040 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1041 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1042 return Walker.Result;
1046 CodeGenModule::shouldEmitFunction(const FunctionDecl *F) {
1047 if (getFunctionLinkage(F) != llvm::Function::AvailableExternallyLinkage)
1049 if (CodeGenOpts.OptimizationLevel == 0 &&
1050 !F->hasAttr<AlwaysInlineAttr>() && !F->hasAttr<ForceInlineAttr>())
1052 // PR9614. Avoid cases where the source code is lying to us. An available
1053 // externally function should have an equivalent function somewhere else,
1054 // but a function that calls itself is clearly not equivalent to the real
1056 // This happens in glibc's btowc and in some configure checks.
1057 return !isTriviallyRecursive(F);
1060 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
1061 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
1063 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1064 Context.getSourceManager(),
1065 "Generating code for declaration");
1067 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1068 // At -O0, don't generate IR for functions with available_externally
1070 if (!shouldEmitFunction(Function))
1073 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
1074 // Make sure to emit the definition(s) before we emit the thunks.
1075 // This is necessary for the generation of certain thunks.
1076 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
1077 EmitCXXConstructor(CD, GD.getCtorType());
1078 else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
1079 EmitCXXDestructor(DD, GD.getDtorType());
1081 EmitGlobalFunctionDefinition(GD);
1083 if (Method->isVirtual())
1084 getVTables().EmitThunks(GD);
1089 return EmitGlobalFunctionDefinition(GD);
1092 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1093 return EmitGlobalVarDefinition(VD);
1095 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1098 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1099 /// module, create and return an llvm Function with the specified type. If there
1100 /// is something in the module with the specified name, return it potentially
1101 /// bitcasted to the right type.
1103 /// If D is non-null, it specifies a decl that correspond to this. This is used
1104 /// to set the attributes on the function when it is first created.
1106 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
1108 GlobalDecl D, bool ForVTable,
1109 llvm::Attributes ExtraAttrs) {
1110 // Lookup the entry, lazily creating it if necessary.
1111 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1113 if (WeakRefReferences.erase(Entry)) {
1114 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
1115 if (FD && !FD->hasAttr<WeakAttr>())
1116 Entry->setLinkage(llvm::Function::ExternalLinkage);
1119 if (Entry->getType()->getElementType() == Ty)
1122 // Make sure the result is of the correct type.
1123 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1126 // This function doesn't have a complete type (for example, the return
1127 // type is an incomplete struct). Use a fake type instead, and make
1128 // sure not to try to set attributes.
1129 bool IsIncompleteFunction = false;
1131 llvm::FunctionType *FTy;
1132 if (isa<llvm::FunctionType>(Ty)) {
1133 FTy = cast<llvm::FunctionType>(Ty);
1135 FTy = llvm::FunctionType::get(VoidTy, false);
1136 IsIncompleteFunction = true;
1139 llvm::Function *F = llvm::Function::Create(FTy,
1140 llvm::Function::ExternalLinkage,
1141 MangledName, &getModule());
1142 assert(F->getName() == MangledName && "name was uniqued!");
1144 SetFunctionAttributes(D, F, IsIncompleteFunction);
1145 if (ExtraAttrs.hasAttributes())
1146 F->addAttribute(llvm::AttrListPtr::FunctionIndex, ExtraAttrs);
1148 // This is the first use or definition of a mangled name. If there is a
1149 // deferred decl with this name, remember that we need to emit it at the end
1151 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1152 if (DDI != DeferredDecls.end()) {
1153 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1154 // list, and remove it from DeferredDecls (since we don't need it anymore).
1155 DeferredDeclsToEmit.push_back(DDI->second);
1156 DeferredDecls.erase(DDI);
1158 // Otherwise, there are cases we have to worry about where we're
1159 // using a declaration for which we must emit a definition but where
1160 // we might not find a top-level definition:
1161 // - member functions defined inline in their classes
1162 // - friend functions defined inline in some class
1163 // - special member functions with implicit definitions
1164 // If we ever change our AST traversal to walk into class methods,
1165 // this will be unnecessary.
1167 // We also don't emit a definition for a function if it's going to be an entry
1168 // in a vtable, unless it's already marked as used.
1169 } else if (getLangOpts().CPlusPlus && D.getDecl()) {
1170 // Look for a declaration that's lexically in a record.
1171 const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
1172 FD = FD->getMostRecentDecl();
1174 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
1175 if (FD->isImplicit() && !ForVTable) {
1176 assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
1177 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
1179 } else if (FD->doesThisDeclarationHaveABody()) {
1180 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
1184 FD = FD->getPreviousDecl();
1188 // Make sure the result is of the requested type.
1189 if (!IsIncompleteFunction) {
1190 assert(F->getType()->getElementType() == Ty);
1194 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1195 return llvm::ConstantExpr::getBitCast(F, PTy);
1198 /// GetAddrOfFunction - Return the address of the given function. If Ty is
1199 /// non-null, then this function will use the specified type if it has to
1200 /// create it (this occurs when we see a definition of the function).
1201 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
1204 // If there was no specific requested type, just convert it now.
1206 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
1208 StringRef MangledName = getMangledName(GD);
1209 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
1212 /// CreateRuntimeFunction - Create a new runtime function with the specified
1215 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
1217 llvm::Attributes ExtraAttrs) {
1218 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1222 /// isTypeConstant - Determine whether an object of this type can be emitted
1225 /// If ExcludeCtor is true, the duration when the object's constructor runs
1226 /// will not be considered. The caller will need to verify that the object is
1227 /// not written to during its construction.
1228 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1229 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
1232 if (Context.getLangOpts().CPlusPlus) {
1233 if (const CXXRecordDecl *Record
1234 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1235 return ExcludeCtor && !Record->hasMutableFields() &&
1236 Record->hasTrivialDestructor();
1242 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1243 /// create and return an llvm GlobalVariable with the specified type. If there
1244 /// is something in the module with the specified name, return it potentially
1245 /// bitcasted to the right type.
1247 /// If D is non-null, it specifies a decl that correspond to this. This is used
1248 /// to set the attributes on the global when it is first created.
1250 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
1251 llvm::PointerType *Ty,
1254 // Lookup the entry, lazily creating it if necessary.
1255 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1257 if (WeakRefReferences.erase(Entry)) {
1258 if (D && !D->hasAttr<WeakAttr>())
1259 Entry->setLinkage(llvm::Function::ExternalLinkage);
1263 Entry->setUnnamedAddr(true);
1265 if (Entry->getType() == Ty)
1268 // Make sure the result is of the correct type.
1269 return llvm::ConstantExpr::getBitCast(Entry, Ty);
1272 // This is the first use or definition of a mangled name. If there is a
1273 // deferred decl with this name, remember that we need to emit it at the end
1275 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1276 if (DDI != DeferredDecls.end()) {
1277 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1278 // list, and remove it from DeferredDecls (since we don't need it anymore).
1279 DeferredDeclsToEmit.push_back(DDI->second);
1280 DeferredDecls.erase(DDI);
1283 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
1284 llvm::GlobalVariable *GV =
1285 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
1286 llvm::GlobalValue::ExternalLinkage,
1288 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
1290 // Handle things which are present even on external declarations.
1292 // FIXME: This code is overly simple and should be merged with other global
1294 GV->setConstant(isTypeConstant(D->getType(), false));
1296 // Set linkage and visibility in case we never see a definition.
1297 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
1298 if (LV.linkage() != ExternalLinkage) {
1299 // Don't set internal linkage on declarations.
1301 if (D->hasAttr<DLLImportAttr>())
1302 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
1303 else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
1304 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1306 // Set visibility on a declaration only if it's explicit.
1307 if (LV.visibilityExplicit())
1308 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
1311 if (D->isThreadSpecified())
1315 if (AddrSpace != Ty->getAddressSpace())
1316 return llvm::ConstantExpr::getBitCast(GV, Ty);
1322 llvm::GlobalVariable *
1323 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
1325 llvm::GlobalValue::LinkageTypes Linkage) {
1326 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1327 llvm::GlobalVariable *OldGV = 0;
1331 // Check if the variable has the right type.
1332 if (GV->getType()->getElementType() == Ty)
1335 // Because C++ name mangling, the only way we can end up with an already
1336 // existing global with the same name is if it has been declared extern "C".
1337 assert(GV->isDeclaration() && "Declaration has wrong type!");
1341 // Create a new variable.
1342 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1346 // Replace occurrences of the old variable if needed.
1347 GV->takeName(OldGV);
1349 if (!OldGV->use_empty()) {
1350 llvm::Constant *NewPtrForOldDecl =
1351 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1352 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1355 OldGV->eraseFromParent();
1361 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1362 /// given global variable. If Ty is non-null and if the global doesn't exist,
1363 /// then it will be created with the specified type instead of whatever the
1364 /// normal requested type would be.
1365 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1367 assert(D->hasGlobalStorage() && "Not a global variable");
1368 QualType ASTTy = D->getType();
1370 Ty = getTypes().ConvertTypeForMem(ASTTy);
1372 llvm::PointerType *PTy =
1373 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1375 StringRef MangledName = getMangledName(D);
1376 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
1379 /// CreateRuntimeVariable - Create a new runtime global variable with the
1380 /// specified type and name.
1382 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
1384 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
1388 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1389 assert(!D->getInit() && "Cannot emit definite definitions here!");
1391 if (MayDeferGeneration(D)) {
1392 // If we have not seen a reference to this variable yet, place it
1393 // into the deferred declarations table to be emitted if needed
1395 StringRef MangledName = getMangledName(D);
1396 if (!GetGlobalValue(MangledName)) {
1397 DeferredDecls[MangledName] = D;
1402 // The tentative definition is the only definition.
1403 EmitGlobalVarDefinition(D);
1406 void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
1407 if (DefinitionRequired)
1408 getCXXABI().EmitVTables(Class);
1411 llvm::GlobalVariable::LinkageTypes
1412 CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
1413 if (RD->getLinkage() != ExternalLinkage)
1414 return llvm::GlobalVariable::InternalLinkage;
1416 if (const CXXMethodDecl *KeyFunction
1417 = RD->getASTContext().getKeyFunction(RD)) {
1418 // If this class has a key function, use that to determine the linkage of
1420 const FunctionDecl *Def = 0;
1421 if (KeyFunction->hasBody(Def))
1422 KeyFunction = cast<CXXMethodDecl>(Def);
1424 switch (KeyFunction->getTemplateSpecializationKind()) {
1425 case TSK_Undeclared:
1426 case TSK_ExplicitSpecialization:
1427 // When compiling with optimizations turned on, we emit all vtables,
1428 // even if the key function is not defined in the current translation
1429 // unit. If this is the case, use available_externally linkage.
1430 if (!Def && CodeGenOpts.OptimizationLevel)
1431 return llvm::GlobalVariable::AvailableExternallyLinkage;
1433 if (KeyFunction->isInlined())
1434 return !Context.getLangOpts().AppleKext ?
1435 llvm::GlobalVariable::LinkOnceODRLinkage :
1436 llvm::Function::InternalLinkage;
1438 return llvm::GlobalVariable::ExternalLinkage;
1440 case TSK_ImplicitInstantiation:
1441 return !Context.getLangOpts().AppleKext ?
1442 llvm::GlobalVariable::LinkOnceODRLinkage :
1443 llvm::Function::InternalLinkage;
1445 case TSK_ExplicitInstantiationDefinition:
1446 return !Context.getLangOpts().AppleKext ?
1447 llvm::GlobalVariable::WeakODRLinkage :
1448 llvm::Function::InternalLinkage;
1450 case TSK_ExplicitInstantiationDeclaration:
1451 // FIXME: Use available_externally linkage. However, this currently
1452 // breaks LLVM's build due to undefined symbols.
1453 // return llvm::GlobalVariable::AvailableExternallyLinkage;
1454 return !Context.getLangOpts().AppleKext ?
1455 llvm::GlobalVariable::LinkOnceODRLinkage :
1456 llvm::Function::InternalLinkage;
1460 if (Context.getLangOpts().AppleKext)
1461 return llvm::Function::InternalLinkage;
1463 switch (RD->getTemplateSpecializationKind()) {
1464 case TSK_Undeclared:
1465 case TSK_ExplicitSpecialization:
1466 case TSK_ImplicitInstantiation:
1467 // FIXME: Use available_externally linkage. However, this currently
1468 // breaks LLVM's build due to undefined symbols.
1469 // return llvm::GlobalVariable::AvailableExternallyLinkage;
1470 case TSK_ExplicitInstantiationDeclaration:
1471 return llvm::GlobalVariable::LinkOnceODRLinkage;
1473 case TSK_ExplicitInstantiationDefinition:
1474 return llvm::GlobalVariable::WeakODRLinkage;
1477 llvm_unreachable("Invalid TemplateSpecializationKind!");
1480 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
1481 return Context.toCharUnitsFromBits(
1482 TheDataLayout.getTypeStoreSizeInBits(Ty));
1486 CodeGenModule::MaybeEmitGlobalStdInitializerListInitializer(const VarDecl *D,
1487 const Expr *rawInit) {
1488 ArrayRef<ExprWithCleanups::CleanupObject> cleanups;
1489 if (const ExprWithCleanups *withCleanups =
1490 dyn_cast<ExprWithCleanups>(rawInit)) {
1491 cleanups = withCleanups->getObjects();
1492 rawInit = withCleanups->getSubExpr();
1495 const InitListExpr *init = dyn_cast<InitListExpr>(rawInit);
1496 if (!init || !init->initializesStdInitializerList() ||
1497 init->getNumInits() == 0)
1500 ASTContext &ctx = getContext();
1501 unsigned numInits = init->getNumInits();
1502 // FIXME: This check is here because we would otherwise silently miscompile
1503 // nested global std::initializer_lists. Better would be to have a real
1505 for (unsigned i = 0; i < numInits; ++i) {
1506 const InitListExpr *inner = dyn_cast<InitListExpr>(init->getInit(i));
1507 if (inner && inner->initializesStdInitializerList()) {
1508 ErrorUnsupported(inner, "nested global std::initializer_list");
1513 // Synthesize a fake VarDecl for the array and initialize that.
1514 QualType elementType = init->getInit(0)->getType();
1515 llvm::APInt numElements(ctx.getTypeSize(ctx.getSizeType()), numInits);
1516 QualType arrayType = ctx.getConstantArrayType(elementType, numElements,
1517 ArrayType::Normal, 0);
1519 IdentifierInfo *name = &ctx.Idents.get(D->getNameAsString() + "__initlist");
1520 TypeSourceInfo *sourceInfo = ctx.getTrivialTypeSourceInfo(
1521 arrayType, D->getLocation());
1522 VarDecl *backingArray = VarDecl::Create(ctx, const_cast<DeclContext*>(
1523 D->getDeclContext()),
1524 D->getLocStart(), D->getLocation(),
1525 name, arrayType, sourceInfo,
1526 SC_Static, SC_Static);
1528 // Now clone the InitListExpr to initialize the array instead.
1529 // Incredible hack: we want to use the existing InitListExpr here, so we need
1530 // to tell it that it no longer initializes a std::initializer_list.
1531 ArrayRef<Expr*> Inits(const_cast<InitListExpr*>(init)->getInits(),
1532 init->getNumInits());
1533 Expr *arrayInit = new (ctx) InitListExpr(ctx, init->getLBraceLoc(), Inits,
1534 init->getRBraceLoc());
1535 arrayInit->setType(arrayType);
1537 if (!cleanups.empty())
1538 arrayInit = ExprWithCleanups::Create(ctx, arrayInit, cleanups);
1540 backingArray->setInit(arrayInit);
1542 // Emit the definition of the array.
1543 EmitGlobalVarDefinition(backingArray);
1545 // Inspect the initializer list to validate it and determine its type.
1546 // FIXME: doing this every time is probably inefficient; caching would be nice
1547 RecordDecl *record = init->getType()->castAs<RecordType>()->getDecl();
1548 RecordDecl::field_iterator field = record->field_begin();
1549 if (field == record->field_end()) {
1550 ErrorUnsupported(D, "weird std::initializer_list");
1553 QualType elementPtr = ctx.getPointerType(elementType.withConst());
1555 if (!ctx.hasSameType(field->getType(), elementPtr)) {
1556 ErrorUnsupported(D, "weird std::initializer_list");
1560 if (field == record->field_end()) {
1561 ErrorUnsupported(D, "weird std::initializer_list");
1564 bool isStartEnd = false;
1565 if (ctx.hasSameType(field->getType(), elementPtr)) {
1568 } else if(!ctx.hasSameType(field->getType(), ctx.getSizeType())) {
1569 ErrorUnsupported(D, "weird std::initializer_list");
1573 // Now build an APValue representing the std::initializer_list.
1574 APValue initListValue(APValue::UninitStruct(), 0, 2);
1575 APValue &startField = initListValue.getStructField(0);
1576 APValue::LValuePathEntry startOffsetPathEntry;
1577 startOffsetPathEntry.ArrayIndex = 0;
1578 startField = APValue(APValue::LValueBase(backingArray),
1579 CharUnits::fromQuantity(0),
1580 llvm::makeArrayRef(startOffsetPathEntry),
1581 /*IsOnePastTheEnd=*/false, 0);
1584 APValue &endField = initListValue.getStructField(1);
1585 APValue::LValuePathEntry endOffsetPathEntry;
1586 endOffsetPathEntry.ArrayIndex = numInits;
1587 endField = APValue(APValue::LValueBase(backingArray),
1588 ctx.getTypeSizeInChars(elementType) * numInits,
1589 llvm::makeArrayRef(endOffsetPathEntry),
1590 /*IsOnePastTheEnd=*/true, 0);
1592 APValue &sizeField = initListValue.getStructField(1);
1593 sizeField = APValue(llvm::APSInt(numElements));
1596 // Emit the constant for the initializer_list.
1597 llvm::Constant *llvmInit =
1598 EmitConstantValueForMemory(initListValue, D->getType());
1599 assert(llvmInit && "failed to initialize as constant");
1603 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
1604 unsigned AddrSpace) {
1605 if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
1606 if (D->hasAttr<CUDAConstantAttr>())
1607 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
1608 else if (D->hasAttr<CUDASharedAttr>())
1609 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
1611 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
1617 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1618 llvm::Constant *Init = 0;
1619 QualType ASTTy = D->getType();
1620 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1621 bool NeedsGlobalCtor = false;
1622 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
1624 const VarDecl *InitDecl;
1625 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
1628 // This is a tentative definition; tentative definitions are
1629 // implicitly initialized with { 0 }.
1631 // Note that tentative definitions are only emitted at the end of
1632 // a translation unit, so they should never have incomplete
1633 // type. In addition, EmitTentativeDefinition makes sure that we
1634 // never attempt to emit a tentative definition if a real one
1635 // exists. A use may still exists, however, so we still may need
1637 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1638 Init = EmitNullConstant(D->getType());
1640 // If this is a std::initializer_list, emit the special initializer.
1641 Init = MaybeEmitGlobalStdInitializerListInitializer(D, InitExpr);
1642 // An empty init list will perform zero-initialization, which happens
1643 // to be exactly what we want.
1644 // FIXME: It does so in a global constructor, which is *not* what we
1648 initializedGlobalDecl = GlobalDecl(D);
1649 Init = EmitConstantInit(*InitDecl);
1652 QualType T = InitExpr->getType();
1653 if (D->getType()->isReferenceType())
1656 if (getLangOpts().CPlusPlus) {
1657 Init = EmitNullConstant(T);
1658 NeedsGlobalCtor = true;
1660 ErrorUnsupported(D, "static initializer");
1661 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1664 // We don't need an initializer, so remove the entry for the delayed
1665 // initializer position (just in case this entry was delayed) if we
1666 // also don't need to register a destructor.
1667 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
1668 DelayedCXXInitPosition.erase(D);
1672 llvm::Type* InitType = Init->getType();
1673 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1675 // Strip off a bitcast if we got one back.
1676 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1677 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1678 // all zero index gep.
1679 CE->getOpcode() == llvm::Instruction::GetElementPtr);
1680 Entry = CE->getOperand(0);
1683 // Entry is now either a Function or GlobalVariable.
1684 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1686 // We have a definition after a declaration with the wrong type.
1687 // We must make a new GlobalVariable* and update everything that used OldGV
1688 // (a declaration or tentative definition) with the new GlobalVariable*
1689 // (which will be a definition).
1691 // This happens if there is a prototype for a global (e.g.
1692 // "extern int x[];") and then a definition of a different type (e.g.
1693 // "int x[10];"). This also happens when an initializer has a different type
1694 // from the type of the global (this happens with unions).
1696 GV->getType()->getElementType() != InitType ||
1697 GV->getType()->getAddressSpace() !=
1698 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
1700 // Move the old entry aside so that we'll create a new one.
1701 Entry->setName(StringRef());
1703 // Make a new global with the correct type, this is now guaranteed to work.
1704 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
1706 // Replace all uses of the old global with the new global
1707 llvm::Constant *NewPtrForOldDecl =
1708 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1709 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1711 // Erase the old global, since it is no longer used.
1712 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1715 if (D->hasAttr<AnnotateAttr>())
1716 AddGlobalAnnotations(D, GV);
1718 GV->setInitializer(Init);
1720 // If it is safe to mark the global 'constant', do so now.
1721 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
1722 isTypeConstant(D->getType(), true));
1724 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1726 // Set the llvm linkage type as appropriate.
1727 llvm::GlobalValue::LinkageTypes Linkage =
1728 GetLLVMLinkageVarDefinition(D, GV);
1729 GV->setLinkage(Linkage);
1730 if (Linkage == llvm::GlobalVariable::CommonLinkage)
1731 // common vars aren't constant even if declared const.
1732 GV->setConstant(false);
1734 SetCommonAttributes(D, GV);
1736 // Emit the initializer function if necessary.
1737 if (NeedsGlobalCtor || NeedsGlobalDtor)
1738 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
1740 // If we are compiling with ASan, add metadata indicating dynamically
1741 // initialized globals.
1742 if (LangOpts.SanitizeAddress && NeedsGlobalCtor) {
1743 llvm::Module &M = getModule();
1745 llvm::NamedMDNode *DynamicInitializers =
1746 M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals");
1747 llvm::Value *GlobalToAdd[] = { GV };
1748 llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd);
1749 DynamicInitializers->addOperand(ThisGlobal);
1752 // Emit global variable debug information.
1753 if (CGDebugInfo *DI = getModuleDebugInfo())
1754 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
1755 DI->EmitGlobalVariable(GV, D);
1758 llvm::GlobalValue::LinkageTypes
1759 CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1760 llvm::GlobalVariable *GV) {
1761 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1762 if (Linkage == GVA_Internal)
1763 return llvm::Function::InternalLinkage;
1764 else if (D->hasAttr<DLLImportAttr>())
1765 return llvm::Function::DLLImportLinkage;
1766 else if (D->hasAttr<DLLExportAttr>())
1767 return llvm::Function::DLLExportLinkage;
1768 else if (D->hasAttr<WeakAttr>()) {
1769 if (GV->isConstant())
1770 return llvm::GlobalVariable::WeakODRLinkage;
1772 return llvm::GlobalVariable::WeakAnyLinkage;
1773 } else if (Linkage == GVA_TemplateInstantiation ||
1774 Linkage == GVA_ExplicitTemplateInstantiation)
1775 return llvm::GlobalVariable::WeakODRLinkage;
1776 else if (!getLangOpts().CPlusPlus &&
1777 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1778 D->getAttr<CommonAttr>()) &&
1779 !D->hasExternalStorage() && !D->getInit() &&
1780 !D->getAttr<SectionAttr>() && !D->isThreadSpecified() &&
1781 !D->getAttr<WeakImportAttr>()) {
1782 // Thread local vars aren't considered common linkage.
1783 return llvm::GlobalVariable::CommonLinkage;
1785 return llvm::GlobalVariable::ExternalLinkage;
1788 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1789 /// implement a function with no prototype, e.g. "int foo() {}". If there are
1790 /// existing call uses of the old function in the module, this adjusts them to
1791 /// call the new function directly.
1793 /// This is not just a cleanup: the always_inline pass requires direct calls to
1794 /// functions to be able to inline them. If there is a bitcast in the way, it
1795 /// won't inline them. Instcombine normally deletes these calls, but it isn't
1797 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1798 llvm::Function *NewFn) {
1799 // If we're redefining a global as a function, don't transform it.
1800 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1801 if (OldFn == 0) return;
1803 llvm::Type *NewRetTy = NewFn->getReturnType();
1804 SmallVector<llvm::Value*, 4> ArgList;
1806 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
1808 // TODO: Do invokes ever occur in C code? If so, we should handle them too.
1809 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1810 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
1811 if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
1812 llvm::CallSite CS(CI);
1813 if (!CI || !CS.isCallee(I)) continue;
1815 // If the return types don't match exactly, and if the call isn't dead, then
1816 // we can't transform this call.
1817 if (CI->getType() != NewRetTy && !CI->use_empty())
1820 // Get the attribute list.
1821 llvm::SmallVector<llvm::AttributeWithIndex, 8> AttrVec;
1822 llvm::AttrListPtr AttrList = CI->getAttributes();
1824 // Get any return attributes.
1825 llvm::Attributes RAttrs = AttrList.getRetAttributes();
1827 // Add the return attributes.
1828 if (RAttrs.hasAttributes())
1829 AttrVec.push_back(llvm::
1830 AttributeWithIndex::get(llvm::AttrListPtr::ReturnIndex,
1833 // If the function was passed too few arguments, don't transform. If extra
1834 // arguments were passed, we silently drop them. If any of the types
1835 // mismatch, we don't transform.
1837 bool DontTransform = false;
1838 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1839 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
1840 if (CS.arg_size() == ArgNo ||
1841 CS.getArgument(ArgNo)->getType() != AI->getType()) {
1842 DontTransform = true;
1846 // Add any parameter attributes.
1847 llvm::Attributes PAttrs = AttrList.getParamAttributes(ArgNo + 1);
1848 if (PAttrs.hasAttributes())
1849 AttrVec.push_back(llvm::AttributeWithIndex::get(ArgNo + 1, PAttrs));
1854 llvm::Attributes FnAttrs = AttrList.getFnAttributes();
1855 if (FnAttrs.hasAttributes())
1856 AttrVec.push_back(llvm::
1857 AttributeWithIndex::get(llvm::AttrListPtr::FunctionIndex,
1860 // Okay, we can transform this. Create the new call instruction and copy
1861 // over the required information.
1862 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
1863 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList, "", CI);
1865 if (!NewCall->getType()->isVoidTy())
1866 NewCall->takeName(CI);
1867 NewCall->setAttributes(llvm::AttrListPtr::get(OldFn->getContext(), AttrVec));
1868 NewCall->setCallingConv(CI->getCallingConv());
1870 // Finally, remove the old call, replacing any uses with the new one.
1871 if (!CI->use_empty())
1872 CI->replaceAllUsesWith(NewCall);
1874 // Copy debug location attached to CI.
1875 if (!CI->getDebugLoc().isUnknown())
1876 NewCall->setDebugLoc(CI->getDebugLoc());
1877 CI->eraseFromParent();
1881 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
1882 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
1883 // If we have a definition, this might be a deferred decl. If the
1884 // instantiation is explicit, make sure we emit it at the end.
1885 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
1886 GetAddrOfGlobalVar(VD);
1889 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
1890 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
1892 // Compute the function info and LLVM type.
1893 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1894 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
1896 // Get or create the prototype for the function.
1897 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
1899 // Strip off a bitcast if we got one back.
1900 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1901 assert(CE->getOpcode() == llvm::Instruction::BitCast);
1902 Entry = CE->getOperand(0);
1906 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
1907 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
1909 // If the types mismatch then we have to rewrite the definition.
1910 assert(OldFn->isDeclaration() &&
1911 "Shouldn't replace non-declaration");
1913 // F is the Function* for the one with the wrong type, we must make a new
1914 // Function* and update everything that used F (a declaration) with the new
1915 // Function* (which will be a definition).
1917 // This happens if there is a prototype for a function
1918 // (e.g. "int f()") and then a definition of a different type
1919 // (e.g. "int f(int x)"). Move the old function aside so that it
1920 // doesn't interfere with GetAddrOfFunction.
1921 OldFn->setName(StringRef());
1922 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
1924 // If this is an implementation of a function without a prototype, try to
1925 // replace any existing uses of the function (which may be calls) with uses
1926 // of the new function
1927 if (D->getType()->isFunctionNoProtoType()) {
1928 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
1929 OldFn->removeDeadConstantUsers();
1932 // Replace uses of F with the Function we will endow with a body.
1933 if (!Entry->use_empty()) {
1934 llvm::Constant *NewPtrForOldDecl =
1935 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
1936 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1939 // Ok, delete the old function now, which is dead.
1940 OldFn->eraseFromParent();
1945 // We need to set linkage and visibility on the function before
1946 // generating code for it because various parts of IR generation
1947 // want to propagate this information down (e.g. to local static
1949 llvm::Function *Fn = cast<llvm::Function>(Entry);
1950 setFunctionLinkage(D, Fn);
1952 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
1953 setGlobalVisibility(Fn, D);
1955 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
1957 SetFunctionDefinitionAttributes(D, Fn);
1958 SetLLVMFunctionAttributesForDefinition(D, Fn);
1960 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
1961 AddGlobalCtor(Fn, CA->getPriority());
1962 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
1963 AddGlobalDtor(Fn, DA->getPriority());
1964 if (D->hasAttr<AnnotateAttr>())
1965 AddGlobalAnnotations(D, Fn);
1968 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1969 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
1970 const AliasAttr *AA = D->getAttr<AliasAttr>();
1971 assert(AA && "Not an alias?");
1973 StringRef MangledName = getMangledName(GD);
1975 // If there is a definition in the module, then it wins over the alias.
1976 // This is dubious, but allow it to be safe. Just ignore the alias.
1977 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1978 if (Entry && !Entry->isDeclaration())
1981 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1983 // Create a reference to the named value. This ensures that it is emitted
1984 // if a deferred decl.
1985 llvm::Constant *Aliasee;
1986 if (isa<llvm::FunctionType>(DeclTy))
1987 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
1988 /*ForVTable=*/false);
1990 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1991 llvm::PointerType::getUnqual(DeclTy), 0);
1993 // Create the new alias itself, but don't set a name yet.
1994 llvm::GlobalValue *GA =
1995 new llvm::GlobalAlias(Aliasee->getType(),
1996 llvm::Function::ExternalLinkage,
1997 "", Aliasee, &getModule());
2000 assert(Entry->isDeclaration());
2002 // If there is a declaration in the module, then we had an extern followed
2003 // by the alias, as in:
2004 // extern int test6();
2006 // int test6() __attribute__((alias("test7")));
2008 // Remove it and replace uses of it with the alias.
2009 GA->takeName(Entry);
2011 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
2013 Entry->eraseFromParent();
2015 GA->setName(MangledName);
2018 // Set attributes which are particular to an alias; this is a
2019 // specialization of the attributes which may be set on a global
2020 // variable/function.
2021 if (D->hasAttr<DLLExportAttr>()) {
2022 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2023 // The dllexport attribute is ignored for undefined symbols.
2025 GA->setLinkage(llvm::Function::DLLExportLinkage);
2027 GA->setLinkage(llvm::Function::DLLExportLinkage);
2029 } else if (D->hasAttr<WeakAttr>() ||
2030 D->hasAttr<WeakRefAttr>() ||
2031 D->isWeakImported()) {
2032 GA->setLinkage(llvm::Function::WeakAnyLinkage);
2035 SetCommonAttributes(D, GA);
2038 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
2039 ArrayRef<llvm::Type*> Tys) {
2040 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
2044 static llvm::StringMapEntry<llvm::Constant*> &
2045 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2046 const StringLiteral *Literal,
2049 unsigned &StringLength) {
2050 StringRef String = Literal->getString();
2051 unsigned NumBytes = String.size();
2053 // Check for simple case.
2054 if (!Literal->containsNonAsciiOrNull()) {
2055 StringLength = NumBytes;
2056 return Map.GetOrCreateValue(String);
2059 // Otherwise, convert the UTF8 literals into a string of shorts.
2062 SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
2063 const UTF8 *FromPtr = (const UTF8 *)String.data();
2064 UTF16 *ToPtr = &ToBuf[0];
2066 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2067 &ToPtr, ToPtr + NumBytes,
2070 // ConvertUTF8toUTF16 returns the length in ToPtr.
2071 StringLength = ToPtr - &ToBuf[0];
2073 // Add an explicit null.
2076 GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2077 (StringLength + 1) * 2));
2080 static llvm::StringMapEntry<llvm::Constant*> &
2081 GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2082 const StringLiteral *Literal,
2083 unsigned &StringLength) {
2084 StringRef String = Literal->getString();
2085 StringLength = String.size();
2086 return Map.GetOrCreateValue(String);
2090 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2091 unsigned StringLength = 0;
2092 bool isUTF16 = false;
2093 llvm::StringMapEntry<llvm::Constant*> &Entry =
2094 GetConstantCFStringEntry(CFConstantStringMap, Literal,
2095 getDataLayout().isLittleEndian(),
2096 isUTF16, StringLength);
2098 if (llvm::Constant *C = Entry.getValue())
2101 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2102 llvm::Constant *Zeros[] = { Zero, Zero };
2104 // If we don't already have it, get __CFConstantStringClassReference.
2105 if (!CFConstantStringClassRef) {
2106 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2107 Ty = llvm::ArrayType::get(Ty, 0);
2108 llvm::Constant *GV = CreateRuntimeVariable(Ty,
2109 "__CFConstantStringClassReference");
2110 // Decay array -> ptr
2111 CFConstantStringClassRef =
2112 llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2115 QualType CFTy = getContext().getCFConstantStringType();
2117 llvm::StructType *STy =
2118 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2120 llvm::Constant *Fields[4];
2123 Fields[0] = CFConstantStringClassRef;
2126 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2127 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
2128 llvm::ConstantInt::get(Ty, 0x07C8);
2131 llvm::Constant *C = 0;
2133 ArrayRef<uint16_t> Arr =
2134 llvm::makeArrayRef<uint16_t>((uint16_t*)Entry.getKey().data(),
2135 Entry.getKey().size() / 2);
2136 C = llvm::ConstantDataArray::get(VMContext, Arr);
2138 C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2141 llvm::GlobalValue::LinkageTypes Linkage;
2143 // FIXME: why do utf strings get "_" labels instead of "L" labels?
2144 Linkage = llvm::GlobalValue::InternalLinkage;
2146 // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
2147 // when using private linkage. It is not clear if this is a bug in ld
2148 // or a reasonable new restriction.
2149 Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
2151 // Note: -fwritable-strings doesn't make the backing store strings of
2152 // CFStrings writable. (See <rdar://problem/10657500>)
2153 llvm::GlobalVariable *GV =
2154 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2155 Linkage, C, ".str");
2156 GV->setUnnamedAddr(true);
2158 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2159 GV->setAlignment(Align.getQuantity());
2161 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2162 GV->setAlignment(Align.getQuantity());
2166 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2169 // Cast the UTF16 string to the correct type.
2170 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2173 Ty = getTypes().ConvertType(getContext().LongTy);
2174 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
2177 C = llvm::ConstantStruct::get(STy, Fields);
2178 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2179 llvm::GlobalVariable::PrivateLinkage, C,
2180 "_unnamed_cfstring_");
2181 if (const char *Sect = getContext().getTargetInfo().getCFStringSection())
2182 GV->setSection(Sect);
2189 CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
2190 DeclContext *DC, IdentifierInfo *Id) {
2192 if (Ctx.getLangOpts().CPlusPlus)
2193 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2195 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2199 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
2200 unsigned StringLength = 0;
2201 llvm::StringMapEntry<llvm::Constant*> &Entry =
2202 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
2204 if (llvm::Constant *C = Entry.getValue())
2207 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2208 llvm::Constant *Zeros[] = { Zero, Zero };
2210 // If we don't already have it, get _NSConstantStringClassReference.
2211 if (!ConstantStringClassRef) {
2212 std::string StringClass(getLangOpts().ObjCConstantStringClass);
2213 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2215 if (LangOpts.ObjCRuntime.isNonFragile()) {
2217 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2218 : "OBJC_CLASS_$_" + StringClass;
2219 GV = getObjCRuntime().GetClassGlobal(str);
2220 // Make sure the result is of the correct type.
2221 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2222 ConstantStringClassRef =
2223 llvm::ConstantExpr::getBitCast(GV, PTy);
2226 StringClass.empty() ? "_NSConstantStringClassReference"
2227 : "_" + StringClass + "ClassReference";
2228 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
2229 GV = CreateRuntimeVariable(PTy, str);
2230 // Decay array -> ptr
2231 ConstantStringClassRef =
2232 llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2236 if (!NSConstantStringType) {
2237 // Construct the type for a constant NSString.
2238 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2239 Context.getTranslationUnitDecl(),
2240 &Context.Idents.get("__builtin_NSString"));
2241 D->startDefinition();
2243 QualType FieldTypes[3];
2246 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2248 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2249 // unsigned int length;
2250 FieldTypes[2] = Context.UnsignedIntTy;
2253 for (unsigned i = 0; i < 3; ++i) {
2254 FieldDecl *Field = FieldDecl::Create(Context, D,
2256 SourceLocation(), 0,
2257 FieldTypes[i], /*TInfo=*/0,
2261 Field->setAccess(AS_public);
2265 D->completeDefinition();
2266 QualType NSTy = Context.getTagDeclType(D);
2267 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2270 llvm::Constant *Fields[3];
2273 Fields[0] = ConstantStringClassRef;
2277 llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2279 llvm::GlobalValue::LinkageTypes Linkage;
2281 Linkage = llvm::GlobalValue::PrivateLinkage;
2282 isConstant = !LangOpts.WritableStrings;
2284 llvm::GlobalVariable *GV =
2285 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
2287 GV->setUnnamedAddr(true);
2288 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2289 GV->setAlignment(Align.getQuantity());
2290 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2293 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2294 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2297 C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
2298 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2299 llvm::GlobalVariable::PrivateLinkage, C,
2300 "_unnamed_nsstring_");
2301 // FIXME. Fix section.
2302 if (const char *Sect =
2303 LangOpts.ObjCRuntime.isNonFragile()
2304 ? getContext().getTargetInfo().getNSStringNonFragileABISection()
2305 : getContext().getTargetInfo().getNSStringSection())
2306 GV->setSection(Sect);
2312 QualType CodeGenModule::getObjCFastEnumerationStateType() {
2313 if (ObjCFastEnumerationStateType.isNull()) {
2314 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2315 Context.getTranslationUnitDecl(),
2316 &Context.Idents.get("__objcFastEnumerationState"));
2317 D->startDefinition();
2319 QualType FieldTypes[] = {
2320 Context.UnsignedLongTy,
2321 Context.getPointerType(Context.getObjCIdType()),
2322 Context.getPointerType(Context.UnsignedLongTy),
2323 Context.getConstantArrayType(Context.UnsignedLongTy,
2324 llvm::APInt(32, 5), ArrayType::Normal, 0)
2327 for (size_t i = 0; i < 4; ++i) {
2328 FieldDecl *Field = FieldDecl::Create(Context,
2331 SourceLocation(), 0,
2332 FieldTypes[i], /*TInfo=*/0,
2336 Field->setAccess(AS_public);
2340 D->completeDefinition();
2341 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2344 return ObjCFastEnumerationStateType;
2348 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2349 assert(!E->getType()->isPointerType() && "Strings are always arrays");
2351 // Don't emit it as the address of the string, emit the string data itself
2352 // as an inline array.
2353 if (E->getCharByteWidth() == 1) {
2354 SmallString<64> Str(E->getString());
2356 // Resize the string to the right size, which is indicated by its type.
2357 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2358 Str.resize(CAT->getSize().getZExtValue());
2359 return llvm::ConstantDataArray::getString(VMContext, Str, false);
2362 llvm::ArrayType *AType =
2363 cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
2364 llvm::Type *ElemTy = AType->getElementType();
2365 unsigned NumElements = AType->getNumElements();
2367 // Wide strings have either 2-byte or 4-byte elements.
2368 if (ElemTy->getPrimitiveSizeInBits() == 16) {
2369 SmallVector<uint16_t, 32> Elements;
2370 Elements.reserve(NumElements);
2372 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2373 Elements.push_back(E->getCodeUnit(i));
2374 Elements.resize(NumElements);
2375 return llvm::ConstantDataArray::get(VMContext, Elements);
2378 assert(ElemTy->getPrimitiveSizeInBits() == 32);
2379 SmallVector<uint32_t, 32> Elements;
2380 Elements.reserve(NumElements);
2382 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2383 Elements.push_back(E->getCodeUnit(i));
2384 Elements.resize(NumElements);
2385 return llvm::ConstantDataArray::get(VMContext, Elements);
2388 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2389 /// constant array for the given string literal.
2391 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
2392 CharUnits Align = getContext().getTypeAlignInChars(S->getType());
2393 if (S->isAscii() || S->isUTF8()) {
2394 SmallString<64> Str(S->getString());
2396 // Resize the string to the right size, which is indicated by its type.
2397 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
2398 Str.resize(CAT->getSize().getZExtValue());
2399 return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity());
2402 // FIXME: the following does not memoize wide strings.
2403 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2404 llvm::GlobalVariable *GV =
2405 new llvm::GlobalVariable(getModule(),C->getType(),
2406 !LangOpts.WritableStrings,
2407 llvm::GlobalValue::PrivateLinkage,
2410 GV->setAlignment(Align.getQuantity());
2411 GV->setUnnamedAddr(true);
2415 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2416 /// array for the given ObjCEncodeExpr node.
2418 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2420 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
2422 return GetAddrOfConstantCString(Str);
2426 /// GenerateWritableString -- Creates storage for a string literal.
2427 static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
2430 const char *GlobalName,
2431 unsigned Alignment) {
2432 // Create Constant for this string literal. Don't add a '\0'.
2434 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
2436 // Create a global variable for this string
2437 llvm::GlobalVariable *GV =
2438 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
2439 llvm::GlobalValue::PrivateLinkage,
2441 GV->setAlignment(Alignment);
2442 GV->setUnnamedAddr(true);
2446 /// GetAddrOfConstantString - Returns a pointer to a character array
2447 /// containing the literal. This contents are exactly that of the
2448 /// given string, i.e. it will not be null terminated automatically;
2449 /// see GetAddrOfConstantCString. Note that whether the result is
2450 /// actually a pointer to an LLVM constant depends on
2451 /// Feature.WriteableStrings.
2453 /// The result has pointer to array type.
2454 llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
2455 const char *GlobalName,
2456 unsigned Alignment) {
2457 // Get the default prefix if a name wasn't specified.
2459 GlobalName = ".str";
2461 // Don't share any string literals if strings aren't constant.
2462 if (LangOpts.WritableStrings)
2463 return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
2465 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2466 ConstantStringMap.GetOrCreateValue(Str);
2468 if (llvm::GlobalVariable *GV = Entry.getValue()) {
2469 if (Alignment > GV->getAlignment()) {
2470 GV->setAlignment(Alignment);
2475 // Create a global variable for this.
2476 llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
2482 /// GetAddrOfConstantCString - Returns a pointer to a character
2483 /// array containing the literal and a terminating '\0'
2484 /// character. The result has pointer to array type.
2485 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
2486 const char *GlobalName,
2487 unsigned Alignment) {
2488 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
2489 return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
2492 /// EmitObjCPropertyImplementations - Emit information for synthesized
2493 /// properties for an implementation.
2494 void CodeGenModule::EmitObjCPropertyImplementations(const
2495 ObjCImplementationDecl *D) {
2496 for (ObjCImplementationDecl::propimpl_iterator
2497 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
2498 ObjCPropertyImplDecl *PID = *i;
2500 // Dynamic is just for type-checking.
2501 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2502 ObjCPropertyDecl *PD = PID->getPropertyDecl();
2504 // Determine which methods need to be implemented, some may have
2505 // been overridden. Note that ::isPropertyAccessor is not the method
2506 // we want, that just indicates if the decl came from a
2507 // property. What we want to know is if the method is defined in
2508 // this implementation.
2509 if (!D->getInstanceMethod(PD->getGetterName()))
2510 CodeGenFunction(*this).GenerateObjCGetter(
2511 const_cast<ObjCImplementationDecl *>(D), PID);
2512 if (!PD->isReadOnly() &&
2513 !D->getInstanceMethod(PD->getSetterName()))
2514 CodeGenFunction(*this).GenerateObjCSetter(
2515 const_cast<ObjCImplementationDecl *>(D), PID);
2520 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
2521 const ObjCInterfaceDecl *iface = impl->getClassInterface();
2522 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
2523 ivar; ivar = ivar->getNextIvar())
2524 if (ivar->getType().isDestructedType())
2530 /// EmitObjCIvarInitializations - Emit information for ivar initialization
2531 /// for an implementation.
2532 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
2533 // We might need a .cxx_destruct even if we don't have any ivar initializers.
2534 if (needsDestructMethod(D)) {
2535 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2536 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2537 ObjCMethodDecl *DTORMethod =
2538 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
2539 cxxSelector, getContext().VoidTy, 0, D,
2540 /*isInstance=*/true, /*isVariadic=*/false,
2541 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
2542 /*isDefined=*/false, ObjCMethodDecl::Required);
2543 D->addInstanceMethod(DTORMethod);
2544 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
2545 D->setHasDestructors(true);
2548 // If the implementation doesn't have any ivar initializers, we don't need
2549 // a .cxx_construct.
2550 if (D->getNumIvarInitializers() == 0)
2553 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2554 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2555 // The constructor returns 'self'.
2556 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2560 getContext().getObjCIdType(), 0,
2561 D, /*isInstance=*/true,
2562 /*isVariadic=*/false,
2563 /*isPropertyAccessor=*/true,
2564 /*isImplicitlyDeclared=*/true,
2565 /*isDefined=*/false,
2566 ObjCMethodDecl::Required);
2567 D->addInstanceMethod(CTORMethod);
2568 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
2569 D->setHasNonZeroConstructors(true);
2572 /// EmitNamespace - Emit all declarations in a namespace.
2573 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
2574 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
2576 EmitTopLevelDecl(*I);
2579 // EmitLinkageSpec - Emit all declarations in a linkage spec.
2580 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
2581 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2582 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
2583 ErrorUnsupported(LSD, "linkage spec");
2587 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
2589 // Meta-data for ObjC class includes references to implemented methods.
2590 // Generate class's method definitions first.
2591 if (ObjCImplDecl *OID = dyn_cast<ObjCImplDecl>(*I)) {
2592 for (ObjCContainerDecl::method_iterator M = OID->meth_begin(),
2593 MEnd = OID->meth_end();
2595 EmitTopLevelDecl(*M);
2597 EmitTopLevelDecl(*I);
2601 /// EmitTopLevelDecl - Emit code for a single top level declaration.
2602 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
2603 // If an error has occurred, stop code generation, but continue
2604 // parsing and semantic analysis (to ensure all warnings and errors
2606 if (Diags.hasErrorOccurred())
2609 // Ignore dependent declarations.
2610 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2613 switch (D->getKind()) {
2614 case Decl::CXXConversion:
2615 case Decl::CXXMethod:
2616 case Decl::Function:
2617 // Skip function templates
2618 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2619 cast<FunctionDecl>(D)->isLateTemplateParsed())
2622 EmitGlobal(cast<FunctionDecl>(D));
2626 EmitGlobal(cast<VarDecl>(D));
2629 // Indirect fields from global anonymous structs and unions can be
2630 // ignored; only the actual variable requires IR gen support.
2631 case Decl::IndirectField:
2635 case Decl::Namespace:
2636 EmitNamespace(cast<NamespaceDecl>(D));
2638 // No code generation needed.
2639 case Decl::UsingShadow:
2641 case Decl::UsingDirective:
2642 case Decl::ClassTemplate:
2643 case Decl::FunctionTemplate:
2644 case Decl::TypeAliasTemplate:
2645 case Decl::NamespaceAlias:
2649 case Decl::CXXConstructor:
2650 // Skip function templates
2651 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2652 cast<FunctionDecl>(D)->isLateTemplateParsed())
2655 EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2657 case Decl::CXXDestructor:
2658 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
2660 EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2663 case Decl::StaticAssert:
2667 // Objective-C Decls
2669 // Forward declarations, no (immediate) code generation.
2670 case Decl::ObjCInterface:
2671 case Decl::ObjCCategory:
2674 case Decl::ObjCProtocol: {
2675 ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
2676 if (Proto->isThisDeclarationADefinition())
2677 ObjCRuntime->GenerateProtocol(Proto);
2681 case Decl::ObjCCategoryImpl:
2682 // Categories have properties but don't support synthesize so we
2683 // can ignore them here.
2684 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2687 case Decl::ObjCImplementation: {
2688 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2689 EmitObjCPropertyImplementations(OMD);
2690 EmitObjCIvarInitializations(OMD);
2691 ObjCRuntime->GenerateClass(OMD);
2692 // Emit global variable debug information.
2693 if (CGDebugInfo *DI = getModuleDebugInfo())
2694 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(OMD->getClassInterface()),
2695 OMD->getLocation());
2699 case Decl::ObjCMethod: {
2700 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2701 // If this is not a prototype, emit the body.
2703 CodeGenFunction(*this).GenerateObjCMethod(OMD);
2706 case Decl::ObjCCompatibleAlias:
2707 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
2710 case Decl::LinkageSpec:
2711 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
2714 case Decl::FileScopeAsm: {
2715 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
2716 StringRef AsmString = AD->getAsmString()->getString();
2718 const std::string &S = getModule().getModuleInlineAsm();
2720 getModule().setModuleInlineAsm(AsmString);
2721 else if (S.end()[-1] == '\n')
2722 getModule().setModuleInlineAsm(S + AsmString.str());
2724 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
2729 // Make sure we handled everything we should, every other kind is a
2730 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
2731 // function. Need to recode Decl::Kind to do that easily.
2732 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2736 /// Turns the given pointer into a constant.
2737 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2739 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2740 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2741 return llvm::ConstantInt::get(i64, PtrInt);
2744 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2745 llvm::NamedMDNode *&GlobalMetadata,
2747 llvm::GlobalValue *Addr) {
2748 if (!GlobalMetadata)
2750 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2752 // TODO: should we report variant information for ctors/dtors?
2753 llvm::Value *Ops[] = {
2755 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2757 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2760 /// Emits metadata nodes associating all the global values in the
2761 /// current module with the Decls they came from. This is useful for
2762 /// projects using IR gen as a subroutine.
2764 /// Since there's currently no way to associate an MDNode directly
2765 /// with an llvm::GlobalValue, we create a global named metadata
2766 /// with the name 'clang.global.decl.ptrs'.
2767 void CodeGenModule::EmitDeclMetadata() {
2768 llvm::NamedMDNode *GlobalMetadata = 0;
2770 // StaticLocalDeclMap
2771 for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
2772 I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2774 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2775 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2779 /// Emits metadata nodes for all the local variables in the current
2781 void CodeGenFunction::EmitDeclMetadata() {
2782 if (LocalDeclMap.empty()) return;
2784 llvm::LLVMContext &Context = getLLVMContext();
2786 // Find the unique metadata ID for this name.
2787 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2789 llvm::NamedMDNode *GlobalMetadata = 0;
2791 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2792 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2793 const Decl *D = I->first;
2794 llvm::Value *Addr = I->second;
2796 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2797 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
2798 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
2799 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2800 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2801 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2806 void CodeGenModule::EmitCoverageFile() {
2807 if (!getCodeGenOpts().CoverageFile.empty()) {
2808 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
2809 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
2810 llvm::LLVMContext &Ctx = TheModule.getContext();
2811 llvm::MDString *CoverageFile =
2812 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
2813 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
2814 llvm::MDNode *CU = CUNode->getOperand(i);
2815 llvm::Value *node[] = { CoverageFile, CU };
2816 llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
2817 GCov->addOperand(N);
2823 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid,
2824 QualType GuidType) {
2825 // Sema has checked that all uuid strings are of the form
2826 // "12345678-1234-1234-1234-1234567890ab".
2827 assert(Uuid.size() == 36);
2828 const char *Uuidstr = Uuid.data();
2829 for (int i = 0; i < 36; ++i) {
2830 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuidstr[i] == '-');
2831 else assert(isxdigit(Uuidstr[i]));
2834 llvm::APInt Field0(32, StringRef(Uuidstr , 8), 16);
2835 llvm::APInt Field1(16, StringRef(Uuidstr + 9, 4), 16);
2836 llvm::APInt Field2(16, StringRef(Uuidstr + 14, 4), 16);
2837 static const int Field3ValueOffsets[] = { 19, 21, 24, 26, 28, 30, 32, 34 };
2839 APValue InitStruct(APValue::UninitStruct(), /*NumBases=*/0, /*NumFields=*/4);
2840 InitStruct.getStructField(0) = APValue(llvm::APSInt(Field0));
2841 InitStruct.getStructField(1) = APValue(llvm::APSInt(Field1));
2842 InitStruct.getStructField(2) = APValue(llvm::APSInt(Field2));
2843 APValue& Arr = InitStruct.getStructField(3);
2844 Arr = APValue(APValue::UninitArray(), 8, 8);
2845 for (int t = 0; t < 8; ++t)
2846 Arr.getArrayInitializedElt(t) = APValue(llvm::APSInt(
2847 llvm::APInt(8, StringRef(Uuidstr + Field3ValueOffsets[t], 2), 16)));
2849 return EmitConstantValue(InitStruct, GuidType);