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 "CGOpenMPRuntime.h"
22 #include "CodeGenFunction.h"
23 #include "CodeGenPGO.h"
24 #include "CodeGenTBAA.h"
25 #include "CoverageMappingGen.h"
26 #include "TargetInfo.h"
27 #include "clang/AST/ASTContext.h"
28 #include "clang/AST/CharUnits.h"
29 #include "clang/AST/DeclCXX.h"
30 #include "clang/AST/DeclObjC.h"
31 #include "clang/AST/DeclTemplate.h"
32 #include "clang/AST/Mangle.h"
33 #include "clang/AST/RecordLayout.h"
34 #include "clang/AST/RecursiveASTVisitor.h"
35 #include "clang/Basic/Builtins.h"
36 #include "clang/Basic/CharInfo.h"
37 #include "clang/Basic/Diagnostic.h"
38 #include "clang/Basic/Module.h"
39 #include "clang/Basic/SourceManager.h"
40 #include "clang/Basic/TargetInfo.h"
41 #include "clang/Basic/Version.h"
42 #include "clang/Frontend/CodeGenOptions.h"
43 #include "clang/Sema/SemaDiagnostic.h"
44 #include "llvm/ADT/APSInt.h"
45 #include "llvm/ADT/Triple.h"
46 #include "llvm/IR/CallSite.h"
47 #include "llvm/IR/CallingConv.h"
48 #include "llvm/IR/DataLayout.h"
49 #include "llvm/IR/Intrinsics.h"
50 #include "llvm/IR/LLVMContext.h"
51 #include "llvm/IR/Module.h"
52 #include "llvm/ProfileData/InstrProfReader.h"
53 #include "llvm/Support/ConvertUTF.h"
54 #include "llvm/Support/ErrorHandling.h"
56 using namespace clang;
57 using namespace CodeGen;
59 static const char AnnotationSection[] = "llvm.metadata";
61 static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
62 switch (CGM.getTarget().getCXXABI().getKind()) {
63 case TargetCXXABI::GenericAArch64:
64 case TargetCXXABI::GenericARM:
65 case TargetCXXABI::iOS:
66 case TargetCXXABI::iOS64:
67 case TargetCXXABI::GenericItanium:
68 return CreateItaniumCXXABI(CGM);
69 case TargetCXXABI::Microsoft:
70 return CreateMicrosoftCXXABI(CGM);
73 llvm_unreachable("invalid C++ ABI kind");
76 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
77 llvm::Module &M, const llvm::DataLayout &TD,
78 DiagnosticsEngine &diags,
79 CoverageSourceInfo *CoverageInfo)
80 : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
81 Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()),
82 ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(nullptr),
83 TheTargetCodeGenInfo(nullptr), Types(*this), VTables(*this),
84 ObjCRuntime(nullptr), OpenCLRuntime(nullptr), OpenMPRuntime(nullptr),
85 CUDARuntime(nullptr), DebugInfo(nullptr), ARCData(nullptr),
86 NoObjCARCExceptionsMetadata(nullptr), RRData(nullptr), PGOReader(nullptr),
87 CFConstantStringClassRef(nullptr), ConstantStringClassRef(nullptr),
88 NSConstantStringType(nullptr), NSConcreteGlobalBlock(nullptr),
89 NSConcreteStackBlock(nullptr), BlockObjectAssign(nullptr),
90 BlockObjectDispose(nullptr), BlockDescriptorType(nullptr),
91 GenericBlockLiteralType(nullptr), LifetimeStartFn(nullptr),
92 LifetimeEndFn(nullptr), SanitizerMD(new SanitizerMetadata(*this)) {
94 // Initialize the type cache.
95 llvm::LLVMContext &LLVMContext = M.getContext();
96 VoidTy = llvm::Type::getVoidTy(LLVMContext);
97 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
98 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
99 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
100 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
101 FloatTy = llvm::Type::getFloatTy(LLVMContext);
102 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
103 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
104 PointerAlignInBytes =
105 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
106 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
107 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
108 Int8PtrTy = Int8Ty->getPointerTo(0);
109 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
111 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
112 BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
117 createOpenCLRuntime();
119 createOpenMPRuntime();
123 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
124 if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
125 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
126 TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
127 getCXXABI().getMangleContext());
129 // If debug info or coverage generation is enabled, create the CGDebugInfo
131 if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
132 CodeGenOpts.EmitGcovArcs ||
133 CodeGenOpts.EmitGcovNotes)
134 DebugInfo = new CGDebugInfo(*this);
136 Block.GlobalUniqueCount = 0;
138 if (C.getLangOpts().ObjCAutoRefCount)
139 ARCData = new ARCEntrypoints();
140 RRData = new RREntrypoints();
142 if (!CodeGenOpts.InstrProfileInput.empty()) {
143 if (std::error_code EC = llvm::IndexedInstrProfReader::create(
144 CodeGenOpts.InstrProfileInput, PGOReader)) {
145 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
146 "Could not read profile: %0");
147 getDiags().Report(DiagID) << EC.message();
151 // If coverage mapping generation is enabled, create the
152 // CoverageMappingModuleGen object.
153 if (CodeGenOpts.CoverageMapping)
154 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
157 CodeGenModule::~CodeGenModule() {
159 delete OpenCLRuntime;
160 delete OpenMPRuntime;
162 delete TheTargetCodeGenInfo;
169 void CodeGenModule::createObjCRuntime() {
170 // This is just isGNUFamily(), but we want to force implementors of
171 // new ABIs to decide how best to do this.
172 switch (LangOpts.ObjCRuntime.getKind()) {
173 case ObjCRuntime::GNUstep:
174 case ObjCRuntime::GCC:
175 case ObjCRuntime::ObjFW:
176 ObjCRuntime = CreateGNUObjCRuntime(*this);
179 case ObjCRuntime::FragileMacOSX:
180 case ObjCRuntime::MacOSX:
181 case ObjCRuntime::iOS:
182 ObjCRuntime = CreateMacObjCRuntime(*this);
185 llvm_unreachable("bad runtime kind");
188 void CodeGenModule::createOpenCLRuntime() {
189 OpenCLRuntime = new CGOpenCLRuntime(*this);
192 void CodeGenModule::createOpenMPRuntime() {
193 OpenMPRuntime = new CGOpenMPRuntime(*this);
196 void CodeGenModule::createCUDARuntime() {
197 CUDARuntime = CreateNVCUDARuntime(*this);
200 void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
201 Replacements[Name] = C;
204 void CodeGenModule::applyReplacements() {
205 for (ReplacementsTy::iterator I = Replacements.begin(),
206 E = Replacements.end();
208 StringRef MangledName = I->first();
209 llvm::Constant *Replacement = I->second;
210 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
213 auto *OldF = cast<llvm::Function>(Entry);
214 auto *NewF = dyn_cast<llvm::Function>(Replacement);
216 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
217 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
219 auto *CE = cast<llvm::ConstantExpr>(Replacement);
220 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
221 CE->getOpcode() == llvm::Instruction::GetElementPtr);
222 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
226 // Replace old with new, but keep the old order.
227 OldF->replaceAllUsesWith(Replacement);
229 NewF->removeFromParent();
230 OldF->getParent()->getFunctionList().insertAfter(OldF, NewF);
232 OldF->eraseFromParent();
236 // This is only used in aliases that we created and we know they have a
238 static const llvm::GlobalObject *getAliasedGlobal(const llvm::GlobalAlias &GA) {
239 llvm::SmallPtrSet<const llvm::GlobalAlias*, 4> Visited;
240 const llvm::Constant *C = &GA;
242 C = C->stripPointerCasts();
243 if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
245 // stripPointerCasts will not walk over weak aliases.
246 auto *GA2 = dyn_cast<llvm::GlobalAlias>(C);
249 if (!Visited.insert(GA2).second)
251 C = GA2->getAliasee();
255 void CodeGenModule::checkAliases() {
256 // Check if the constructed aliases are well formed. It is really unfortunate
257 // that we have to do this in CodeGen, but we only construct mangled names
258 // and aliases during codegen.
260 DiagnosticsEngine &Diags = getDiags();
261 for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
262 E = Aliases.end(); I != E; ++I) {
263 const GlobalDecl &GD = *I;
264 const auto *D = cast<ValueDecl>(GD.getDecl());
265 const AliasAttr *AA = D->getAttr<AliasAttr>();
266 StringRef MangledName = getMangledName(GD);
267 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
268 auto *Alias = cast<llvm::GlobalAlias>(Entry);
269 const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
272 Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
273 } else if (GV->isDeclaration()) {
275 Diags.Report(AA->getLocation(), diag::err_alias_to_undefined);
278 llvm::Constant *Aliasee = Alias->getAliasee();
279 llvm::GlobalValue *AliaseeGV;
280 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
281 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
283 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
285 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
286 StringRef AliasSection = SA->getName();
287 if (AliasSection != AliaseeGV->getSection())
288 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
292 // We have to handle alias to weak aliases in here. LLVM itself disallows
293 // this since the object semantics would not match the IL one. For
294 // compatibility with gcc we implement it by just pointing the alias
295 // to its aliasee's aliasee. We also warn, since the user is probably
296 // expecting the link to be weak.
297 if (auto GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
298 if (GA->mayBeOverridden()) {
299 Diags.Report(AA->getLocation(), diag::warn_alias_to_weak_alias)
300 << GV->getName() << GA->getName();
301 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
302 GA->getAliasee(), Alias->getType());
303 Alias->setAliasee(Aliasee);
310 for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
311 E = Aliases.end(); I != E; ++I) {
312 const GlobalDecl &GD = *I;
313 StringRef MangledName = getMangledName(GD);
314 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
315 auto *Alias = cast<llvm::GlobalAlias>(Entry);
316 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
317 Alias->eraseFromParent();
321 void CodeGenModule::clear() {
322 DeferredDeclsToEmit.clear();
325 void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
326 StringRef MainFile) {
327 if (!hasDiagnostics())
329 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
330 if (MainFile.empty())
331 MainFile = "<stdin>";
332 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
334 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Missing
338 void CodeGenModule::Release() {
342 EmitCXXGlobalInitFunc();
343 EmitCXXGlobalDtorFunc();
344 EmitCXXThreadLocalInitFunc();
346 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
347 AddGlobalCtor(ObjCInitFunction);
348 if (PGOReader && PGOStats.hasDiagnostics())
349 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
350 EmitCtorList(GlobalCtors, "llvm.global_ctors");
351 EmitCtorList(GlobalDtors, "llvm.global_dtors");
352 EmitGlobalAnnotations();
353 EmitStaticExternCAliases();
354 EmitDeferredUnusedCoverageMappings();
356 CoverageMapping->emit();
359 if (CodeGenOpts.Autolink &&
360 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
361 EmitModuleLinkOptions();
363 if (CodeGenOpts.DwarfVersion)
364 // We actually want the latest version when there are conflicts.
365 // We can change from Warning to Latest if such mode is supported.
366 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
367 CodeGenOpts.DwarfVersion);
369 // We support a single version in the linked module. The LLVM
370 // parser will drop debug info with a different version number
371 // (and warn about it, too).
372 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
373 llvm::DEBUG_METADATA_VERSION);
375 // We need to record the widths of enums and wchar_t, so that we can generate
376 // the correct build attributes in the ARM backend.
377 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
378 if ( Arch == llvm::Triple::arm
379 || Arch == llvm::Triple::armeb
380 || Arch == llvm::Triple::thumb
381 || Arch == llvm::Triple::thumbeb) {
382 // Width of wchar_t in bytes
383 uint64_t WCharWidth =
384 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
385 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
387 // The minimum width of an enum in bytes
388 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
389 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
392 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
393 llvm::PICLevel::Level PL = llvm::PICLevel::Default;
396 case 1: PL = llvm::PICLevel::Small; break;
397 case 2: PL = llvm::PICLevel::Large; break;
398 default: llvm_unreachable("Invalid PIC Level");
401 getModule().setPICLevel(PL);
404 SimplifyPersonality();
406 if (getCodeGenOpts().EmitDeclMetadata)
409 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
413 DebugInfo->finalize();
415 EmitVersionIdentMetadata();
417 EmitTargetMetadata();
420 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
421 // Make sure that this type is translated.
422 Types.UpdateCompletedType(TD);
425 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
428 return TBAA->getTBAAInfo(QTy);
431 llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
434 return TBAA->getTBAAInfoForVTablePtr();
437 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
440 return TBAA->getTBAAStructInfo(QTy);
443 llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) {
446 return TBAA->getTBAAStructTypeInfo(QTy);
449 llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
450 llvm::MDNode *AccessN,
454 return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
457 /// Decorate the instruction with a TBAA tag. For both scalar TBAA
458 /// and struct-path aware TBAA, the tag has the same format:
459 /// base type, access type and offset.
460 /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
461 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
462 llvm::MDNode *TBAAInfo,
463 bool ConvertTypeToTag) {
464 if (ConvertTypeToTag && TBAA)
465 Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
466 TBAA->getTBAAScalarTagInfo(TBAAInfo));
468 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
471 void CodeGenModule::Error(SourceLocation loc, StringRef message) {
472 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
473 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
476 /// ErrorUnsupported - Print out an error that codegen doesn't support the
477 /// specified stmt yet.
478 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
479 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
480 "cannot compile this %0 yet");
481 std::string Msg = Type;
482 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
483 << Msg << S->getSourceRange();
486 /// ErrorUnsupported - Print out an error that codegen doesn't support the
487 /// specified decl yet.
488 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
489 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
490 "cannot compile this %0 yet");
491 std::string Msg = Type;
492 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
495 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
496 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
499 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
500 const NamedDecl *D) const {
501 // Internal definitions always have default visibility.
502 if (GV->hasLocalLinkage()) {
503 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
507 // Set visibility for definitions.
508 LinkageInfo LV = D->getLinkageAndVisibility();
509 if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
510 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
513 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
514 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
515 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
516 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
517 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
518 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
521 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
522 CodeGenOptions::TLSModel M) {
524 case CodeGenOptions::GeneralDynamicTLSModel:
525 return llvm::GlobalVariable::GeneralDynamicTLSModel;
526 case CodeGenOptions::LocalDynamicTLSModel:
527 return llvm::GlobalVariable::LocalDynamicTLSModel;
528 case CodeGenOptions::InitialExecTLSModel:
529 return llvm::GlobalVariable::InitialExecTLSModel;
530 case CodeGenOptions::LocalExecTLSModel:
531 return llvm::GlobalVariable::LocalExecTLSModel;
533 llvm_unreachable("Invalid TLS model!");
536 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
537 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
539 llvm::GlobalValue::ThreadLocalMode TLM;
540 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
542 // Override the TLS model if it is explicitly specified.
543 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
544 TLM = GetLLVMTLSModel(Attr->getModel());
547 GV->setThreadLocalMode(TLM);
550 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
551 StringRef &FoundStr = MangledDeclNames[GD.getCanonicalDecl()];
552 if (!FoundStr.empty())
555 const auto *ND = cast<NamedDecl>(GD.getDecl());
556 SmallString<256> Buffer;
558 if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
559 llvm::raw_svector_ostream Out(Buffer);
560 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
561 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
562 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
563 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
565 getCXXABI().getMangleContext().mangleName(ND, Out);
568 IdentifierInfo *II = ND->getIdentifier();
569 assert(II && "Attempt to mangle unnamed decl.");
573 // Keep the first result in the case of a mangling collision.
574 auto Result = Manglings.insert(std::make_pair(Str, GD));
575 return FoundStr = Result.first->first();
578 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
579 const BlockDecl *BD) {
580 MangleContext &MangleCtx = getCXXABI().getMangleContext();
581 const Decl *D = GD.getDecl();
583 SmallString<256> Buffer;
584 llvm::raw_svector_ostream Out(Buffer);
586 MangleCtx.mangleGlobalBlock(BD,
587 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
588 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
589 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
590 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
591 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
593 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
595 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
596 return Result.first->first();
599 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
600 return getModule().getNamedValue(Name);
603 /// AddGlobalCtor - Add a function to the list that will be called before
605 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
606 llvm::Constant *AssociatedData) {
607 // FIXME: Type coercion of void()* types.
608 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
611 /// AddGlobalDtor - Add a function to the list that will be called
612 /// when the module is unloaded.
613 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
614 // FIXME: Type coercion of void()* types.
615 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
618 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
619 // Ctor function type is void()*.
620 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
621 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
623 // Get the type of a ctor entry, { i32, void ()*, i8* }.
624 llvm::StructType *CtorStructTy = llvm::StructType::get(
625 Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr);
627 // Construct the constructor and destructor arrays.
628 SmallVector<llvm::Constant*, 8> Ctors;
629 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
630 llvm::Constant *S[] = {
631 llvm::ConstantInt::get(Int32Ty, I->Priority, false),
632 llvm::ConstantExpr::getBitCast(I->Initializer, CtorPFTy),
634 ? llvm::ConstantExpr::getBitCast(I->AssociatedData, VoidPtrTy)
635 : llvm::Constant::getNullValue(VoidPtrTy))
637 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
640 if (!Ctors.empty()) {
641 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
642 new llvm::GlobalVariable(TheModule, AT, false,
643 llvm::GlobalValue::AppendingLinkage,
644 llvm::ConstantArray::get(AT, Ctors),
649 llvm::GlobalValue::LinkageTypes
650 CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
651 const auto *D = cast<FunctionDecl>(GD.getDecl());
653 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
655 if (isa<CXXDestructorDecl>(D) &&
656 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
658 // Destructor variants in the Microsoft C++ ABI are always internal or
659 // linkonce_odr thunks emitted on an as-needed basis.
660 return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
661 : llvm::GlobalValue::LinkOnceODRLinkage;
664 return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
667 void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
669 setNonAliasAttributes(D, F);
672 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
673 const CGFunctionInfo &Info,
675 unsigned CallingConv;
676 AttributeListType AttributeList;
677 ConstructAttributeList(Info, D, AttributeList, CallingConv, false);
678 F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
679 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
682 /// Determines whether the language options require us to model
683 /// unwind exceptions. We treat -fexceptions as mandating this
684 /// except under the fragile ObjC ABI with only ObjC exceptions
685 /// enabled. This means, for example, that C with -fexceptions
687 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
688 // If exceptions are completely disabled, obviously this is false.
689 if (!LangOpts.Exceptions) return false;
691 // If C++ exceptions are enabled, this is true.
692 if (LangOpts.CXXExceptions) return true;
694 // If ObjC exceptions are enabled, this depends on the ABI.
695 if (LangOpts.ObjCExceptions) {
696 return LangOpts.ObjCRuntime.hasUnwindExceptions();
702 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
706 if (CodeGenOpts.UnwindTables)
707 B.addAttribute(llvm::Attribute::UWTable);
709 if (!hasUnwindExceptions(LangOpts))
710 B.addAttribute(llvm::Attribute::NoUnwind);
712 if (D->hasAttr<NakedAttr>()) {
713 // Naked implies noinline: we should not be inlining such functions.
714 B.addAttribute(llvm::Attribute::Naked);
715 B.addAttribute(llvm::Attribute::NoInline);
716 } else if (D->hasAttr<NoDuplicateAttr>()) {
717 B.addAttribute(llvm::Attribute::NoDuplicate);
718 } else if (D->hasAttr<NoInlineAttr>()) {
719 B.addAttribute(llvm::Attribute::NoInline);
720 } else if (D->hasAttr<AlwaysInlineAttr>() &&
721 !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
722 llvm::Attribute::NoInline)) {
723 // (noinline wins over always_inline, and we can't specify both in IR)
724 B.addAttribute(llvm::Attribute::AlwaysInline);
727 if (D->hasAttr<ColdAttr>()) {
728 if (!D->hasAttr<OptimizeNoneAttr>())
729 B.addAttribute(llvm::Attribute::OptimizeForSize);
730 B.addAttribute(llvm::Attribute::Cold);
733 if (D->hasAttr<MinSizeAttr>())
734 B.addAttribute(llvm::Attribute::MinSize);
736 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
737 B.addAttribute(llvm::Attribute::StackProtect);
738 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
739 B.addAttribute(llvm::Attribute::StackProtectStrong);
740 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
741 B.addAttribute(llvm::Attribute::StackProtectReq);
743 // Add sanitizer attributes if function is not blacklisted.
744 if (!isInSanitizerBlacklist(F, D->getLocation())) {
745 // When AddressSanitizer is enabled, set SanitizeAddress attribute
746 // unless __attribute__((no_sanitize_address)) is used.
747 if (LangOpts.Sanitize.has(SanitizerKind::Address) &&
748 !D->hasAttr<NoSanitizeAddressAttr>())
749 B.addAttribute(llvm::Attribute::SanitizeAddress);
750 // Same for ThreadSanitizer and __attribute__((no_sanitize_thread))
751 if (LangOpts.Sanitize.has(SanitizerKind::Thread) &&
752 !D->hasAttr<NoSanitizeThreadAttr>())
753 B.addAttribute(llvm::Attribute::SanitizeThread);
754 // Same for MemorySanitizer and __attribute__((no_sanitize_memory))
755 if (LangOpts.Sanitize.has(SanitizerKind::Memory) &&
756 !D->hasAttr<NoSanitizeMemoryAttr>())
757 B.addAttribute(llvm::Attribute::SanitizeMemory);
760 F->addAttributes(llvm::AttributeSet::FunctionIndex,
761 llvm::AttributeSet::get(
762 F->getContext(), llvm::AttributeSet::FunctionIndex, B));
764 if (D->hasAttr<OptimizeNoneAttr>()) {
765 // OptimizeNone implies noinline; we should not be inlining such functions.
766 F->addFnAttr(llvm::Attribute::OptimizeNone);
767 F->addFnAttr(llvm::Attribute::NoInline);
769 // OptimizeNone wins over OptimizeForSize, MinSize, AlwaysInline.
770 assert(!F->hasFnAttribute(llvm::Attribute::OptimizeForSize) &&
771 "OptimizeNone and OptimizeForSize on same function!");
772 assert(!F->hasFnAttribute(llvm::Attribute::MinSize) &&
773 "OptimizeNone and MinSize on same function!");
774 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
775 "OptimizeNone and AlwaysInline on same function!");
777 // Attribute 'inlinehint' has no effect on 'optnone' functions.
778 // Explicitly remove it from the set of function attributes.
779 F->removeFnAttr(llvm::Attribute::InlineHint);
782 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
783 F->setUnnamedAddr(true);
784 else if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
786 F->setUnnamedAddr(true);
788 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
790 F->setAlignment(alignment);
792 // C++ ABI requires 2-byte alignment for member functions.
793 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
797 void CodeGenModule::SetCommonAttributes(const Decl *D,
798 llvm::GlobalValue *GV) {
799 if (const auto *ND = dyn_cast<NamedDecl>(D))
800 setGlobalVisibility(GV, ND);
802 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
804 if (D->hasAttr<UsedAttr>())
808 void CodeGenModule::setAliasAttributes(const Decl *D,
809 llvm::GlobalValue *GV) {
810 SetCommonAttributes(D, GV);
812 // Process the dllexport attribute based on whether the original definition
813 // (not necessarily the aliasee) was exported.
814 if (D->hasAttr<DLLExportAttr>())
815 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
818 void CodeGenModule::setNonAliasAttributes(const Decl *D,
819 llvm::GlobalObject *GO) {
820 SetCommonAttributes(D, GO);
822 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
823 GO->setSection(SA->getName());
825 getTargetCodeGenInfo().SetTargetAttributes(D, GO, *this);
828 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
830 const CGFunctionInfo &FI) {
831 SetLLVMFunctionAttributes(D, FI, F);
832 SetLLVMFunctionAttributesForDefinition(D, F);
834 F->setLinkage(llvm::Function::InternalLinkage);
836 setNonAliasAttributes(D, F);
839 static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
840 const NamedDecl *ND) {
841 // Set linkage and visibility in case we never see a definition.
842 LinkageInfo LV = ND->getLinkageAndVisibility();
843 if (LV.getLinkage() != ExternalLinkage) {
844 // Don't set internal linkage on declarations.
846 if (ND->hasAttr<DLLImportAttr>()) {
847 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
848 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
849 } else if (ND->hasAttr<DLLExportAttr>()) {
850 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
851 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
852 } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
853 // "extern_weak" is overloaded in LLVM; we probably should have
854 // separate linkage types for this.
855 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
858 // Set visibility on a declaration only if it's explicit.
859 if (LV.isVisibilityExplicit())
860 GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
864 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
865 bool IsIncompleteFunction,
867 if (unsigned IID = F->getIntrinsicID()) {
868 // If this is an intrinsic function, set the function's attributes
869 // to the intrinsic's attributes.
870 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(),
871 (llvm::Intrinsic::ID)IID));
875 const auto *FD = cast<FunctionDecl>(GD.getDecl());
877 if (!IsIncompleteFunction)
878 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
880 // Add the Returned attribute for "this", except for iOS 5 and earlier
881 // where substantial code, including the libstdc++ dylib, was compiled with
882 // GCC and does not actually return "this".
883 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
884 !(getTarget().getTriple().isiOS() &&
885 getTarget().getTriple().isOSVersionLT(6))) {
886 assert(!F->arg_empty() &&
887 F->arg_begin()->getType()
888 ->canLosslesslyBitCastTo(F->getReturnType()) &&
889 "unexpected this return");
890 F->addAttribute(1, llvm::Attribute::Returned);
893 // Only a few attributes are set on declarations; these may later be
894 // overridden by a definition.
896 setLinkageAndVisibilityForGV(F, FD);
898 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
899 if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
900 // Don't dllexport/import destructor thunks.
901 F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
905 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
906 F->setSection(SA->getName());
908 // A replaceable global allocation function does not act like a builtin by
909 // default, only if it is invoked by a new-expression or delete-expression.
910 if (FD->isReplaceableGlobalAllocationFunction())
911 F->addAttribute(llvm::AttributeSet::FunctionIndex,
912 llvm::Attribute::NoBuiltin);
915 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
916 assert(!GV->isDeclaration() &&
917 "Only globals with definition can force usage.");
918 LLVMUsed.push_back(GV);
921 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
922 assert(!GV->isDeclaration() &&
923 "Only globals with definition can force usage.");
924 LLVMCompilerUsed.push_back(GV);
927 static void emitUsed(CodeGenModule &CGM, StringRef Name,
928 std::vector<llvm::WeakVH> &List) {
929 // Don't create llvm.used if there is no need.
933 // Convert List to what ConstantArray needs.
934 SmallVector<llvm::Constant*, 8> UsedArray;
935 UsedArray.resize(List.size());
936 for (unsigned i = 0, e = List.size(); i != e; ++i) {
938 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*List[i]),
942 if (UsedArray.empty())
944 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
946 auto *GV = new llvm::GlobalVariable(
947 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
948 llvm::ConstantArray::get(ATy, UsedArray), Name);
950 GV->setSection("llvm.metadata");
953 void CodeGenModule::emitLLVMUsed() {
954 emitUsed(*this, "llvm.used", LLVMUsed);
955 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
958 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
959 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
960 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
963 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
964 llvm::SmallString<32> Opt;
965 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
966 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
967 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
970 void CodeGenModule::AddDependentLib(StringRef Lib) {
971 llvm::SmallString<24> Opt;
972 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
973 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
974 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
977 /// \brief Add link options implied by the given module, including modules
978 /// it depends on, using a postorder walk.
979 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
980 SmallVectorImpl<llvm::Metadata *> &Metadata,
981 llvm::SmallPtrSet<Module *, 16> &Visited) {
982 // Import this module's parent.
983 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
984 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
987 // Import this module's dependencies.
988 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
989 if (Visited.insert(Mod->Imports[I - 1]).second)
990 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
993 // Add linker options to link against the libraries/frameworks
994 // described by this module.
995 llvm::LLVMContext &Context = CGM.getLLVMContext();
996 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
997 // Link against a framework. Frameworks are currently Darwin only, so we
998 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
999 if (Mod->LinkLibraries[I-1].IsFramework) {
1000 llvm::Metadata *Args[2] = {
1001 llvm::MDString::get(Context, "-framework"),
1002 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1004 Metadata.push_back(llvm::MDNode::get(Context, Args));
1008 // Link against a library.
1009 llvm::SmallString<24> Opt;
1010 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1011 Mod->LinkLibraries[I-1].Library, Opt);
1012 auto *OptString = llvm::MDString::get(Context, Opt);
1013 Metadata.push_back(llvm::MDNode::get(Context, OptString));
1017 void CodeGenModule::EmitModuleLinkOptions() {
1018 // Collect the set of all of the modules we want to visit to emit link
1019 // options, which is essentially the imported modules and all of their
1020 // non-explicit child modules.
1021 llvm::SetVector<clang::Module *> LinkModules;
1022 llvm::SmallPtrSet<clang::Module *, 16> Visited;
1023 SmallVector<clang::Module *, 16> Stack;
1025 // Seed the stack with imported modules.
1026 for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(),
1027 MEnd = ImportedModules.end();
1029 if (Visited.insert(*M).second)
1030 Stack.push_back(*M);
1033 // Find all of the modules to import, making a little effort to prune
1034 // non-leaf modules.
1035 while (!Stack.empty()) {
1036 clang::Module *Mod = Stack.pop_back_val();
1038 bool AnyChildren = false;
1040 // Visit the submodules of this module.
1041 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1042 SubEnd = Mod->submodule_end();
1043 Sub != SubEnd; ++Sub) {
1044 // Skip explicit children; they need to be explicitly imported to be
1046 if ((*Sub)->IsExplicit)
1049 if (Visited.insert(*Sub).second) {
1050 Stack.push_back(*Sub);
1055 // We didn't find any children, so add this module to the list of
1056 // modules to link against.
1058 LinkModules.insert(Mod);
1062 // Add link options for all of the imported modules in reverse topological
1063 // order. We don't do anything to try to order import link flags with respect
1064 // to linker options inserted by things like #pragma comment().
1065 SmallVector<llvm::Metadata *, 16> MetadataArgs;
1067 for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(),
1068 MEnd = LinkModules.end();
1070 if (Visited.insert(*M).second)
1071 addLinkOptionsPostorder(*this, *M, MetadataArgs, Visited);
1073 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1074 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1076 // Add the linker options metadata flag.
1077 getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
1078 llvm::MDNode::get(getLLVMContext(),
1079 LinkerOptionsMetadata));
1082 void CodeGenModule::EmitDeferred() {
1083 // Emit code for any potentially referenced deferred decls. Since a
1084 // previously unused static decl may become used during the generation of code
1085 // for a static function, iterate until no changes are made.
1088 if (!DeferredVTables.empty()) {
1089 EmitDeferredVTables();
1091 // Emitting a v-table doesn't directly cause more v-tables to
1092 // become deferred, although it can cause functions to be
1093 // emitted that then need those v-tables.
1094 assert(DeferredVTables.empty());
1097 // Stop if we're out of both deferred v-tables and deferred declarations.
1098 if (DeferredDeclsToEmit.empty()) break;
1100 DeferredGlobal &G = DeferredDeclsToEmit.back();
1101 GlobalDecl D = G.GD;
1102 llvm::GlobalValue *GV = G.GV;
1103 DeferredDeclsToEmit.pop_back();
1105 assert(!GV || GV == GetGlobalValue(getMangledName(D)));
1107 GV = GetGlobalValue(getMangledName(D));
1110 // Check to see if we've already emitted this. This is necessary
1111 // for a couple of reasons: first, decls can end up in the
1112 // deferred-decls queue multiple times, and second, decls can end
1113 // up with definitions in unusual ways (e.g. by an extern inline
1114 // function acquiring a strong function redefinition). Just
1115 // ignore these cases.
1116 if (GV && !GV->isDeclaration())
1119 // Otherwise, emit the definition and move on to the next one.
1120 EmitGlobalDefinition(D, GV);
1124 void CodeGenModule::EmitGlobalAnnotations() {
1125 if (Annotations.empty())
1128 // Create a new global variable for the ConstantStruct in the Module.
1129 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1130 Annotations[0]->getType(), Annotations.size()), Annotations);
1131 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1132 llvm::GlobalValue::AppendingLinkage,
1133 Array, "llvm.global.annotations");
1134 gv->setSection(AnnotationSection);
1137 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1138 llvm::Constant *&AStr = AnnotationStrings[Str];
1142 // Not found yet, create a new global.
1143 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
1145 new llvm::GlobalVariable(getModule(), s->getType(), true,
1146 llvm::GlobalValue::PrivateLinkage, s, ".str");
1147 gv->setSection(AnnotationSection);
1148 gv->setUnnamedAddr(true);
1153 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1154 SourceManager &SM = getContext().getSourceManager();
1155 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1157 return EmitAnnotationString(PLoc.getFilename());
1158 return EmitAnnotationString(SM.getBufferName(Loc));
1161 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1162 SourceManager &SM = getContext().getSourceManager();
1163 PresumedLoc PLoc = SM.getPresumedLoc(L);
1164 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1165 SM.getExpansionLineNumber(L);
1166 return llvm::ConstantInt::get(Int32Ty, LineNo);
1169 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1170 const AnnotateAttr *AA,
1172 // Get the globals for file name, annotation, and the line number.
1173 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1174 *UnitGV = EmitAnnotationUnit(L),
1175 *LineNoCst = EmitAnnotationLineNo(L);
1177 // Create the ConstantStruct for the global annotation.
1178 llvm::Constant *Fields[4] = {
1179 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1180 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1181 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1184 return llvm::ConstantStruct::getAnon(Fields);
1187 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1188 llvm::GlobalValue *GV) {
1189 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1190 // Get the struct elements for these annotations.
1191 for (const auto *I : D->specific_attrs<AnnotateAttr>())
1192 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
1195 bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
1196 SourceLocation Loc) const {
1197 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1198 // Blacklist by function name.
1199 if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
1201 // Blacklist by location.
1202 if (!Loc.isInvalid())
1203 return SanitizerBL.isBlacklistedLocation(Loc);
1204 // If location is unknown, this may be a compiler-generated function. Assume
1205 // it's located in the main file.
1206 auto &SM = Context.getSourceManager();
1207 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1208 return SanitizerBL.isBlacklistedFile(MainFile->getName());
1213 bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1214 SourceLocation Loc, QualType Ty,
1215 StringRef Category) const {
1216 // For now globals can be blacklisted only in ASan.
1217 if (!LangOpts.Sanitize.has(SanitizerKind::Address))
1219 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1220 if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
1222 if (SanitizerBL.isBlacklistedLocation(Loc, Category))
1224 // Check global type.
1226 // Drill down the array types: if global variable of a fixed type is
1227 // blacklisted, we also don't instrument arrays of them.
1228 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1229 Ty = AT->getElementType();
1230 Ty = Ty.getCanonicalType().getUnqualifiedType();
1231 // We allow to blacklist only record types (classes, structs etc.)
1232 if (Ty->isRecordType()) {
1233 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
1234 if (SanitizerBL.isBlacklistedType(TypeStr, Category))
1241 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
1242 // Never defer when EmitAllDecls is specified.
1243 if (LangOpts.EmitAllDecls)
1246 return getContext().DeclMustBeEmitted(Global);
1249 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
1250 if (const auto *FD = dyn_cast<FunctionDecl>(Global))
1251 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1252 // Implicit template instantiations may change linkage if they are later
1253 // explicitly instantiated, so they should not be emitted eagerly.
1259 llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
1260 const CXXUuidofExpr* E) {
1261 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1263 StringRef Uuid = E->getUuidAsStringRef(Context);
1264 std::string Name = "_GUID_" + Uuid.lower();
1265 std::replace(Name.begin(), Name.end(), '-', '_');
1267 // Look for an existing global.
1268 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1271 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
1272 assert(Init && "failed to initialize as constant");
1274 auto *GV = new llvm::GlobalVariable(
1275 getModule(), Init->getType(),
1276 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
1280 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1281 const AliasAttr *AA = VD->getAttr<AliasAttr>();
1282 assert(AA && "No alias?");
1284 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1286 // See if there is already something with the target's name in the module.
1287 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
1289 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1290 return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1293 llvm::Constant *Aliasee;
1294 if (isa<llvm::FunctionType>(DeclTy))
1295 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1296 GlobalDecl(cast<FunctionDecl>(VD)),
1297 /*ForVTable=*/false);
1299 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1300 llvm::PointerType::getUnqual(DeclTy),
1303 auto *F = cast<llvm::GlobalValue>(Aliasee);
1304 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1305 WeakRefReferences.insert(F);
1310 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
1311 const auto *Global = cast<ValueDecl>(GD.getDecl());
1313 // Weak references don't produce any output by themselves.
1314 if (Global->hasAttr<WeakRefAttr>())
1317 // If this is an alias definition (which otherwise looks like a declaration)
1319 if (Global->hasAttr<AliasAttr>())
1320 return EmitAliasDefinition(GD);
1322 // If this is CUDA, be selective about which declarations we emit.
1323 if (LangOpts.CUDA) {
1324 if (CodeGenOpts.CUDAIsDevice) {
1325 if (!Global->hasAttr<CUDADeviceAttr>() &&
1326 !Global->hasAttr<CUDAGlobalAttr>() &&
1327 !Global->hasAttr<CUDAConstantAttr>() &&
1328 !Global->hasAttr<CUDASharedAttr>())
1331 if (!Global->hasAttr<CUDAHostAttr>() && (
1332 Global->hasAttr<CUDADeviceAttr>() ||
1333 Global->hasAttr<CUDAConstantAttr>() ||
1334 Global->hasAttr<CUDASharedAttr>()))
1339 // Ignore declarations, they will be emitted on their first use.
1340 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1341 // Forward declarations are emitted lazily on first use.
1342 if (!FD->doesThisDeclarationHaveABody()) {
1343 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1346 StringRef MangledName = getMangledName(GD);
1348 // Compute the function info and LLVM type.
1349 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1350 llvm::Type *Ty = getTypes().GetFunctionType(FI);
1352 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
1353 /*DontDefer=*/false);
1357 const auto *VD = cast<VarDecl>(Global);
1358 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1360 if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
1361 !Context.isMSStaticDataMemberInlineDefinition(VD))
1365 // Defer code generation to first use when possible, e.g. if this is an inline
1366 // function. If the global must always be emitted, do it eagerly if possible
1367 // to benefit from cache locality.
1368 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
1369 // Emit the definition if it can't be deferred.
1370 EmitGlobalDefinition(GD);
1374 // If we're deferring emission of a C++ variable with an
1375 // initializer, remember the order in which it appeared in the file.
1376 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1377 cast<VarDecl>(Global)->hasInit()) {
1378 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1379 CXXGlobalInits.push_back(nullptr);
1382 StringRef MangledName = getMangledName(GD);
1383 if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) {
1384 // The value has already been used and should therefore be emitted.
1385 addDeferredDeclToEmit(GV, GD);
1386 } else if (MustBeEmitted(Global)) {
1387 // The value must be emitted, but cannot be emitted eagerly.
1388 assert(!MayBeEmittedEagerly(Global));
1389 addDeferredDeclToEmit(/*GV=*/nullptr, GD);
1391 // Otherwise, remember that we saw a deferred decl with this name. The
1392 // first use of the mangled name will cause it to move into
1393 // DeferredDeclsToEmit.
1394 DeferredDecls[MangledName] = GD;
1399 struct FunctionIsDirectlyRecursive :
1400 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1401 const StringRef Name;
1402 const Builtin::Context &BI;
1404 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1405 Name(N), BI(C), Result(false) {
1407 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1409 bool TraverseCallExpr(CallExpr *E) {
1410 const FunctionDecl *FD = E->getDirectCallee();
1413 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1414 if (Attr && Name == Attr->getLabel()) {
1418 unsigned BuiltinID = FD->getBuiltinID();
1421 StringRef BuiltinName = BI.GetName(BuiltinID);
1422 if (BuiltinName.startswith("__builtin_") &&
1423 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1432 // isTriviallyRecursive - Check if this function calls another
1433 // decl that, because of the asm attribute or the other decl being a builtin,
1434 // ends up pointing to itself.
1436 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1438 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1439 // asm labels are a special kind of mangling we have to support.
1440 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1443 Name = Attr->getLabel();
1445 Name = FD->getName();
1448 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1449 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1450 return Walker.Result;
1454 CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1455 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1457 const auto *F = cast<FunctionDecl>(GD.getDecl());
1458 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1460 // PR9614. Avoid cases where the source code is lying to us. An available
1461 // externally function should have an equivalent function somewhere else,
1462 // but a function that calls itself is clearly not equivalent to the real
1464 // This happens in glibc's btowc and in some configure checks.
1465 return !isTriviallyRecursive(F);
1468 /// If the type for the method's class was generated by
1469 /// CGDebugInfo::createContextChain(), the cache contains only a
1470 /// limited DIType without any declarations. Since EmitFunctionStart()
1471 /// needs to find the canonical declaration for each method, we need
1472 /// to construct the complete type prior to emitting the method.
1473 void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
1474 if (!D->isInstance())
1477 if (CGDebugInfo *DI = getModuleDebugInfo())
1478 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
1479 const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext()));
1480 DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
1484 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
1485 const auto *D = cast<ValueDecl>(GD.getDecl());
1487 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1488 Context.getSourceManager(),
1489 "Generating code for declaration");
1491 if (isa<FunctionDecl>(D)) {
1492 // At -O0, don't generate IR for functions with available_externally
1494 if (!shouldEmitFunction(GD))
1497 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
1498 CompleteDIClassType(Method);
1499 // Make sure to emit the definition(s) before we emit the thunks.
1500 // This is necessary for the generation of certain thunks.
1501 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
1502 ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
1503 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
1504 ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
1506 EmitGlobalFunctionDefinition(GD, GV);
1508 if (Method->isVirtual())
1509 getVTables().EmitThunks(GD);
1514 return EmitGlobalFunctionDefinition(GD, GV);
1517 if (const auto *VD = dyn_cast<VarDecl>(D))
1518 return EmitGlobalVarDefinition(VD);
1520 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1523 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1524 /// module, create and return an llvm Function with the specified type. If there
1525 /// is something in the module with the specified name, return it potentially
1526 /// bitcasted to the right type.
1528 /// If D is non-null, it specifies a decl that correspond to this. This is used
1529 /// to set the attributes on the function when it is first created.
1531 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
1533 GlobalDecl GD, bool ForVTable,
1534 bool DontDefer, bool IsThunk,
1535 llvm::AttributeSet ExtraAttrs) {
1536 const Decl *D = GD.getDecl();
1538 // Lookup the entry, lazily creating it if necessary.
1539 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1541 if (WeakRefReferences.erase(Entry)) {
1542 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
1543 if (FD && !FD->hasAttr<WeakAttr>())
1544 Entry->setLinkage(llvm::Function::ExternalLinkage);
1547 // Handle dropped DLL attributes.
1548 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
1549 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1551 if (Entry->getType()->getElementType() == Ty)
1554 // Make sure the result is of the correct type.
1555 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1558 // This function doesn't have a complete type (for example, the return
1559 // type is an incomplete struct). Use a fake type instead, and make
1560 // sure not to try to set attributes.
1561 bool IsIncompleteFunction = false;
1563 llvm::FunctionType *FTy;
1564 if (isa<llvm::FunctionType>(Ty)) {
1565 FTy = cast<llvm::FunctionType>(Ty);
1567 FTy = llvm::FunctionType::get(VoidTy, false);
1568 IsIncompleteFunction = true;
1571 llvm::Function *F = llvm::Function::Create(FTy,
1572 llvm::Function::ExternalLinkage,
1573 MangledName, &getModule());
1574 assert(F->getName() == MangledName && "name was uniqued!");
1576 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
1577 if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1578 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
1579 F->addAttributes(llvm::AttributeSet::FunctionIndex,
1580 llvm::AttributeSet::get(VMContext,
1581 llvm::AttributeSet::FunctionIndex,
1586 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
1587 // each other bottoming out with the base dtor. Therefore we emit non-base
1588 // dtors on usage, even if there is no dtor definition in the TU.
1589 if (D && isa<CXXDestructorDecl>(D) &&
1590 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
1592 addDeferredDeclToEmit(F, GD);
1594 // This is the first use or definition of a mangled name. If there is a
1595 // deferred decl with this name, remember that we need to emit it at the end
1597 auto DDI = DeferredDecls.find(MangledName);
1598 if (DDI != DeferredDecls.end()) {
1599 // Move the potentially referenced deferred decl to the
1600 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
1601 // don't need it anymore).
1602 addDeferredDeclToEmit(F, DDI->second);
1603 DeferredDecls.erase(DDI);
1605 // Otherwise, if this is a sized deallocation function, emit a weak
1607 // for it at the end of the translation unit.
1608 } else if (D && cast<FunctionDecl>(D)
1609 ->getCorrespondingUnsizedGlobalDeallocationFunction()) {
1610 addDeferredDeclToEmit(F, GD);
1612 // Otherwise, there are cases we have to worry about where we're
1613 // using a declaration for which we must emit a definition but where
1614 // we might not find a top-level definition:
1615 // - member functions defined inline in their classes
1616 // - friend functions defined inline in some class
1617 // - special member functions with implicit definitions
1618 // If we ever change our AST traversal to walk into class methods,
1619 // this will be unnecessary.
1621 // We also don't emit a definition for a function if it's going to be an
1622 // entry in a vtable, unless it's already marked as used.
1623 } else if (getLangOpts().CPlusPlus && D) {
1624 // Look for a declaration that's lexically in a record.
1625 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
1626 FD = FD->getPreviousDecl()) {
1627 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
1628 if (FD->doesThisDeclarationHaveABody()) {
1629 addDeferredDeclToEmit(F, GD.getWithDecl(FD));
1637 // Make sure the result is of the requested type.
1638 if (!IsIncompleteFunction) {
1639 assert(F->getType()->getElementType() == Ty);
1643 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1644 return llvm::ConstantExpr::getBitCast(F, PTy);
1647 /// GetAddrOfFunction - Return the address of the given function. If Ty is
1648 /// non-null, then this function will use the specified type if it has to
1649 /// create it (this occurs when we see a definition of the function).
1650 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
1654 // If there was no specific requested type, just convert it now.
1656 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
1658 StringRef MangledName = getMangledName(GD);
1659 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer);
1662 /// CreateRuntimeFunction - Create a new runtime function with the specified
1665 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
1667 llvm::AttributeSet ExtraAttrs) {
1669 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1670 /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
1671 if (auto *F = dyn_cast<llvm::Function>(C))
1673 F->setCallingConv(getRuntimeCC());
1677 /// CreateBuiltinFunction - Create a new builtin function with the specified
1680 CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy,
1682 llvm::AttributeSet ExtraAttrs) {
1684 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1685 /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
1686 if (auto *F = dyn_cast<llvm::Function>(C))
1688 F->setCallingConv(getBuiltinCC());
1692 /// isTypeConstant - Determine whether an object of this type can be emitted
1695 /// If ExcludeCtor is true, the duration when the object's constructor runs
1696 /// will not be considered. The caller will need to verify that the object is
1697 /// not written to during its construction.
1698 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1699 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
1702 if (Context.getLangOpts().CPlusPlus) {
1703 if (const CXXRecordDecl *Record
1704 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1705 return ExcludeCtor && !Record->hasMutableFields() &&
1706 Record->hasTrivialDestructor();
1712 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1713 /// create and return an llvm GlobalVariable with the specified type. If there
1714 /// is something in the module with the specified name, return it potentially
1715 /// bitcasted to the right type.
1717 /// If D is non-null, it specifies a decl that correspond to this. This is used
1718 /// to set the attributes on the global when it is first created.
1720 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
1721 llvm::PointerType *Ty,
1723 // Lookup the entry, lazily creating it if necessary.
1724 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1726 if (WeakRefReferences.erase(Entry)) {
1727 if (D && !D->hasAttr<WeakAttr>())
1728 Entry->setLinkage(llvm::Function::ExternalLinkage);
1731 // Handle dropped DLL attributes.
1732 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
1733 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1735 if (Entry->getType() == Ty)
1738 // Make sure the result is of the correct type.
1739 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
1740 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
1742 return llvm::ConstantExpr::getBitCast(Entry, Ty);
1745 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
1746 auto *GV = new llvm::GlobalVariable(
1747 getModule(), Ty->getElementType(), false,
1748 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
1749 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
1751 // This is the first use or definition of a mangled name. If there is a
1752 // deferred decl with this name, remember that we need to emit it at the end
1754 auto DDI = DeferredDecls.find(MangledName);
1755 if (DDI != DeferredDecls.end()) {
1756 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1757 // list, and remove it from DeferredDecls (since we don't need it anymore).
1758 addDeferredDeclToEmit(GV, DDI->second);
1759 DeferredDecls.erase(DDI);
1762 // Handle things which are present even on external declarations.
1764 // FIXME: This code is overly simple and should be merged with other global
1766 GV->setConstant(isTypeConstant(D->getType(), false));
1768 setLinkageAndVisibilityForGV(GV, D);
1770 if (D->getTLSKind()) {
1771 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
1772 CXXThreadLocals.push_back(std::make_pair(D, GV));
1776 // If required by the ABI, treat declarations of static data members with
1777 // inline initializers as definitions.
1778 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
1779 EmitGlobalVarDefinition(D);
1782 // Handle XCore specific ABI requirements.
1783 if (getTarget().getTriple().getArch() == llvm::Triple::xcore &&
1784 D->getLanguageLinkage() == CLanguageLinkage &&
1785 D->getType().isConstant(Context) &&
1786 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
1787 GV->setSection(".cp.rodata");
1790 if (AddrSpace != Ty->getAddressSpace())
1791 return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
1797 llvm::GlobalVariable *
1798 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
1800 llvm::GlobalValue::LinkageTypes Linkage) {
1801 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1802 llvm::GlobalVariable *OldGV = nullptr;
1805 // Check if the variable has the right type.
1806 if (GV->getType()->getElementType() == Ty)
1809 // Because C++ name mangling, the only way we can end up with an already
1810 // existing global with the same name is if it has been declared extern "C".
1811 assert(GV->isDeclaration() && "Declaration has wrong type!");
1815 // Create a new variable.
1816 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1817 Linkage, nullptr, Name);
1820 // Replace occurrences of the old variable if needed.
1821 GV->takeName(OldGV);
1823 if (!OldGV->use_empty()) {
1824 llvm::Constant *NewPtrForOldDecl =
1825 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1826 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1829 OldGV->eraseFromParent();
1835 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1836 /// given global variable. If Ty is non-null and if the global doesn't exist,
1837 /// then it will be created with the specified type instead of whatever the
1838 /// normal requested type would be.
1839 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1841 assert(D->hasGlobalStorage() && "Not a global variable");
1842 QualType ASTTy = D->getType();
1844 Ty = getTypes().ConvertTypeForMem(ASTTy);
1846 llvm::PointerType *PTy =
1847 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1849 StringRef MangledName = getMangledName(D);
1850 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
1853 /// CreateRuntimeVariable - Create a new runtime global variable with the
1854 /// specified type and name.
1856 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
1858 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
1861 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1862 assert(!D->getInit() && "Cannot emit definite definitions here!");
1864 if (!MustBeEmitted(D)) {
1865 // If we have not seen a reference to this variable yet, place it
1866 // into the deferred declarations table to be emitted if needed
1868 StringRef MangledName = getMangledName(D);
1869 if (!GetGlobalValue(MangledName)) {
1870 DeferredDecls[MangledName] = D;
1875 // The tentative definition is the only definition.
1876 EmitGlobalVarDefinition(D);
1879 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
1880 return Context.toCharUnitsFromBits(
1881 TheDataLayout.getTypeStoreSizeInBits(Ty));
1884 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
1885 unsigned AddrSpace) {
1886 if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
1887 if (D->hasAttr<CUDAConstantAttr>())
1888 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
1889 else if (D->hasAttr<CUDASharedAttr>())
1890 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
1892 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
1898 template<typename SomeDecl>
1899 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
1900 llvm::GlobalValue *GV) {
1901 if (!getLangOpts().CPlusPlus)
1904 // Must have 'used' attribute, or else inline assembly can't rely on
1905 // the name existing.
1906 if (!D->template hasAttr<UsedAttr>())
1909 // Must have internal linkage and an ordinary name.
1910 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
1913 // Must be in an extern "C" context. Entities declared directly within
1914 // a record are not extern "C" even if the record is in such a context.
1915 const SomeDecl *First = D->getFirstDecl();
1916 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
1919 // OK, this is an internal linkage entity inside an extern "C" linkage
1920 // specification. Make a note of that so we can give it the "expected"
1921 // mangled name if nothing else is using that name.
1922 std::pair<StaticExternCMap::iterator, bool> R =
1923 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
1925 // If we have multiple internal linkage entities with the same name
1926 // in extern "C" regions, none of them gets that name.
1928 R.first->second = nullptr;
1931 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
1932 if (!CGM.supportsCOMDAT())
1935 if (D.hasAttr<SelectAnyAttr>())
1939 if (auto *VD = dyn_cast<VarDecl>(&D))
1940 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
1942 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
1946 case GVA_AvailableExternally:
1947 case GVA_StrongExternal:
1949 case GVA_DiscardableODR:
1953 llvm_unreachable("No such linkage");
1956 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1957 llvm::Constant *Init = nullptr;
1958 QualType ASTTy = D->getType();
1959 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1960 bool NeedsGlobalCtor = false;
1961 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
1963 const VarDecl *InitDecl;
1964 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
1967 // This is a tentative definition; tentative definitions are
1968 // implicitly initialized with { 0 }.
1970 // Note that tentative definitions are only emitted at the end of
1971 // a translation unit, so they should never have incomplete
1972 // type. In addition, EmitTentativeDefinition makes sure that we
1973 // never attempt to emit a tentative definition if a real one
1974 // exists. A use may still exists, however, so we still may need
1976 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1977 Init = EmitNullConstant(D->getType());
1979 initializedGlobalDecl = GlobalDecl(D);
1980 Init = EmitConstantInit(*InitDecl);
1983 QualType T = InitExpr->getType();
1984 if (D->getType()->isReferenceType())
1987 if (getLangOpts().CPlusPlus) {
1988 Init = EmitNullConstant(T);
1989 NeedsGlobalCtor = true;
1991 ErrorUnsupported(D, "static initializer");
1992 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1995 // We don't need an initializer, so remove the entry for the delayed
1996 // initializer position (just in case this entry was delayed) if we
1997 // also don't need to register a destructor.
1998 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
1999 DelayedCXXInitPosition.erase(D);
2003 llvm::Type* InitType = Init->getType();
2004 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
2006 // Strip off a bitcast if we got one back.
2007 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2008 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2009 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2010 // All zero index gep.
2011 CE->getOpcode() == llvm::Instruction::GetElementPtr);
2012 Entry = CE->getOperand(0);
2015 // Entry is now either a Function or GlobalVariable.
2016 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2018 // We have a definition after a declaration with the wrong type.
2019 // We must make a new GlobalVariable* and update everything that used OldGV
2020 // (a declaration or tentative definition) with the new GlobalVariable*
2021 // (which will be a definition).
2023 // This happens if there is a prototype for a global (e.g.
2024 // "extern int x[];") and then a definition of a different type (e.g.
2025 // "int x[10];"). This also happens when an initializer has a different type
2026 // from the type of the global (this happens with unions).
2028 GV->getType()->getElementType() != InitType ||
2029 GV->getType()->getAddressSpace() !=
2030 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
2032 // Move the old entry aside so that we'll create a new one.
2033 Entry->setName(StringRef());
2035 // Make a new global with the correct type, this is now guaranteed to work.
2036 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
2038 // Replace all uses of the old global with the new global
2039 llvm::Constant *NewPtrForOldDecl =
2040 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2041 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2043 // Erase the old global, since it is no longer used.
2044 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2047 MaybeHandleStaticInExternC(D, GV);
2049 if (D->hasAttr<AnnotateAttr>())
2050 AddGlobalAnnotations(D, GV);
2052 GV->setInitializer(Init);
2054 // If it is safe to mark the global 'constant', do so now.
2055 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2056 isTypeConstant(D->getType(), true));
2058 // If it is in a read-only section, mark it 'constant'.
2059 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
2060 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
2061 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
2062 GV->setConstant(true);
2065 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2067 // Set the llvm linkage type as appropriate.
2068 llvm::GlobalValue::LinkageTypes Linkage =
2069 getLLVMLinkageVarDefinition(D, GV->isConstant());
2071 // On Darwin, the backing variable for a C++11 thread_local variable always
2072 // has internal linkage; all accesses should just be calls to the
2073 // Itanium-specified entry point, which has the normal linkage of the
2075 if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
2076 Context.getTargetInfo().getTriple().isMacOSX())
2077 Linkage = llvm::GlobalValue::InternalLinkage;
2079 GV->setLinkage(Linkage);
2080 if (D->hasAttr<DLLImportAttr>())
2081 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2082 else if (D->hasAttr<DLLExportAttr>())
2083 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2085 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2087 if (Linkage == llvm::GlobalVariable::CommonLinkage)
2088 // common vars aren't constant even if declared const.
2089 GV->setConstant(false);
2091 setNonAliasAttributes(D, GV);
2093 if (D->getTLSKind() && !GV->isThreadLocal()) {
2094 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2095 CXXThreadLocals.push_back(std::make_pair(D, GV));
2099 if (shouldBeInCOMDAT(*this, *D))
2100 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2102 // Emit the initializer function if necessary.
2103 if (NeedsGlobalCtor || NeedsGlobalDtor)
2104 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
2106 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
2108 // Emit global variable debug information.
2109 if (CGDebugInfo *DI = getModuleDebugInfo())
2110 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
2111 DI->EmitGlobalVariable(GV, D);
2114 static bool isVarDeclStrongDefinition(const ASTContext &Context,
2115 const VarDecl *D, bool NoCommon) {
2116 // Don't give variables common linkage if -fno-common was specified unless it
2117 // was overridden by a NoCommon attribute.
2118 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
2122 // A declaration of an identifier for an object that has file scope without
2123 // an initializer, and without a storage-class specifier or with the
2124 // storage-class specifier static, constitutes a tentative definition.
2125 if (D->getInit() || D->hasExternalStorage())
2128 // A variable cannot be both common and exist in a section.
2129 if (D->hasAttr<SectionAttr>())
2132 // Thread local vars aren't considered common linkage.
2133 if (D->getTLSKind())
2136 // Tentative definitions marked with WeakImportAttr are true definitions.
2137 if (D->hasAttr<WeakImportAttr>())
2140 // Declarations with a required alignment do not have common linakge in MSVC
2142 if (Context.getLangOpts().MSVCCompat &&
2143 (Context.isAlignmentRequired(D->getType()) || D->hasAttr<AlignedAttr>()))
2149 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
2150 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
2151 if (Linkage == GVA_Internal)
2152 return llvm::Function::InternalLinkage;
2154 if (D->hasAttr<WeakAttr>()) {
2155 if (IsConstantVariable)
2156 return llvm::GlobalVariable::WeakODRLinkage;
2158 return llvm::GlobalVariable::WeakAnyLinkage;
2161 // We are guaranteed to have a strong definition somewhere else,
2162 // so we can use available_externally linkage.
2163 if (Linkage == GVA_AvailableExternally)
2164 return llvm::Function::AvailableExternallyLinkage;
2166 // Note that Apple's kernel linker doesn't support symbol
2167 // coalescing, so we need to avoid linkonce and weak linkages there.
2168 // Normally, this means we just map to internal, but for explicit
2169 // instantiations we'll map to external.
2171 // In C++, the compiler has to emit a definition in every translation unit
2172 // that references the function. We should use linkonce_odr because
2173 // a) if all references in this translation unit are optimized away, we
2174 // don't need to codegen it. b) if the function persists, it needs to be
2175 // merged with other definitions. c) C++ has the ODR, so we know the
2176 // definition is dependable.
2177 if (Linkage == GVA_DiscardableODR)
2178 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
2179 : llvm::Function::InternalLinkage;
2181 // An explicit instantiation of a template has weak linkage, since
2182 // explicit instantiations can occur in multiple translation units
2183 // and must all be equivalent. However, we are not allowed to
2184 // throw away these explicit instantiations.
2185 if (Linkage == GVA_StrongODR)
2186 return !Context.getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage
2187 : llvm::Function::ExternalLinkage;
2189 // C++ doesn't have tentative definitions and thus cannot have common
2191 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
2192 !isVarDeclStrongDefinition(Context, cast<VarDecl>(D),
2193 CodeGenOpts.NoCommon))
2194 return llvm::GlobalVariable::CommonLinkage;
2196 // selectany symbols are externally visible, so use weak instead of
2197 // linkonce. MSVC optimizes away references to const selectany globals, so
2198 // all definitions should be the same and ODR linkage should be used.
2199 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
2200 if (D->hasAttr<SelectAnyAttr>())
2201 return llvm::GlobalVariable::WeakODRLinkage;
2203 // Otherwise, we have strong external linkage.
2204 assert(Linkage == GVA_StrongExternal);
2205 return llvm::GlobalVariable::ExternalLinkage;
2208 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
2209 const VarDecl *VD, bool IsConstant) {
2210 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
2211 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
2214 /// Replace the uses of a function that was declared with a non-proto type.
2215 /// We want to silently drop extra arguments from call sites
2216 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2217 llvm::Function *newFn) {
2219 if (old->use_empty()) return;
2221 llvm::Type *newRetTy = newFn->getReturnType();
2222 SmallVector<llvm::Value*, 4> newArgs;
2224 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2226 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
2227 llvm::User *user = use->getUser();
2229 // Recognize and replace uses of bitcasts. Most calls to
2230 // unprototyped functions will use bitcasts.
2231 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
2232 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2233 replaceUsesOfNonProtoConstant(bitcast, newFn);
2237 // Recognize calls to the function.
2238 llvm::CallSite callSite(user);
2239 if (!callSite) continue;
2240 if (!callSite.isCallee(&*use)) continue;
2242 // If the return types don't match exactly, then we can't
2243 // transform this call unless it's dead.
2244 if (callSite->getType() != newRetTy && !callSite->use_empty())
2247 // Get the call site's attribute list.
2248 SmallVector<llvm::AttributeSet, 8> newAttrs;
2249 llvm::AttributeSet oldAttrs = callSite.getAttributes();
2251 // Collect any return attributes from the call.
2252 if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
2254 llvm::AttributeSet::get(newFn->getContext(),
2255 oldAttrs.getRetAttributes()));
2257 // If the function was passed too few arguments, don't transform.
2258 unsigned newNumArgs = newFn->arg_size();
2259 if (callSite.arg_size() < newNumArgs) continue;
2261 // If extra arguments were passed, we silently drop them.
2262 // If any of the types mismatch, we don't transform.
2264 bool dontTransform = false;
2265 for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
2266 ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
2267 if (callSite.getArgument(argNo)->getType() != ai->getType()) {
2268 dontTransform = true;
2272 // Add any parameter attributes.
2273 if (oldAttrs.hasAttributes(argNo + 1))
2276 AttributeSet::get(newFn->getContext(),
2277 oldAttrs.getParamAttributes(argNo + 1)));
2282 if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
2283 newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
2284 oldAttrs.getFnAttributes()));
2286 // Okay, we can transform this. Create the new call instruction and copy
2287 // over the required information.
2288 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2290 llvm::CallSite newCall;
2291 if (callSite.isCall()) {
2292 newCall = llvm::CallInst::Create(newFn, newArgs, "",
2293 callSite.getInstruction());
2295 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
2296 newCall = llvm::InvokeInst::Create(newFn,
2297 oldInvoke->getNormalDest(),
2298 oldInvoke->getUnwindDest(),
2300 callSite.getInstruction());
2302 newArgs.clear(); // for the next iteration
2304 if (!newCall->getType()->isVoidTy())
2305 newCall->takeName(callSite.getInstruction());
2306 newCall.setAttributes(
2307 llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2308 newCall.setCallingConv(callSite.getCallingConv());
2310 // Finally, remove the old call, replacing any uses with the new one.
2311 if (!callSite->use_empty())
2312 callSite->replaceAllUsesWith(newCall.getInstruction());
2314 // Copy debug location attached to CI.
2315 if (!callSite->getDebugLoc().isUnknown())
2316 newCall->setDebugLoc(callSite->getDebugLoc());
2317 callSite->eraseFromParent();
2321 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2322 /// implement a function with no prototype, e.g. "int foo() {}". If there are
2323 /// existing call uses of the old function in the module, this adjusts them to
2324 /// call the new function directly.
2326 /// This is not just a cleanup: the always_inline pass requires direct calls to
2327 /// functions to be able to inline them. If there is a bitcast in the way, it
2328 /// won't inline them. Instcombine normally deletes these calls, but it isn't
2330 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2331 llvm::Function *NewFn) {
2332 // If we're redefining a global as a function, don't transform it.
2333 if (!isa<llvm::Function>(Old)) return;
2335 replaceUsesOfNonProtoConstant(Old, NewFn);
2338 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2339 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2340 // If we have a definition, this might be a deferred decl. If the
2341 // instantiation is explicit, make sure we emit it at the end.
2342 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2343 GetAddrOfGlobalVar(VD);
2345 EmitTopLevelDecl(VD);
2348 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
2349 llvm::GlobalValue *GV) {
2350 const auto *D = cast<FunctionDecl>(GD.getDecl());
2352 // Compute the function info and LLVM type.
2353 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2354 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2356 // Get or create the prototype for the function.
2359 GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer*/ true);
2361 // Strip off a bitcast if we got one back.
2362 if (auto *CE = dyn_cast<llvm::ConstantExpr>(C)) {
2363 assert(CE->getOpcode() == llvm::Instruction::BitCast);
2364 GV = cast<llvm::GlobalValue>(CE->getOperand(0));
2366 GV = cast<llvm::GlobalValue>(C);
2370 if (!GV->isDeclaration()) {
2371 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name);
2372 GlobalDecl OldGD = Manglings.lookup(GV->getName());
2373 if (auto *Prev = OldGD.getDecl())
2374 getDiags().Report(Prev->getLocation(), diag::note_previous_definition);
2378 if (GV->getType()->getElementType() != Ty) {
2379 // If the types mismatch then we have to rewrite the definition.
2380 assert(GV->isDeclaration() && "Shouldn't replace non-declaration");
2382 // F is the Function* for the one with the wrong type, we must make a new
2383 // Function* and update everything that used F (a declaration) with the new
2384 // Function* (which will be a definition).
2386 // This happens if there is a prototype for a function
2387 // (e.g. "int f()") and then a definition of a different type
2388 // (e.g. "int f(int x)"). Move the old function aside so that it
2389 // doesn't interfere with GetAddrOfFunction.
2390 GV->setName(StringRef());
2391 auto *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
2393 // This might be an implementation of a function without a
2394 // prototype, in which case, try to do special replacement of
2395 // calls which match the new prototype. The really key thing here
2396 // is that we also potentially drop arguments from the call site
2397 // so as to make a direct call, which makes the inliner happier
2398 // and suppresses a number of optimizer warnings (!) about
2399 // dropping arguments.
2400 if (!GV->use_empty()) {
2401 ReplaceUsesOfNonProtoTypeWithRealFunction(GV, NewFn);
2402 GV->removeDeadConstantUsers();
2405 // Replace uses of F with the Function we will endow with a body.
2406 if (!GV->use_empty()) {
2407 llvm::Constant *NewPtrForOldDecl =
2408 llvm::ConstantExpr::getBitCast(NewFn, GV->getType());
2409 GV->replaceAllUsesWith(NewPtrForOldDecl);
2412 // Ok, delete the old function now, which is dead.
2413 GV->eraseFromParent();
2418 // We need to set linkage and visibility on the function before
2419 // generating code for it because various parts of IR generation
2420 // want to propagate this information down (e.g. to local static
2422 auto *Fn = cast<llvm::Function>(GV);
2423 setFunctionLinkage(GD, Fn);
2424 if (D->hasAttr<DLLImportAttr>())
2425 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2426 else if (D->hasAttr<DLLExportAttr>())
2427 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2429 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2431 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
2432 setGlobalVisibility(Fn, D);
2434 MaybeHandleStaticInExternC(D, Fn);
2436 if (shouldBeInCOMDAT(*this, *D))
2437 Fn->setComdat(TheModule.getOrInsertComdat(Fn->getName()));
2439 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
2441 setFunctionDefinitionAttributes(D, Fn);
2442 SetLLVMFunctionAttributesForDefinition(D, Fn);
2444 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
2445 AddGlobalCtor(Fn, CA->getPriority());
2446 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
2447 AddGlobalDtor(Fn, DA->getPriority());
2448 if (D->hasAttr<AnnotateAttr>())
2449 AddGlobalAnnotations(D, Fn);
2452 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
2453 const auto *D = cast<ValueDecl>(GD.getDecl());
2454 const AliasAttr *AA = D->getAttr<AliasAttr>();
2455 assert(AA && "Not an alias?");
2457 StringRef MangledName = getMangledName(GD);
2459 // If there is a definition in the module, then it wins over the alias.
2460 // This is dubious, but allow it to be safe. Just ignore the alias.
2461 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2462 if (Entry && !Entry->isDeclaration())
2465 Aliases.push_back(GD);
2467 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
2469 // Create a reference to the named value. This ensures that it is emitted
2470 // if a deferred decl.
2471 llvm::Constant *Aliasee;
2472 if (isa<llvm::FunctionType>(DeclTy))
2473 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
2474 /*ForVTable=*/false);
2476 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2477 llvm::PointerType::getUnqual(DeclTy),
2480 // Create the new alias itself, but don't set a name yet.
2481 auto *GA = llvm::GlobalAlias::create(
2482 cast<llvm::PointerType>(Aliasee->getType())->getElementType(), 0,
2483 llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
2486 if (GA->getAliasee() == Entry) {
2487 Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
2491 assert(Entry->isDeclaration());
2493 // If there is a declaration in the module, then we had an extern followed
2494 // by the alias, as in:
2495 // extern int test6();
2497 // int test6() __attribute__((alias("test7")));
2499 // Remove it and replace uses of it with the alias.
2500 GA->takeName(Entry);
2502 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
2504 Entry->eraseFromParent();
2506 GA->setName(MangledName);
2509 // Set attributes which are particular to an alias; this is a
2510 // specialization of the attributes which may be set on a global
2511 // variable/function.
2512 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
2513 D->isWeakImported()) {
2514 GA->setLinkage(llvm::Function::WeakAnyLinkage);
2517 if (const auto *VD = dyn_cast<VarDecl>(D))
2518 if (VD->getTLSKind())
2519 setTLSMode(GA, *VD);
2521 setAliasAttributes(D, GA);
2524 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
2525 ArrayRef<llvm::Type*> Tys) {
2526 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
2530 static llvm::StringMapEntry<llvm::Constant*> &
2531 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2532 const StringLiteral *Literal,
2535 unsigned &StringLength) {
2536 StringRef String = Literal->getString();
2537 unsigned NumBytes = String.size();
2539 // Check for simple case.
2540 if (!Literal->containsNonAsciiOrNull()) {
2541 StringLength = NumBytes;
2542 return *Map.insert(std::make_pair(String, nullptr)).first;
2545 // Otherwise, convert the UTF8 literals into a string of shorts.
2548 SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
2549 const UTF8 *FromPtr = (const UTF8 *)String.data();
2550 UTF16 *ToPtr = &ToBuf[0];
2552 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2553 &ToPtr, ToPtr + NumBytes,
2556 // ConvertUTF8toUTF16 returns the length in ToPtr.
2557 StringLength = ToPtr - &ToBuf[0];
2559 // Add an explicit null.
2561 return *Map.insert(std::make_pair(
2562 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2563 (StringLength + 1) * 2),
2567 static llvm::StringMapEntry<llvm::Constant*> &
2568 GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2569 const StringLiteral *Literal,
2570 unsigned &StringLength) {
2571 StringRef String = Literal->getString();
2572 StringLength = String.size();
2573 return *Map.insert(std::make_pair(String, nullptr)).first;
2577 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2578 unsigned StringLength = 0;
2579 bool isUTF16 = false;
2580 llvm::StringMapEntry<llvm::Constant*> &Entry =
2581 GetConstantCFStringEntry(CFConstantStringMap, Literal,
2582 getDataLayout().isLittleEndian(),
2583 isUTF16, StringLength);
2585 if (auto *C = Entry.second)
2588 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2589 llvm::Constant *Zeros[] = { Zero, Zero };
2592 // If we don't already have it, get __CFConstantStringClassReference.
2593 if (!CFConstantStringClassRef) {
2594 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2595 Ty = llvm::ArrayType::get(Ty, 0);
2596 llvm::Constant *GV = CreateRuntimeVariable(Ty,
2597 "__CFConstantStringClassReference");
2598 // Decay array -> ptr
2599 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2600 CFConstantStringClassRef = V;
2603 V = CFConstantStringClassRef;
2605 QualType CFTy = getContext().getCFConstantStringType();
2607 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2609 llvm::Constant *Fields[4];
2612 Fields[0] = cast<llvm::ConstantExpr>(V);
2615 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2616 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
2617 llvm::ConstantInt::get(Ty, 0x07C8);
2620 llvm::Constant *C = nullptr;
2622 ArrayRef<uint16_t> Arr = llvm::makeArrayRef<uint16_t>(
2623 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
2624 Entry.first().size() / 2);
2625 C = llvm::ConstantDataArray::get(VMContext, Arr);
2627 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
2630 // Note: -fwritable-strings doesn't make the backing store strings of
2631 // CFStrings writable. (See <rdar://problem/10657500>)
2633 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2634 llvm::GlobalValue::PrivateLinkage, C, ".str");
2635 GV->setUnnamedAddr(true);
2636 // Don't enforce the target's minimum global alignment, since the only use
2637 // of the string is via this class initializer.
2638 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without
2639 // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing
2640 // that changes the section it ends in, which surprises ld64.
2642 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2643 GV->setAlignment(Align.getQuantity());
2644 GV->setSection("__TEXT,__ustring");
2646 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2647 GV->setAlignment(Align.getQuantity());
2648 GV->setSection("__TEXT,__cstring,cstring_literals");
2652 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2655 // Cast the UTF16 string to the correct type.
2656 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2659 Ty = getTypes().ConvertType(getContext().LongTy);
2660 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
2663 C = llvm::ConstantStruct::get(STy, Fields);
2664 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2665 llvm::GlobalVariable::PrivateLinkage, C,
2666 "_unnamed_cfstring_");
2667 GV->setSection("__DATA,__cfstring");
2674 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
2675 unsigned StringLength = 0;
2676 llvm::StringMapEntry<llvm::Constant*> &Entry =
2677 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
2679 if (auto *C = Entry.second)
2682 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2683 llvm::Constant *Zeros[] = { Zero, Zero };
2685 // If we don't already have it, get _NSConstantStringClassReference.
2686 if (!ConstantStringClassRef) {
2687 std::string StringClass(getLangOpts().ObjCConstantStringClass);
2688 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2690 if (LangOpts.ObjCRuntime.isNonFragile()) {
2692 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2693 : "OBJC_CLASS_$_" + StringClass;
2694 GV = getObjCRuntime().GetClassGlobal(str);
2695 // Make sure the result is of the correct type.
2696 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2697 V = llvm::ConstantExpr::getBitCast(GV, PTy);
2698 ConstantStringClassRef = V;
2701 StringClass.empty() ? "_NSConstantStringClassReference"
2702 : "_" + StringClass + "ClassReference";
2703 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
2704 GV = CreateRuntimeVariable(PTy, str);
2705 // Decay array -> ptr
2706 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2707 ConstantStringClassRef = V;
2711 V = ConstantStringClassRef;
2713 if (!NSConstantStringType) {
2714 // Construct the type for a constant NSString.
2715 RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString");
2716 D->startDefinition();
2718 QualType FieldTypes[3];
2721 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2723 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2724 // unsigned int length;
2725 FieldTypes[2] = Context.UnsignedIntTy;
2728 for (unsigned i = 0; i < 3; ++i) {
2729 FieldDecl *Field = FieldDecl::Create(Context, D,
2731 SourceLocation(), nullptr,
2732 FieldTypes[i], /*TInfo=*/nullptr,
2733 /*BitWidth=*/nullptr,
2736 Field->setAccess(AS_public);
2740 D->completeDefinition();
2741 QualType NSTy = Context.getTagDeclType(D);
2742 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2745 llvm::Constant *Fields[3];
2748 Fields[0] = cast<llvm::ConstantExpr>(V);
2752 llvm::ConstantDataArray::getString(VMContext, Entry.first());
2754 llvm::GlobalValue::LinkageTypes Linkage;
2756 Linkage = llvm::GlobalValue::PrivateLinkage;
2757 isConstant = !LangOpts.WritableStrings;
2759 auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant,
2760 Linkage, C, ".str");
2761 GV->setUnnamedAddr(true);
2762 // Don't enforce the target's minimum global alignment, since the only use
2763 // of the string is via this class initializer.
2764 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2765 GV->setAlignment(Align.getQuantity());
2766 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2769 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2770 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2773 C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
2774 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2775 llvm::GlobalVariable::PrivateLinkage, C,
2776 "_unnamed_nsstring_");
2777 const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";
2778 const char *NSStringNonFragileABISection =
2779 "__DATA,__objc_stringobj,regular,no_dead_strip";
2780 // FIXME. Fix section.
2781 GV->setSection(LangOpts.ObjCRuntime.isNonFragile()
2782 ? NSStringNonFragileABISection
2789 QualType CodeGenModule::getObjCFastEnumerationStateType() {
2790 if (ObjCFastEnumerationStateType.isNull()) {
2791 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
2792 D->startDefinition();
2794 QualType FieldTypes[] = {
2795 Context.UnsignedLongTy,
2796 Context.getPointerType(Context.getObjCIdType()),
2797 Context.getPointerType(Context.UnsignedLongTy),
2798 Context.getConstantArrayType(Context.UnsignedLongTy,
2799 llvm::APInt(32, 5), ArrayType::Normal, 0)
2802 for (size_t i = 0; i < 4; ++i) {
2803 FieldDecl *Field = FieldDecl::Create(Context,
2806 SourceLocation(), nullptr,
2807 FieldTypes[i], /*TInfo=*/nullptr,
2808 /*BitWidth=*/nullptr,
2811 Field->setAccess(AS_public);
2815 D->completeDefinition();
2816 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2819 return ObjCFastEnumerationStateType;
2823 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2824 assert(!E->getType()->isPointerType() && "Strings are always arrays");
2826 // Don't emit it as the address of the string, emit the string data itself
2827 // as an inline array.
2828 if (E->getCharByteWidth() == 1) {
2829 SmallString<64> Str(E->getString());
2831 // Resize the string to the right size, which is indicated by its type.
2832 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2833 Str.resize(CAT->getSize().getZExtValue());
2834 return llvm::ConstantDataArray::getString(VMContext, Str, false);
2837 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
2838 llvm::Type *ElemTy = AType->getElementType();
2839 unsigned NumElements = AType->getNumElements();
2841 // Wide strings have either 2-byte or 4-byte elements.
2842 if (ElemTy->getPrimitiveSizeInBits() == 16) {
2843 SmallVector<uint16_t, 32> Elements;
2844 Elements.reserve(NumElements);
2846 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2847 Elements.push_back(E->getCodeUnit(i));
2848 Elements.resize(NumElements);
2849 return llvm::ConstantDataArray::get(VMContext, Elements);
2852 assert(ElemTy->getPrimitiveSizeInBits() == 32);
2853 SmallVector<uint32_t, 32> Elements;
2854 Elements.reserve(NumElements);
2856 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2857 Elements.push_back(E->getCodeUnit(i));
2858 Elements.resize(NumElements);
2859 return llvm::ConstantDataArray::get(VMContext, Elements);
2862 static llvm::GlobalVariable *
2863 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
2864 CodeGenModule &CGM, StringRef GlobalName,
2865 unsigned Alignment) {
2866 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
2867 unsigned AddrSpace = 0;
2868 if (CGM.getLangOpts().OpenCL)
2869 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
2871 // Create a global variable for this string
2872 auto *GV = new llvm::GlobalVariable(
2873 CGM.getModule(), C->getType(), !CGM.getLangOpts().WritableStrings, LT, C,
2874 GlobalName, nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
2875 GV->setAlignment(Alignment);
2876 GV->setUnnamedAddr(true);
2880 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2881 /// constant array for the given string literal.
2882 llvm::GlobalVariable *
2883 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
2886 getContext().getAlignOfGlobalVarInChars(S->getType()).getQuantity();
2888 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2889 llvm::GlobalVariable **Entry = nullptr;
2890 if (!LangOpts.WritableStrings) {
2891 Entry = &ConstantStringMap[C];
2892 if (auto GV = *Entry) {
2893 if (Alignment > GV->getAlignment())
2894 GV->setAlignment(Alignment);
2899 SmallString<256> MangledNameBuffer;
2900 StringRef GlobalVariableName;
2901 llvm::GlobalValue::LinkageTypes LT;
2903 // Mangle the string literal if the ABI allows for it. However, we cannot
2904 // do this if we are compiling with ASan or -fwritable-strings because they
2905 // rely on strings having normal linkage.
2906 if (!LangOpts.WritableStrings &&
2907 !LangOpts.Sanitize.has(SanitizerKind::Address) &&
2908 getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
2909 llvm::raw_svector_ostream Out(MangledNameBuffer);
2910 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
2913 LT = llvm::GlobalValue::LinkOnceODRLinkage;
2914 GlobalVariableName = MangledNameBuffer;
2916 LT = llvm::GlobalValue::PrivateLinkage;
2917 GlobalVariableName = Name;
2920 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
2924 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
2929 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2930 /// array for the given ObjCEncodeExpr node.
2931 llvm::GlobalVariable *
2932 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2934 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
2936 return GetAddrOfConstantCString(Str);
2939 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
2940 /// the literal and a terminating '\0' character.
2941 /// The result has pointer to array type.
2942 llvm::GlobalVariable *CodeGenModule::GetAddrOfConstantCString(
2943 const std::string &Str, const char *GlobalName, unsigned Alignment) {
2944 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
2945 if (Alignment == 0) {
2946 Alignment = getContext()
2947 .getAlignOfGlobalVarInChars(getContext().CharTy)
2952 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
2954 // Don't share any string literals if strings aren't constant.
2955 llvm::GlobalVariable **Entry = nullptr;
2956 if (!LangOpts.WritableStrings) {
2957 Entry = &ConstantStringMap[C];
2958 if (auto GV = *Entry) {
2959 if (Alignment > GV->getAlignment())
2960 GV->setAlignment(Alignment);
2965 // Get the default prefix if a name wasn't specified.
2967 GlobalName = ".str";
2968 // Create a global variable for this.
2969 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
2970 GlobalName, Alignment);
2976 llvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary(
2977 const MaterializeTemporaryExpr *E, const Expr *Init) {
2978 assert((E->getStorageDuration() == SD_Static ||
2979 E->getStorageDuration() == SD_Thread) && "not a global temporary");
2980 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
2982 // If we're not materializing a subobject of the temporary, keep the
2983 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
2984 QualType MaterializedType = Init->getType();
2985 if (Init == E->GetTemporaryExpr())
2986 MaterializedType = E->getType();
2988 llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E];
2992 // FIXME: If an externally-visible declaration extends multiple temporaries,
2993 // we need to give each temporary the same name in every translation unit (and
2994 // we also need to make the temporaries externally-visible).
2995 SmallString<256> Name;
2996 llvm::raw_svector_ostream Out(Name);
2997 getCXXABI().getMangleContext().mangleReferenceTemporary(
2998 VD, E->getManglingNumber(), Out);
3001 APValue *Value = nullptr;
3002 if (E->getStorageDuration() == SD_Static) {
3003 // We might have a cached constant initializer for this temporary. Note
3004 // that this might have a different value from the value computed by
3005 // evaluating the initializer if the surrounding constant expression
3006 // modifies the temporary.
3007 Value = getContext().getMaterializedTemporaryValue(E, false);
3008 if (Value && Value->isUninit())
3012 // Try evaluating it now, it might have a constant initializer.
3013 Expr::EvalResult EvalResult;
3014 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3015 !EvalResult.hasSideEffects())
3016 Value = &EvalResult.Val;
3018 llvm::Constant *InitialValue = nullptr;
3019 bool Constant = false;
3022 // The temporary has a constant initializer, use it.
3023 InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
3024 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3025 Type = InitialValue->getType();
3027 // No initializer, the initialization will be provided when we
3028 // initialize the declaration which performed lifetime extension.
3029 Type = getTypes().ConvertTypeForMem(MaterializedType);
3032 // Create a global variable for this lifetime-extended temporary.
3033 llvm::GlobalValue::LinkageTypes Linkage =
3034 getLLVMLinkageVarDefinition(VD, Constant);
3035 // There is no need for this temporary to have global linkage if the global
3036 // variable has external linkage.
3037 if (Linkage == llvm::GlobalVariable::ExternalLinkage)
3038 Linkage = llvm::GlobalVariable::PrivateLinkage;
3039 unsigned AddrSpace = GetGlobalVarAddressSpace(
3040 VD, getContext().getTargetAddressSpace(MaterializedType));
3041 auto *GV = new llvm::GlobalVariable(
3042 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
3043 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3045 setGlobalVisibility(GV, VD);
3047 getContext().getTypeAlignInChars(MaterializedType).getQuantity());
3048 if (VD->getTLSKind())
3049 setTLSMode(GV, *VD);
3054 /// EmitObjCPropertyImplementations - Emit information for synthesized
3055 /// properties for an implementation.
3056 void CodeGenModule::EmitObjCPropertyImplementations(const
3057 ObjCImplementationDecl *D) {
3058 for (const auto *PID : D->property_impls()) {
3059 // Dynamic is just for type-checking.
3060 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3061 ObjCPropertyDecl *PD = PID->getPropertyDecl();
3063 // Determine which methods need to be implemented, some may have
3064 // been overridden. Note that ::isPropertyAccessor is not the method
3065 // we want, that just indicates if the decl came from a
3066 // property. What we want to know is if the method is defined in
3067 // this implementation.
3068 if (!D->getInstanceMethod(PD->getGetterName()))
3069 CodeGenFunction(*this).GenerateObjCGetter(
3070 const_cast<ObjCImplementationDecl *>(D), PID);
3071 if (!PD->isReadOnly() &&
3072 !D->getInstanceMethod(PD->getSetterName()))
3073 CodeGenFunction(*this).GenerateObjCSetter(
3074 const_cast<ObjCImplementationDecl *>(D), PID);
3079 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
3080 const ObjCInterfaceDecl *iface = impl->getClassInterface();
3081 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
3082 ivar; ivar = ivar->getNextIvar())
3083 if (ivar->getType().isDestructedType())
3089 static bool AllTrivialInitializers(CodeGenModule &CGM,
3090 ObjCImplementationDecl *D) {
3091 CodeGenFunction CGF(CGM);
3092 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
3093 E = D->init_end(); B != E; ++B) {
3094 CXXCtorInitializer *CtorInitExp = *B;
3095 Expr *Init = CtorInitExp->getInit();
3096 if (!CGF.isTrivialInitializer(Init))
3102 /// EmitObjCIvarInitializations - Emit information for ivar initialization
3103 /// for an implementation.
3104 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
3105 // We might need a .cxx_destruct even if we don't have any ivar initializers.
3106 if (needsDestructMethod(D)) {
3107 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3108 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3109 ObjCMethodDecl *DTORMethod =
3110 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
3111 cxxSelector, getContext().VoidTy, nullptr, D,
3112 /*isInstance=*/true, /*isVariadic=*/false,
3113 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
3114 /*isDefined=*/false, ObjCMethodDecl::Required);
3115 D->addInstanceMethod(DTORMethod);
3116 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
3117 D->setHasDestructors(true);
3120 // If the implementation doesn't have any ivar initializers, we don't need
3121 // a .cxx_construct.
3122 if (D->getNumIvarInitializers() == 0 ||
3123 AllTrivialInitializers(*this, D))
3126 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
3127 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3128 // The constructor returns 'self'.
3129 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3133 getContext().getObjCIdType(),
3134 nullptr, D, /*isInstance=*/true,
3135 /*isVariadic=*/false,
3136 /*isPropertyAccessor=*/true,
3137 /*isImplicitlyDeclared=*/true,
3138 /*isDefined=*/false,
3139 ObjCMethodDecl::Required);
3140 D->addInstanceMethod(CTORMethod);
3141 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
3142 D->setHasNonZeroConstructors(true);
3145 /// EmitNamespace - Emit all declarations in a namespace.
3146 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
3147 for (auto *I : ND->decls()) {
3148 if (const auto *VD = dyn_cast<VarDecl>(I))
3149 if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
3150 VD->getTemplateSpecializationKind() != TSK_Undeclared)
3152 EmitTopLevelDecl(I);
3156 // EmitLinkageSpec - Emit all declarations in a linkage spec.
3157 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
3158 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3159 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
3160 ErrorUnsupported(LSD, "linkage spec");
3164 for (auto *I : LSD->decls()) {
3165 // Meta-data for ObjC class includes references to implemented methods.
3166 // Generate class's method definitions first.
3167 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
3168 for (auto *M : OID->methods())
3169 EmitTopLevelDecl(M);
3171 EmitTopLevelDecl(I);
3175 /// EmitTopLevelDecl - Emit code for a single top level declaration.
3176 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
3177 // Ignore dependent declarations.
3178 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3181 switch (D->getKind()) {
3182 case Decl::CXXConversion:
3183 case Decl::CXXMethod:
3184 case Decl::Function:
3185 // Skip function templates
3186 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3187 cast<FunctionDecl>(D)->isLateTemplateParsed())
3190 EmitGlobal(cast<FunctionDecl>(D));
3191 // Always provide some coverage mapping
3192 // even for the functions that aren't emitted.
3193 AddDeferredUnusedCoverageMapping(D);
3197 // Skip variable templates
3198 if (cast<VarDecl>(D)->getDescribedVarTemplate())
3200 case Decl::VarTemplateSpecialization:
3201 EmitGlobal(cast<VarDecl>(D));
3204 // Indirect fields from global anonymous structs and unions can be
3205 // ignored; only the actual variable requires IR gen support.
3206 case Decl::IndirectField:
3210 case Decl::Namespace:
3211 EmitNamespace(cast<NamespaceDecl>(D));
3213 // No code generation needed.
3214 case Decl::UsingShadow:
3215 case Decl::ClassTemplate:
3216 case Decl::VarTemplate:
3217 case Decl::VarTemplatePartialSpecialization:
3218 case Decl::FunctionTemplate:
3219 case Decl::TypeAliasTemplate:
3223 case Decl::Using: // using X; [C++]
3224 if (CGDebugInfo *DI = getModuleDebugInfo())
3225 DI->EmitUsingDecl(cast<UsingDecl>(*D));
3227 case Decl::NamespaceAlias:
3228 if (CGDebugInfo *DI = getModuleDebugInfo())
3229 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3231 case Decl::UsingDirective: // using namespace X; [C++]
3232 if (CGDebugInfo *DI = getModuleDebugInfo())
3233 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3235 case Decl::CXXConstructor:
3236 // Skip function templates
3237 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3238 cast<FunctionDecl>(D)->isLateTemplateParsed())
3241 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
3243 case Decl::CXXDestructor:
3244 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3246 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
3249 case Decl::StaticAssert:
3253 // Objective-C Decls
3255 // Forward declarations, no (immediate) code generation.
3256 case Decl::ObjCInterface:
3257 case Decl::ObjCCategory:
3260 case Decl::ObjCProtocol: {
3261 auto *Proto = cast<ObjCProtocolDecl>(D);
3262 if (Proto->isThisDeclarationADefinition())
3263 ObjCRuntime->GenerateProtocol(Proto);
3267 case Decl::ObjCCategoryImpl:
3268 // Categories have properties but don't support synthesize so we
3269 // can ignore them here.
3270 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
3273 case Decl::ObjCImplementation: {
3274 auto *OMD = cast<ObjCImplementationDecl>(D);
3275 EmitObjCPropertyImplementations(OMD);
3276 EmitObjCIvarInitializations(OMD);
3277 ObjCRuntime->GenerateClass(OMD);
3278 // Emit global variable debug information.
3279 if (CGDebugInfo *DI = getModuleDebugInfo())
3280 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
3281 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3282 OMD->getClassInterface()), OMD->getLocation());
3285 case Decl::ObjCMethod: {
3286 auto *OMD = cast<ObjCMethodDecl>(D);
3287 // If this is not a prototype, emit the body.
3289 CodeGenFunction(*this).GenerateObjCMethod(OMD);
3292 case Decl::ObjCCompatibleAlias:
3293 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3296 case Decl::LinkageSpec:
3297 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
3300 case Decl::FileScopeAsm: {
3301 auto *AD = cast<FileScopeAsmDecl>(D);
3302 StringRef AsmString = AD->getAsmString()->getString();
3304 const std::string &S = getModule().getModuleInlineAsm();
3306 getModule().setModuleInlineAsm(AsmString);
3307 else if (S.end()[-1] == '\n')
3308 getModule().setModuleInlineAsm(S + AsmString.str());
3310 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
3314 case Decl::Import: {
3315 auto *Import = cast<ImportDecl>(D);
3317 // Ignore import declarations that come from imported modules.
3318 if (clang::Module *Owner = Import->getOwningModule()) {
3319 if (getLangOpts().CurrentModule.empty() ||
3320 Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
3324 ImportedModules.insert(Import->getImportedModule());
3328 case Decl::OMPThreadPrivate:
3329 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
3332 case Decl::ClassTemplateSpecialization: {
3333 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
3335 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
3336 Spec->hasDefinition())
3337 DebugInfo->completeTemplateDefinition(*Spec);
3342 // Make sure we handled everything we should, every other kind is a
3343 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
3344 // function. Need to recode Decl::Kind to do that easily.
3345 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
3350 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
3351 // Do we need to generate coverage mapping?
3352 if (!CodeGenOpts.CoverageMapping)
3354 switch (D->getKind()) {
3355 case Decl::CXXConversion:
3356 case Decl::CXXMethod:
3357 case Decl::Function:
3358 case Decl::ObjCMethod:
3359 case Decl::CXXConstructor:
3360 case Decl::CXXDestructor: {
3361 if (!cast<FunctionDecl>(D)->hasBody())
3363 auto I = DeferredEmptyCoverageMappingDecls.find(D);
3364 if (I == DeferredEmptyCoverageMappingDecls.end())
3365 DeferredEmptyCoverageMappingDecls[D] = true;
3373 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
3374 // Do we need to generate coverage mapping?
3375 if (!CodeGenOpts.CoverageMapping)
3377 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
3378 if (Fn->isTemplateInstantiation())
3379 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
3381 auto I = DeferredEmptyCoverageMappingDecls.find(D);
3382 if (I == DeferredEmptyCoverageMappingDecls.end())
3383 DeferredEmptyCoverageMappingDecls[D] = false;
3388 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
3389 std::vector<const Decl *> DeferredDecls;
3390 for (const auto I : DeferredEmptyCoverageMappingDecls) {
3393 DeferredDecls.push_back(I.first);
3395 // Sort the declarations by their location to make sure that the tests get a
3396 // predictable order for the coverage mapping for the unused declarations.
3397 if (CodeGenOpts.DumpCoverageMapping)
3398 std::sort(DeferredDecls.begin(), DeferredDecls.end(),
3399 [] (const Decl *LHS, const Decl *RHS) {
3400 return LHS->getLocStart() < RHS->getLocStart();
3402 for (const auto *D : DeferredDecls) {
3403 switch (D->getKind()) {
3404 case Decl::CXXConversion:
3405 case Decl::CXXMethod:
3406 case Decl::Function:
3407 case Decl::ObjCMethod: {
3408 CodeGenPGO PGO(*this);
3409 GlobalDecl GD(cast<FunctionDecl>(D));
3410 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3411 getFunctionLinkage(GD));
3414 case Decl::CXXConstructor: {
3415 CodeGenPGO PGO(*this);
3416 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
3417 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3418 getFunctionLinkage(GD));
3421 case Decl::CXXDestructor: {
3422 CodeGenPGO PGO(*this);
3423 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
3424 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3425 getFunctionLinkage(GD));
3434 /// Turns the given pointer into a constant.
3435 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
3437 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
3438 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
3439 return llvm::ConstantInt::get(i64, PtrInt);
3442 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
3443 llvm::NamedMDNode *&GlobalMetadata,
3445 llvm::GlobalValue *Addr) {
3446 if (!GlobalMetadata)
3448 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
3450 // TODO: should we report variant information for ctors/dtors?
3451 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
3452 llvm::ConstantAsMetadata::get(GetPointerConstant(
3453 CGM.getLLVMContext(), D.getDecl()))};
3454 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
3457 /// For each function which is declared within an extern "C" region and marked
3458 /// as 'used', but has internal linkage, create an alias from the unmangled
3459 /// name to the mangled name if possible. People expect to be able to refer
3460 /// to such functions with an unmangled name from inline assembly within the
3461 /// same translation unit.
3462 void CodeGenModule::EmitStaticExternCAliases() {
3463 for (StaticExternCMap::iterator I = StaticExternCValues.begin(),
3464 E = StaticExternCValues.end();
3466 IdentifierInfo *Name = I->first;
3467 llvm::GlobalValue *Val = I->second;
3468 if (Val && !getModule().getNamedValue(Name->getName()))
3469 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
3473 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
3474 GlobalDecl &Result) const {
3475 auto Res = Manglings.find(MangledName);
3476 if (Res == Manglings.end())
3478 Result = Res->getValue();
3482 /// Emits metadata nodes associating all the global values in the
3483 /// current module with the Decls they came from. This is useful for
3484 /// projects using IR gen as a subroutine.
3486 /// Since there's currently no way to associate an MDNode directly
3487 /// with an llvm::GlobalValue, we create a global named metadata
3488 /// with the name 'clang.global.decl.ptrs'.
3489 void CodeGenModule::EmitDeclMetadata() {
3490 llvm::NamedMDNode *GlobalMetadata = nullptr;
3492 // StaticLocalDeclMap
3493 for (auto &I : MangledDeclNames) {
3494 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
3495 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
3499 /// Emits metadata nodes for all the local variables in the current
3501 void CodeGenFunction::EmitDeclMetadata() {
3502 if (LocalDeclMap.empty()) return;
3504 llvm::LLVMContext &Context = getLLVMContext();
3506 // Find the unique metadata ID for this name.
3507 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
3509 llvm::NamedMDNode *GlobalMetadata = nullptr;
3511 for (auto &I : LocalDeclMap) {
3512 const Decl *D = I.first;
3513 llvm::Value *Addr = I.second;
3514 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
3515 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
3516 Alloca->setMetadata(
3517 DeclPtrKind, llvm::MDNode::get(
3518 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
3519 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
3520 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
3521 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
3526 void CodeGenModule::EmitVersionIdentMetadata() {
3527 llvm::NamedMDNode *IdentMetadata =
3528 TheModule.getOrInsertNamedMetadata("llvm.ident");
3529 std::string Version = getClangFullVersion();
3530 llvm::LLVMContext &Ctx = TheModule.getContext();
3532 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
3533 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
3536 void CodeGenModule::EmitTargetMetadata() {
3537 // Warning, new MangledDeclNames may be appended within this loop.
3538 // We rely on MapVector insertions adding new elements to the end
3539 // of the container.
3540 // FIXME: Move this loop into the one target that needs it, and only
3541 // loop over those declarations for which we couldn't emit the target
3542 // metadata when we emitted the declaration.
3543 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
3544 auto Val = *(MangledDeclNames.begin() + I);
3545 const Decl *D = Val.first.getDecl()->getMostRecentDecl();
3546 llvm::GlobalValue *GV = GetGlobalValue(Val.second);
3547 getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
3551 void CodeGenModule::EmitCoverageFile() {
3552 if (!getCodeGenOpts().CoverageFile.empty()) {
3553 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
3554 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
3555 llvm::LLVMContext &Ctx = TheModule.getContext();
3556 llvm::MDString *CoverageFile =
3557 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
3558 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
3559 llvm::MDNode *CU = CUNode->getOperand(i);
3560 llvm::Metadata *Elts[] = {CoverageFile, CU};
3561 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
3567 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
3568 // Sema has checked that all uuid strings are of the form
3569 // "12345678-1234-1234-1234-1234567890ab".
3570 assert(Uuid.size() == 36);
3571 for (unsigned i = 0; i < 36; ++i) {
3572 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
3573 else assert(isHexDigit(Uuid[i]));
3576 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
3577 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
3579 llvm::Constant *Field3[8];
3580 for (unsigned Idx = 0; Idx < 8; ++Idx)
3581 Field3[Idx] = llvm::ConstantInt::get(
3582 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
3584 llvm::Constant *Fields[4] = {
3585 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
3586 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
3587 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
3588 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
3591 return llvm::ConstantStruct::getAnon(Fields);
3594 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
3596 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
3597 // FIXME: should we even be calling this method if RTTI is disabled
3598 // and it's not for EH?
3599 if (!ForEH && !getLangOpts().RTTI)
3600 return llvm::Constant::getNullValue(Int8PtrTy);
3602 if (ForEH && Ty->isObjCObjectPointerType() &&
3603 LangOpts.ObjCRuntime.isGNUFamily())
3604 return ObjCRuntime->GetEHType(Ty);
3606 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
3609 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
3610 for (auto RefExpr : D->varlists()) {
3611 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
3613 VD->getAnyInitializer() &&
3614 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
3616 if (auto InitFunction =
3617 getOpenMPRuntime().EmitOMPThreadPrivateVarDefinition(
3618 VD, GetAddrOfGlobalVar(VD), RefExpr->getLocStart(),
3620 CXXGlobalInits.push_back(InitFunction);