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 "CGCUDARuntime.h"
18 #include "CGDebugInfo.h"
19 #include "CGObjCRuntime.h"
20 #include "CGOpenCLRuntime.h"
21 #include "CodeGenFunction.h"
22 #include "CodeGenTBAA.h"
23 #include "TargetInfo.h"
24 #include "clang/AST/ASTContext.h"
25 #include "clang/AST/CharUnits.h"
26 #include "clang/AST/DeclCXX.h"
27 #include "clang/AST/DeclObjC.h"
28 #include "clang/AST/DeclTemplate.h"
29 #include "clang/AST/Mangle.h"
30 #include "clang/AST/RecordLayout.h"
31 #include "clang/AST/RecursiveASTVisitor.h"
32 #include "clang/Basic/Builtins.h"
33 #include "clang/Basic/CharInfo.h"
34 #include "clang/Basic/Diagnostic.h"
35 #include "clang/Basic/Module.h"
36 #include "clang/Basic/SourceManager.h"
37 #include "clang/Basic/TargetInfo.h"
38 #include "clang/Frontend/CodeGenOptions.h"
39 #include "llvm/ADT/APSInt.h"
40 #include "llvm/ADT/Triple.h"
41 #include "llvm/IR/CallingConv.h"
42 #include "llvm/IR/DataLayout.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/LLVMContext.h"
45 #include "llvm/IR/Module.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/ConvertUTF.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Target/Mangler.h"
51 using namespace clang;
52 using namespace CodeGen;
54 static const char AnnotationSection[] = "llvm.metadata";
56 static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
57 switch (CGM.getTarget().getCXXABI().getKind()) {
58 case TargetCXXABI::GenericAArch64:
59 case TargetCXXABI::GenericARM:
60 case TargetCXXABI::iOS:
61 case TargetCXXABI::GenericItanium:
62 return *CreateItaniumCXXABI(CGM);
63 case TargetCXXABI::Microsoft:
64 return *CreateMicrosoftCXXABI(CGM);
67 llvm_unreachable("invalid C++ ABI kind");
71 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
72 llvm::Module &M, const llvm::DataLayout &TD,
73 DiagnosticsEngine &diags)
74 : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
75 Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()),
76 ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(0),
77 TheTargetCodeGenInfo(0), Types(*this), VTables(*this),
78 ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0),
79 DebugInfo(0), ARCData(0), NoObjCARCExceptionsMetadata(0),
80 RRData(0), CFConstantStringClassRef(0),
81 ConstantStringClassRef(0), NSConstantStringType(0),
82 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
83 BlockObjectAssign(0), BlockObjectDispose(0),
84 BlockDescriptorType(0), GenericBlockLiteralType(0),
85 LifetimeStartFn(0), LifetimeEndFn(0),
86 SanitizerBlacklist(CGO.SanitizerBlacklistFile),
87 SanOpts(SanitizerBlacklist.isIn(M) ?
88 SanitizerOptions::Disabled : LangOpts.Sanitize) {
90 // Initialize the type cache.
91 llvm::LLVMContext &LLVMContext = M.getContext();
92 VoidTy = llvm::Type::getVoidTy(LLVMContext);
93 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
94 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
95 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
96 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
97 FloatTy = llvm::Type::getFloatTy(LLVMContext);
98 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
99 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
100 PointerAlignInBytes =
101 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
102 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
103 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
104 Int8PtrTy = Int8Ty->getPointerTo(0);
105 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
107 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
112 createOpenCLRuntime();
116 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
117 if (SanOpts.Thread ||
118 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
119 TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
120 ABI.getMangleContext());
122 // If debug info or coverage generation is enabled, create the CGDebugInfo
124 if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
125 CodeGenOpts.EmitGcovArcs ||
126 CodeGenOpts.EmitGcovNotes)
127 DebugInfo = new CGDebugInfo(*this);
129 Block.GlobalUniqueCount = 0;
131 if (C.getLangOpts().ObjCAutoRefCount)
132 ARCData = new ARCEntrypoints();
133 RRData = new RREntrypoints();
136 CodeGenModule::~CodeGenModule() {
138 delete OpenCLRuntime;
140 delete TheTargetCodeGenInfo;
148 void CodeGenModule::createObjCRuntime() {
149 // This is just isGNUFamily(), but we want to force implementors of
150 // new ABIs to decide how best to do this.
151 switch (LangOpts.ObjCRuntime.getKind()) {
152 case ObjCRuntime::GNUstep:
153 case ObjCRuntime::GCC:
154 case ObjCRuntime::ObjFW:
155 ObjCRuntime = CreateGNUObjCRuntime(*this);
158 case ObjCRuntime::FragileMacOSX:
159 case ObjCRuntime::MacOSX:
160 case ObjCRuntime::iOS:
161 ObjCRuntime = CreateMacObjCRuntime(*this);
164 llvm_unreachable("bad runtime kind");
167 void CodeGenModule::createOpenCLRuntime() {
168 OpenCLRuntime = new CGOpenCLRuntime(*this);
171 void CodeGenModule::createCUDARuntime() {
172 CUDARuntime = CreateNVCUDARuntime(*this);
175 void CodeGenModule::Release() {
177 EmitCXXGlobalInitFunc();
178 EmitCXXGlobalDtorFunc();
179 EmitCXXThreadLocalInitFunc();
181 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
182 AddGlobalCtor(ObjCInitFunction);
183 EmitCtorList(GlobalCtors, "llvm.global_ctors");
184 EmitCtorList(GlobalDtors, "llvm.global_dtors");
185 EmitGlobalAnnotations();
186 EmitStaticExternCAliases();
189 if (CodeGenOpts.Autolink && Context.getLangOpts().Modules) {
190 EmitModuleLinkOptions();
193 SimplifyPersonality();
195 if (getCodeGenOpts().EmitDeclMetadata)
198 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
202 DebugInfo->finalize();
205 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
206 // Make sure that this type is translated.
207 Types.UpdateCompletedType(TD);
210 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
213 return TBAA->getTBAAInfo(QTy);
216 llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
219 return TBAA->getTBAAInfoForVTablePtr();
222 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
225 return TBAA->getTBAAStructInfo(QTy);
228 llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) {
231 return TBAA->getTBAAStructTypeInfo(QTy);
234 llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
235 llvm::MDNode *AccessN,
239 return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
242 /// Decorate the instruction with a TBAA tag. For scalar TBAA, the tag
243 /// is the same as the type. For struct-path aware TBAA, the tag
244 /// is different from the type: base type, access type and offset.
245 /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
246 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
247 llvm::MDNode *TBAAInfo,
248 bool ConvertTypeToTag) {
249 if (ConvertTypeToTag && TBAA && CodeGenOpts.StructPathTBAA)
250 Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
251 TBAA->getTBAAScalarTagInfo(TBAAInfo));
253 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
256 void CodeGenModule::Error(SourceLocation loc, StringRef error) {
257 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error);
258 getDiags().Report(Context.getFullLoc(loc), diagID);
261 /// ErrorUnsupported - Print out an error that codegen doesn't support the
262 /// specified stmt yet.
263 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
265 if (OmitOnError && getDiags().hasErrorOccurred())
267 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
268 "cannot compile this %0 yet");
269 std::string Msg = Type;
270 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
271 << Msg << S->getSourceRange();
274 /// ErrorUnsupported - Print out an error that codegen doesn't support the
275 /// specified decl yet.
276 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
278 if (OmitOnError && getDiags().hasErrorOccurred())
280 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
281 "cannot compile this %0 yet");
282 std::string Msg = Type;
283 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
286 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
287 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
290 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
291 const NamedDecl *D) const {
292 // Internal definitions always have default visibility.
293 if (GV->hasLocalLinkage()) {
294 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
298 // Set visibility for definitions.
299 LinkageInfo LV = D->getLinkageAndVisibility();
300 if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
301 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
304 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
305 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
306 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
307 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
308 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
309 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
312 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
313 CodeGenOptions::TLSModel M) {
315 case CodeGenOptions::GeneralDynamicTLSModel:
316 return llvm::GlobalVariable::GeneralDynamicTLSModel;
317 case CodeGenOptions::LocalDynamicTLSModel:
318 return llvm::GlobalVariable::LocalDynamicTLSModel;
319 case CodeGenOptions::InitialExecTLSModel:
320 return llvm::GlobalVariable::InitialExecTLSModel;
321 case CodeGenOptions::LocalExecTLSModel:
322 return llvm::GlobalVariable::LocalExecTLSModel;
324 llvm_unreachable("Invalid TLS model!");
327 void CodeGenModule::setTLSMode(llvm::GlobalVariable *GV,
328 const VarDecl &D) const {
329 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
331 llvm::GlobalVariable::ThreadLocalMode TLM;
332 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
334 // Override the TLS model if it is explicitly specified.
335 if (D.hasAttr<TLSModelAttr>()) {
336 const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>();
337 TLM = GetLLVMTLSModel(Attr->getModel());
340 GV->setThreadLocalMode(TLM);
343 /// Set the symbol visibility of type information (vtable and RTTI)
344 /// associated with the given type.
345 void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
346 const CXXRecordDecl *RD,
347 TypeVisibilityKind TVK) const {
348 setGlobalVisibility(GV, RD);
350 if (!CodeGenOpts.HiddenWeakVTables)
353 // We never want to drop the visibility for RTTI names.
354 if (TVK == TVK_ForRTTIName)
357 // We want to drop the visibility to hidden for weak type symbols.
358 // This isn't possible if there might be unresolved references
359 // elsewhere that rely on this symbol being visible.
361 // This should be kept roughly in sync with setThunkVisibility
365 if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
366 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
369 // Don't override an explicit visibility attribute.
370 if (RD->getExplicitVisibility(NamedDecl::VisibilityForType))
373 switch (RD->getTemplateSpecializationKind()) {
374 // We have to disable the optimization if this is an EI definition
375 // because there might be EI declarations in other shared objects.
376 case TSK_ExplicitInstantiationDefinition:
377 case TSK_ExplicitInstantiationDeclaration:
380 // Every use of a non-template class's type information has to emit it.
384 // In theory, implicit instantiations can ignore the possibility of
385 // an explicit instantiation declaration because there necessarily
386 // must be an EI definition somewhere with default visibility. In
387 // practice, it's possible to have an explicit instantiation for
388 // an arbitrary template class, and linkers aren't necessarily able
389 // to deal with mixed-visibility symbols.
390 case TSK_ExplicitSpecialization:
391 case TSK_ImplicitInstantiation:
395 // If there's a key function, there may be translation units
396 // that don't have the key function's definition. But ignore
397 // this if we're emitting RTTI under -fno-rtti.
398 if (!(TVK != TVK_ForRTTI) || LangOpts.RTTI) {
399 // FIXME: what should we do if we "lose" the key function during
400 // the emission of the file?
401 if (Context.getCurrentKeyFunction(RD))
405 // Otherwise, drop the visibility to hidden.
406 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
407 GV->setUnnamedAddr(true);
410 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
411 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
413 StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
417 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
418 IdentifierInfo *II = ND->getIdentifier();
419 assert(II && "Attempt to mangle unnamed decl.");
425 SmallString<256> Buffer;
426 llvm::raw_svector_ostream Out(Buffer);
427 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
428 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
429 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
430 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
431 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
432 getCXXABI().getMangleContext().mangleBlock(BD, Out,
433 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()));
435 getCXXABI().getMangleContext().mangleName(ND, Out);
437 // Allocate space for the mangled name.
439 size_t Length = Buffer.size();
440 char *Name = MangledNamesAllocator.Allocate<char>(Length);
441 std::copy(Buffer.begin(), Buffer.end(), Name);
443 Str = StringRef(Name, Length);
448 void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
449 const BlockDecl *BD) {
450 MangleContext &MangleCtx = getCXXABI().getMangleContext();
451 const Decl *D = GD.getDecl();
452 llvm::raw_svector_ostream Out(Buffer.getBuffer());
454 MangleCtx.mangleGlobalBlock(BD,
455 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
456 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
457 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
458 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
459 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
461 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
464 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
465 return getModule().getNamedValue(Name);
468 /// AddGlobalCtor - Add a function to the list that will be called before
470 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
471 // FIXME: Type coercion of void()* types.
472 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
475 /// AddGlobalDtor - Add a function to the list that will be called
476 /// when the module is unloaded.
477 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
478 // FIXME: Type coercion of void()* types.
479 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
482 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
483 // Ctor function type is void()*.
484 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
485 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
487 // Get the type of a ctor entry, { i32, void ()* }.
488 llvm::StructType *CtorStructTy =
489 llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL);
491 // Construct the constructor and destructor arrays.
492 SmallVector<llvm::Constant*, 8> Ctors;
493 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
494 llvm::Constant *S[] = {
495 llvm::ConstantInt::get(Int32Ty, I->second, false),
496 llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)
498 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
501 if (!Ctors.empty()) {
502 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
503 new llvm::GlobalVariable(TheModule, AT, false,
504 llvm::GlobalValue::AppendingLinkage,
505 llvm::ConstantArray::get(AT, Ctors),
510 llvm::GlobalValue::LinkageTypes
511 CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
512 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
514 if (Linkage == GVA_Internal)
515 return llvm::Function::InternalLinkage;
517 if (D->hasAttr<DLLExportAttr>())
518 return llvm::Function::DLLExportLinkage;
520 if (D->hasAttr<WeakAttr>())
521 return llvm::Function::WeakAnyLinkage;
523 // In C99 mode, 'inline' functions are guaranteed to have a strong
524 // definition somewhere else, so we can use available_externally linkage.
525 if (Linkage == GVA_C99Inline)
526 return llvm::Function::AvailableExternallyLinkage;
528 // Note that Apple's kernel linker doesn't support symbol
529 // coalescing, so we need to avoid linkonce and weak linkages there.
530 // Normally, this means we just map to internal, but for explicit
531 // instantiations we'll map to external.
533 // In C++, the compiler has to emit a definition in every translation unit
534 // that references the function. We should use linkonce_odr because
535 // a) if all references in this translation unit are optimized away, we
536 // don't need to codegen it. b) if the function persists, it needs to be
537 // merged with other definitions. c) C++ has the ODR, so we know the
538 // definition is dependable.
539 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
540 return !Context.getLangOpts().AppleKext
541 ? llvm::Function::LinkOnceODRLinkage
542 : llvm::Function::InternalLinkage;
544 // An explicit instantiation of a template has weak linkage, since
545 // explicit instantiations can occur in multiple translation units
546 // and must all be equivalent. However, we are not allowed to
547 // throw away these explicit instantiations.
548 if (Linkage == GVA_ExplicitTemplateInstantiation)
549 return !Context.getLangOpts().AppleKext
550 ? llvm::Function::WeakODRLinkage
551 : llvm::Function::ExternalLinkage;
553 // Otherwise, we have strong external linkage.
554 assert(Linkage == GVA_StrongExternal);
555 return llvm::Function::ExternalLinkage;
559 /// SetFunctionDefinitionAttributes - Set attributes for a global.
561 /// FIXME: This is currently only done for aliases and functions, but not for
562 /// variables (these details are set in EmitGlobalVarDefinition for variables).
563 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
564 llvm::GlobalValue *GV) {
565 SetCommonAttributes(D, GV);
568 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
569 const CGFunctionInfo &Info,
571 unsigned CallingConv;
572 AttributeListType AttributeList;
573 ConstructAttributeList(Info, D, AttributeList, CallingConv, false);
574 F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
575 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
578 /// Determines whether the language options require us to model
579 /// unwind exceptions. We treat -fexceptions as mandating this
580 /// except under the fragile ObjC ABI with only ObjC exceptions
581 /// enabled. This means, for example, that C with -fexceptions
583 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
584 // If exceptions are completely disabled, obviously this is false.
585 if (!LangOpts.Exceptions) return false;
587 // If C++ exceptions are enabled, this is true.
588 if (LangOpts.CXXExceptions) return true;
590 // If ObjC exceptions are enabled, this depends on the ABI.
591 if (LangOpts.ObjCExceptions) {
592 return LangOpts.ObjCRuntime.hasUnwindExceptions();
598 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
600 if (CodeGenOpts.UnwindTables)
603 if (!hasUnwindExceptions(LangOpts))
604 F->addFnAttr(llvm::Attribute::NoUnwind);
606 if (D->hasAttr<NakedAttr>()) {
607 // Naked implies noinline: we should not be inlining such functions.
608 F->addFnAttr(llvm::Attribute::Naked);
609 F->addFnAttr(llvm::Attribute::NoInline);
612 if (D->hasAttr<NoInlineAttr>())
613 F->addFnAttr(llvm::Attribute::NoInline);
615 // (noinline wins over always_inline, and we can't specify both in IR)
616 if ((D->hasAttr<AlwaysInlineAttr>() || D->hasAttr<ForceInlineAttr>()) &&
617 !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
618 llvm::Attribute::NoInline))
619 F->addFnAttr(llvm::Attribute::AlwaysInline);
621 // FIXME: Communicate hot and cold attributes to LLVM more directly.
622 if (D->hasAttr<ColdAttr>())
623 F->addFnAttr(llvm::Attribute::OptimizeForSize);
625 if (D->hasAttr<MinSizeAttr>())
626 F->addFnAttr(llvm::Attribute::MinSize);
628 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
629 F->setUnnamedAddr(true);
631 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
633 F->setUnnamedAddr(true);
635 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
636 F->addFnAttr(llvm::Attribute::StackProtect);
637 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
638 F->addFnAttr(llvm::Attribute::StackProtectReq);
640 // Add sanitizer attributes if function is not blacklisted.
641 if (!SanitizerBlacklist.isIn(*F)) {
642 // When AddressSanitizer is enabled, set SanitizeAddress attribute
643 // unless __attribute__((no_sanitize_address)) is used.
644 if (SanOpts.Address && !D->hasAttr<NoSanitizeAddressAttr>())
645 F->addFnAttr(llvm::Attribute::SanitizeAddress);
646 // Same for ThreadSanitizer and __attribute__((no_sanitize_thread))
647 if (SanOpts.Thread && !D->hasAttr<NoSanitizeThreadAttr>()) {
648 F->addFnAttr(llvm::Attribute::SanitizeThread);
650 // Same for MemorySanitizer and __attribute__((no_sanitize_memory))
651 if (SanOpts.Memory && !D->hasAttr<NoSanitizeMemoryAttr>())
652 F->addFnAttr(llvm::Attribute::SanitizeMemory);
655 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
657 F->setAlignment(alignment);
659 // C++ ABI requires 2-byte alignment for member functions.
660 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
664 void CodeGenModule::SetCommonAttributes(const Decl *D,
665 llvm::GlobalValue *GV) {
666 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
667 setGlobalVisibility(GV, ND);
669 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
671 if (D->hasAttr<UsedAttr>())
674 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
675 GV->setSection(SA->getName());
677 // Alias cannot have attributes. Filter them here.
678 if (!isa<llvm::GlobalAlias>(GV))
679 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
682 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
684 const CGFunctionInfo &FI) {
685 SetLLVMFunctionAttributes(D, FI, F);
686 SetLLVMFunctionAttributesForDefinition(D, F);
688 F->setLinkage(llvm::Function::InternalLinkage);
690 SetCommonAttributes(D, F);
693 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
695 bool IsIncompleteFunction) {
696 if (unsigned IID = F->getIntrinsicID()) {
697 // If this is an intrinsic function, set the function's attributes
698 // to the intrinsic's attributes.
699 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(),
700 (llvm::Intrinsic::ID)IID));
704 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
706 if (!IsIncompleteFunction)
707 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
709 // Only a few attributes are set on declarations; these may later be
710 // overridden by a definition.
712 if (FD->hasAttr<DLLImportAttr>()) {
713 F->setLinkage(llvm::Function::DLLImportLinkage);
714 } else if (FD->hasAttr<WeakAttr>() ||
715 FD->isWeakImported()) {
716 // "extern_weak" is overloaded in LLVM; we probably should have
717 // separate linkage types for this.
718 F->setLinkage(llvm::Function::ExternalWeakLinkage);
720 F->setLinkage(llvm::Function::ExternalLinkage);
722 LinkageInfo LV = FD->getLinkageAndVisibility();
723 if (LV.getLinkage() == ExternalLinkage && LV.isVisibilityExplicit()) {
724 F->setVisibility(GetLLVMVisibility(LV.getVisibility()));
728 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
729 F->setSection(SA->getName());
732 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
733 assert(!GV->isDeclaration() &&
734 "Only globals with definition can force usage.");
735 LLVMUsed.push_back(GV);
738 void CodeGenModule::EmitLLVMUsed() {
739 // Don't create llvm.used if there is no need.
740 if (LLVMUsed.empty())
743 // Convert LLVMUsed to what ConstantArray needs.
744 SmallVector<llvm::Constant*, 8> UsedArray;
745 UsedArray.resize(LLVMUsed.size());
746 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
748 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
752 if (UsedArray.empty())
754 llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
756 llvm::GlobalVariable *GV =
757 new llvm::GlobalVariable(getModule(), ATy, false,
758 llvm::GlobalValue::AppendingLinkage,
759 llvm::ConstantArray::get(ATy, UsedArray),
762 GV->setSection("llvm.metadata");
765 /// \brief Add link options implied by the given module, including modules
766 /// it depends on, using a postorder walk.
767 static void addLinkOptionsPostorder(llvm::LLVMContext &Context,
769 SmallVectorImpl<llvm::Value *> &Metadata,
770 llvm::SmallPtrSet<Module *, 16> &Visited) {
771 // Import this module's parent.
772 if (Mod->Parent && Visited.insert(Mod->Parent)) {
773 addLinkOptionsPostorder(Context, Mod->Parent, Metadata, Visited);
776 // Import this module's dependencies.
777 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
778 if (Visited.insert(Mod->Imports[I-1]))
779 addLinkOptionsPostorder(Context, Mod->Imports[I-1], Metadata, Visited);
782 // Add linker options to link against the libraries/frameworks
783 // described by this module.
784 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
785 // FIXME: -lfoo is Unix-centric and -framework Foo is Darwin-centric.
786 // We need to know more about the linker to know how to encode these
787 // options propertly.
789 // Link against a framework.
790 if (Mod->LinkLibraries[I-1].IsFramework) {
791 llvm::Value *Args[2] = {
792 llvm::MDString::get(Context, "-framework"),
793 llvm::MDString::get(Context, Mod->LinkLibraries[I-1].Library)
796 Metadata.push_back(llvm::MDNode::get(Context, Args));
800 // Link against a library.
801 llvm::Value *OptString
802 = llvm::MDString::get(Context,
803 "-l" + Mod->LinkLibraries[I-1].Library);
804 Metadata.push_back(llvm::MDNode::get(Context, OptString));
808 void CodeGenModule::EmitModuleLinkOptions() {
809 // Collect the set of all of the modules we want to visit to emit link
810 // options, which is essentially the imported modules and all of their
811 // non-explicit child modules.
812 llvm::SetVector<clang::Module *> LinkModules;
813 llvm::SmallPtrSet<clang::Module *, 16> Visited;
814 SmallVector<clang::Module *, 16> Stack;
816 // Seed the stack with imported modules.
817 for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(),
818 MEnd = ImportedModules.end();
820 if (Visited.insert(*M))
824 // Find all of the modules to import, making a little effort to prune
826 while (!Stack.empty()) {
827 clang::Module *Mod = Stack.back();
830 bool AnyChildren = false;
832 // Visit the submodules of this module.
833 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
834 SubEnd = Mod->submodule_end();
835 Sub != SubEnd; ++Sub) {
836 // Skip explicit children; they need to be explicitly imported to be
838 if ((*Sub)->IsExplicit)
841 if (Visited.insert(*Sub)) {
842 Stack.push_back(*Sub);
847 // We didn't find any children, so add this module to the list of
848 // modules to link against.
850 LinkModules.insert(Mod);
854 // Add link options for all of the imported modules in reverse topological
856 SmallVector<llvm::Value *, 16> MetadataArgs;
858 for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(),
859 MEnd = LinkModules.end();
861 if (Visited.insert(*M))
862 addLinkOptionsPostorder(getLLVMContext(), *M, MetadataArgs, Visited);
864 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
866 // Add the linker options metadata flag.
867 getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
868 llvm::MDNode::get(getLLVMContext(), MetadataArgs));
871 void CodeGenModule::EmitDeferred() {
872 // Emit code for any potentially referenced deferred decls. Since a
873 // previously unused static decl may become used during the generation of code
874 // for a static function, iterate until no changes are made.
877 if (!DeferredVTables.empty()) {
878 EmitDeferredVTables();
880 // Emitting a v-table doesn't directly cause more v-tables to
881 // become deferred, although it can cause functions to be
882 // emitted that then need those v-tables.
883 assert(DeferredVTables.empty());
886 // Stop if we're out of both deferred v-tables and deferred declarations.
887 if (DeferredDeclsToEmit.empty()) break;
889 GlobalDecl D = DeferredDeclsToEmit.back();
890 DeferredDeclsToEmit.pop_back();
892 // Check to see if we've already emitted this. This is necessary
893 // for a couple of reasons: first, decls can end up in the
894 // deferred-decls queue multiple times, and second, decls can end
895 // up with definitions in unusual ways (e.g. by an extern inline
896 // function acquiring a strong function redefinition). Just
897 // ignore these cases.
899 // TODO: That said, looking this up multiple times is very wasteful.
900 StringRef Name = getMangledName(D);
901 llvm::GlobalValue *CGRef = GetGlobalValue(Name);
902 assert(CGRef && "Deferred decl wasn't referenced?");
904 if (!CGRef->isDeclaration())
907 // GlobalAlias::isDeclaration() defers to the aliasee, but for our
908 // purposes an alias counts as a definition.
909 if (isa<llvm::GlobalAlias>(CGRef))
912 // Otherwise, emit the definition and move on to the next one.
913 EmitGlobalDefinition(D);
917 void CodeGenModule::EmitGlobalAnnotations() {
918 if (Annotations.empty())
921 // Create a new global variable for the ConstantStruct in the Module.
922 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
923 Annotations[0]->getType(), Annotations.size()), Annotations);
924 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
925 Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
926 "llvm.global.annotations");
927 gv->setSection(AnnotationSection);
930 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
931 llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str);
932 if (i != AnnotationStrings.end())
935 // Not found yet, create a new global.
936 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
937 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
938 true, llvm::GlobalValue::PrivateLinkage, s, ".str");
939 gv->setSection(AnnotationSection);
940 gv->setUnnamedAddr(true);
941 AnnotationStrings[Str] = gv;
945 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
946 SourceManager &SM = getContext().getSourceManager();
947 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
949 return EmitAnnotationString(PLoc.getFilename());
950 return EmitAnnotationString(SM.getBufferName(Loc));
953 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
954 SourceManager &SM = getContext().getSourceManager();
955 PresumedLoc PLoc = SM.getPresumedLoc(L);
956 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
957 SM.getExpansionLineNumber(L);
958 return llvm::ConstantInt::get(Int32Ty, LineNo);
961 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
962 const AnnotateAttr *AA,
964 // Get the globals for file name, annotation, and the line number.
965 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
966 *UnitGV = EmitAnnotationUnit(L),
967 *LineNoCst = EmitAnnotationLineNo(L);
969 // Create the ConstantStruct for the global annotation.
970 llvm::Constant *Fields[4] = {
971 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
972 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
973 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
976 return llvm::ConstantStruct::getAnon(Fields);
979 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
980 llvm::GlobalValue *GV) {
981 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
982 // Get the struct elements for these annotations.
983 for (specific_attr_iterator<AnnotateAttr>
984 ai = D->specific_attr_begin<AnnotateAttr>(),
985 ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
986 Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
989 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
990 // Never defer when EmitAllDecls is specified.
991 if (LangOpts.EmitAllDecls)
994 return !getContext().DeclMustBeEmitted(Global);
997 llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
998 const CXXUuidofExpr* E) {
999 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1002 if (E->isTypeOperand())
1003 Uuid = CXXUuidofExpr::GetUuidAttrOfType(E->getTypeOperand())->getGuid();
1005 // Special case: __uuidof(0) means an all-zero GUID.
1006 Expr *Op = E->getExprOperand();
1007 if (!Op->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
1008 Uuid = CXXUuidofExpr::GetUuidAttrOfType(Op->getType())->getGuid();
1010 Uuid = "00000000-0000-0000-0000-000000000000";
1012 std::string Name = "__uuid_" + Uuid.str();
1014 // Look for an existing global.
1015 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1018 llvm::Constant *Init = EmitUuidofInitializer(Uuid, E->getType());
1019 assert(Init && "failed to initialize as constant");
1021 // GUIDs are assumed to be 16 bytes, spread over 4-2-2-8 bytes. However, the
1022 // first field is declared as "long", which for many targets is 8 bytes.
1023 // Those architectures are not supported. (With the MS abi, long is always 4
1025 llvm::Type *GuidType = getTypes().ConvertType(E->getType());
1026 if (Init->getType() != GuidType) {
1027 DiagnosticsEngine &Diags = getDiags();
1028 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1029 "__uuidof codegen is not supported on this architecture");
1030 Diags.Report(E->getExprLoc(), DiagID) << E->getSourceRange();
1031 Init = llvm::UndefValue::get(GuidType);
1034 llvm::GlobalVariable *GV = new llvm::GlobalVariable(getModule(), GuidType,
1035 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, Init, Name);
1036 GV->setUnnamedAddr(true);
1040 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1041 const AliasAttr *AA = VD->getAttr<AliasAttr>();
1042 assert(AA && "No alias?");
1044 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1046 // See if there is already something with the target's name in the module.
1047 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
1049 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1050 return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1053 llvm::Constant *Aliasee;
1054 if (isa<llvm::FunctionType>(DeclTy))
1055 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1056 GlobalDecl(cast<FunctionDecl>(VD)),
1057 /*ForVTable=*/false);
1059 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1060 llvm::PointerType::getUnqual(DeclTy), 0);
1062 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
1063 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1064 WeakRefReferences.insert(F);
1069 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
1070 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
1072 // Weak references don't produce any output by themselves.
1073 if (Global->hasAttr<WeakRefAttr>())
1076 // If this is an alias definition (which otherwise looks like a declaration)
1078 if (Global->hasAttr<AliasAttr>())
1079 return EmitAliasDefinition(GD);
1081 // If this is CUDA, be selective about which declarations we emit.
1082 if (LangOpts.CUDA) {
1083 if (CodeGenOpts.CUDAIsDevice) {
1084 if (!Global->hasAttr<CUDADeviceAttr>() &&
1085 !Global->hasAttr<CUDAGlobalAttr>() &&
1086 !Global->hasAttr<CUDAConstantAttr>() &&
1087 !Global->hasAttr<CUDASharedAttr>())
1090 if (!Global->hasAttr<CUDAHostAttr>() && (
1091 Global->hasAttr<CUDADeviceAttr>() ||
1092 Global->hasAttr<CUDAConstantAttr>() ||
1093 Global->hasAttr<CUDASharedAttr>()))
1098 // Ignore declarations, they will be emitted on their first use.
1099 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
1100 // Forward declarations are emitted lazily on first use.
1101 if (!FD->doesThisDeclarationHaveABody()) {
1102 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1105 const FunctionDecl *InlineDefinition = 0;
1106 FD->getBody(InlineDefinition);
1108 StringRef MangledName = getMangledName(GD);
1109 DeferredDecls.erase(MangledName);
1110 EmitGlobalDefinition(InlineDefinition);
1114 const VarDecl *VD = cast<VarDecl>(Global);
1115 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1117 if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
1121 // Defer code generation when possible if this is a static definition, inline
1122 // function etc. These we only want to emit if they are used.
1123 if (!MayDeferGeneration(Global)) {
1124 // Emit the definition if it can't be deferred.
1125 EmitGlobalDefinition(GD);
1129 // If we're deferring emission of a C++ variable with an
1130 // initializer, remember the order in which it appeared in the file.
1131 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1132 cast<VarDecl>(Global)->hasInit()) {
1133 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1134 CXXGlobalInits.push_back(0);
1137 // If the value has already been used, add it directly to the
1138 // DeferredDeclsToEmit list.
1139 StringRef MangledName = getMangledName(GD);
1140 if (GetGlobalValue(MangledName))
1141 DeferredDeclsToEmit.push_back(GD);
1143 // Otherwise, remember that we saw a deferred decl with this name. The
1144 // first use of the mangled name will cause it to move into
1145 // DeferredDeclsToEmit.
1146 DeferredDecls[MangledName] = GD;
1151 struct FunctionIsDirectlyRecursive :
1152 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1153 const StringRef Name;
1154 const Builtin::Context &BI;
1156 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1157 Name(N), BI(C), Result(false) {
1159 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1161 bool TraverseCallExpr(CallExpr *E) {
1162 const FunctionDecl *FD = E->getDirectCallee();
1165 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1166 if (Attr && Name == Attr->getLabel()) {
1170 unsigned BuiltinID = FD->getBuiltinID();
1173 StringRef BuiltinName = BI.GetName(BuiltinID);
1174 if (BuiltinName.startswith("__builtin_") &&
1175 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1184 // isTriviallyRecursive - Check if this function calls another
1185 // decl that, because of the asm attribute or the other decl being a builtin,
1186 // ends up pointing to itself.
1188 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1190 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1191 // asm labels are a special kind of mangling we have to support.
1192 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1195 Name = Attr->getLabel();
1197 Name = FD->getName();
1200 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1201 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1202 return Walker.Result;
1206 CodeGenModule::shouldEmitFunction(const FunctionDecl *F) {
1207 if (getFunctionLinkage(F) != llvm::Function::AvailableExternallyLinkage)
1209 if (CodeGenOpts.OptimizationLevel == 0 &&
1210 !F->hasAttr<AlwaysInlineAttr>() && !F->hasAttr<ForceInlineAttr>())
1212 // PR9614. Avoid cases where the source code is lying to us. An available
1213 // externally function should have an equivalent function somewhere else,
1214 // but a function that calls itself is clearly not equivalent to the real
1216 // This happens in glibc's btowc and in some configure checks.
1217 return !isTriviallyRecursive(F);
1220 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
1221 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
1223 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1224 Context.getSourceManager(),
1225 "Generating code for declaration");
1227 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1228 // At -O0, don't generate IR for functions with available_externally
1230 if (!shouldEmitFunction(Function))
1233 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
1234 // Make sure to emit the definition(s) before we emit the thunks.
1235 // This is necessary for the generation of certain thunks.
1236 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
1237 EmitCXXConstructor(CD, GD.getCtorType());
1238 else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
1239 EmitCXXDestructor(DD, GD.getDtorType());
1241 EmitGlobalFunctionDefinition(GD);
1243 if (Method->isVirtual())
1244 getVTables().EmitThunks(GD);
1249 return EmitGlobalFunctionDefinition(GD);
1252 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1253 return EmitGlobalVarDefinition(VD);
1255 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1258 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1259 /// module, create and return an llvm Function with the specified type. If there
1260 /// is something in the module with the specified name, return it potentially
1261 /// bitcasted to the right type.
1263 /// If D is non-null, it specifies a decl that correspond to this. This is used
1264 /// to set the attributes on the function when it is first created.
1266 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
1268 GlobalDecl D, bool ForVTable,
1269 llvm::AttributeSet ExtraAttrs) {
1270 // Lookup the entry, lazily creating it if necessary.
1271 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1273 if (WeakRefReferences.erase(Entry)) {
1274 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
1275 if (FD && !FD->hasAttr<WeakAttr>())
1276 Entry->setLinkage(llvm::Function::ExternalLinkage);
1279 if (Entry->getType()->getElementType() == Ty)
1282 // Make sure the result is of the correct type.
1283 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1286 // This function doesn't have a complete type (for example, the return
1287 // type is an incomplete struct). Use a fake type instead, and make
1288 // sure not to try to set attributes.
1289 bool IsIncompleteFunction = false;
1291 llvm::FunctionType *FTy;
1292 if (isa<llvm::FunctionType>(Ty)) {
1293 FTy = cast<llvm::FunctionType>(Ty);
1295 FTy = llvm::FunctionType::get(VoidTy, false);
1296 IsIncompleteFunction = true;
1299 llvm::Function *F = llvm::Function::Create(FTy,
1300 llvm::Function::ExternalLinkage,
1301 MangledName, &getModule());
1302 assert(F->getName() == MangledName && "name was uniqued!");
1304 SetFunctionAttributes(D, F, IsIncompleteFunction);
1305 if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1306 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
1307 F->addAttributes(llvm::AttributeSet::FunctionIndex,
1308 llvm::AttributeSet::get(VMContext,
1309 llvm::AttributeSet::FunctionIndex,
1313 // This is the first use or definition of a mangled name. If there is a
1314 // deferred decl with this name, remember that we need to emit it at the end
1316 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1317 if (DDI != DeferredDecls.end()) {
1318 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1319 // list, and remove it from DeferredDecls (since we don't need it anymore).
1320 DeferredDeclsToEmit.push_back(DDI->second);
1321 DeferredDecls.erase(DDI);
1323 // Otherwise, there are cases we have to worry about where we're
1324 // using a declaration for which we must emit a definition but where
1325 // we might not find a top-level definition:
1326 // - member functions defined inline in their classes
1327 // - friend functions defined inline in some class
1328 // - special member functions with implicit definitions
1329 // If we ever change our AST traversal to walk into class methods,
1330 // this will be unnecessary.
1332 // We also don't emit a definition for a function if it's going to be an entry
1333 // in a vtable, unless it's already marked as used.
1334 } else if (getLangOpts().CPlusPlus && D.getDecl()) {
1335 // Look for a declaration that's lexically in a record.
1336 const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
1337 FD = FD->getMostRecentDecl();
1339 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
1340 if (FD->isImplicit() && !ForVTable) {
1341 assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
1342 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
1344 } else if (FD->doesThisDeclarationHaveABody()) {
1345 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
1349 FD = FD->getPreviousDecl();
1353 // Make sure the result is of the requested type.
1354 if (!IsIncompleteFunction) {
1355 assert(F->getType()->getElementType() == Ty);
1359 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1360 return llvm::ConstantExpr::getBitCast(F, PTy);
1363 /// GetAddrOfFunction - Return the address of the given function. If Ty is
1364 /// non-null, then this function will use the specified type if it has to
1365 /// create it (this occurs when we see a definition of the function).
1366 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
1369 // If there was no specific requested type, just convert it now.
1371 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
1373 StringRef MangledName = getMangledName(GD);
1374 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
1377 /// CreateRuntimeFunction - Create a new runtime function with the specified
1380 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
1382 llvm::AttributeSet ExtraAttrs) {
1384 = GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1386 if (llvm::Function *F = dyn_cast<llvm::Function>(C))
1388 F->setCallingConv(getRuntimeCC());
1392 /// isTypeConstant - Determine whether an object of this type can be emitted
1395 /// If ExcludeCtor is true, the duration when the object's constructor runs
1396 /// will not be considered. The caller will need to verify that the object is
1397 /// not written to during its construction.
1398 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1399 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
1402 if (Context.getLangOpts().CPlusPlus) {
1403 if (const CXXRecordDecl *Record
1404 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1405 return ExcludeCtor && !Record->hasMutableFields() &&
1406 Record->hasTrivialDestructor();
1412 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1413 /// create and return an llvm GlobalVariable with the specified type. If there
1414 /// is something in the module with the specified name, return it potentially
1415 /// bitcasted to the right type.
1417 /// If D is non-null, it specifies a decl that correspond to this. This is used
1418 /// to set the attributes on the global when it is first created.
1420 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
1421 llvm::PointerType *Ty,
1424 // Lookup the entry, lazily creating it if necessary.
1425 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1427 if (WeakRefReferences.erase(Entry)) {
1428 if (D && !D->hasAttr<WeakAttr>())
1429 Entry->setLinkage(llvm::Function::ExternalLinkage);
1433 Entry->setUnnamedAddr(true);
1435 if (Entry->getType() == Ty)
1438 // Make sure the result is of the correct type.
1439 return llvm::ConstantExpr::getBitCast(Entry, Ty);
1442 // This is the first use or definition of a mangled name. If there is a
1443 // deferred decl with this name, remember that we need to emit it at the end
1445 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1446 if (DDI != DeferredDecls.end()) {
1447 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1448 // list, and remove it from DeferredDecls (since we don't need it anymore).
1449 DeferredDeclsToEmit.push_back(DDI->second);
1450 DeferredDecls.erase(DDI);
1453 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
1454 llvm::GlobalVariable *GV =
1455 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
1456 llvm::GlobalValue::ExternalLinkage,
1458 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
1460 // Handle things which are present even on external declarations.
1462 // FIXME: This code is overly simple and should be merged with other global
1464 GV->setConstant(isTypeConstant(D->getType(), false));
1466 // Set linkage and visibility in case we never see a definition.
1467 LinkageInfo LV = D->getLinkageAndVisibility();
1468 if (LV.getLinkage() != ExternalLinkage) {
1469 // Don't set internal linkage on declarations.
1471 if (D->hasAttr<DLLImportAttr>())
1472 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
1473 else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
1474 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1476 // Set visibility on a declaration only if it's explicit.
1477 if (LV.isVisibilityExplicit())
1478 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
1481 if (D->getTLSKind()) {
1482 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
1483 CXXThreadLocals.push_back(std::make_pair(D, GV));
1488 if (AddrSpace != Ty->getAddressSpace())
1489 return llvm::ConstantExpr::getBitCast(GV, Ty);
1495 llvm::GlobalVariable *
1496 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
1498 llvm::GlobalValue::LinkageTypes Linkage) {
1499 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1500 llvm::GlobalVariable *OldGV = 0;
1504 // Check if the variable has the right type.
1505 if (GV->getType()->getElementType() == Ty)
1508 // Because C++ name mangling, the only way we can end up with an already
1509 // existing global with the same name is if it has been declared extern "C".
1510 assert(GV->isDeclaration() && "Declaration has wrong type!");
1514 // Create a new variable.
1515 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1519 // Replace occurrences of the old variable if needed.
1520 GV->takeName(OldGV);
1522 if (!OldGV->use_empty()) {
1523 llvm::Constant *NewPtrForOldDecl =
1524 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1525 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1528 OldGV->eraseFromParent();
1534 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1535 /// given global variable. If Ty is non-null and if the global doesn't exist,
1536 /// then it will be created with the specified type instead of whatever the
1537 /// normal requested type would be.
1538 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1540 assert(D->hasGlobalStorage() && "Not a global variable");
1541 QualType ASTTy = D->getType();
1543 Ty = getTypes().ConvertTypeForMem(ASTTy);
1545 llvm::PointerType *PTy =
1546 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1548 StringRef MangledName = getMangledName(D);
1549 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
1552 /// CreateRuntimeVariable - Create a new runtime global variable with the
1553 /// specified type and name.
1555 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
1557 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
1561 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1562 assert(!D->getInit() && "Cannot emit definite definitions here!");
1564 if (MayDeferGeneration(D)) {
1565 // If we have not seen a reference to this variable yet, place it
1566 // into the deferred declarations table to be emitted if needed
1568 StringRef MangledName = getMangledName(D);
1569 if (!GetGlobalValue(MangledName)) {
1570 DeferredDecls[MangledName] = D;
1575 // The tentative definition is the only definition.
1576 EmitGlobalVarDefinition(D);
1579 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
1580 return Context.toCharUnitsFromBits(
1581 TheDataLayout.getTypeStoreSizeInBits(Ty));
1585 CodeGenModule::MaybeEmitGlobalStdInitializerListInitializer(const VarDecl *D,
1586 const Expr *rawInit) {
1587 ArrayRef<ExprWithCleanups::CleanupObject> cleanups;
1588 if (const ExprWithCleanups *withCleanups =
1589 dyn_cast<ExprWithCleanups>(rawInit)) {
1590 cleanups = withCleanups->getObjects();
1591 rawInit = withCleanups->getSubExpr();
1594 const InitListExpr *init = dyn_cast<InitListExpr>(rawInit);
1595 if (!init || !init->initializesStdInitializerList() ||
1596 init->getNumInits() == 0)
1599 ASTContext &ctx = getContext();
1600 unsigned numInits = init->getNumInits();
1601 // FIXME: This check is here because we would otherwise silently miscompile
1602 // nested global std::initializer_lists. Better would be to have a real
1604 for (unsigned i = 0; i < numInits; ++i) {
1605 const InitListExpr *inner = dyn_cast<InitListExpr>(init->getInit(i));
1606 if (inner && inner->initializesStdInitializerList()) {
1607 ErrorUnsupported(inner, "nested global std::initializer_list");
1612 // Synthesize a fake VarDecl for the array and initialize that.
1613 QualType elementType = init->getInit(0)->getType();
1614 llvm::APInt numElements(ctx.getTypeSize(ctx.getSizeType()), numInits);
1615 QualType arrayType = ctx.getConstantArrayType(elementType, numElements,
1616 ArrayType::Normal, 0);
1618 IdentifierInfo *name = &ctx.Idents.get(D->getNameAsString() + "__initlist");
1619 TypeSourceInfo *sourceInfo = ctx.getTrivialTypeSourceInfo(
1620 arrayType, D->getLocation());
1621 VarDecl *backingArray = VarDecl::Create(ctx, const_cast<DeclContext*>(
1622 D->getDeclContext()),
1623 D->getLocStart(), D->getLocation(),
1624 name, arrayType, sourceInfo,
1626 backingArray->setTSCSpec(D->getTSCSpec());
1628 // Now clone the InitListExpr to initialize the array instead.
1629 // Incredible hack: we want to use the existing InitListExpr here, so we need
1630 // to tell it that it no longer initializes a std::initializer_list.
1631 ArrayRef<Expr*> Inits(const_cast<InitListExpr*>(init)->getInits(),
1632 init->getNumInits());
1633 Expr *arrayInit = new (ctx) InitListExpr(ctx, init->getLBraceLoc(), Inits,
1634 init->getRBraceLoc());
1635 arrayInit->setType(arrayType);
1637 if (!cleanups.empty())
1638 arrayInit = ExprWithCleanups::Create(ctx, arrayInit, cleanups);
1640 backingArray->setInit(arrayInit);
1642 // Emit the definition of the array.
1643 EmitGlobalVarDefinition(backingArray);
1645 // Inspect the initializer list to validate it and determine its type.
1646 // FIXME: doing this every time is probably inefficient; caching would be nice
1647 RecordDecl *record = init->getType()->castAs<RecordType>()->getDecl();
1648 RecordDecl::field_iterator field = record->field_begin();
1649 if (field == record->field_end()) {
1650 ErrorUnsupported(D, "weird std::initializer_list");
1653 QualType elementPtr = ctx.getPointerType(elementType.withConst());
1655 if (!ctx.hasSameType(field->getType(), elementPtr)) {
1656 ErrorUnsupported(D, "weird std::initializer_list");
1660 if (field == record->field_end()) {
1661 ErrorUnsupported(D, "weird std::initializer_list");
1664 bool isStartEnd = false;
1665 if (ctx.hasSameType(field->getType(), elementPtr)) {
1668 } else if(!ctx.hasSameType(field->getType(), ctx.getSizeType())) {
1669 ErrorUnsupported(D, "weird std::initializer_list");
1673 // Now build an APValue representing the std::initializer_list.
1674 APValue initListValue(APValue::UninitStruct(), 0, 2);
1675 APValue &startField = initListValue.getStructField(0);
1676 APValue::LValuePathEntry startOffsetPathEntry;
1677 startOffsetPathEntry.ArrayIndex = 0;
1678 startField = APValue(APValue::LValueBase(backingArray),
1679 CharUnits::fromQuantity(0),
1680 llvm::makeArrayRef(startOffsetPathEntry),
1681 /*IsOnePastTheEnd=*/false, 0);
1684 APValue &endField = initListValue.getStructField(1);
1685 APValue::LValuePathEntry endOffsetPathEntry;
1686 endOffsetPathEntry.ArrayIndex = numInits;
1687 endField = APValue(APValue::LValueBase(backingArray),
1688 ctx.getTypeSizeInChars(elementType) * numInits,
1689 llvm::makeArrayRef(endOffsetPathEntry),
1690 /*IsOnePastTheEnd=*/true, 0);
1692 APValue &sizeField = initListValue.getStructField(1);
1693 sizeField = APValue(llvm::APSInt(numElements));
1696 // Emit the constant for the initializer_list.
1697 llvm::Constant *llvmInit =
1698 EmitConstantValueForMemory(initListValue, D->getType());
1699 assert(llvmInit && "failed to initialize as constant");
1703 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
1704 unsigned AddrSpace) {
1705 if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
1706 if (D->hasAttr<CUDAConstantAttr>())
1707 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
1708 else if (D->hasAttr<CUDASharedAttr>())
1709 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
1711 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
1717 template<typename SomeDecl>
1718 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
1719 llvm::GlobalValue *GV) {
1720 if (!getLangOpts().CPlusPlus)
1723 // Must have 'used' attribute, or else inline assembly can't rely on
1724 // the name existing.
1725 if (!D->template hasAttr<UsedAttr>())
1728 // Must have internal linkage and an ordinary name.
1729 if (!D->getIdentifier() || D->getLinkage() != InternalLinkage)
1732 // Must be in an extern "C" context. Entities declared directly within
1733 // a record are not extern "C" even if the record is in such a context.
1734 const SomeDecl *First = D->getFirstDeclaration();
1735 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
1738 // OK, this is an internal linkage entity inside an extern "C" linkage
1739 // specification. Make a note of that so we can give it the "expected"
1740 // mangled name if nothing else is using that name.
1741 std::pair<StaticExternCMap::iterator, bool> R =
1742 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
1744 // If we have multiple internal linkage entities with the same name
1745 // in extern "C" regions, none of them gets that name.
1747 R.first->second = 0;
1750 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1751 llvm::Constant *Init = 0;
1752 QualType ASTTy = D->getType();
1753 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1754 bool NeedsGlobalCtor = false;
1755 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
1757 const VarDecl *InitDecl;
1758 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
1761 // This is a tentative definition; tentative definitions are
1762 // implicitly initialized with { 0 }.
1764 // Note that tentative definitions are only emitted at the end of
1765 // a translation unit, so they should never have incomplete
1766 // type. In addition, EmitTentativeDefinition makes sure that we
1767 // never attempt to emit a tentative definition if a real one
1768 // exists. A use may still exists, however, so we still may need
1770 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1771 Init = EmitNullConstant(D->getType());
1773 // If this is a std::initializer_list, emit the special initializer.
1774 Init = MaybeEmitGlobalStdInitializerListInitializer(D, InitExpr);
1775 // An empty init list will perform zero-initialization, which happens
1776 // to be exactly what we want.
1777 // FIXME: It does so in a global constructor, which is *not* what we
1781 initializedGlobalDecl = GlobalDecl(D);
1782 Init = EmitConstantInit(*InitDecl);
1785 QualType T = InitExpr->getType();
1786 if (D->getType()->isReferenceType())
1789 if (getLangOpts().CPlusPlus) {
1790 Init = EmitNullConstant(T);
1791 NeedsGlobalCtor = true;
1793 ErrorUnsupported(D, "static initializer");
1794 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1797 // We don't need an initializer, so remove the entry for the delayed
1798 // initializer position (just in case this entry was delayed) if we
1799 // also don't need to register a destructor.
1800 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
1801 DelayedCXXInitPosition.erase(D);
1805 llvm::Type* InitType = Init->getType();
1806 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1808 // Strip off a bitcast if we got one back.
1809 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1810 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1811 // all zero index gep.
1812 CE->getOpcode() == llvm::Instruction::GetElementPtr);
1813 Entry = CE->getOperand(0);
1816 // Entry is now either a Function or GlobalVariable.
1817 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1819 // We have a definition after a declaration with the wrong type.
1820 // We must make a new GlobalVariable* and update everything that used OldGV
1821 // (a declaration or tentative definition) with the new GlobalVariable*
1822 // (which will be a definition).
1824 // This happens if there is a prototype for a global (e.g.
1825 // "extern int x[];") and then a definition of a different type (e.g.
1826 // "int x[10];"). This also happens when an initializer has a different type
1827 // from the type of the global (this happens with unions).
1829 GV->getType()->getElementType() != InitType ||
1830 GV->getType()->getAddressSpace() !=
1831 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
1833 // Move the old entry aside so that we'll create a new one.
1834 Entry->setName(StringRef());
1836 // Make a new global with the correct type, this is now guaranteed to work.
1837 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
1839 // Replace all uses of the old global with the new global
1840 llvm::Constant *NewPtrForOldDecl =
1841 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1842 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1844 // Erase the old global, since it is no longer used.
1845 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1848 MaybeHandleStaticInExternC(D, GV);
1850 if (D->hasAttr<AnnotateAttr>())
1851 AddGlobalAnnotations(D, GV);
1853 GV->setInitializer(Init);
1855 // If it is safe to mark the global 'constant', do so now.
1856 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
1857 isTypeConstant(D->getType(), true));
1859 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1861 // Set the llvm linkage type as appropriate.
1862 llvm::GlobalValue::LinkageTypes Linkage =
1863 GetLLVMLinkageVarDefinition(D, GV);
1864 GV->setLinkage(Linkage);
1865 if (Linkage == llvm::GlobalVariable::CommonLinkage)
1866 // common vars aren't constant even if declared const.
1867 GV->setConstant(false);
1869 SetCommonAttributes(D, GV);
1871 // Emit the initializer function if necessary.
1872 if (NeedsGlobalCtor || NeedsGlobalDtor)
1873 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
1875 // If we are compiling with ASan, add metadata indicating dynamically
1876 // initialized globals.
1877 if (SanOpts.Address && NeedsGlobalCtor) {
1878 llvm::Module &M = getModule();
1880 llvm::NamedMDNode *DynamicInitializers =
1881 M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals");
1882 llvm::Value *GlobalToAdd[] = { GV };
1883 llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd);
1884 DynamicInitializers->addOperand(ThisGlobal);
1887 // Emit global variable debug information.
1888 if (CGDebugInfo *DI = getModuleDebugInfo())
1889 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
1890 DI->EmitGlobalVariable(GV, D);
1893 llvm::GlobalValue::LinkageTypes
1894 CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1895 llvm::GlobalVariable *GV) {
1896 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1897 if (Linkage == GVA_Internal)
1898 return llvm::Function::InternalLinkage;
1899 else if (D->hasAttr<DLLImportAttr>())
1900 return llvm::Function::DLLImportLinkage;
1901 else if (D->hasAttr<DLLExportAttr>())
1902 return llvm::Function::DLLExportLinkage;
1903 else if (D->hasAttr<WeakAttr>()) {
1904 if (GV->isConstant())
1905 return llvm::GlobalVariable::WeakODRLinkage;
1907 return llvm::GlobalVariable::WeakAnyLinkage;
1908 } else if (Linkage == GVA_TemplateInstantiation ||
1909 Linkage == GVA_ExplicitTemplateInstantiation)
1910 return llvm::GlobalVariable::WeakODRLinkage;
1911 else if (!getLangOpts().CPlusPlus &&
1912 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1913 D->getAttr<CommonAttr>()) &&
1914 !D->hasExternalStorage() && !D->getInit() &&
1915 !D->getAttr<SectionAttr>() && !D->getTLSKind() &&
1916 !D->getAttr<WeakImportAttr>()) {
1917 // Thread local vars aren't considered common linkage.
1918 return llvm::GlobalVariable::CommonLinkage;
1919 } else if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
1920 getTarget().getTriple().isMacOSX())
1921 // On Darwin, the backing variable for a C++11 thread_local variable always
1922 // has internal linkage; all accesses should just be calls to the
1923 // Itanium-specified entry point, which has the normal linkage of the
1925 return llvm::GlobalValue::InternalLinkage;
1926 return llvm::GlobalVariable::ExternalLinkage;
1929 /// Replace the uses of a function that was declared with a non-proto type.
1930 /// We want to silently drop extra arguments from call sites
1931 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
1932 llvm::Function *newFn) {
1934 if (old->use_empty()) return;
1936 llvm::Type *newRetTy = newFn->getReturnType();
1937 SmallVector<llvm::Value*, 4> newArgs;
1939 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
1941 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
1942 llvm::User *user = *use;
1944 // Recognize and replace uses of bitcasts. Most calls to
1945 // unprototyped functions will use bitcasts.
1946 if (llvm::ConstantExpr *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
1947 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
1948 replaceUsesOfNonProtoConstant(bitcast, newFn);
1952 // Recognize calls to the function.
1953 llvm::CallSite callSite(user);
1954 if (!callSite) continue;
1955 if (!callSite.isCallee(use)) continue;
1957 // If the return types don't match exactly, then we can't
1958 // transform this call unless it's dead.
1959 if (callSite->getType() != newRetTy && !callSite->use_empty())
1962 // Get the call site's attribute list.
1963 SmallVector<llvm::AttributeSet, 8> newAttrs;
1964 llvm::AttributeSet oldAttrs = callSite.getAttributes();
1966 // Collect any return attributes from the call.
1967 if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
1969 llvm::AttributeSet::get(newFn->getContext(),
1970 oldAttrs.getRetAttributes()));
1972 // If the function was passed too few arguments, don't transform.
1973 unsigned newNumArgs = newFn->arg_size();
1974 if (callSite.arg_size() < newNumArgs) continue;
1976 // If extra arguments were passed, we silently drop them.
1977 // If any of the types mismatch, we don't transform.
1979 bool dontTransform = false;
1980 for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
1981 ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
1982 if (callSite.getArgument(argNo)->getType() != ai->getType()) {
1983 dontTransform = true;
1987 // Add any parameter attributes.
1988 if (oldAttrs.hasAttributes(argNo + 1))
1991 AttributeSet::get(newFn->getContext(),
1992 oldAttrs.getParamAttributes(argNo + 1)));
1997 if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
1998 newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
1999 oldAttrs.getFnAttributes()));
2001 // Okay, we can transform this. Create the new call instruction and copy
2002 // over the required information.
2003 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2005 llvm::CallSite newCall;
2006 if (callSite.isCall()) {
2007 newCall = llvm::CallInst::Create(newFn, newArgs, "",
2008 callSite.getInstruction());
2010 llvm::InvokeInst *oldInvoke =
2011 cast<llvm::InvokeInst>(callSite.getInstruction());
2012 newCall = llvm::InvokeInst::Create(newFn,
2013 oldInvoke->getNormalDest(),
2014 oldInvoke->getUnwindDest(),
2016 callSite.getInstruction());
2018 newArgs.clear(); // for the next iteration
2020 if (!newCall->getType()->isVoidTy())
2021 newCall->takeName(callSite.getInstruction());
2022 newCall.setAttributes(
2023 llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2024 newCall.setCallingConv(callSite.getCallingConv());
2026 // Finally, remove the old call, replacing any uses with the new one.
2027 if (!callSite->use_empty())
2028 callSite->replaceAllUsesWith(newCall.getInstruction());
2030 // Copy debug location attached to CI.
2031 if (!callSite->getDebugLoc().isUnknown())
2032 newCall->setDebugLoc(callSite->getDebugLoc());
2033 callSite->eraseFromParent();
2037 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2038 /// implement a function with no prototype, e.g. "int foo() {}". If there are
2039 /// existing call uses of the old function in the module, this adjusts them to
2040 /// call the new function directly.
2042 /// This is not just a cleanup: the always_inline pass requires direct calls to
2043 /// functions to be able to inline them. If there is a bitcast in the way, it
2044 /// won't inline them. Instcombine normally deletes these calls, but it isn't
2046 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2047 llvm::Function *NewFn) {
2048 // If we're redefining a global as a function, don't transform it.
2049 if (!isa<llvm::Function>(Old)) return;
2051 replaceUsesOfNonProtoConstant(Old, NewFn);
2054 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2055 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2056 // If we have a definition, this might be a deferred decl. If the
2057 // instantiation is explicit, make sure we emit it at the end.
2058 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2059 GetAddrOfGlobalVar(VD);
2061 EmitTopLevelDecl(VD);
2064 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
2065 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
2067 // Compute the function info and LLVM type.
2068 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2069 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2071 // Get or create the prototype for the function.
2072 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
2074 // Strip off a bitcast if we got one back.
2075 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2076 assert(CE->getOpcode() == llvm::Instruction::BitCast);
2077 Entry = CE->getOperand(0);
2081 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
2082 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
2084 // If the types mismatch then we have to rewrite the definition.
2085 assert(OldFn->isDeclaration() &&
2086 "Shouldn't replace non-declaration");
2088 // F is the Function* for the one with the wrong type, we must make a new
2089 // Function* and update everything that used F (a declaration) with the new
2090 // Function* (which will be a definition).
2092 // This happens if there is a prototype for a function
2093 // (e.g. "int f()") and then a definition of a different type
2094 // (e.g. "int f(int x)"). Move the old function aside so that it
2095 // doesn't interfere with GetAddrOfFunction.
2096 OldFn->setName(StringRef());
2097 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
2099 // This might be an implementation of a function without a
2100 // prototype, in which case, try to do special replacement of
2101 // calls which match the new prototype. The really key thing here
2102 // is that we also potentially drop arguments from the call site
2103 // so as to make a direct call, which makes the inliner happier
2104 // and suppresses a number of optimizer warnings (!) about
2105 // dropping arguments.
2106 if (!OldFn->use_empty()) {
2107 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
2108 OldFn->removeDeadConstantUsers();
2111 // Replace uses of F with the Function we will endow with a body.
2112 if (!Entry->use_empty()) {
2113 llvm::Constant *NewPtrForOldDecl =
2114 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
2115 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2118 // Ok, delete the old function now, which is dead.
2119 OldFn->eraseFromParent();
2124 // We need to set linkage and visibility on the function before
2125 // generating code for it because various parts of IR generation
2126 // want to propagate this information down (e.g. to local static
2128 llvm::Function *Fn = cast<llvm::Function>(Entry);
2129 setFunctionLinkage(D, Fn);
2131 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
2132 setGlobalVisibility(Fn, D);
2134 MaybeHandleStaticInExternC(D, Fn);
2136 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
2138 SetFunctionDefinitionAttributes(D, Fn);
2139 SetLLVMFunctionAttributesForDefinition(D, Fn);
2141 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
2142 AddGlobalCtor(Fn, CA->getPriority());
2143 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
2144 AddGlobalDtor(Fn, DA->getPriority());
2145 if (D->hasAttr<AnnotateAttr>())
2146 AddGlobalAnnotations(D, Fn);
2149 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
2150 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
2151 const AliasAttr *AA = D->getAttr<AliasAttr>();
2152 assert(AA && "Not an alias?");
2154 StringRef MangledName = getMangledName(GD);
2156 // If there is a definition in the module, then it wins over the alias.
2157 // This is dubious, but allow it to be safe. Just ignore the alias.
2158 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2159 if (Entry && !Entry->isDeclaration())
2162 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
2164 // Create a reference to the named value. This ensures that it is emitted
2165 // if a deferred decl.
2166 llvm::Constant *Aliasee;
2167 if (isa<llvm::FunctionType>(DeclTy))
2168 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
2169 /*ForVTable=*/false);
2171 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2172 llvm::PointerType::getUnqual(DeclTy), 0);
2174 // Create the new alias itself, but don't set a name yet.
2175 llvm::GlobalValue *GA =
2176 new llvm::GlobalAlias(Aliasee->getType(),
2177 llvm::Function::ExternalLinkage,
2178 "", Aliasee, &getModule());
2181 assert(Entry->isDeclaration());
2183 // If there is a declaration in the module, then we had an extern followed
2184 // by the alias, as in:
2185 // extern int test6();
2187 // int test6() __attribute__((alias("test7")));
2189 // Remove it and replace uses of it with the alias.
2190 GA->takeName(Entry);
2192 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
2194 Entry->eraseFromParent();
2196 GA->setName(MangledName);
2199 // Set attributes which are particular to an alias; this is a
2200 // specialization of the attributes which may be set on a global
2201 // variable/function.
2202 if (D->hasAttr<DLLExportAttr>()) {
2203 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2204 // The dllexport attribute is ignored for undefined symbols.
2206 GA->setLinkage(llvm::Function::DLLExportLinkage);
2208 GA->setLinkage(llvm::Function::DLLExportLinkage);
2210 } else if (D->hasAttr<WeakAttr>() ||
2211 D->hasAttr<WeakRefAttr>() ||
2212 D->isWeakImported()) {
2213 GA->setLinkage(llvm::Function::WeakAnyLinkage);
2216 SetCommonAttributes(D, GA);
2219 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
2220 ArrayRef<llvm::Type*> Tys) {
2221 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
2225 static llvm::StringMapEntry<llvm::Constant*> &
2226 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2227 const StringLiteral *Literal,
2230 unsigned &StringLength) {
2231 StringRef String = Literal->getString();
2232 unsigned NumBytes = String.size();
2234 // Check for simple case.
2235 if (!Literal->containsNonAsciiOrNull()) {
2236 StringLength = NumBytes;
2237 return Map.GetOrCreateValue(String);
2240 // Otherwise, convert the UTF8 literals into a string of shorts.
2243 SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
2244 const UTF8 *FromPtr = (const UTF8 *)String.data();
2245 UTF16 *ToPtr = &ToBuf[0];
2247 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2248 &ToPtr, ToPtr + NumBytes,
2251 // ConvertUTF8toUTF16 returns the length in ToPtr.
2252 StringLength = ToPtr - &ToBuf[0];
2254 // Add an explicit null.
2257 GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2258 (StringLength + 1) * 2));
2261 static llvm::StringMapEntry<llvm::Constant*> &
2262 GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2263 const StringLiteral *Literal,
2264 unsigned &StringLength) {
2265 StringRef String = Literal->getString();
2266 StringLength = String.size();
2267 return Map.GetOrCreateValue(String);
2271 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2272 unsigned StringLength = 0;
2273 bool isUTF16 = false;
2274 llvm::StringMapEntry<llvm::Constant*> &Entry =
2275 GetConstantCFStringEntry(CFConstantStringMap, Literal,
2276 getDataLayout().isLittleEndian(),
2277 isUTF16, StringLength);
2279 if (llvm::Constant *C = Entry.getValue())
2282 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2283 llvm::Constant *Zeros[] = { Zero, Zero };
2286 // If we don't already have it, get __CFConstantStringClassReference.
2287 if (!CFConstantStringClassRef) {
2288 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2289 Ty = llvm::ArrayType::get(Ty, 0);
2290 llvm::Constant *GV = CreateRuntimeVariable(Ty,
2291 "__CFConstantStringClassReference");
2292 // Decay array -> ptr
2293 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2294 CFConstantStringClassRef = V;
2297 V = CFConstantStringClassRef;
2299 QualType CFTy = getContext().getCFConstantStringType();
2301 llvm::StructType *STy =
2302 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2304 llvm::Constant *Fields[4];
2307 Fields[0] = cast<llvm::ConstantExpr>(V);
2310 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2311 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
2312 llvm::ConstantInt::get(Ty, 0x07C8);
2315 llvm::Constant *C = 0;
2317 ArrayRef<uint16_t> Arr =
2318 llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>(
2319 const_cast<char *>(Entry.getKey().data())),
2320 Entry.getKey().size() / 2);
2321 C = llvm::ConstantDataArray::get(VMContext, Arr);
2323 C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2326 llvm::GlobalValue::LinkageTypes Linkage;
2328 // FIXME: why do utf strings get "_" labels instead of "L" labels?
2329 Linkage = llvm::GlobalValue::InternalLinkage;
2331 // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
2332 // when using private linkage. It is not clear if this is a bug in ld
2333 // or a reasonable new restriction.
2334 Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
2336 // Note: -fwritable-strings doesn't make the backing store strings of
2337 // CFStrings writable. (See <rdar://problem/10657500>)
2338 llvm::GlobalVariable *GV =
2339 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2340 Linkage, C, ".str");
2341 GV->setUnnamedAddr(true);
2342 // Don't enforce the target's minimum global alignment, since the only use
2343 // of the string is via this class initializer.
2345 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2346 GV->setAlignment(Align.getQuantity());
2348 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2349 GV->setAlignment(Align.getQuantity());
2353 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2356 // Cast the UTF16 string to the correct type.
2357 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2360 Ty = getTypes().ConvertType(getContext().LongTy);
2361 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
2364 C = llvm::ConstantStruct::get(STy, Fields);
2365 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2366 llvm::GlobalVariable::PrivateLinkage, C,
2367 "_unnamed_cfstring_");
2368 if (const char *Sect = getTarget().getCFStringSection())
2369 GV->setSection(Sect);
2376 CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
2377 DeclContext *DC, IdentifierInfo *Id) {
2379 if (Ctx.getLangOpts().CPlusPlus)
2380 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2382 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2386 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
2387 unsigned StringLength = 0;
2388 llvm::StringMapEntry<llvm::Constant*> &Entry =
2389 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
2391 if (llvm::Constant *C = Entry.getValue())
2394 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2395 llvm::Constant *Zeros[] = { Zero, Zero };
2397 // If we don't already have it, get _NSConstantStringClassReference.
2398 if (!ConstantStringClassRef) {
2399 std::string StringClass(getLangOpts().ObjCConstantStringClass);
2400 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2402 if (LangOpts.ObjCRuntime.isNonFragile()) {
2404 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2405 : "OBJC_CLASS_$_" + StringClass;
2406 GV = getObjCRuntime().GetClassGlobal(str);
2407 // Make sure the result is of the correct type.
2408 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2409 V = llvm::ConstantExpr::getBitCast(GV, PTy);
2410 ConstantStringClassRef = V;
2413 StringClass.empty() ? "_NSConstantStringClassReference"
2414 : "_" + StringClass + "ClassReference";
2415 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
2416 GV = CreateRuntimeVariable(PTy, str);
2417 // Decay array -> ptr
2418 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2419 ConstantStringClassRef = V;
2423 V = ConstantStringClassRef;
2425 if (!NSConstantStringType) {
2426 // Construct the type for a constant NSString.
2427 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2428 Context.getTranslationUnitDecl(),
2429 &Context.Idents.get("__builtin_NSString"));
2430 D->startDefinition();
2432 QualType FieldTypes[3];
2435 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2437 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2438 // unsigned int length;
2439 FieldTypes[2] = Context.UnsignedIntTy;
2442 for (unsigned i = 0; i < 3; ++i) {
2443 FieldDecl *Field = FieldDecl::Create(Context, D,
2445 SourceLocation(), 0,
2446 FieldTypes[i], /*TInfo=*/0,
2450 Field->setAccess(AS_public);
2454 D->completeDefinition();
2455 QualType NSTy = Context.getTagDeclType(D);
2456 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2459 llvm::Constant *Fields[3];
2462 Fields[0] = cast<llvm::ConstantExpr>(V);
2466 llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2468 llvm::GlobalValue::LinkageTypes Linkage;
2470 Linkage = llvm::GlobalValue::PrivateLinkage;
2471 isConstant = !LangOpts.WritableStrings;
2473 llvm::GlobalVariable *GV =
2474 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
2476 GV->setUnnamedAddr(true);
2477 // Don't enforce the target's minimum global alignment, since the only use
2478 // of the string is via this class initializer.
2479 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2480 GV->setAlignment(Align.getQuantity());
2481 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2484 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2485 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2488 C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
2489 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2490 llvm::GlobalVariable::PrivateLinkage, C,
2491 "_unnamed_nsstring_");
2492 // FIXME. Fix section.
2493 if (const char *Sect =
2494 LangOpts.ObjCRuntime.isNonFragile()
2495 ? getTarget().getNSStringNonFragileABISection()
2496 : getTarget().getNSStringSection())
2497 GV->setSection(Sect);
2503 QualType CodeGenModule::getObjCFastEnumerationStateType() {
2504 if (ObjCFastEnumerationStateType.isNull()) {
2505 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2506 Context.getTranslationUnitDecl(),
2507 &Context.Idents.get("__objcFastEnumerationState"));
2508 D->startDefinition();
2510 QualType FieldTypes[] = {
2511 Context.UnsignedLongTy,
2512 Context.getPointerType(Context.getObjCIdType()),
2513 Context.getPointerType(Context.UnsignedLongTy),
2514 Context.getConstantArrayType(Context.UnsignedLongTy,
2515 llvm::APInt(32, 5), ArrayType::Normal, 0)
2518 for (size_t i = 0; i < 4; ++i) {
2519 FieldDecl *Field = FieldDecl::Create(Context,
2522 SourceLocation(), 0,
2523 FieldTypes[i], /*TInfo=*/0,
2527 Field->setAccess(AS_public);
2531 D->completeDefinition();
2532 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2535 return ObjCFastEnumerationStateType;
2539 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2540 assert(!E->getType()->isPointerType() && "Strings are always arrays");
2542 // Don't emit it as the address of the string, emit the string data itself
2543 // as an inline array.
2544 if (E->getCharByteWidth() == 1) {
2545 SmallString<64> Str(E->getString());
2547 // Resize the string to the right size, which is indicated by its type.
2548 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2549 Str.resize(CAT->getSize().getZExtValue());
2550 return llvm::ConstantDataArray::getString(VMContext, Str, false);
2553 llvm::ArrayType *AType =
2554 cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
2555 llvm::Type *ElemTy = AType->getElementType();
2556 unsigned NumElements = AType->getNumElements();
2558 // Wide strings have either 2-byte or 4-byte elements.
2559 if (ElemTy->getPrimitiveSizeInBits() == 16) {
2560 SmallVector<uint16_t, 32> Elements;
2561 Elements.reserve(NumElements);
2563 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2564 Elements.push_back(E->getCodeUnit(i));
2565 Elements.resize(NumElements);
2566 return llvm::ConstantDataArray::get(VMContext, Elements);
2569 assert(ElemTy->getPrimitiveSizeInBits() == 32);
2570 SmallVector<uint32_t, 32> Elements;
2571 Elements.reserve(NumElements);
2573 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2574 Elements.push_back(E->getCodeUnit(i));
2575 Elements.resize(NumElements);
2576 return llvm::ConstantDataArray::get(VMContext, Elements);
2579 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2580 /// constant array for the given string literal.
2582 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
2583 CharUnits Align = getContext().getAlignOfGlobalVarInChars(S->getType());
2584 if (S->isAscii() || S->isUTF8()) {
2585 SmallString<64> Str(S->getString());
2587 // Resize the string to the right size, which is indicated by its type.
2588 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
2589 Str.resize(CAT->getSize().getZExtValue());
2590 return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity());
2593 // FIXME: the following does not memoize wide strings.
2594 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2595 llvm::GlobalVariable *GV =
2596 new llvm::GlobalVariable(getModule(),C->getType(),
2597 !LangOpts.WritableStrings,
2598 llvm::GlobalValue::PrivateLinkage,
2601 GV->setAlignment(Align.getQuantity());
2602 GV->setUnnamedAddr(true);
2606 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2607 /// array for the given ObjCEncodeExpr node.
2609 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2611 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
2613 return GetAddrOfConstantCString(Str);
2617 /// GenerateWritableString -- Creates storage for a string literal.
2618 static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
2621 const char *GlobalName,
2622 unsigned Alignment) {
2623 // Create Constant for this string literal. Don't add a '\0'.
2625 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
2627 // Create a global variable for this string
2628 llvm::GlobalVariable *GV =
2629 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
2630 llvm::GlobalValue::PrivateLinkage,
2632 GV->setAlignment(Alignment);
2633 GV->setUnnamedAddr(true);
2637 /// GetAddrOfConstantString - Returns a pointer to a character array
2638 /// containing the literal. This contents are exactly that of the
2639 /// given string, i.e. it will not be null terminated automatically;
2640 /// see GetAddrOfConstantCString. Note that whether the result is
2641 /// actually a pointer to an LLVM constant depends on
2642 /// Feature.WriteableStrings.
2644 /// The result has pointer to array type.
2645 llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
2646 const char *GlobalName,
2647 unsigned Alignment) {
2648 // Get the default prefix if a name wasn't specified.
2650 GlobalName = ".str";
2653 Alignment = getContext().getAlignOfGlobalVarInChars(getContext().CharTy)
2656 // Don't share any string literals if strings aren't constant.
2657 if (LangOpts.WritableStrings)
2658 return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
2660 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2661 ConstantStringMap.GetOrCreateValue(Str);
2663 if (llvm::GlobalVariable *GV = Entry.getValue()) {
2664 if (Alignment > GV->getAlignment()) {
2665 GV->setAlignment(Alignment);
2670 // Create a global variable for this.
2671 llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
2677 /// GetAddrOfConstantCString - Returns a pointer to a character
2678 /// array containing the literal and a terminating '\0'
2679 /// character. The result has pointer to array type.
2680 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
2681 const char *GlobalName,
2682 unsigned Alignment) {
2683 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
2684 return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
2687 /// EmitObjCPropertyImplementations - Emit information for synthesized
2688 /// properties for an implementation.
2689 void CodeGenModule::EmitObjCPropertyImplementations(const
2690 ObjCImplementationDecl *D) {
2691 for (ObjCImplementationDecl::propimpl_iterator
2692 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
2693 ObjCPropertyImplDecl *PID = *i;
2695 // Dynamic is just for type-checking.
2696 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2697 ObjCPropertyDecl *PD = PID->getPropertyDecl();
2699 // Determine which methods need to be implemented, some may have
2700 // been overridden. Note that ::isPropertyAccessor is not the method
2701 // we want, that just indicates if the decl came from a
2702 // property. What we want to know is if the method is defined in
2703 // this implementation.
2704 if (!D->getInstanceMethod(PD->getGetterName()))
2705 CodeGenFunction(*this).GenerateObjCGetter(
2706 const_cast<ObjCImplementationDecl *>(D), PID);
2707 if (!PD->isReadOnly() &&
2708 !D->getInstanceMethod(PD->getSetterName()))
2709 CodeGenFunction(*this).GenerateObjCSetter(
2710 const_cast<ObjCImplementationDecl *>(D), PID);
2715 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
2716 const ObjCInterfaceDecl *iface = impl->getClassInterface();
2717 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
2718 ivar; ivar = ivar->getNextIvar())
2719 if (ivar->getType().isDestructedType())
2725 /// EmitObjCIvarInitializations - Emit information for ivar initialization
2726 /// for an implementation.
2727 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
2728 // We might need a .cxx_destruct even if we don't have any ivar initializers.
2729 if (needsDestructMethod(D)) {
2730 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2731 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2732 ObjCMethodDecl *DTORMethod =
2733 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
2734 cxxSelector, getContext().VoidTy, 0, D,
2735 /*isInstance=*/true, /*isVariadic=*/false,
2736 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
2737 /*isDefined=*/false, ObjCMethodDecl::Required);
2738 D->addInstanceMethod(DTORMethod);
2739 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
2740 D->setHasDestructors(true);
2743 // If the implementation doesn't have any ivar initializers, we don't need
2744 // a .cxx_construct.
2745 if (D->getNumIvarInitializers() == 0)
2748 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2749 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2750 // The constructor returns 'self'.
2751 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2755 getContext().getObjCIdType(), 0,
2756 D, /*isInstance=*/true,
2757 /*isVariadic=*/false,
2758 /*isPropertyAccessor=*/true,
2759 /*isImplicitlyDeclared=*/true,
2760 /*isDefined=*/false,
2761 ObjCMethodDecl::Required);
2762 D->addInstanceMethod(CTORMethod);
2763 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
2764 D->setHasNonZeroConstructors(true);
2767 /// EmitNamespace - Emit all declarations in a namespace.
2768 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
2769 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
2771 EmitTopLevelDecl(*I);
2774 // EmitLinkageSpec - Emit all declarations in a linkage spec.
2775 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
2776 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2777 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
2778 ErrorUnsupported(LSD, "linkage spec");
2782 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
2784 // Meta-data for ObjC class includes references to implemented methods.
2785 // Generate class's method definitions first.
2786 if (ObjCImplDecl *OID = dyn_cast<ObjCImplDecl>(*I)) {
2787 for (ObjCContainerDecl::method_iterator M = OID->meth_begin(),
2788 MEnd = OID->meth_end();
2790 EmitTopLevelDecl(*M);
2792 EmitTopLevelDecl(*I);
2796 /// EmitTopLevelDecl - Emit code for a single top level declaration.
2797 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
2798 // If an error has occurred, stop code generation, but continue
2799 // parsing and semantic analysis (to ensure all warnings and errors
2801 if (Diags.hasErrorOccurred())
2804 // Ignore dependent declarations.
2805 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2808 switch (D->getKind()) {
2809 case Decl::CXXConversion:
2810 case Decl::CXXMethod:
2811 case Decl::Function:
2812 // Skip function templates
2813 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2814 cast<FunctionDecl>(D)->isLateTemplateParsed())
2817 EmitGlobal(cast<FunctionDecl>(D));
2821 EmitGlobal(cast<VarDecl>(D));
2824 // Indirect fields from global anonymous structs and unions can be
2825 // ignored; only the actual variable requires IR gen support.
2826 case Decl::IndirectField:
2830 case Decl::Namespace:
2831 EmitNamespace(cast<NamespaceDecl>(D));
2833 // No code generation needed.
2834 case Decl::UsingShadow:
2836 case Decl::ClassTemplate:
2837 case Decl::FunctionTemplate:
2838 case Decl::TypeAliasTemplate:
2839 case Decl::NamespaceAlias:
2843 case Decl::UsingDirective: // using namespace X; [C++]
2844 if (CGDebugInfo *DI = getModuleDebugInfo())
2845 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
2847 case Decl::CXXConstructor:
2848 // Skip function templates
2849 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2850 cast<FunctionDecl>(D)->isLateTemplateParsed())
2853 EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2855 case Decl::CXXDestructor:
2856 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
2858 EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2861 case Decl::StaticAssert:
2865 // Objective-C Decls
2867 // Forward declarations, no (immediate) code generation.
2868 case Decl::ObjCInterface:
2869 case Decl::ObjCCategory:
2872 case Decl::ObjCProtocol: {
2873 ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
2874 if (Proto->isThisDeclarationADefinition())
2875 ObjCRuntime->GenerateProtocol(Proto);
2879 case Decl::ObjCCategoryImpl:
2880 // Categories have properties but don't support synthesize so we
2881 // can ignore them here.
2882 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2885 case Decl::ObjCImplementation: {
2886 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2887 EmitObjCPropertyImplementations(OMD);
2888 EmitObjCIvarInitializations(OMD);
2889 ObjCRuntime->GenerateClass(OMD);
2890 // Emit global variable debug information.
2891 if (CGDebugInfo *DI = getModuleDebugInfo())
2892 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
2893 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
2894 OMD->getClassInterface()), OMD->getLocation());
2897 case Decl::ObjCMethod: {
2898 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2899 // If this is not a prototype, emit the body.
2901 CodeGenFunction(*this).GenerateObjCMethod(OMD);
2904 case Decl::ObjCCompatibleAlias:
2905 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
2908 case Decl::LinkageSpec:
2909 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
2912 case Decl::FileScopeAsm: {
2913 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
2914 StringRef AsmString = AD->getAsmString()->getString();
2916 const std::string &S = getModule().getModuleInlineAsm();
2918 getModule().setModuleInlineAsm(AsmString);
2919 else if (S.end()[-1] == '\n')
2920 getModule().setModuleInlineAsm(S + AsmString.str());
2922 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
2926 case Decl::Import: {
2927 ImportDecl *Import = cast<ImportDecl>(D);
2929 // Ignore import declarations that come from imported modules.
2930 if (clang::Module *Owner = Import->getOwningModule()) {
2931 if (getLangOpts().CurrentModule.empty() ||
2932 Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
2936 ImportedModules.insert(Import->getImportedModule());
2941 // Make sure we handled everything we should, every other kind is a
2942 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
2943 // function. Need to recode Decl::Kind to do that easily.
2944 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2948 /// Turns the given pointer into a constant.
2949 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2951 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2952 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2953 return llvm::ConstantInt::get(i64, PtrInt);
2956 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2957 llvm::NamedMDNode *&GlobalMetadata,
2959 llvm::GlobalValue *Addr) {
2960 if (!GlobalMetadata)
2962 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2964 // TODO: should we report variant information for ctors/dtors?
2965 llvm::Value *Ops[] = {
2967 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2969 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2972 /// For each function which is declared within an extern "C" region and marked
2973 /// as 'used', but has internal linkage, create an alias from the unmangled
2974 /// name to the mangled name if possible. People expect to be able to refer
2975 /// to such functions with an unmangled name from inline assembly within the
2976 /// same translation unit.
2977 void CodeGenModule::EmitStaticExternCAliases() {
2978 for (StaticExternCMap::iterator I = StaticExternCValues.begin(),
2979 E = StaticExternCValues.end();
2981 IdentifierInfo *Name = I->first;
2982 llvm::GlobalValue *Val = I->second;
2983 if (Val && !getModule().getNamedValue(Name->getName()))
2984 AddUsedGlobal(new llvm::GlobalAlias(Val->getType(), Val->getLinkage(),
2985 Name->getName(), Val, &getModule()));
2989 /// Emits metadata nodes associating all the global values in the
2990 /// current module with the Decls they came from. This is useful for
2991 /// projects using IR gen as a subroutine.
2993 /// Since there's currently no way to associate an MDNode directly
2994 /// with an llvm::GlobalValue, we create a global named metadata
2995 /// with the name 'clang.global.decl.ptrs'.
2996 void CodeGenModule::EmitDeclMetadata() {
2997 llvm::NamedMDNode *GlobalMetadata = 0;
2999 // StaticLocalDeclMap
3000 for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
3001 I = MangledDeclNames.begin(), E = MangledDeclNames.end();
3003 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
3004 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
3008 /// Emits metadata nodes for all the local variables in the current
3010 void CodeGenFunction::EmitDeclMetadata() {
3011 if (LocalDeclMap.empty()) return;
3013 llvm::LLVMContext &Context = getLLVMContext();
3015 // Find the unique metadata ID for this name.
3016 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
3018 llvm::NamedMDNode *GlobalMetadata = 0;
3020 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
3021 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
3022 const Decl *D = I->first;
3023 llvm::Value *Addr = I->second;
3025 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
3026 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
3027 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
3028 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
3029 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
3030 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
3035 void CodeGenModule::EmitCoverageFile() {
3036 if (!getCodeGenOpts().CoverageFile.empty()) {
3037 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
3038 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
3039 llvm::LLVMContext &Ctx = TheModule.getContext();
3040 llvm::MDString *CoverageFile =
3041 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
3042 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
3043 llvm::MDNode *CU = CUNode->getOperand(i);
3044 llvm::Value *node[] = { CoverageFile, CU };
3045 llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
3046 GCov->addOperand(N);
3052 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid,
3053 QualType GuidType) {
3054 // Sema has checked that all uuid strings are of the form
3055 // "12345678-1234-1234-1234-1234567890ab".
3056 assert(Uuid.size() == 36);
3057 const char *Uuidstr = Uuid.data();
3058 for (int i = 0; i < 36; ++i) {
3059 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuidstr[i] == '-');
3060 else assert(isHexDigit(Uuidstr[i]));
3063 llvm::APInt Field0(32, StringRef(Uuidstr , 8), 16);
3064 llvm::APInt Field1(16, StringRef(Uuidstr + 9, 4), 16);
3065 llvm::APInt Field2(16, StringRef(Uuidstr + 14, 4), 16);
3066 static const int Field3ValueOffsets[] = { 19, 21, 24, 26, 28, 30, 32, 34 };
3068 APValue InitStruct(APValue::UninitStruct(), /*NumBases=*/0, /*NumFields=*/4);
3069 InitStruct.getStructField(0) = APValue(llvm::APSInt(Field0));
3070 InitStruct.getStructField(1) = APValue(llvm::APSInt(Field1));
3071 InitStruct.getStructField(2) = APValue(llvm::APSInt(Field2));
3072 APValue& Arr = InitStruct.getStructField(3);
3073 Arr = APValue(APValue::UninitArray(), 8, 8);
3074 for (int t = 0; t < 8; ++t)
3075 Arr.getArrayInitializedElt(t) = APValue(llvm::APSInt(
3076 llvm::APInt(8, StringRef(Uuidstr + Field3ValueOffsets[t], 2), 16)));
3078 return EmitConstantValue(InitStruct, GuidType);