xref: /minix3/external/bsd/llvm/dist/clang/lib/CodeGen/CodeGenModule.cpp (revision 0a6a1f1d05b60e214de2f05a7310ddd1f0e590e7)
1f4a2713aSLionel Sambuc //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2f4a2713aSLionel Sambuc //
3f4a2713aSLionel Sambuc //                     The LLVM Compiler Infrastructure
4f4a2713aSLionel Sambuc //
5f4a2713aSLionel Sambuc // This file is distributed under the University of Illinois Open Source
6f4a2713aSLionel Sambuc // License. See LICENSE.TXT for details.
7f4a2713aSLionel Sambuc //
8f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
9f4a2713aSLionel Sambuc //
10f4a2713aSLionel Sambuc // This coordinates the per-module state used while generating code.
11f4a2713aSLionel Sambuc //
12f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
13f4a2713aSLionel Sambuc 
14f4a2713aSLionel Sambuc #include "CodeGenModule.h"
15f4a2713aSLionel Sambuc #include "CGCUDARuntime.h"
16f4a2713aSLionel Sambuc #include "CGCXXABI.h"
17f4a2713aSLionel Sambuc #include "CGCall.h"
18f4a2713aSLionel Sambuc #include "CGDebugInfo.h"
19f4a2713aSLionel Sambuc #include "CGObjCRuntime.h"
20f4a2713aSLionel Sambuc #include "CGOpenCLRuntime.h"
21*0a6a1f1dSLionel Sambuc #include "CGOpenMPRuntime.h"
22f4a2713aSLionel Sambuc #include "CodeGenFunction.h"
23*0a6a1f1dSLionel Sambuc #include "CodeGenPGO.h"
24f4a2713aSLionel Sambuc #include "CodeGenTBAA.h"
25*0a6a1f1dSLionel Sambuc #include "CoverageMappingGen.h"
26f4a2713aSLionel Sambuc #include "TargetInfo.h"
27f4a2713aSLionel Sambuc #include "clang/AST/ASTContext.h"
28f4a2713aSLionel Sambuc #include "clang/AST/CharUnits.h"
29f4a2713aSLionel Sambuc #include "clang/AST/DeclCXX.h"
30f4a2713aSLionel Sambuc #include "clang/AST/DeclObjC.h"
31f4a2713aSLionel Sambuc #include "clang/AST/DeclTemplate.h"
32f4a2713aSLionel Sambuc #include "clang/AST/Mangle.h"
33f4a2713aSLionel Sambuc #include "clang/AST/RecordLayout.h"
34f4a2713aSLionel Sambuc #include "clang/AST/RecursiveASTVisitor.h"
35f4a2713aSLionel Sambuc #include "clang/Basic/Builtins.h"
36f4a2713aSLionel Sambuc #include "clang/Basic/CharInfo.h"
37f4a2713aSLionel Sambuc #include "clang/Basic/Diagnostic.h"
38f4a2713aSLionel Sambuc #include "clang/Basic/Module.h"
39f4a2713aSLionel Sambuc #include "clang/Basic/SourceManager.h"
40f4a2713aSLionel Sambuc #include "clang/Basic/TargetInfo.h"
41f4a2713aSLionel Sambuc #include "clang/Basic/Version.h"
42f4a2713aSLionel Sambuc #include "clang/Frontend/CodeGenOptions.h"
43f4a2713aSLionel Sambuc #include "clang/Sema/SemaDiagnostic.h"
44f4a2713aSLionel Sambuc #include "llvm/ADT/APSInt.h"
45f4a2713aSLionel Sambuc #include "llvm/ADT/Triple.h"
46*0a6a1f1dSLionel Sambuc #include "llvm/IR/CallSite.h"
47f4a2713aSLionel Sambuc #include "llvm/IR/CallingConv.h"
48f4a2713aSLionel Sambuc #include "llvm/IR/DataLayout.h"
49f4a2713aSLionel Sambuc #include "llvm/IR/Intrinsics.h"
50f4a2713aSLionel Sambuc #include "llvm/IR/LLVMContext.h"
51f4a2713aSLionel Sambuc #include "llvm/IR/Module.h"
52*0a6a1f1dSLionel Sambuc #include "llvm/ProfileData/InstrProfReader.h"
53f4a2713aSLionel Sambuc #include "llvm/Support/ConvertUTF.h"
54f4a2713aSLionel Sambuc #include "llvm/Support/ErrorHandling.h"
55f4a2713aSLionel Sambuc 
56f4a2713aSLionel Sambuc using namespace clang;
57f4a2713aSLionel Sambuc using namespace CodeGen;
58f4a2713aSLionel Sambuc 
59f4a2713aSLionel Sambuc static const char AnnotationSection[] = "llvm.metadata";
60f4a2713aSLionel Sambuc 
createCXXABI(CodeGenModule & CGM)61*0a6a1f1dSLionel Sambuc static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
62f4a2713aSLionel Sambuc   switch (CGM.getTarget().getCXXABI().getKind()) {
63f4a2713aSLionel Sambuc   case TargetCXXABI::GenericAArch64:
64f4a2713aSLionel Sambuc   case TargetCXXABI::GenericARM:
65f4a2713aSLionel Sambuc   case TargetCXXABI::iOS:
66*0a6a1f1dSLionel Sambuc   case TargetCXXABI::iOS64:
67*0a6a1f1dSLionel Sambuc   case TargetCXXABI::GenericMIPS:
68f4a2713aSLionel Sambuc   case TargetCXXABI::GenericItanium:
69*0a6a1f1dSLionel Sambuc     return CreateItaniumCXXABI(CGM);
70f4a2713aSLionel Sambuc   case TargetCXXABI::Microsoft:
71*0a6a1f1dSLionel Sambuc     return CreateMicrosoftCXXABI(CGM);
72f4a2713aSLionel Sambuc   }
73f4a2713aSLionel Sambuc 
74f4a2713aSLionel Sambuc   llvm_unreachable("invalid C++ ABI kind");
75f4a2713aSLionel Sambuc }
76f4a2713aSLionel Sambuc 
CodeGenModule(ASTContext & C,const CodeGenOptions & CGO,llvm::Module & M,const llvm::DataLayout & TD,DiagnosticsEngine & diags,CoverageSourceInfo * CoverageInfo)77f4a2713aSLionel Sambuc CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
78f4a2713aSLionel Sambuc                              llvm::Module &M, const llvm::DataLayout &TD,
79*0a6a1f1dSLionel Sambuc                              DiagnosticsEngine &diags,
80*0a6a1f1dSLionel Sambuc                              CoverageSourceInfo *CoverageInfo)
81f4a2713aSLionel Sambuc     : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
82f4a2713aSLionel Sambuc       Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()),
83*0a6a1f1dSLionel Sambuc       ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(nullptr),
84*0a6a1f1dSLionel Sambuc       TheTargetCodeGenInfo(nullptr), Types(*this), VTables(*this),
85*0a6a1f1dSLionel Sambuc       ObjCRuntime(nullptr), OpenCLRuntime(nullptr), OpenMPRuntime(nullptr),
86*0a6a1f1dSLionel Sambuc       CUDARuntime(nullptr), DebugInfo(nullptr), ARCData(nullptr),
87*0a6a1f1dSLionel Sambuc       NoObjCARCExceptionsMetadata(nullptr), RRData(nullptr), PGOReader(nullptr),
88*0a6a1f1dSLionel Sambuc       CFConstantStringClassRef(nullptr), ConstantStringClassRef(nullptr),
89*0a6a1f1dSLionel Sambuc       NSConstantStringType(nullptr), NSConcreteGlobalBlock(nullptr),
90*0a6a1f1dSLionel Sambuc       NSConcreteStackBlock(nullptr), BlockObjectAssign(nullptr),
91*0a6a1f1dSLionel Sambuc       BlockObjectDispose(nullptr), BlockDescriptorType(nullptr),
92*0a6a1f1dSLionel Sambuc       GenericBlockLiteralType(nullptr), LifetimeStartFn(nullptr),
93*0a6a1f1dSLionel Sambuc       LifetimeEndFn(nullptr), SanitizerMD(new SanitizerMetadata(*this)) {
94f4a2713aSLionel Sambuc 
95f4a2713aSLionel Sambuc   // Initialize the type cache.
96f4a2713aSLionel Sambuc   llvm::LLVMContext &LLVMContext = M.getContext();
97f4a2713aSLionel Sambuc   VoidTy = llvm::Type::getVoidTy(LLVMContext);
98f4a2713aSLionel Sambuc   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
99f4a2713aSLionel Sambuc   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
100f4a2713aSLionel Sambuc   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
101f4a2713aSLionel Sambuc   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
102f4a2713aSLionel Sambuc   FloatTy = llvm::Type::getFloatTy(LLVMContext);
103f4a2713aSLionel Sambuc   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
104f4a2713aSLionel Sambuc   PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
105f4a2713aSLionel Sambuc   PointerAlignInBytes =
106f4a2713aSLionel Sambuc   C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
107f4a2713aSLionel Sambuc   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
108f4a2713aSLionel Sambuc   IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
109f4a2713aSLionel Sambuc   Int8PtrTy = Int8Ty->getPointerTo(0);
110f4a2713aSLionel Sambuc   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
111f4a2713aSLionel Sambuc 
112f4a2713aSLionel Sambuc   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
113*0a6a1f1dSLionel Sambuc   BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
114f4a2713aSLionel Sambuc 
115f4a2713aSLionel Sambuc   if (LangOpts.ObjC1)
116f4a2713aSLionel Sambuc     createObjCRuntime();
117f4a2713aSLionel Sambuc   if (LangOpts.OpenCL)
118f4a2713aSLionel Sambuc     createOpenCLRuntime();
119*0a6a1f1dSLionel Sambuc   if (LangOpts.OpenMP)
120*0a6a1f1dSLionel Sambuc     createOpenMPRuntime();
121f4a2713aSLionel Sambuc   if (LangOpts.CUDA)
122f4a2713aSLionel Sambuc     createCUDARuntime();
123f4a2713aSLionel Sambuc 
124f4a2713aSLionel Sambuc   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
125*0a6a1f1dSLionel Sambuc   if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
126f4a2713aSLionel Sambuc       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
127f4a2713aSLionel Sambuc     TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
128*0a6a1f1dSLionel Sambuc                            getCXXABI().getMangleContext());
129f4a2713aSLionel Sambuc 
130f4a2713aSLionel Sambuc   // If debug info or coverage generation is enabled, create the CGDebugInfo
131f4a2713aSLionel Sambuc   // object.
132f4a2713aSLionel Sambuc   if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
133f4a2713aSLionel Sambuc       CodeGenOpts.EmitGcovArcs ||
134f4a2713aSLionel Sambuc       CodeGenOpts.EmitGcovNotes)
135f4a2713aSLionel Sambuc     DebugInfo = new CGDebugInfo(*this);
136f4a2713aSLionel Sambuc 
137f4a2713aSLionel Sambuc   Block.GlobalUniqueCount = 0;
138f4a2713aSLionel Sambuc 
139f4a2713aSLionel Sambuc   if (C.getLangOpts().ObjCAutoRefCount)
140f4a2713aSLionel Sambuc     ARCData = new ARCEntrypoints();
141f4a2713aSLionel Sambuc   RRData = new RREntrypoints();
142*0a6a1f1dSLionel Sambuc 
143*0a6a1f1dSLionel Sambuc   if (!CodeGenOpts.InstrProfileInput.empty()) {
144*0a6a1f1dSLionel Sambuc     if (std::error_code EC = llvm::IndexedInstrProfReader::create(
145*0a6a1f1dSLionel Sambuc             CodeGenOpts.InstrProfileInput, PGOReader)) {
146*0a6a1f1dSLionel Sambuc       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
147*0a6a1f1dSLionel Sambuc                                               "Could not read profile: %0");
148*0a6a1f1dSLionel Sambuc       getDiags().Report(DiagID) << EC.message();
149*0a6a1f1dSLionel Sambuc     }
150*0a6a1f1dSLionel Sambuc   }
151*0a6a1f1dSLionel Sambuc 
152*0a6a1f1dSLionel Sambuc   // If coverage mapping generation is enabled, create the
153*0a6a1f1dSLionel Sambuc   // CoverageMappingModuleGen object.
154*0a6a1f1dSLionel Sambuc   if (CodeGenOpts.CoverageMapping)
155*0a6a1f1dSLionel Sambuc     CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
156f4a2713aSLionel Sambuc }
157f4a2713aSLionel Sambuc 
~CodeGenModule()158f4a2713aSLionel Sambuc CodeGenModule::~CodeGenModule() {
159f4a2713aSLionel Sambuc   delete ObjCRuntime;
160f4a2713aSLionel Sambuc   delete OpenCLRuntime;
161*0a6a1f1dSLionel Sambuc   delete OpenMPRuntime;
162f4a2713aSLionel Sambuc   delete CUDARuntime;
163f4a2713aSLionel Sambuc   delete TheTargetCodeGenInfo;
164f4a2713aSLionel Sambuc   delete TBAA;
165f4a2713aSLionel Sambuc   delete DebugInfo;
166f4a2713aSLionel Sambuc   delete ARCData;
167f4a2713aSLionel Sambuc   delete RRData;
168f4a2713aSLionel Sambuc }
169f4a2713aSLionel Sambuc 
createObjCRuntime()170f4a2713aSLionel Sambuc void CodeGenModule::createObjCRuntime() {
171f4a2713aSLionel Sambuc   // This is just isGNUFamily(), but we want to force implementors of
172f4a2713aSLionel Sambuc   // new ABIs to decide how best to do this.
173f4a2713aSLionel Sambuc   switch (LangOpts.ObjCRuntime.getKind()) {
174f4a2713aSLionel Sambuc   case ObjCRuntime::GNUstep:
175f4a2713aSLionel Sambuc   case ObjCRuntime::GCC:
176f4a2713aSLionel Sambuc   case ObjCRuntime::ObjFW:
177f4a2713aSLionel Sambuc     ObjCRuntime = CreateGNUObjCRuntime(*this);
178f4a2713aSLionel Sambuc     return;
179f4a2713aSLionel Sambuc 
180f4a2713aSLionel Sambuc   case ObjCRuntime::FragileMacOSX:
181f4a2713aSLionel Sambuc   case ObjCRuntime::MacOSX:
182f4a2713aSLionel Sambuc   case ObjCRuntime::iOS:
183f4a2713aSLionel Sambuc     ObjCRuntime = CreateMacObjCRuntime(*this);
184f4a2713aSLionel Sambuc     return;
185f4a2713aSLionel Sambuc   }
186f4a2713aSLionel Sambuc   llvm_unreachable("bad runtime kind");
187f4a2713aSLionel Sambuc }
188f4a2713aSLionel Sambuc 
createOpenCLRuntime()189f4a2713aSLionel Sambuc void CodeGenModule::createOpenCLRuntime() {
190f4a2713aSLionel Sambuc   OpenCLRuntime = new CGOpenCLRuntime(*this);
191f4a2713aSLionel Sambuc }
192f4a2713aSLionel Sambuc 
createOpenMPRuntime()193*0a6a1f1dSLionel Sambuc void CodeGenModule::createOpenMPRuntime() {
194*0a6a1f1dSLionel Sambuc   OpenMPRuntime = new CGOpenMPRuntime(*this);
195*0a6a1f1dSLionel Sambuc }
196*0a6a1f1dSLionel Sambuc 
createCUDARuntime()197f4a2713aSLionel Sambuc void CodeGenModule::createCUDARuntime() {
198f4a2713aSLionel Sambuc   CUDARuntime = CreateNVCUDARuntime(*this);
199f4a2713aSLionel Sambuc }
200f4a2713aSLionel Sambuc 
addReplacement(StringRef Name,llvm::Constant * C)201*0a6a1f1dSLionel Sambuc void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
202*0a6a1f1dSLionel Sambuc   Replacements[Name] = C;
203*0a6a1f1dSLionel Sambuc }
204*0a6a1f1dSLionel Sambuc 
applyReplacements()205f4a2713aSLionel Sambuc void CodeGenModule::applyReplacements() {
206f4a2713aSLionel Sambuc   for (ReplacementsTy::iterator I = Replacements.begin(),
207f4a2713aSLionel Sambuc                                 E = Replacements.end();
208f4a2713aSLionel Sambuc        I != E; ++I) {
209f4a2713aSLionel Sambuc     StringRef MangledName = I->first();
210f4a2713aSLionel Sambuc     llvm::Constant *Replacement = I->second;
211f4a2713aSLionel Sambuc     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
212f4a2713aSLionel Sambuc     if (!Entry)
213f4a2713aSLionel Sambuc       continue;
214*0a6a1f1dSLionel Sambuc     auto *OldF = cast<llvm::Function>(Entry);
215*0a6a1f1dSLionel Sambuc     auto *NewF = dyn_cast<llvm::Function>(Replacement);
216f4a2713aSLionel Sambuc     if (!NewF) {
217*0a6a1f1dSLionel Sambuc       if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
218*0a6a1f1dSLionel Sambuc         NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
219*0a6a1f1dSLionel Sambuc       } else {
220*0a6a1f1dSLionel Sambuc         auto *CE = cast<llvm::ConstantExpr>(Replacement);
221f4a2713aSLionel Sambuc         assert(CE->getOpcode() == llvm::Instruction::BitCast ||
222f4a2713aSLionel Sambuc                CE->getOpcode() == llvm::Instruction::GetElementPtr);
223f4a2713aSLionel Sambuc         NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
224f4a2713aSLionel Sambuc       }
225*0a6a1f1dSLionel Sambuc     }
226f4a2713aSLionel Sambuc 
227f4a2713aSLionel Sambuc     // Replace old with new, but keep the old order.
228f4a2713aSLionel Sambuc     OldF->replaceAllUsesWith(Replacement);
229f4a2713aSLionel Sambuc     if (NewF) {
230f4a2713aSLionel Sambuc       NewF->removeFromParent();
231f4a2713aSLionel Sambuc       OldF->getParent()->getFunctionList().insertAfter(OldF, NewF);
232f4a2713aSLionel Sambuc     }
233f4a2713aSLionel Sambuc     OldF->eraseFromParent();
234f4a2713aSLionel Sambuc   }
235f4a2713aSLionel Sambuc }
236f4a2713aSLionel Sambuc 
237*0a6a1f1dSLionel Sambuc // This is only used in aliases that we created and we know they have a
238*0a6a1f1dSLionel Sambuc // linear structure.
getAliasedGlobal(const llvm::GlobalAlias & GA)239*0a6a1f1dSLionel Sambuc static const llvm::GlobalObject *getAliasedGlobal(const llvm::GlobalAlias &GA) {
240*0a6a1f1dSLionel Sambuc   llvm::SmallPtrSet<const llvm::GlobalAlias*, 4> Visited;
241*0a6a1f1dSLionel Sambuc   const llvm::Constant *C = &GA;
242*0a6a1f1dSLionel Sambuc   for (;;) {
243*0a6a1f1dSLionel Sambuc     C = C->stripPointerCasts();
244*0a6a1f1dSLionel Sambuc     if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
245*0a6a1f1dSLionel Sambuc       return GO;
246*0a6a1f1dSLionel Sambuc     // stripPointerCasts will not walk over weak aliases.
247*0a6a1f1dSLionel Sambuc     auto *GA2 = dyn_cast<llvm::GlobalAlias>(C);
248*0a6a1f1dSLionel Sambuc     if (!GA2)
249*0a6a1f1dSLionel Sambuc       return nullptr;
250*0a6a1f1dSLionel Sambuc     if (!Visited.insert(GA2).second)
251*0a6a1f1dSLionel Sambuc       return nullptr;
252*0a6a1f1dSLionel Sambuc     C = GA2->getAliasee();
253*0a6a1f1dSLionel Sambuc   }
254*0a6a1f1dSLionel Sambuc }
255*0a6a1f1dSLionel Sambuc 
checkAliases()256f4a2713aSLionel Sambuc void CodeGenModule::checkAliases() {
257*0a6a1f1dSLionel Sambuc   // Check if the constructed aliases are well formed. It is really unfortunate
258*0a6a1f1dSLionel Sambuc   // that we have to do this in CodeGen, but we only construct mangled names
259*0a6a1f1dSLionel Sambuc   // and aliases during codegen.
260f4a2713aSLionel Sambuc   bool Error = false;
261*0a6a1f1dSLionel Sambuc   DiagnosticsEngine &Diags = getDiags();
262f4a2713aSLionel Sambuc   for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
263f4a2713aSLionel Sambuc          E = Aliases.end(); I != E; ++I) {
264f4a2713aSLionel Sambuc     const GlobalDecl &GD = *I;
265*0a6a1f1dSLionel Sambuc     const auto *D = cast<ValueDecl>(GD.getDecl());
266f4a2713aSLionel Sambuc     const AliasAttr *AA = D->getAttr<AliasAttr>();
267f4a2713aSLionel Sambuc     StringRef MangledName = getMangledName(GD);
268f4a2713aSLionel Sambuc     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
269*0a6a1f1dSLionel Sambuc     auto *Alias = cast<llvm::GlobalAlias>(Entry);
270*0a6a1f1dSLionel Sambuc     const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
271*0a6a1f1dSLionel Sambuc     if (!GV) {
272f4a2713aSLionel Sambuc       Error = true;
273*0a6a1f1dSLionel Sambuc       Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
274*0a6a1f1dSLionel Sambuc     } else if (GV->isDeclaration()) {
275f4a2713aSLionel Sambuc       Error = true;
276*0a6a1f1dSLionel Sambuc       Diags.Report(AA->getLocation(), diag::err_alias_to_undefined);
277*0a6a1f1dSLionel Sambuc     }
278*0a6a1f1dSLionel Sambuc 
279*0a6a1f1dSLionel Sambuc     llvm::Constant *Aliasee = Alias->getAliasee();
280*0a6a1f1dSLionel Sambuc     llvm::GlobalValue *AliaseeGV;
281*0a6a1f1dSLionel Sambuc     if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
282*0a6a1f1dSLionel Sambuc       AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
283*0a6a1f1dSLionel Sambuc     else
284*0a6a1f1dSLionel Sambuc       AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
285*0a6a1f1dSLionel Sambuc 
286*0a6a1f1dSLionel Sambuc     if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
287*0a6a1f1dSLionel Sambuc       StringRef AliasSection = SA->getName();
288*0a6a1f1dSLionel Sambuc       if (AliasSection != AliaseeGV->getSection())
289*0a6a1f1dSLionel Sambuc         Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
290*0a6a1f1dSLionel Sambuc             << AliasSection;
291*0a6a1f1dSLionel Sambuc     }
292*0a6a1f1dSLionel Sambuc 
293*0a6a1f1dSLionel Sambuc     // We have to handle alias to weak aliases in here. LLVM itself disallows
294*0a6a1f1dSLionel Sambuc     // this since the object semantics would not match the IL one. For
295*0a6a1f1dSLionel Sambuc     // compatibility with gcc we implement it by just pointing the alias
296*0a6a1f1dSLionel Sambuc     // to its aliasee's aliasee. We also warn, since the user is probably
297*0a6a1f1dSLionel Sambuc     // expecting the link to be weak.
298*0a6a1f1dSLionel Sambuc     if (auto GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
299*0a6a1f1dSLionel Sambuc       if (GA->mayBeOverridden()) {
300*0a6a1f1dSLionel Sambuc         Diags.Report(AA->getLocation(), diag::warn_alias_to_weak_alias)
301*0a6a1f1dSLionel Sambuc             << GV->getName() << GA->getName();
302*0a6a1f1dSLionel Sambuc         Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
303*0a6a1f1dSLionel Sambuc             GA->getAliasee(), Alias->getType());
304*0a6a1f1dSLionel Sambuc         Alias->setAliasee(Aliasee);
305*0a6a1f1dSLionel Sambuc       }
306f4a2713aSLionel Sambuc     }
307f4a2713aSLionel Sambuc   }
308f4a2713aSLionel Sambuc   if (!Error)
309f4a2713aSLionel Sambuc     return;
310f4a2713aSLionel Sambuc 
311f4a2713aSLionel Sambuc   for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
312f4a2713aSLionel Sambuc          E = Aliases.end(); I != E; ++I) {
313f4a2713aSLionel Sambuc     const GlobalDecl &GD = *I;
314f4a2713aSLionel Sambuc     StringRef MangledName = getMangledName(GD);
315f4a2713aSLionel Sambuc     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
316*0a6a1f1dSLionel Sambuc     auto *Alias = cast<llvm::GlobalAlias>(Entry);
317f4a2713aSLionel Sambuc     Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
318f4a2713aSLionel Sambuc     Alias->eraseFromParent();
319f4a2713aSLionel Sambuc   }
320f4a2713aSLionel Sambuc }
321f4a2713aSLionel Sambuc 
clear()322*0a6a1f1dSLionel Sambuc void CodeGenModule::clear() {
323*0a6a1f1dSLionel Sambuc   DeferredDeclsToEmit.clear();
324*0a6a1f1dSLionel Sambuc }
325*0a6a1f1dSLionel Sambuc 
reportDiagnostics(DiagnosticsEngine & Diags,StringRef MainFile)326*0a6a1f1dSLionel Sambuc void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
327*0a6a1f1dSLionel Sambuc                                        StringRef MainFile) {
328*0a6a1f1dSLionel Sambuc   if (!hasDiagnostics())
329*0a6a1f1dSLionel Sambuc     return;
330*0a6a1f1dSLionel Sambuc   if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
331*0a6a1f1dSLionel Sambuc     if (MainFile.empty())
332*0a6a1f1dSLionel Sambuc       MainFile = "<stdin>";
333*0a6a1f1dSLionel Sambuc     Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
334*0a6a1f1dSLionel Sambuc   } else
335*0a6a1f1dSLionel Sambuc     Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Missing
336*0a6a1f1dSLionel Sambuc                                                       << Mismatched;
337*0a6a1f1dSLionel Sambuc }
338*0a6a1f1dSLionel Sambuc 
Release()339f4a2713aSLionel Sambuc void CodeGenModule::Release() {
340f4a2713aSLionel Sambuc   EmitDeferred();
341f4a2713aSLionel Sambuc   applyReplacements();
342f4a2713aSLionel Sambuc   checkAliases();
343f4a2713aSLionel Sambuc   EmitCXXGlobalInitFunc();
344f4a2713aSLionel Sambuc   EmitCXXGlobalDtorFunc();
345f4a2713aSLionel Sambuc   EmitCXXThreadLocalInitFunc();
346f4a2713aSLionel Sambuc   if (ObjCRuntime)
347f4a2713aSLionel Sambuc     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
348f4a2713aSLionel Sambuc       AddGlobalCtor(ObjCInitFunction);
349*0a6a1f1dSLionel Sambuc   if (PGOReader && PGOStats.hasDiagnostics())
350*0a6a1f1dSLionel Sambuc     PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
351f4a2713aSLionel Sambuc   EmitCtorList(GlobalCtors, "llvm.global_ctors");
352f4a2713aSLionel Sambuc   EmitCtorList(GlobalDtors, "llvm.global_dtors");
353f4a2713aSLionel Sambuc   EmitGlobalAnnotations();
354f4a2713aSLionel Sambuc   EmitStaticExternCAliases();
355*0a6a1f1dSLionel Sambuc   EmitDeferredUnusedCoverageMappings();
356*0a6a1f1dSLionel Sambuc   if (CoverageMapping)
357*0a6a1f1dSLionel Sambuc     CoverageMapping->emit();
358*0a6a1f1dSLionel Sambuc   emitLLVMUsed();
359f4a2713aSLionel Sambuc 
360f4a2713aSLionel Sambuc   if (CodeGenOpts.Autolink &&
361f4a2713aSLionel Sambuc       (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
362f4a2713aSLionel Sambuc     EmitModuleLinkOptions();
363f4a2713aSLionel Sambuc   }
364f4a2713aSLionel Sambuc   if (CodeGenOpts.DwarfVersion)
365f4a2713aSLionel Sambuc     // We actually want the latest version when there are conflicts.
366f4a2713aSLionel Sambuc     // We can change from Warning to Latest if such mode is supported.
367f4a2713aSLionel Sambuc     getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
368f4a2713aSLionel Sambuc                               CodeGenOpts.DwarfVersion);
369*0a6a1f1dSLionel Sambuc   if (DebugInfo)
370*0a6a1f1dSLionel Sambuc     // We support a single version in the linked module. The LLVM
371*0a6a1f1dSLionel Sambuc     // parser will drop debug info with a different version number
372*0a6a1f1dSLionel Sambuc     // (and warn about it, too).
373*0a6a1f1dSLionel Sambuc     getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
374*0a6a1f1dSLionel Sambuc                               llvm::DEBUG_METADATA_VERSION);
375*0a6a1f1dSLionel Sambuc 
376*0a6a1f1dSLionel Sambuc   // We need to record the widths of enums and wchar_t, so that we can generate
377*0a6a1f1dSLionel Sambuc   // the correct build attributes in the ARM backend.
378*0a6a1f1dSLionel Sambuc   llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
379*0a6a1f1dSLionel Sambuc   if (   Arch == llvm::Triple::arm
380*0a6a1f1dSLionel Sambuc       || Arch == llvm::Triple::armeb
381*0a6a1f1dSLionel Sambuc       || Arch == llvm::Triple::thumb
382*0a6a1f1dSLionel Sambuc       || Arch == llvm::Triple::thumbeb) {
383*0a6a1f1dSLionel Sambuc     // Width of wchar_t in bytes
384*0a6a1f1dSLionel Sambuc     uint64_t WCharWidth =
385*0a6a1f1dSLionel Sambuc         Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
386*0a6a1f1dSLionel Sambuc     getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
387*0a6a1f1dSLionel Sambuc 
388*0a6a1f1dSLionel Sambuc     // The minimum width of an enum in bytes
389*0a6a1f1dSLionel Sambuc     uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
390*0a6a1f1dSLionel Sambuc     getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
391*0a6a1f1dSLionel Sambuc   }
392*0a6a1f1dSLionel Sambuc 
393*0a6a1f1dSLionel Sambuc   if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
394*0a6a1f1dSLionel Sambuc     llvm::PICLevel::Level PL = llvm::PICLevel::Default;
395*0a6a1f1dSLionel Sambuc     switch (PLevel) {
396*0a6a1f1dSLionel Sambuc     case 0: break;
397*0a6a1f1dSLionel Sambuc     case 1: PL = llvm::PICLevel::Small; break;
398*0a6a1f1dSLionel Sambuc     case 2: PL = llvm::PICLevel::Large; break;
399*0a6a1f1dSLionel Sambuc     default: llvm_unreachable("Invalid PIC Level");
400*0a6a1f1dSLionel Sambuc     }
401*0a6a1f1dSLionel Sambuc 
402*0a6a1f1dSLionel Sambuc     getModule().setPICLevel(PL);
403*0a6a1f1dSLionel Sambuc   }
404f4a2713aSLionel Sambuc 
405f4a2713aSLionel Sambuc   SimplifyPersonality();
406f4a2713aSLionel Sambuc 
407f4a2713aSLionel Sambuc   if (getCodeGenOpts().EmitDeclMetadata)
408f4a2713aSLionel Sambuc     EmitDeclMetadata();
409f4a2713aSLionel Sambuc 
410f4a2713aSLionel Sambuc   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
411f4a2713aSLionel Sambuc     EmitCoverageFile();
412f4a2713aSLionel Sambuc 
413f4a2713aSLionel Sambuc   if (DebugInfo)
414f4a2713aSLionel Sambuc     DebugInfo->finalize();
415f4a2713aSLionel Sambuc 
416f4a2713aSLionel Sambuc   EmitVersionIdentMetadata();
417*0a6a1f1dSLionel Sambuc 
418*0a6a1f1dSLionel Sambuc   EmitTargetMetadata();
419f4a2713aSLionel Sambuc }
420f4a2713aSLionel Sambuc 
UpdateCompletedType(const TagDecl * TD)421f4a2713aSLionel Sambuc void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
422f4a2713aSLionel Sambuc   // Make sure that this type is translated.
423f4a2713aSLionel Sambuc   Types.UpdateCompletedType(TD);
424f4a2713aSLionel Sambuc }
425f4a2713aSLionel Sambuc 
getTBAAInfo(QualType QTy)426f4a2713aSLionel Sambuc llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
427f4a2713aSLionel Sambuc   if (!TBAA)
428*0a6a1f1dSLionel Sambuc     return nullptr;
429f4a2713aSLionel Sambuc   return TBAA->getTBAAInfo(QTy);
430f4a2713aSLionel Sambuc }
431f4a2713aSLionel Sambuc 
getTBAAInfoForVTablePtr()432f4a2713aSLionel Sambuc llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
433f4a2713aSLionel Sambuc   if (!TBAA)
434*0a6a1f1dSLionel Sambuc     return nullptr;
435f4a2713aSLionel Sambuc   return TBAA->getTBAAInfoForVTablePtr();
436f4a2713aSLionel Sambuc }
437f4a2713aSLionel Sambuc 
getTBAAStructInfo(QualType QTy)438f4a2713aSLionel Sambuc llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
439f4a2713aSLionel Sambuc   if (!TBAA)
440*0a6a1f1dSLionel Sambuc     return nullptr;
441f4a2713aSLionel Sambuc   return TBAA->getTBAAStructInfo(QTy);
442f4a2713aSLionel Sambuc }
443f4a2713aSLionel Sambuc 
getTBAAStructTypeInfo(QualType QTy)444f4a2713aSLionel Sambuc llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) {
445f4a2713aSLionel Sambuc   if (!TBAA)
446*0a6a1f1dSLionel Sambuc     return nullptr;
447f4a2713aSLionel Sambuc   return TBAA->getTBAAStructTypeInfo(QTy);
448f4a2713aSLionel Sambuc }
449f4a2713aSLionel Sambuc 
getTBAAStructTagInfo(QualType BaseTy,llvm::MDNode * AccessN,uint64_t O)450f4a2713aSLionel Sambuc llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
451f4a2713aSLionel Sambuc                                                   llvm::MDNode *AccessN,
452f4a2713aSLionel Sambuc                                                   uint64_t O) {
453f4a2713aSLionel Sambuc   if (!TBAA)
454*0a6a1f1dSLionel Sambuc     return nullptr;
455f4a2713aSLionel Sambuc   return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
456f4a2713aSLionel Sambuc }
457f4a2713aSLionel Sambuc 
458f4a2713aSLionel Sambuc /// Decorate the instruction with a TBAA tag. For both scalar TBAA
459f4a2713aSLionel Sambuc /// and struct-path aware TBAA, the tag has the same format:
460f4a2713aSLionel Sambuc /// base type, access type and offset.
461f4a2713aSLionel Sambuc /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
DecorateInstruction(llvm::Instruction * Inst,llvm::MDNode * TBAAInfo,bool ConvertTypeToTag)462f4a2713aSLionel Sambuc void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
463f4a2713aSLionel Sambuc                                         llvm::MDNode *TBAAInfo,
464f4a2713aSLionel Sambuc                                         bool ConvertTypeToTag) {
465f4a2713aSLionel Sambuc   if (ConvertTypeToTag && TBAA)
466f4a2713aSLionel Sambuc     Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
467f4a2713aSLionel Sambuc                       TBAA->getTBAAScalarTagInfo(TBAAInfo));
468f4a2713aSLionel Sambuc   else
469f4a2713aSLionel Sambuc     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
470f4a2713aSLionel Sambuc }
471f4a2713aSLionel Sambuc 
Error(SourceLocation loc,StringRef message)472*0a6a1f1dSLionel Sambuc void CodeGenModule::Error(SourceLocation loc, StringRef message) {
473*0a6a1f1dSLionel Sambuc   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
474*0a6a1f1dSLionel Sambuc   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
475f4a2713aSLionel Sambuc }
476f4a2713aSLionel Sambuc 
477f4a2713aSLionel Sambuc /// ErrorUnsupported - Print out an error that codegen doesn't support the
478f4a2713aSLionel Sambuc /// specified stmt yet.
ErrorUnsupported(const Stmt * S,const char * Type)479f4a2713aSLionel Sambuc void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
480f4a2713aSLionel Sambuc   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
481f4a2713aSLionel Sambuc                                                "cannot compile this %0 yet");
482f4a2713aSLionel Sambuc   std::string Msg = Type;
483f4a2713aSLionel Sambuc   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
484f4a2713aSLionel Sambuc     << Msg << S->getSourceRange();
485f4a2713aSLionel Sambuc }
486f4a2713aSLionel Sambuc 
487f4a2713aSLionel Sambuc /// ErrorUnsupported - Print out an error that codegen doesn't support the
488f4a2713aSLionel Sambuc /// specified decl yet.
ErrorUnsupported(const Decl * D,const char * Type)489f4a2713aSLionel Sambuc void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
490f4a2713aSLionel Sambuc   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
491f4a2713aSLionel Sambuc                                                "cannot compile this %0 yet");
492f4a2713aSLionel Sambuc   std::string Msg = Type;
493f4a2713aSLionel Sambuc   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
494f4a2713aSLionel Sambuc }
495f4a2713aSLionel Sambuc 
getSize(CharUnits size)496f4a2713aSLionel Sambuc llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
497f4a2713aSLionel Sambuc   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
498f4a2713aSLionel Sambuc }
499f4a2713aSLionel Sambuc 
setGlobalVisibility(llvm::GlobalValue * GV,const NamedDecl * D) const500f4a2713aSLionel Sambuc void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
501f4a2713aSLionel Sambuc                                         const NamedDecl *D) const {
502f4a2713aSLionel Sambuc   // Internal definitions always have default visibility.
503f4a2713aSLionel Sambuc   if (GV->hasLocalLinkage()) {
504f4a2713aSLionel Sambuc     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
505f4a2713aSLionel Sambuc     return;
506f4a2713aSLionel Sambuc   }
507f4a2713aSLionel Sambuc 
508f4a2713aSLionel Sambuc   // Set visibility for definitions.
509f4a2713aSLionel Sambuc   LinkageInfo LV = D->getLinkageAndVisibility();
510f4a2713aSLionel Sambuc   if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
511f4a2713aSLionel Sambuc     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
512f4a2713aSLionel Sambuc }
513f4a2713aSLionel Sambuc 
GetLLVMTLSModel(StringRef S)514f4a2713aSLionel Sambuc static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
515f4a2713aSLionel Sambuc   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
516f4a2713aSLionel Sambuc       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
517f4a2713aSLionel Sambuc       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
518f4a2713aSLionel Sambuc       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
519f4a2713aSLionel Sambuc       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
520f4a2713aSLionel Sambuc }
521f4a2713aSLionel Sambuc 
GetLLVMTLSModel(CodeGenOptions::TLSModel M)522f4a2713aSLionel Sambuc static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
523f4a2713aSLionel Sambuc     CodeGenOptions::TLSModel M) {
524f4a2713aSLionel Sambuc   switch (M) {
525f4a2713aSLionel Sambuc   case CodeGenOptions::GeneralDynamicTLSModel:
526f4a2713aSLionel Sambuc     return llvm::GlobalVariable::GeneralDynamicTLSModel;
527f4a2713aSLionel Sambuc   case CodeGenOptions::LocalDynamicTLSModel:
528f4a2713aSLionel Sambuc     return llvm::GlobalVariable::LocalDynamicTLSModel;
529f4a2713aSLionel Sambuc   case CodeGenOptions::InitialExecTLSModel:
530f4a2713aSLionel Sambuc     return llvm::GlobalVariable::InitialExecTLSModel;
531f4a2713aSLionel Sambuc   case CodeGenOptions::LocalExecTLSModel:
532f4a2713aSLionel Sambuc     return llvm::GlobalVariable::LocalExecTLSModel;
533f4a2713aSLionel Sambuc   }
534f4a2713aSLionel Sambuc   llvm_unreachable("Invalid TLS model!");
535f4a2713aSLionel Sambuc }
536f4a2713aSLionel Sambuc 
setTLSMode(llvm::GlobalValue * GV,const VarDecl & D) const537*0a6a1f1dSLionel Sambuc void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
538f4a2713aSLionel Sambuc   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
539f4a2713aSLionel Sambuc 
540*0a6a1f1dSLionel Sambuc   llvm::GlobalValue::ThreadLocalMode TLM;
541f4a2713aSLionel Sambuc   TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
542f4a2713aSLionel Sambuc 
543f4a2713aSLionel Sambuc   // Override the TLS model if it is explicitly specified.
544*0a6a1f1dSLionel Sambuc   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
545f4a2713aSLionel Sambuc     TLM = GetLLVMTLSModel(Attr->getModel());
546f4a2713aSLionel Sambuc   }
547f4a2713aSLionel Sambuc 
548f4a2713aSLionel Sambuc   GV->setThreadLocalMode(TLM);
549f4a2713aSLionel Sambuc }
550f4a2713aSLionel Sambuc 
getMangledName(GlobalDecl GD)551f4a2713aSLionel Sambuc StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
552*0a6a1f1dSLionel Sambuc   StringRef &FoundStr = MangledDeclNames[GD.getCanonicalDecl()];
553*0a6a1f1dSLionel Sambuc   if (!FoundStr.empty())
554*0a6a1f1dSLionel Sambuc     return FoundStr;
555f4a2713aSLionel Sambuc 
556*0a6a1f1dSLionel Sambuc   const auto *ND = cast<NamedDecl>(GD.getDecl());
557f4a2713aSLionel Sambuc   SmallString<256> Buffer;
558*0a6a1f1dSLionel Sambuc   StringRef Str;
559*0a6a1f1dSLionel Sambuc   if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
560f4a2713aSLionel Sambuc     llvm::raw_svector_ostream Out(Buffer);
561*0a6a1f1dSLionel Sambuc     if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
562f4a2713aSLionel Sambuc       getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
563*0a6a1f1dSLionel Sambuc     else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
564f4a2713aSLionel Sambuc       getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
565f4a2713aSLionel Sambuc     else
566f4a2713aSLionel Sambuc       getCXXABI().getMangleContext().mangleName(ND, Out);
567*0a6a1f1dSLionel Sambuc     Str = Out.str();
568*0a6a1f1dSLionel Sambuc   } else {
569*0a6a1f1dSLionel Sambuc     IdentifierInfo *II = ND->getIdentifier();
570*0a6a1f1dSLionel Sambuc     assert(II && "Attempt to mangle unnamed decl.");
571*0a6a1f1dSLionel Sambuc     Str = II->getName();
572f4a2713aSLionel Sambuc   }
573f4a2713aSLionel Sambuc 
574*0a6a1f1dSLionel Sambuc   // Keep the first result in the case of a mangling collision.
575*0a6a1f1dSLionel Sambuc   auto Result = Manglings.insert(std::make_pair(Str, GD));
576*0a6a1f1dSLionel Sambuc   return FoundStr = Result.first->first();
577*0a6a1f1dSLionel Sambuc }
578*0a6a1f1dSLionel Sambuc 
getBlockMangledName(GlobalDecl GD,const BlockDecl * BD)579*0a6a1f1dSLionel Sambuc StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
580f4a2713aSLionel Sambuc                                              const BlockDecl *BD) {
581f4a2713aSLionel Sambuc   MangleContext &MangleCtx = getCXXABI().getMangleContext();
582f4a2713aSLionel Sambuc   const Decl *D = GD.getDecl();
583*0a6a1f1dSLionel Sambuc 
584*0a6a1f1dSLionel Sambuc   SmallString<256> Buffer;
585*0a6a1f1dSLionel Sambuc   llvm::raw_svector_ostream Out(Buffer);
586*0a6a1f1dSLionel Sambuc   if (!D)
587f4a2713aSLionel Sambuc     MangleCtx.mangleGlobalBlock(BD,
588f4a2713aSLionel Sambuc       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
589*0a6a1f1dSLionel Sambuc   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
590f4a2713aSLionel Sambuc     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
591*0a6a1f1dSLionel Sambuc   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
592f4a2713aSLionel Sambuc     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
593f4a2713aSLionel Sambuc   else
594f4a2713aSLionel Sambuc     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
595*0a6a1f1dSLionel Sambuc 
596*0a6a1f1dSLionel Sambuc   auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
597*0a6a1f1dSLionel Sambuc   return Result.first->first();
598f4a2713aSLionel Sambuc }
599f4a2713aSLionel Sambuc 
GetGlobalValue(StringRef Name)600f4a2713aSLionel Sambuc llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
601f4a2713aSLionel Sambuc   return getModule().getNamedValue(Name);
602f4a2713aSLionel Sambuc }
603f4a2713aSLionel Sambuc 
604f4a2713aSLionel Sambuc /// AddGlobalCtor - Add a function to the list that will be called before
605f4a2713aSLionel Sambuc /// main() runs.
AddGlobalCtor(llvm::Function * Ctor,int Priority,llvm::Constant * AssociatedData)606*0a6a1f1dSLionel Sambuc void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
607*0a6a1f1dSLionel Sambuc                                   llvm::Constant *AssociatedData) {
608f4a2713aSLionel Sambuc   // FIXME: Type coercion of void()* types.
609*0a6a1f1dSLionel Sambuc   GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
610f4a2713aSLionel Sambuc }
611f4a2713aSLionel Sambuc 
612f4a2713aSLionel Sambuc /// AddGlobalDtor - Add a function to the list that will be called
613f4a2713aSLionel Sambuc /// when the module is unloaded.
AddGlobalDtor(llvm::Function * Dtor,int Priority)614f4a2713aSLionel Sambuc void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
615f4a2713aSLionel Sambuc   // FIXME: Type coercion of void()* types.
616*0a6a1f1dSLionel Sambuc   GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
617f4a2713aSLionel Sambuc }
618f4a2713aSLionel Sambuc 
EmitCtorList(const CtorList & Fns,const char * GlobalName)619f4a2713aSLionel Sambuc void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
620f4a2713aSLionel Sambuc   // Ctor function type is void()*.
621f4a2713aSLionel Sambuc   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
622f4a2713aSLionel Sambuc   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
623f4a2713aSLionel Sambuc 
624*0a6a1f1dSLionel Sambuc   // Get the type of a ctor entry, { i32, void ()*, i8* }.
625*0a6a1f1dSLionel Sambuc   llvm::StructType *CtorStructTy = llvm::StructType::get(
626*0a6a1f1dSLionel Sambuc       Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr);
627f4a2713aSLionel Sambuc 
628f4a2713aSLionel Sambuc   // Construct the constructor and destructor arrays.
629f4a2713aSLionel Sambuc   SmallVector<llvm::Constant*, 8> Ctors;
630f4a2713aSLionel Sambuc   for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
631f4a2713aSLionel Sambuc     llvm::Constant *S[] = {
632*0a6a1f1dSLionel Sambuc       llvm::ConstantInt::get(Int32Ty, I->Priority, false),
633*0a6a1f1dSLionel Sambuc       llvm::ConstantExpr::getBitCast(I->Initializer, CtorPFTy),
634*0a6a1f1dSLionel Sambuc       (I->AssociatedData
635*0a6a1f1dSLionel Sambuc            ? llvm::ConstantExpr::getBitCast(I->AssociatedData, VoidPtrTy)
636*0a6a1f1dSLionel Sambuc            : llvm::Constant::getNullValue(VoidPtrTy))
637f4a2713aSLionel Sambuc     };
638f4a2713aSLionel Sambuc     Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
639f4a2713aSLionel Sambuc   }
640f4a2713aSLionel Sambuc 
641f4a2713aSLionel Sambuc   if (!Ctors.empty()) {
642f4a2713aSLionel Sambuc     llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
643f4a2713aSLionel Sambuc     new llvm::GlobalVariable(TheModule, AT, false,
644f4a2713aSLionel Sambuc                              llvm::GlobalValue::AppendingLinkage,
645f4a2713aSLionel Sambuc                              llvm::ConstantArray::get(AT, Ctors),
646f4a2713aSLionel Sambuc                              GlobalName);
647f4a2713aSLionel Sambuc   }
648f4a2713aSLionel Sambuc }
649f4a2713aSLionel Sambuc 
650f4a2713aSLionel Sambuc llvm::GlobalValue::LinkageTypes
getFunctionLinkage(GlobalDecl GD)651f4a2713aSLionel Sambuc CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
652*0a6a1f1dSLionel Sambuc   const auto *D = cast<FunctionDecl>(GD.getDecl());
653f4a2713aSLionel Sambuc 
654f4a2713aSLionel Sambuc   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
655f4a2713aSLionel Sambuc 
656*0a6a1f1dSLionel Sambuc   if (isa<CXXDestructorDecl>(D) &&
657*0a6a1f1dSLionel Sambuc       getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
658*0a6a1f1dSLionel Sambuc                                          GD.getDtorType())) {
659*0a6a1f1dSLionel Sambuc     // Destructor variants in the Microsoft C++ ABI are always internal or
660*0a6a1f1dSLionel Sambuc     // linkonce_odr thunks emitted on an as-needed basis.
661*0a6a1f1dSLionel Sambuc     return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
662*0a6a1f1dSLionel Sambuc                                    : llvm::GlobalValue::LinkOnceODRLinkage;
663f4a2713aSLionel Sambuc   }
664f4a2713aSLionel Sambuc 
665*0a6a1f1dSLionel Sambuc   return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
666*0a6a1f1dSLionel Sambuc }
667f4a2713aSLionel Sambuc 
setFunctionDefinitionAttributes(const FunctionDecl * D,llvm::Function * F)668*0a6a1f1dSLionel Sambuc void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
669*0a6a1f1dSLionel Sambuc                                                     llvm::Function *F) {
670*0a6a1f1dSLionel Sambuc   setNonAliasAttributes(D, F);
671f4a2713aSLionel Sambuc }
672f4a2713aSLionel Sambuc 
SetLLVMFunctionAttributes(const Decl * D,const CGFunctionInfo & Info,llvm::Function * F)673f4a2713aSLionel Sambuc void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
674f4a2713aSLionel Sambuc                                               const CGFunctionInfo &Info,
675f4a2713aSLionel Sambuc                                               llvm::Function *F) {
676f4a2713aSLionel Sambuc   unsigned CallingConv;
677f4a2713aSLionel Sambuc   AttributeListType AttributeList;
678f4a2713aSLionel Sambuc   ConstructAttributeList(Info, D, AttributeList, CallingConv, false);
679f4a2713aSLionel Sambuc   F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
680f4a2713aSLionel Sambuc   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
681f4a2713aSLionel Sambuc }
682f4a2713aSLionel Sambuc 
683f4a2713aSLionel Sambuc /// Determines whether the language options require us to model
684f4a2713aSLionel Sambuc /// unwind exceptions.  We treat -fexceptions as mandating this
685f4a2713aSLionel Sambuc /// except under the fragile ObjC ABI with only ObjC exceptions
686f4a2713aSLionel Sambuc /// enabled.  This means, for example, that C with -fexceptions
687f4a2713aSLionel Sambuc /// enables this.
hasUnwindExceptions(const LangOptions & LangOpts)688f4a2713aSLionel Sambuc static bool hasUnwindExceptions(const LangOptions &LangOpts) {
689f4a2713aSLionel Sambuc   // If exceptions are completely disabled, obviously this is false.
690f4a2713aSLionel Sambuc   if (!LangOpts.Exceptions) return false;
691f4a2713aSLionel Sambuc 
692f4a2713aSLionel Sambuc   // If C++ exceptions are enabled, this is true.
693f4a2713aSLionel Sambuc   if (LangOpts.CXXExceptions) return true;
694f4a2713aSLionel Sambuc 
695f4a2713aSLionel Sambuc   // If ObjC exceptions are enabled, this depends on the ABI.
696f4a2713aSLionel Sambuc   if (LangOpts.ObjCExceptions) {
697f4a2713aSLionel Sambuc     return LangOpts.ObjCRuntime.hasUnwindExceptions();
698f4a2713aSLionel Sambuc   }
699f4a2713aSLionel Sambuc 
700f4a2713aSLionel Sambuc   return true;
701f4a2713aSLionel Sambuc }
702f4a2713aSLionel Sambuc 
SetLLVMFunctionAttributesForDefinition(const Decl * D,llvm::Function * F)703f4a2713aSLionel Sambuc void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
704f4a2713aSLionel Sambuc                                                            llvm::Function *F) {
705f4a2713aSLionel Sambuc   llvm::AttrBuilder B;
706f4a2713aSLionel Sambuc 
707f4a2713aSLionel Sambuc   if (CodeGenOpts.UnwindTables)
708f4a2713aSLionel Sambuc     B.addAttribute(llvm::Attribute::UWTable);
709f4a2713aSLionel Sambuc 
710f4a2713aSLionel Sambuc   if (!hasUnwindExceptions(LangOpts))
711f4a2713aSLionel Sambuc     B.addAttribute(llvm::Attribute::NoUnwind);
712f4a2713aSLionel Sambuc 
713f4a2713aSLionel Sambuc   if (D->hasAttr<NakedAttr>()) {
714f4a2713aSLionel Sambuc     // Naked implies noinline: we should not be inlining such functions.
715f4a2713aSLionel Sambuc     B.addAttribute(llvm::Attribute::Naked);
716f4a2713aSLionel Sambuc     B.addAttribute(llvm::Attribute::NoInline);
717*0a6a1f1dSLionel Sambuc   } else if (D->hasAttr<NoDuplicateAttr>()) {
718*0a6a1f1dSLionel Sambuc     B.addAttribute(llvm::Attribute::NoDuplicate);
719f4a2713aSLionel Sambuc   } else if (D->hasAttr<NoInlineAttr>()) {
720f4a2713aSLionel Sambuc     B.addAttribute(llvm::Attribute::NoInline);
721*0a6a1f1dSLionel Sambuc   } else if (D->hasAttr<AlwaysInlineAttr>() &&
722f4a2713aSLionel Sambuc              !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
723f4a2713aSLionel Sambuc                                               llvm::Attribute::NoInline)) {
724f4a2713aSLionel Sambuc     // (noinline wins over always_inline, and we can't specify both in IR)
725f4a2713aSLionel Sambuc     B.addAttribute(llvm::Attribute::AlwaysInline);
726f4a2713aSLionel Sambuc   }
727f4a2713aSLionel Sambuc 
728f4a2713aSLionel Sambuc   if (D->hasAttr<ColdAttr>()) {
729*0a6a1f1dSLionel Sambuc     if (!D->hasAttr<OptimizeNoneAttr>())
730f4a2713aSLionel Sambuc       B.addAttribute(llvm::Attribute::OptimizeForSize);
731f4a2713aSLionel Sambuc     B.addAttribute(llvm::Attribute::Cold);
732f4a2713aSLionel Sambuc   }
733f4a2713aSLionel Sambuc 
734f4a2713aSLionel Sambuc   if (D->hasAttr<MinSizeAttr>())
735f4a2713aSLionel Sambuc     B.addAttribute(llvm::Attribute::MinSize);
736f4a2713aSLionel Sambuc 
737f4a2713aSLionel Sambuc   if (LangOpts.getStackProtector() == LangOptions::SSPOn)
738f4a2713aSLionel Sambuc     B.addAttribute(llvm::Attribute::StackProtect);
739*0a6a1f1dSLionel Sambuc   else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
740*0a6a1f1dSLionel Sambuc     B.addAttribute(llvm::Attribute::StackProtectStrong);
741f4a2713aSLionel Sambuc   else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
742f4a2713aSLionel Sambuc     B.addAttribute(llvm::Attribute::StackProtectReq);
743f4a2713aSLionel Sambuc 
744f4a2713aSLionel Sambuc   // Add sanitizer attributes if function is not blacklisted.
745*0a6a1f1dSLionel Sambuc   if (!isInSanitizerBlacklist(F, D->getLocation())) {
746f4a2713aSLionel Sambuc     // When AddressSanitizer is enabled, set SanitizeAddress attribute
747f4a2713aSLionel Sambuc     // unless __attribute__((no_sanitize_address)) is used.
748*0a6a1f1dSLionel Sambuc     if (LangOpts.Sanitize.has(SanitizerKind::Address) &&
749*0a6a1f1dSLionel Sambuc         !D->hasAttr<NoSanitizeAddressAttr>())
750f4a2713aSLionel Sambuc       B.addAttribute(llvm::Attribute::SanitizeAddress);
751f4a2713aSLionel Sambuc     // Same for ThreadSanitizer and __attribute__((no_sanitize_thread))
752*0a6a1f1dSLionel Sambuc     if (LangOpts.Sanitize.has(SanitizerKind::Thread) &&
753*0a6a1f1dSLionel Sambuc         !D->hasAttr<NoSanitizeThreadAttr>())
754f4a2713aSLionel Sambuc       B.addAttribute(llvm::Attribute::SanitizeThread);
755f4a2713aSLionel Sambuc     // Same for MemorySanitizer and __attribute__((no_sanitize_memory))
756*0a6a1f1dSLionel Sambuc     if (LangOpts.Sanitize.has(SanitizerKind::Memory) &&
757*0a6a1f1dSLionel Sambuc         !D->hasAttr<NoSanitizeMemoryAttr>())
758f4a2713aSLionel Sambuc       B.addAttribute(llvm::Attribute::SanitizeMemory);
759f4a2713aSLionel Sambuc   }
760f4a2713aSLionel Sambuc 
761f4a2713aSLionel Sambuc   F->addAttributes(llvm::AttributeSet::FunctionIndex,
762f4a2713aSLionel Sambuc                    llvm::AttributeSet::get(
763f4a2713aSLionel Sambuc                        F->getContext(), llvm::AttributeSet::FunctionIndex, B));
764f4a2713aSLionel Sambuc 
765*0a6a1f1dSLionel Sambuc   if (D->hasAttr<OptimizeNoneAttr>()) {
766*0a6a1f1dSLionel Sambuc     // OptimizeNone implies noinline; we should not be inlining such functions.
767*0a6a1f1dSLionel Sambuc     F->addFnAttr(llvm::Attribute::OptimizeNone);
768*0a6a1f1dSLionel Sambuc     F->addFnAttr(llvm::Attribute::NoInline);
769*0a6a1f1dSLionel Sambuc 
770*0a6a1f1dSLionel Sambuc     // OptimizeNone wins over OptimizeForSize, MinSize, AlwaysInline.
771*0a6a1f1dSLionel Sambuc     assert(!F->hasFnAttribute(llvm::Attribute::OptimizeForSize) &&
772*0a6a1f1dSLionel Sambuc            "OptimizeNone and OptimizeForSize on same function!");
773*0a6a1f1dSLionel Sambuc     assert(!F->hasFnAttribute(llvm::Attribute::MinSize) &&
774*0a6a1f1dSLionel Sambuc            "OptimizeNone and MinSize on same function!");
775*0a6a1f1dSLionel Sambuc     assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
776*0a6a1f1dSLionel Sambuc            "OptimizeNone and AlwaysInline on same function!");
777*0a6a1f1dSLionel Sambuc 
778*0a6a1f1dSLionel Sambuc     // Attribute 'inlinehint' has no effect on 'optnone' functions.
779*0a6a1f1dSLionel Sambuc     // Explicitly remove it from the set of function attributes.
780*0a6a1f1dSLionel Sambuc     F->removeFnAttr(llvm::Attribute::InlineHint);
781*0a6a1f1dSLionel Sambuc   }
782*0a6a1f1dSLionel Sambuc 
783f4a2713aSLionel Sambuc   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
784f4a2713aSLionel Sambuc     F->setUnnamedAddr(true);
785*0a6a1f1dSLionel Sambuc   else if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
786f4a2713aSLionel Sambuc     if (MD->isVirtual())
787f4a2713aSLionel Sambuc       F->setUnnamedAddr(true);
788f4a2713aSLionel Sambuc 
789f4a2713aSLionel Sambuc   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
790f4a2713aSLionel Sambuc   if (alignment)
791f4a2713aSLionel Sambuc     F->setAlignment(alignment);
792f4a2713aSLionel Sambuc 
793f4a2713aSLionel Sambuc   // C++ ABI requires 2-byte alignment for member functions.
794f4a2713aSLionel Sambuc   if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
795f4a2713aSLionel Sambuc     F->setAlignment(2);
796f4a2713aSLionel Sambuc }
797f4a2713aSLionel Sambuc 
SetCommonAttributes(const Decl * D,llvm::GlobalValue * GV)798f4a2713aSLionel Sambuc void CodeGenModule::SetCommonAttributes(const Decl *D,
799f4a2713aSLionel Sambuc                                         llvm::GlobalValue *GV) {
800*0a6a1f1dSLionel Sambuc   if (const auto *ND = dyn_cast<NamedDecl>(D))
801f4a2713aSLionel Sambuc     setGlobalVisibility(GV, ND);
802f4a2713aSLionel Sambuc   else
803f4a2713aSLionel Sambuc     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
804f4a2713aSLionel Sambuc 
805f4a2713aSLionel Sambuc   if (D->hasAttr<UsedAttr>())
806*0a6a1f1dSLionel Sambuc     addUsedGlobal(GV);
807*0a6a1f1dSLionel Sambuc }
808*0a6a1f1dSLionel Sambuc 
setAliasAttributes(const Decl * D,llvm::GlobalValue * GV)809*0a6a1f1dSLionel Sambuc void CodeGenModule::setAliasAttributes(const Decl *D,
810*0a6a1f1dSLionel Sambuc                                        llvm::GlobalValue *GV) {
811*0a6a1f1dSLionel Sambuc   SetCommonAttributes(D, GV);
812*0a6a1f1dSLionel Sambuc 
813*0a6a1f1dSLionel Sambuc   // Process the dllexport attribute based on whether the original definition
814*0a6a1f1dSLionel Sambuc   // (not necessarily the aliasee) was exported.
815*0a6a1f1dSLionel Sambuc   if (D->hasAttr<DLLExportAttr>())
816*0a6a1f1dSLionel Sambuc     GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
817*0a6a1f1dSLionel Sambuc }
818*0a6a1f1dSLionel Sambuc 
setNonAliasAttributes(const Decl * D,llvm::GlobalObject * GO)819*0a6a1f1dSLionel Sambuc void CodeGenModule::setNonAliasAttributes(const Decl *D,
820*0a6a1f1dSLionel Sambuc                                           llvm::GlobalObject *GO) {
821*0a6a1f1dSLionel Sambuc   SetCommonAttributes(D, GO);
822f4a2713aSLionel Sambuc 
823f4a2713aSLionel Sambuc   if (const SectionAttr *SA = D->getAttr<SectionAttr>())
824*0a6a1f1dSLionel Sambuc     GO->setSection(SA->getName());
825f4a2713aSLionel Sambuc 
826*0a6a1f1dSLionel Sambuc   getTargetCodeGenInfo().SetTargetAttributes(D, GO, *this);
827f4a2713aSLionel Sambuc }
828f4a2713aSLionel Sambuc 
SetInternalFunctionAttributes(const Decl * D,llvm::Function * F,const CGFunctionInfo & FI)829f4a2713aSLionel Sambuc void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
830f4a2713aSLionel Sambuc                                                   llvm::Function *F,
831f4a2713aSLionel Sambuc                                                   const CGFunctionInfo &FI) {
832f4a2713aSLionel Sambuc   SetLLVMFunctionAttributes(D, FI, F);
833f4a2713aSLionel Sambuc   SetLLVMFunctionAttributesForDefinition(D, F);
834f4a2713aSLionel Sambuc 
835f4a2713aSLionel Sambuc   F->setLinkage(llvm::Function::InternalLinkage);
836f4a2713aSLionel Sambuc 
837*0a6a1f1dSLionel Sambuc   setNonAliasAttributes(D, F);
838f4a2713aSLionel Sambuc }
839f4a2713aSLionel Sambuc 
setLinkageAndVisibilityForGV(llvm::GlobalValue * GV,const NamedDecl * ND)840*0a6a1f1dSLionel Sambuc static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
841*0a6a1f1dSLionel Sambuc                                          const NamedDecl *ND) {
842*0a6a1f1dSLionel Sambuc   // Set linkage and visibility in case we never see a definition.
843*0a6a1f1dSLionel Sambuc   LinkageInfo LV = ND->getLinkageAndVisibility();
844*0a6a1f1dSLionel Sambuc   if (LV.getLinkage() != ExternalLinkage) {
845*0a6a1f1dSLionel Sambuc     // Don't set internal linkage on declarations.
846*0a6a1f1dSLionel Sambuc   } else {
847*0a6a1f1dSLionel Sambuc     if (ND->hasAttr<DLLImportAttr>()) {
848*0a6a1f1dSLionel Sambuc       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
849*0a6a1f1dSLionel Sambuc       GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
850*0a6a1f1dSLionel Sambuc     } else if (ND->hasAttr<DLLExportAttr>()) {
851*0a6a1f1dSLionel Sambuc       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
852*0a6a1f1dSLionel Sambuc       GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
853*0a6a1f1dSLionel Sambuc     } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
854*0a6a1f1dSLionel Sambuc       // "extern_weak" is overloaded in LLVM; we probably should have
855*0a6a1f1dSLionel Sambuc       // separate linkage types for this.
856*0a6a1f1dSLionel Sambuc       GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
857*0a6a1f1dSLionel Sambuc     }
858*0a6a1f1dSLionel Sambuc 
859*0a6a1f1dSLionel Sambuc     // Set visibility on a declaration only if it's explicit.
860*0a6a1f1dSLionel Sambuc     if (LV.isVisibilityExplicit())
861*0a6a1f1dSLionel Sambuc       GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
862*0a6a1f1dSLionel Sambuc   }
863*0a6a1f1dSLionel Sambuc }
864*0a6a1f1dSLionel Sambuc 
SetFunctionAttributes(GlobalDecl GD,llvm::Function * F,bool IsIncompleteFunction,bool IsThunk)865*0a6a1f1dSLionel Sambuc void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
866*0a6a1f1dSLionel Sambuc                                           bool IsIncompleteFunction,
867*0a6a1f1dSLionel Sambuc                                           bool IsThunk) {
868f4a2713aSLionel Sambuc   if (unsigned IID = F->getIntrinsicID()) {
869f4a2713aSLionel Sambuc     // If this is an intrinsic function, set the function's attributes
870f4a2713aSLionel Sambuc     // to the intrinsic's attributes.
871f4a2713aSLionel Sambuc     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(),
872f4a2713aSLionel Sambuc                                                     (llvm::Intrinsic::ID)IID));
873f4a2713aSLionel Sambuc     return;
874f4a2713aSLionel Sambuc   }
875f4a2713aSLionel Sambuc 
876*0a6a1f1dSLionel Sambuc   const auto *FD = cast<FunctionDecl>(GD.getDecl());
877f4a2713aSLionel Sambuc 
878f4a2713aSLionel Sambuc   if (!IsIncompleteFunction)
879f4a2713aSLionel Sambuc     SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
880f4a2713aSLionel Sambuc 
881*0a6a1f1dSLionel Sambuc   // Add the Returned attribute for "this", except for iOS 5 and earlier
882*0a6a1f1dSLionel Sambuc   // where substantial code, including the libstdc++ dylib, was compiled with
883*0a6a1f1dSLionel Sambuc   // GCC and does not actually return "this".
884*0a6a1f1dSLionel Sambuc   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
885*0a6a1f1dSLionel Sambuc       !(getTarget().getTriple().isiOS() &&
886*0a6a1f1dSLionel Sambuc         getTarget().getTriple().isOSVersionLT(6))) {
887f4a2713aSLionel Sambuc     assert(!F->arg_empty() &&
888f4a2713aSLionel Sambuc            F->arg_begin()->getType()
889f4a2713aSLionel Sambuc              ->canLosslesslyBitCastTo(F->getReturnType()) &&
890f4a2713aSLionel Sambuc            "unexpected this return");
891f4a2713aSLionel Sambuc     F->addAttribute(1, llvm::Attribute::Returned);
892f4a2713aSLionel Sambuc   }
893f4a2713aSLionel Sambuc 
894f4a2713aSLionel Sambuc   // Only a few attributes are set on declarations; these may later be
895f4a2713aSLionel Sambuc   // overridden by a definition.
896f4a2713aSLionel Sambuc 
897*0a6a1f1dSLionel Sambuc   setLinkageAndVisibilityForGV(F, FD);
898f4a2713aSLionel Sambuc 
899*0a6a1f1dSLionel Sambuc   if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
900*0a6a1f1dSLionel Sambuc     if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
901*0a6a1f1dSLionel Sambuc       // Don't dllexport/import destructor thunks.
902*0a6a1f1dSLionel Sambuc       F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
903f4a2713aSLionel Sambuc     }
904f4a2713aSLionel Sambuc   }
905f4a2713aSLionel Sambuc 
906f4a2713aSLionel Sambuc   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
907f4a2713aSLionel Sambuc     F->setSection(SA->getName());
908f4a2713aSLionel Sambuc 
909f4a2713aSLionel Sambuc   // A replaceable global allocation function does not act like a builtin by
910f4a2713aSLionel Sambuc   // default, only if it is invoked by a new-expression or delete-expression.
911f4a2713aSLionel Sambuc   if (FD->isReplaceableGlobalAllocationFunction())
912f4a2713aSLionel Sambuc     F->addAttribute(llvm::AttributeSet::FunctionIndex,
913f4a2713aSLionel Sambuc                     llvm::Attribute::NoBuiltin);
914f4a2713aSLionel Sambuc }
915f4a2713aSLionel Sambuc 
addUsedGlobal(llvm::GlobalValue * GV)916*0a6a1f1dSLionel Sambuc void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
917f4a2713aSLionel Sambuc   assert(!GV->isDeclaration() &&
918f4a2713aSLionel Sambuc          "Only globals with definition can force usage.");
919f4a2713aSLionel Sambuc   LLVMUsed.push_back(GV);
920f4a2713aSLionel Sambuc }
921f4a2713aSLionel Sambuc 
addCompilerUsedGlobal(llvm::GlobalValue * GV)922*0a6a1f1dSLionel Sambuc void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
923*0a6a1f1dSLionel Sambuc   assert(!GV->isDeclaration() &&
924*0a6a1f1dSLionel Sambuc          "Only globals with definition can force usage.");
925*0a6a1f1dSLionel Sambuc   LLVMCompilerUsed.push_back(GV);
926*0a6a1f1dSLionel Sambuc }
927*0a6a1f1dSLionel Sambuc 
emitUsed(CodeGenModule & CGM,StringRef Name,std::vector<llvm::WeakVH> & List)928*0a6a1f1dSLionel Sambuc static void emitUsed(CodeGenModule &CGM, StringRef Name,
929*0a6a1f1dSLionel Sambuc                      std::vector<llvm::WeakVH> &List) {
930f4a2713aSLionel Sambuc   // Don't create llvm.used if there is no need.
931*0a6a1f1dSLionel Sambuc   if (List.empty())
932f4a2713aSLionel Sambuc     return;
933f4a2713aSLionel Sambuc 
934*0a6a1f1dSLionel Sambuc   // Convert List to what ConstantArray needs.
935f4a2713aSLionel Sambuc   SmallVector<llvm::Constant*, 8> UsedArray;
936*0a6a1f1dSLionel Sambuc   UsedArray.resize(List.size());
937*0a6a1f1dSLionel Sambuc   for (unsigned i = 0, e = List.size(); i != e; ++i) {
938f4a2713aSLionel Sambuc     UsedArray[i] =
939*0a6a1f1dSLionel Sambuc         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
940*0a6a1f1dSLionel Sambuc             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
941f4a2713aSLionel Sambuc   }
942f4a2713aSLionel Sambuc 
943f4a2713aSLionel Sambuc   if (UsedArray.empty())
944f4a2713aSLionel Sambuc     return;
945*0a6a1f1dSLionel Sambuc   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
946f4a2713aSLionel Sambuc 
947*0a6a1f1dSLionel Sambuc   auto *GV = new llvm::GlobalVariable(
948*0a6a1f1dSLionel Sambuc       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
949*0a6a1f1dSLionel Sambuc       llvm::ConstantArray::get(ATy, UsedArray), Name);
950f4a2713aSLionel Sambuc 
951f4a2713aSLionel Sambuc   GV->setSection("llvm.metadata");
952f4a2713aSLionel Sambuc }
953f4a2713aSLionel Sambuc 
emitLLVMUsed()954*0a6a1f1dSLionel Sambuc void CodeGenModule::emitLLVMUsed() {
955*0a6a1f1dSLionel Sambuc   emitUsed(*this, "llvm.used", LLVMUsed);
956*0a6a1f1dSLionel Sambuc   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
957*0a6a1f1dSLionel Sambuc }
958*0a6a1f1dSLionel Sambuc 
AppendLinkerOptions(StringRef Opts)959f4a2713aSLionel Sambuc void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
960*0a6a1f1dSLionel Sambuc   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
961f4a2713aSLionel Sambuc   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
962f4a2713aSLionel Sambuc }
963f4a2713aSLionel Sambuc 
AddDetectMismatch(StringRef Name,StringRef Value)964f4a2713aSLionel Sambuc void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
965f4a2713aSLionel Sambuc   llvm::SmallString<32> Opt;
966f4a2713aSLionel Sambuc   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
967*0a6a1f1dSLionel Sambuc   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
968f4a2713aSLionel Sambuc   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
969f4a2713aSLionel Sambuc }
970f4a2713aSLionel Sambuc 
AddDependentLib(StringRef Lib)971f4a2713aSLionel Sambuc void CodeGenModule::AddDependentLib(StringRef Lib) {
972f4a2713aSLionel Sambuc   llvm::SmallString<24> Opt;
973f4a2713aSLionel Sambuc   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
974*0a6a1f1dSLionel Sambuc   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
975f4a2713aSLionel Sambuc   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
976f4a2713aSLionel Sambuc }
977f4a2713aSLionel Sambuc 
978f4a2713aSLionel Sambuc /// \brief Add link options implied by the given module, including modules
979f4a2713aSLionel Sambuc /// it depends on, using a postorder walk.
addLinkOptionsPostorder(CodeGenModule & CGM,Module * Mod,SmallVectorImpl<llvm::Metadata * > & Metadata,llvm::SmallPtrSet<Module *,16> & Visited)980*0a6a1f1dSLionel Sambuc static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
981*0a6a1f1dSLionel Sambuc                                     SmallVectorImpl<llvm::Metadata *> &Metadata,
982f4a2713aSLionel Sambuc                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
983f4a2713aSLionel Sambuc   // Import this module's parent.
984*0a6a1f1dSLionel Sambuc   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
985f4a2713aSLionel Sambuc     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
986f4a2713aSLionel Sambuc   }
987f4a2713aSLionel Sambuc 
988f4a2713aSLionel Sambuc   // Import this module's dependencies.
989f4a2713aSLionel Sambuc   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
990*0a6a1f1dSLionel Sambuc     if (Visited.insert(Mod->Imports[I - 1]).second)
991f4a2713aSLionel Sambuc       addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
992f4a2713aSLionel Sambuc   }
993f4a2713aSLionel Sambuc 
994f4a2713aSLionel Sambuc   // Add linker options to link against the libraries/frameworks
995f4a2713aSLionel Sambuc   // described by this module.
996f4a2713aSLionel Sambuc   llvm::LLVMContext &Context = CGM.getLLVMContext();
997f4a2713aSLionel Sambuc   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
998f4a2713aSLionel Sambuc     // Link against a framework.  Frameworks are currently Darwin only, so we
999f4a2713aSLionel Sambuc     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
1000f4a2713aSLionel Sambuc     if (Mod->LinkLibraries[I-1].IsFramework) {
1001*0a6a1f1dSLionel Sambuc       llvm::Metadata *Args[2] = {
1002f4a2713aSLionel Sambuc           llvm::MDString::get(Context, "-framework"),
1003*0a6a1f1dSLionel Sambuc           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1004f4a2713aSLionel Sambuc 
1005f4a2713aSLionel Sambuc       Metadata.push_back(llvm::MDNode::get(Context, Args));
1006f4a2713aSLionel Sambuc       continue;
1007f4a2713aSLionel Sambuc     }
1008f4a2713aSLionel Sambuc 
1009f4a2713aSLionel Sambuc     // Link against a library.
1010f4a2713aSLionel Sambuc     llvm::SmallString<24> Opt;
1011f4a2713aSLionel Sambuc     CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1012f4a2713aSLionel Sambuc       Mod->LinkLibraries[I-1].Library, Opt);
1013*0a6a1f1dSLionel Sambuc     auto *OptString = llvm::MDString::get(Context, Opt);
1014f4a2713aSLionel Sambuc     Metadata.push_back(llvm::MDNode::get(Context, OptString));
1015f4a2713aSLionel Sambuc   }
1016f4a2713aSLionel Sambuc }
1017f4a2713aSLionel Sambuc 
EmitModuleLinkOptions()1018f4a2713aSLionel Sambuc void CodeGenModule::EmitModuleLinkOptions() {
1019f4a2713aSLionel Sambuc   // Collect the set of all of the modules we want to visit to emit link
1020f4a2713aSLionel Sambuc   // options, which is essentially the imported modules and all of their
1021f4a2713aSLionel Sambuc   // non-explicit child modules.
1022f4a2713aSLionel Sambuc   llvm::SetVector<clang::Module *> LinkModules;
1023f4a2713aSLionel Sambuc   llvm::SmallPtrSet<clang::Module *, 16> Visited;
1024f4a2713aSLionel Sambuc   SmallVector<clang::Module *, 16> Stack;
1025f4a2713aSLionel Sambuc 
1026f4a2713aSLionel Sambuc   // Seed the stack with imported modules.
1027f4a2713aSLionel Sambuc   for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(),
1028f4a2713aSLionel Sambuc                                                MEnd = ImportedModules.end();
1029f4a2713aSLionel Sambuc        M != MEnd; ++M) {
1030*0a6a1f1dSLionel Sambuc     if (Visited.insert(*M).second)
1031f4a2713aSLionel Sambuc       Stack.push_back(*M);
1032f4a2713aSLionel Sambuc   }
1033f4a2713aSLionel Sambuc 
1034f4a2713aSLionel Sambuc   // Find all of the modules to import, making a little effort to prune
1035f4a2713aSLionel Sambuc   // non-leaf modules.
1036f4a2713aSLionel Sambuc   while (!Stack.empty()) {
1037f4a2713aSLionel Sambuc     clang::Module *Mod = Stack.pop_back_val();
1038f4a2713aSLionel Sambuc 
1039f4a2713aSLionel Sambuc     bool AnyChildren = false;
1040f4a2713aSLionel Sambuc 
1041f4a2713aSLionel Sambuc     // Visit the submodules of this module.
1042f4a2713aSLionel Sambuc     for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1043f4a2713aSLionel Sambuc                                         SubEnd = Mod->submodule_end();
1044f4a2713aSLionel Sambuc          Sub != SubEnd; ++Sub) {
1045f4a2713aSLionel Sambuc       // Skip explicit children; they need to be explicitly imported to be
1046f4a2713aSLionel Sambuc       // linked against.
1047f4a2713aSLionel Sambuc       if ((*Sub)->IsExplicit)
1048f4a2713aSLionel Sambuc         continue;
1049f4a2713aSLionel Sambuc 
1050*0a6a1f1dSLionel Sambuc       if (Visited.insert(*Sub).second) {
1051f4a2713aSLionel Sambuc         Stack.push_back(*Sub);
1052f4a2713aSLionel Sambuc         AnyChildren = true;
1053f4a2713aSLionel Sambuc       }
1054f4a2713aSLionel Sambuc     }
1055f4a2713aSLionel Sambuc 
1056f4a2713aSLionel Sambuc     // We didn't find any children, so add this module to the list of
1057f4a2713aSLionel Sambuc     // modules to link against.
1058f4a2713aSLionel Sambuc     if (!AnyChildren) {
1059f4a2713aSLionel Sambuc       LinkModules.insert(Mod);
1060f4a2713aSLionel Sambuc     }
1061f4a2713aSLionel Sambuc   }
1062f4a2713aSLionel Sambuc 
1063f4a2713aSLionel Sambuc   // Add link options for all of the imported modules in reverse topological
1064f4a2713aSLionel Sambuc   // order.  We don't do anything to try to order import link flags with respect
1065f4a2713aSLionel Sambuc   // to linker options inserted by things like #pragma comment().
1066*0a6a1f1dSLionel Sambuc   SmallVector<llvm::Metadata *, 16> MetadataArgs;
1067f4a2713aSLionel Sambuc   Visited.clear();
1068f4a2713aSLionel Sambuc   for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(),
1069f4a2713aSLionel Sambuc                                                MEnd = LinkModules.end();
1070f4a2713aSLionel Sambuc        M != MEnd; ++M) {
1071*0a6a1f1dSLionel Sambuc     if (Visited.insert(*M).second)
1072f4a2713aSLionel Sambuc       addLinkOptionsPostorder(*this, *M, MetadataArgs, Visited);
1073f4a2713aSLionel Sambuc   }
1074f4a2713aSLionel Sambuc   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1075f4a2713aSLionel Sambuc   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1076f4a2713aSLionel Sambuc 
1077f4a2713aSLionel Sambuc   // Add the linker options metadata flag.
1078f4a2713aSLionel Sambuc   getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
1079f4a2713aSLionel Sambuc                             llvm::MDNode::get(getLLVMContext(),
1080f4a2713aSLionel Sambuc                                               LinkerOptionsMetadata));
1081f4a2713aSLionel Sambuc }
1082f4a2713aSLionel Sambuc 
EmitDeferred()1083f4a2713aSLionel Sambuc void CodeGenModule::EmitDeferred() {
1084f4a2713aSLionel Sambuc   // Emit code for any potentially referenced deferred decls.  Since a
1085f4a2713aSLionel Sambuc   // previously unused static decl may become used during the generation of code
1086f4a2713aSLionel Sambuc   // for a static function, iterate until no changes are made.
1087f4a2713aSLionel Sambuc 
1088f4a2713aSLionel Sambuc   while (true) {
1089f4a2713aSLionel Sambuc     if (!DeferredVTables.empty()) {
1090f4a2713aSLionel Sambuc       EmitDeferredVTables();
1091f4a2713aSLionel Sambuc 
1092f4a2713aSLionel Sambuc       // Emitting a v-table doesn't directly cause more v-tables to
1093f4a2713aSLionel Sambuc       // become deferred, although it can cause functions to be
1094f4a2713aSLionel Sambuc       // emitted that then need those v-tables.
1095f4a2713aSLionel Sambuc       assert(DeferredVTables.empty());
1096f4a2713aSLionel Sambuc     }
1097f4a2713aSLionel Sambuc 
1098f4a2713aSLionel Sambuc     // Stop if we're out of both deferred v-tables and deferred declarations.
1099f4a2713aSLionel Sambuc     if (DeferredDeclsToEmit.empty()) break;
1100f4a2713aSLionel Sambuc 
1101*0a6a1f1dSLionel Sambuc     DeferredGlobal &G = DeferredDeclsToEmit.back();
1102*0a6a1f1dSLionel Sambuc     GlobalDecl D = G.GD;
1103*0a6a1f1dSLionel Sambuc     llvm::GlobalValue *GV = G.GV;
1104f4a2713aSLionel Sambuc     DeferredDeclsToEmit.pop_back();
1105f4a2713aSLionel Sambuc 
1106*0a6a1f1dSLionel Sambuc     assert(!GV || GV == GetGlobalValue(getMangledName(D)));
1107*0a6a1f1dSLionel Sambuc     if (!GV)
1108*0a6a1f1dSLionel Sambuc       GV = GetGlobalValue(getMangledName(D));
1109*0a6a1f1dSLionel Sambuc 
1110*0a6a1f1dSLionel Sambuc 
1111f4a2713aSLionel Sambuc     // Check to see if we've already emitted this.  This is necessary
1112f4a2713aSLionel Sambuc     // for a couple of reasons: first, decls can end up in the
1113f4a2713aSLionel Sambuc     // deferred-decls queue multiple times, and second, decls can end
1114f4a2713aSLionel Sambuc     // up with definitions in unusual ways (e.g. by an extern inline
1115f4a2713aSLionel Sambuc     // function acquiring a strong function redefinition).  Just
1116f4a2713aSLionel Sambuc     // ignore these cases.
1117*0a6a1f1dSLionel Sambuc     if (GV && !GV->isDeclaration())
1118f4a2713aSLionel Sambuc       continue;
1119f4a2713aSLionel Sambuc 
1120f4a2713aSLionel Sambuc     // Otherwise, emit the definition and move on to the next one.
1121*0a6a1f1dSLionel Sambuc     EmitGlobalDefinition(D, GV);
1122f4a2713aSLionel Sambuc   }
1123f4a2713aSLionel Sambuc }
1124f4a2713aSLionel Sambuc 
EmitGlobalAnnotations()1125f4a2713aSLionel Sambuc void CodeGenModule::EmitGlobalAnnotations() {
1126f4a2713aSLionel Sambuc   if (Annotations.empty())
1127f4a2713aSLionel Sambuc     return;
1128f4a2713aSLionel Sambuc 
1129f4a2713aSLionel Sambuc   // Create a new global variable for the ConstantStruct in the Module.
1130f4a2713aSLionel Sambuc   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1131f4a2713aSLionel Sambuc     Annotations[0]->getType(), Annotations.size()), Annotations);
1132*0a6a1f1dSLionel Sambuc   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1133*0a6a1f1dSLionel Sambuc                                       llvm::GlobalValue::AppendingLinkage,
1134*0a6a1f1dSLionel Sambuc                                       Array, "llvm.global.annotations");
1135f4a2713aSLionel Sambuc   gv->setSection(AnnotationSection);
1136f4a2713aSLionel Sambuc }
1137f4a2713aSLionel Sambuc 
EmitAnnotationString(StringRef Str)1138f4a2713aSLionel Sambuc llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1139f4a2713aSLionel Sambuc   llvm::Constant *&AStr = AnnotationStrings[Str];
1140f4a2713aSLionel Sambuc   if (AStr)
1141f4a2713aSLionel Sambuc     return AStr;
1142f4a2713aSLionel Sambuc 
1143f4a2713aSLionel Sambuc   // Not found yet, create a new global.
1144f4a2713aSLionel Sambuc   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
1145*0a6a1f1dSLionel Sambuc   auto *gv =
1146*0a6a1f1dSLionel Sambuc       new llvm::GlobalVariable(getModule(), s->getType(), true,
1147*0a6a1f1dSLionel Sambuc                                llvm::GlobalValue::PrivateLinkage, s, ".str");
1148f4a2713aSLionel Sambuc   gv->setSection(AnnotationSection);
1149f4a2713aSLionel Sambuc   gv->setUnnamedAddr(true);
1150f4a2713aSLionel Sambuc   AStr = gv;
1151f4a2713aSLionel Sambuc   return gv;
1152f4a2713aSLionel Sambuc }
1153f4a2713aSLionel Sambuc 
EmitAnnotationUnit(SourceLocation Loc)1154f4a2713aSLionel Sambuc llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1155f4a2713aSLionel Sambuc   SourceManager &SM = getContext().getSourceManager();
1156f4a2713aSLionel Sambuc   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1157f4a2713aSLionel Sambuc   if (PLoc.isValid())
1158f4a2713aSLionel Sambuc     return EmitAnnotationString(PLoc.getFilename());
1159f4a2713aSLionel Sambuc   return EmitAnnotationString(SM.getBufferName(Loc));
1160f4a2713aSLionel Sambuc }
1161f4a2713aSLionel Sambuc 
EmitAnnotationLineNo(SourceLocation L)1162f4a2713aSLionel Sambuc llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1163f4a2713aSLionel Sambuc   SourceManager &SM = getContext().getSourceManager();
1164f4a2713aSLionel Sambuc   PresumedLoc PLoc = SM.getPresumedLoc(L);
1165f4a2713aSLionel Sambuc   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1166f4a2713aSLionel Sambuc     SM.getExpansionLineNumber(L);
1167f4a2713aSLionel Sambuc   return llvm::ConstantInt::get(Int32Ty, LineNo);
1168f4a2713aSLionel Sambuc }
1169f4a2713aSLionel Sambuc 
EmitAnnotateAttr(llvm::GlobalValue * GV,const AnnotateAttr * AA,SourceLocation L)1170f4a2713aSLionel Sambuc llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1171f4a2713aSLionel Sambuc                                                 const AnnotateAttr *AA,
1172f4a2713aSLionel Sambuc                                                 SourceLocation L) {
1173f4a2713aSLionel Sambuc   // Get the globals for file name, annotation, and the line number.
1174f4a2713aSLionel Sambuc   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1175f4a2713aSLionel Sambuc                  *UnitGV = EmitAnnotationUnit(L),
1176f4a2713aSLionel Sambuc                  *LineNoCst = EmitAnnotationLineNo(L);
1177f4a2713aSLionel Sambuc 
1178f4a2713aSLionel Sambuc   // Create the ConstantStruct for the global annotation.
1179f4a2713aSLionel Sambuc   llvm::Constant *Fields[4] = {
1180f4a2713aSLionel Sambuc     llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1181f4a2713aSLionel Sambuc     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1182f4a2713aSLionel Sambuc     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1183f4a2713aSLionel Sambuc     LineNoCst
1184f4a2713aSLionel Sambuc   };
1185f4a2713aSLionel Sambuc   return llvm::ConstantStruct::getAnon(Fields);
1186f4a2713aSLionel Sambuc }
1187f4a2713aSLionel Sambuc 
AddGlobalAnnotations(const ValueDecl * D,llvm::GlobalValue * GV)1188f4a2713aSLionel Sambuc void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1189f4a2713aSLionel Sambuc                                          llvm::GlobalValue *GV) {
1190f4a2713aSLionel Sambuc   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1191f4a2713aSLionel Sambuc   // Get the struct elements for these annotations.
1192*0a6a1f1dSLionel Sambuc   for (const auto *I : D->specific_attrs<AnnotateAttr>())
1193*0a6a1f1dSLionel Sambuc     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
1194f4a2713aSLionel Sambuc }
1195f4a2713aSLionel Sambuc 
isInSanitizerBlacklist(llvm::Function * Fn,SourceLocation Loc) const1196*0a6a1f1dSLionel Sambuc bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
1197*0a6a1f1dSLionel Sambuc                                            SourceLocation Loc) const {
1198*0a6a1f1dSLionel Sambuc   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1199*0a6a1f1dSLionel Sambuc   // Blacklist by function name.
1200*0a6a1f1dSLionel Sambuc   if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
1201*0a6a1f1dSLionel Sambuc     return true;
1202*0a6a1f1dSLionel Sambuc   // Blacklist by location.
1203*0a6a1f1dSLionel Sambuc   if (!Loc.isInvalid())
1204*0a6a1f1dSLionel Sambuc     return SanitizerBL.isBlacklistedLocation(Loc);
1205*0a6a1f1dSLionel Sambuc   // If location is unknown, this may be a compiler-generated function. Assume
1206*0a6a1f1dSLionel Sambuc   // it's located in the main file.
1207*0a6a1f1dSLionel Sambuc   auto &SM = Context.getSourceManager();
1208*0a6a1f1dSLionel Sambuc   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1209*0a6a1f1dSLionel Sambuc     return SanitizerBL.isBlacklistedFile(MainFile->getName());
1210*0a6a1f1dSLionel Sambuc   }
1211*0a6a1f1dSLionel Sambuc   return false;
1212*0a6a1f1dSLionel Sambuc }
1213*0a6a1f1dSLionel Sambuc 
isInSanitizerBlacklist(llvm::GlobalVariable * GV,SourceLocation Loc,QualType Ty,StringRef Category) const1214*0a6a1f1dSLionel Sambuc bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1215*0a6a1f1dSLionel Sambuc                                            SourceLocation Loc, QualType Ty,
1216*0a6a1f1dSLionel Sambuc                                            StringRef Category) const {
1217*0a6a1f1dSLionel Sambuc   // For now globals can be blacklisted only in ASan.
1218*0a6a1f1dSLionel Sambuc   if (!LangOpts.Sanitize.has(SanitizerKind::Address))
1219*0a6a1f1dSLionel Sambuc     return false;
1220*0a6a1f1dSLionel Sambuc   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1221*0a6a1f1dSLionel Sambuc   if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
1222*0a6a1f1dSLionel Sambuc     return true;
1223*0a6a1f1dSLionel Sambuc   if (SanitizerBL.isBlacklistedLocation(Loc, Category))
1224*0a6a1f1dSLionel Sambuc     return true;
1225*0a6a1f1dSLionel Sambuc   // Check global type.
1226*0a6a1f1dSLionel Sambuc   if (!Ty.isNull()) {
1227*0a6a1f1dSLionel Sambuc     // Drill down the array types: if global variable of a fixed type is
1228*0a6a1f1dSLionel Sambuc     // blacklisted, we also don't instrument arrays of them.
1229*0a6a1f1dSLionel Sambuc     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1230*0a6a1f1dSLionel Sambuc       Ty = AT->getElementType();
1231*0a6a1f1dSLionel Sambuc     Ty = Ty.getCanonicalType().getUnqualifiedType();
1232*0a6a1f1dSLionel Sambuc     // We allow to blacklist only record types (classes, structs etc.)
1233*0a6a1f1dSLionel Sambuc     if (Ty->isRecordType()) {
1234*0a6a1f1dSLionel Sambuc       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
1235*0a6a1f1dSLionel Sambuc       if (SanitizerBL.isBlacklistedType(TypeStr, Category))
1236*0a6a1f1dSLionel Sambuc         return true;
1237*0a6a1f1dSLionel Sambuc     }
1238*0a6a1f1dSLionel Sambuc   }
1239*0a6a1f1dSLionel Sambuc   return false;
1240*0a6a1f1dSLionel Sambuc }
1241*0a6a1f1dSLionel Sambuc 
MustBeEmitted(const ValueDecl * Global)1242*0a6a1f1dSLionel Sambuc bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
1243f4a2713aSLionel Sambuc   // Never defer when EmitAllDecls is specified.
1244f4a2713aSLionel Sambuc   if (LangOpts.EmitAllDecls)
1245*0a6a1f1dSLionel Sambuc     return true;
1246*0a6a1f1dSLionel Sambuc 
1247*0a6a1f1dSLionel Sambuc   return getContext().DeclMustBeEmitted(Global);
1248*0a6a1f1dSLionel Sambuc }
1249*0a6a1f1dSLionel Sambuc 
MayBeEmittedEagerly(const ValueDecl * Global)1250*0a6a1f1dSLionel Sambuc bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
1251*0a6a1f1dSLionel Sambuc   if (const auto *FD = dyn_cast<FunctionDecl>(Global))
1252*0a6a1f1dSLionel Sambuc     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1253*0a6a1f1dSLionel Sambuc       // Implicit template instantiations may change linkage if they are later
1254*0a6a1f1dSLionel Sambuc       // explicitly instantiated, so they should not be emitted eagerly.
1255f4a2713aSLionel Sambuc       return false;
1256f4a2713aSLionel Sambuc 
1257*0a6a1f1dSLionel Sambuc   return true;
1258f4a2713aSLionel Sambuc }
1259f4a2713aSLionel Sambuc 
GetAddrOfUuidDescriptor(const CXXUuidofExpr * E)1260f4a2713aSLionel Sambuc llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
1261f4a2713aSLionel Sambuc     const CXXUuidofExpr* E) {
1262f4a2713aSLionel Sambuc   // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1263f4a2713aSLionel Sambuc   // well-formed.
1264f4a2713aSLionel Sambuc   StringRef Uuid = E->getUuidAsStringRef(Context);
1265f4a2713aSLionel Sambuc   std::string Name = "_GUID_" + Uuid.lower();
1266f4a2713aSLionel Sambuc   std::replace(Name.begin(), Name.end(), '-', '_');
1267f4a2713aSLionel Sambuc 
1268f4a2713aSLionel Sambuc   // Look for an existing global.
1269f4a2713aSLionel Sambuc   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1270f4a2713aSLionel Sambuc     return GV;
1271f4a2713aSLionel Sambuc 
1272*0a6a1f1dSLionel Sambuc   llvm::Constant *Init = EmitUuidofInitializer(Uuid);
1273f4a2713aSLionel Sambuc   assert(Init && "failed to initialize as constant");
1274f4a2713aSLionel Sambuc 
1275*0a6a1f1dSLionel Sambuc   auto *GV = new llvm::GlobalVariable(
1276f4a2713aSLionel Sambuc       getModule(), Init->getType(),
1277f4a2713aSLionel Sambuc       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
1278f4a2713aSLionel Sambuc   return GV;
1279f4a2713aSLionel Sambuc }
1280f4a2713aSLionel Sambuc 
GetWeakRefReference(const ValueDecl * VD)1281f4a2713aSLionel Sambuc llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1282f4a2713aSLionel Sambuc   const AliasAttr *AA = VD->getAttr<AliasAttr>();
1283f4a2713aSLionel Sambuc   assert(AA && "No alias?");
1284f4a2713aSLionel Sambuc 
1285f4a2713aSLionel Sambuc   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1286f4a2713aSLionel Sambuc 
1287f4a2713aSLionel Sambuc   // See if there is already something with the target's name in the module.
1288f4a2713aSLionel Sambuc   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
1289f4a2713aSLionel Sambuc   if (Entry) {
1290f4a2713aSLionel Sambuc     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1291f4a2713aSLionel Sambuc     return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1292f4a2713aSLionel Sambuc   }
1293f4a2713aSLionel Sambuc 
1294f4a2713aSLionel Sambuc   llvm::Constant *Aliasee;
1295f4a2713aSLionel Sambuc   if (isa<llvm::FunctionType>(DeclTy))
1296f4a2713aSLionel Sambuc     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1297f4a2713aSLionel Sambuc                                       GlobalDecl(cast<FunctionDecl>(VD)),
1298f4a2713aSLionel Sambuc                                       /*ForVTable=*/false);
1299f4a2713aSLionel Sambuc   else
1300f4a2713aSLionel Sambuc     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1301*0a6a1f1dSLionel Sambuc                                     llvm::PointerType::getUnqual(DeclTy),
1302*0a6a1f1dSLionel Sambuc                                     nullptr);
1303f4a2713aSLionel Sambuc 
1304*0a6a1f1dSLionel Sambuc   auto *F = cast<llvm::GlobalValue>(Aliasee);
1305f4a2713aSLionel Sambuc   F->setLinkage(llvm::Function::ExternalWeakLinkage);
1306f4a2713aSLionel Sambuc   WeakRefReferences.insert(F);
1307f4a2713aSLionel Sambuc 
1308f4a2713aSLionel Sambuc   return Aliasee;
1309f4a2713aSLionel Sambuc }
1310f4a2713aSLionel Sambuc 
EmitGlobal(GlobalDecl GD)1311f4a2713aSLionel Sambuc void CodeGenModule::EmitGlobal(GlobalDecl GD) {
1312*0a6a1f1dSLionel Sambuc   const auto *Global = cast<ValueDecl>(GD.getDecl());
1313f4a2713aSLionel Sambuc 
1314f4a2713aSLionel Sambuc   // Weak references don't produce any output by themselves.
1315f4a2713aSLionel Sambuc   if (Global->hasAttr<WeakRefAttr>())
1316f4a2713aSLionel Sambuc     return;
1317f4a2713aSLionel Sambuc 
1318f4a2713aSLionel Sambuc   // If this is an alias definition (which otherwise looks like a declaration)
1319f4a2713aSLionel Sambuc   // emit it now.
1320f4a2713aSLionel Sambuc   if (Global->hasAttr<AliasAttr>())
1321f4a2713aSLionel Sambuc     return EmitAliasDefinition(GD);
1322f4a2713aSLionel Sambuc 
1323f4a2713aSLionel Sambuc   // If this is CUDA, be selective about which declarations we emit.
1324f4a2713aSLionel Sambuc   if (LangOpts.CUDA) {
1325f4a2713aSLionel Sambuc     if (CodeGenOpts.CUDAIsDevice) {
1326f4a2713aSLionel Sambuc       if (!Global->hasAttr<CUDADeviceAttr>() &&
1327f4a2713aSLionel Sambuc           !Global->hasAttr<CUDAGlobalAttr>() &&
1328f4a2713aSLionel Sambuc           !Global->hasAttr<CUDAConstantAttr>() &&
1329f4a2713aSLionel Sambuc           !Global->hasAttr<CUDASharedAttr>())
1330f4a2713aSLionel Sambuc         return;
1331f4a2713aSLionel Sambuc     } else {
1332f4a2713aSLionel Sambuc       if (!Global->hasAttr<CUDAHostAttr>() && (
1333f4a2713aSLionel Sambuc             Global->hasAttr<CUDADeviceAttr>() ||
1334f4a2713aSLionel Sambuc             Global->hasAttr<CUDAConstantAttr>() ||
1335f4a2713aSLionel Sambuc             Global->hasAttr<CUDASharedAttr>()))
1336f4a2713aSLionel Sambuc         return;
1337f4a2713aSLionel Sambuc     }
1338f4a2713aSLionel Sambuc   }
1339f4a2713aSLionel Sambuc 
1340f4a2713aSLionel Sambuc   // Ignore declarations, they will be emitted on their first use.
1341*0a6a1f1dSLionel Sambuc   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1342f4a2713aSLionel Sambuc     // Forward declarations are emitted lazily on first use.
1343f4a2713aSLionel Sambuc     if (!FD->doesThisDeclarationHaveABody()) {
1344f4a2713aSLionel Sambuc       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1345f4a2713aSLionel Sambuc         return;
1346f4a2713aSLionel Sambuc 
1347f4a2713aSLionel Sambuc       StringRef MangledName = getMangledName(GD);
1348*0a6a1f1dSLionel Sambuc 
1349*0a6a1f1dSLionel Sambuc       // Compute the function info and LLVM type.
1350*0a6a1f1dSLionel Sambuc       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1351*0a6a1f1dSLionel Sambuc       llvm::Type *Ty = getTypes().GetFunctionType(FI);
1352*0a6a1f1dSLionel Sambuc 
1353*0a6a1f1dSLionel Sambuc       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
1354*0a6a1f1dSLionel Sambuc                               /*DontDefer=*/false);
1355f4a2713aSLionel Sambuc       return;
1356f4a2713aSLionel Sambuc     }
1357f4a2713aSLionel Sambuc   } else {
1358*0a6a1f1dSLionel Sambuc     const auto *VD = cast<VarDecl>(Global);
1359f4a2713aSLionel Sambuc     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1360f4a2713aSLionel Sambuc 
1361*0a6a1f1dSLionel Sambuc     if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
1362*0a6a1f1dSLionel Sambuc         !Context.isMSStaticDataMemberInlineDefinition(VD))
1363f4a2713aSLionel Sambuc       return;
1364f4a2713aSLionel Sambuc   }
1365f4a2713aSLionel Sambuc 
1366*0a6a1f1dSLionel Sambuc   // Defer code generation to first use when possible, e.g. if this is an inline
1367*0a6a1f1dSLionel Sambuc   // function. If the global must always be emitted, do it eagerly if possible
1368*0a6a1f1dSLionel Sambuc   // to benefit from cache locality.
1369*0a6a1f1dSLionel Sambuc   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
1370f4a2713aSLionel Sambuc     // Emit the definition if it can't be deferred.
1371f4a2713aSLionel Sambuc     EmitGlobalDefinition(GD);
1372f4a2713aSLionel Sambuc     return;
1373f4a2713aSLionel Sambuc   }
1374f4a2713aSLionel Sambuc 
1375f4a2713aSLionel Sambuc   // If we're deferring emission of a C++ variable with an
1376f4a2713aSLionel Sambuc   // initializer, remember the order in which it appeared in the file.
1377f4a2713aSLionel Sambuc   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1378f4a2713aSLionel Sambuc       cast<VarDecl>(Global)->hasInit()) {
1379f4a2713aSLionel Sambuc     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1380*0a6a1f1dSLionel Sambuc     CXXGlobalInits.push_back(nullptr);
1381f4a2713aSLionel Sambuc   }
1382f4a2713aSLionel Sambuc 
1383f4a2713aSLionel Sambuc   StringRef MangledName = getMangledName(GD);
1384*0a6a1f1dSLionel Sambuc   if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) {
1385*0a6a1f1dSLionel Sambuc     // The value has already been used and should therefore be emitted.
1386*0a6a1f1dSLionel Sambuc     addDeferredDeclToEmit(GV, GD);
1387*0a6a1f1dSLionel Sambuc   } else if (MustBeEmitted(Global)) {
1388*0a6a1f1dSLionel Sambuc     // The value must be emitted, but cannot be emitted eagerly.
1389*0a6a1f1dSLionel Sambuc     assert(!MayBeEmittedEagerly(Global));
1390*0a6a1f1dSLionel Sambuc     addDeferredDeclToEmit(/*GV=*/nullptr, GD);
1391*0a6a1f1dSLionel Sambuc   } else {
1392f4a2713aSLionel Sambuc     // Otherwise, remember that we saw a deferred decl with this name.  The
1393f4a2713aSLionel Sambuc     // first use of the mangled name will cause it to move into
1394f4a2713aSLionel Sambuc     // DeferredDeclsToEmit.
1395f4a2713aSLionel Sambuc     DeferredDecls[MangledName] = GD;
1396f4a2713aSLionel Sambuc   }
1397f4a2713aSLionel Sambuc }
1398f4a2713aSLionel Sambuc 
1399f4a2713aSLionel Sambuc namespace {
1400f4a2713aSLionel Sambuc   struct FunctionIsDirectlyRecursive :
1401f4a2713aSLionel Sambuc     public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1402f4a2713aSLionel Sambuc     const StringRef Name;
1403f4a2713aSLionel Sambuc     const Builtin::Context &BI;
1404f4a2713aSLionel Sambuc     bool Result;
FunctionIsDirectlyRecursive__anonb0b3316c0111::FunctionIsDirectlyRecursive1405f4a2713aSLionel Sambuc     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1406f4a2713aSLionel Sambuc       Name(N), BI(C), Result(false) {
1407f4a2713aSLionel Sambuc     }
1408f4a2713aSLionel Sambuc     typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1409f4a2713aSLionel Sambuc 
TraverseCallExpr__anonb0b3316c0111::FunctionIsDirectlyRecursive1410f4a2713aSLionel Sambuc     bool TraverseCallExpr(CallExpr *E) {
1411f4a2713aSLionel Sambuc       const FunctionDecl *FD = E->getDirectCallee();
1412f4a2713aSLionel Sambuc       if (!FD)
1413f4a2713aSLionel Sambuc         return true;
1414f4a2713aSLionel Sambuc       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1415f4a2713aSLionel Sambuc       if (Attr && Name == Attr->getLabel()) {
1416f4a2713aSLionel Sambuc         Result = true;
1417f4a2713aSLionel Sambuc         return false;
1418f4a2713aSLionel Sambuc       }
1419f4a2713aSLionel Sambuc       unsigned BuiltinID = FD->getBuiltinID();
1420f4a2713aSLionel Sambuc       if (!BuiltinID)
1421f4a2713aSLionel Sambuc         return true;
1422f4a2713aSLionel Sambuc       StringRef BuiltinName = BI.GetName(BuiltinID);
1423f4a2713aSLionel Sambuc       if (BuiltinName.startswith("__builtin_") &&
1424f4a2713aSLionel Sambuc           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1425f4a2713aSLionel Sambuc         Result = true;
1426f4a2713aSLionel Sambuc         return false;
1427f4a2713aSLionel Sambuc       }
1428f4a2713aSLionel Sambuc       return true;
1429f4a2713aSLionel Sambuc     }
1430f4a2713aSLionel Sambuc   };
1431f4a2713aSLionel Sambuc }
1432f4a2713aSLionel Sambuc 
1433f4a2713aSLionel Sambuc // isTriviallyRecursive - Check if this function calls another
1434f4a2713aSLionel Sambuc // decl that, because of the asm attribute or the other decl being a builtin,
1435f4a2713aSLionel Sambuc // ends up pointing to itself.
1436f4a2713aSLionel Sambuc bool
isTriviallyRecursive(const FunctionDecl * FD)1437f4a2713aSLionel Sambuc CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1438f4a2713aSLionel Sambuc   StringRef Name;
1439f4a2713aSLionel Sambuc   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1440f4a2713aSLionel Sambuc     // asm labels are a special kind of mangling we have to support.
1441f4a2713aSLionel Sambuc     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1442f4a2713aSLionel Sambuc     if (!Attr)
1443f4a2713aSLionel Sambuc       return false;
1444f4a2713aSLionel Sambuc     Name = Attr->getLabel();
1445f4a2713aSLionel Sambuc   } else {
1446f4a2713aSLionel Sambuc     Name = FD->getName();
1447f4a2713aSLionel Sambuc   }
1448f4a2713aSLionel Sambuc 
1449f4a2713aSLionel Sambuc   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1450f4a2713aSLionel Sambuc   Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1451f4a2713aSLionel Sambuc   return Walker.Result;
1452f4a2713aSLionel Sambuc }
1453f4a2713aSLionel Sambuc 
1454f4a2713aSLionel Sambuc bool
shouldEmitFunction(GlobalDecl GD)1455f4a2713aSLionel Sambuc CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1456f4a2713aSLionel Sambuc   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1457f4a2713aSLionel Sambuc     return true;
1458*0a6a1f1dSLionel Sambuc   const auto *F = cast<FunctionDecl>(GD.getDecl());
1459*0a6a1f1dSLionel Sambuc   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1460f4a2713aSLionel Sambuc     return false;
1461f4a2713aSLionel Sambuc   // PR9614. Avoid cases where the source code is lying to us. An available
1462f4a2713aSLionel Sambuc   // externally function should have an equivalent function somewhere else,
1463f4a2713aSLionel Sambuc   // but a function that calls itself is clearly not equivalent to the real
1464f4a2713aSLionel Sambuc   // implementation.
1465f4a2713aSLionel Sambuc   // This happens in glibc's btowc and in some configure checks.
1466f4a2713aSLionel Sambuc   return !isTriviallyRecursive(F);
1467f4a2713aSLionel Sambuc }
1468f4a2713aSLionel Sambuc 
1469f4a2713aSLionel Sambuc /// If the type for the method's class was generated by
1470f4a2713aSLionel Sambuc /// CGDebugInfo::createContextChain(), the cache contains only a
1471f4a2713aSLionel Sambuc /// limited DIType without any declarations. Since EmitFunctionStart()
1472f4a2713aSLionel Sambuc /// needs to find the canonical declaration for each method, we need
1473f4a2713aSLionel Sambuc /// to construct the complete type prior to emitting the method.
CompleteDIClassType(const CXXMethodDecl * D)1474f4a2713aSLionel Sambuc void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
1475f4a2713aSLionel Sambuc   if (!D->isInstance())
1476f4a2713aSLionel Sambuc     return;
1477f4a2713aSLionel Sambuc 
1478f4a2713aSLionel Sambuc   if (CGDebugInfo *DI = getModuleDebugInfo())
1479f4a2713aSLionel Sambuc     if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
1480*0a6a1f1dSLionel Sambuc       const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext()));
1481f4a2713aSLionel Sambuc       DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
1482f4a2713aSLionel Sambuc     }
1483f4a2713aSLionel Sambuc }
1484f4a2713aSLionel Sambuc 
EmitGlobalDefinition(GlobalDecl GD,llvm::GlobalValue * GV)1485*0a6a1f1dSLionel Sambuc void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
1486*0a6a1f1dSLionel Sambuc   const auto *D = cast<ValueDecl>(GD.getDecl());
1487f4a2713aSLionel Sambuc 
1488f4a2713aSLionel Sambuc   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1489f4a2713aSLionel Sambuc                                  Context.getSourceManager(),
1490f4a2713aSLionel Sambuc                                  "Generating code for declaration");
1491f4a2713aSLionel Sambuc 
1492f4a2713aSLionel Sambuc   if (isa<FunctionDecl>(D)) {
1493f4a2713aSLionel Sambuc     // At -O0, don't generate IR for functions with available_externally
1494f4a2713aSLionel Sambuc     // linkage.
1495f4a2713aSLionel Sambuc     if (!shouldEmitFunction(GD))
1496f4a2713aSLionel Sambuc       return;
1497f4a2713aSLionel Sambuc 
1498*0a6a1f1dSLionel Sambuc     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
1499f4a2713aSLionel Sambuc       CompleteDIClassType(Method);
1500f4a2713aSLionel Sambuc       // Make sure to emit the definition(s) before we emit the thunks.
1501f4a2713aSLionel Sambuc       // This is necessary for the generation of certain thunks.
1502*0a6a1f1dSLionel Sambuc       if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
1503*0a6a1f1dSLionel Sambuc         ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
1504*0a6a1f1dSLionel Sambuc       else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
1505*0a6a1f1dSLionel Sambuc         ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
1506f4a2713aSLionel Sambuc       else
1507*0a6a1f1dSLionel Sambuc         EmitGlobalFunctionDefinition(GD, GV);
1508f4a2713aSLionel Sambuc 
1509f4a2713aSLionel Sambuc       if (Method->isVirtual())
1510f4a2713aSLionel Sambuc         getVTables().EmitThunks(GD);
1511f4a2713aSLionel Sambuc 
1512f4a2713aSLionel Sambuc       return;
1513f4a2713aSLionel Sambuc     }
1514f4a2713aSLionel Sambuc 
1515*0a6a1f1dSLionel Sambuc     return EmitGlobalFunctionDefinition(GD, GV);
1516f4a2713aSLionel Sambuc   }
1517f4a2713aSLionel Sambuc 
1518*0a6a1f1dSLionel Sambuc   if (const auto *VD = dyn_cast<VarDecl>(D))
1519f4a2713aSLionel Sambuc     return EmitGlobalVarDefinition(VD);
1520f4a2713aSLionel Sambuc 
1521f4a2713aSLionel Sambuc   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1522f4a2713aSLionel Sambuc }
1523f4a2713aSLionel Sambuc 
1524f4a2713aSLionel Sambuc /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1525f4a2713aSLionel Sambuc /// module, create and return an llvm Function with the specified type. If there
1526f4a2713aSLionel Sambuc /// is something in the module with the specified name, return it potentially
1527f4a2713aSLionel Sambuc /// bitcasted to the right type.
1528f4a2713aSLionel Sambuc ///
1529f4a2713aSLionel Sambuc /// If D is non-null, it specifies a decl that correspond to this.  This is used
1530f4a2713aSLionel Sambuc /// to set the attributes on the function when it is first created.
1531f4a2713aSLionel Sambuc llvm::Constant *
GetOrCreateLLVMFunction(StringRef MangledName,llvm::Type * Ty,GlobalDecl GD,bool ForVTable,bool DontDefer,bool IsThunk,llvm::AttributeSet ExtraAttrs)1532f4a2713aSLionel Sambuc CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
1533f4a2713aSLionel Sambuc                                        llvm::Type *Ty,
1534f4a2713aSLionel Sambuc                                        GlobalDecl GD, bool ForVTable,
1535*0a6a1f1dSLionel Sambuc                                        bool DontDefer, bool IsThunk,
1536f4a2713aSLionel Sambuc                                        llvm::AttributeSet ExtraAttrs) {
1537f4a2713aSLionel Sambuc   const Decl *D = GD.getDecl();
1538f4a2713aSLionel Sambuc 
1539f4a2713aSLionel Sambuc   // Lookup the entry, lazily creating it if necessary.
1540f4a2713aSLionel Sambuc   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1541f4a2713aSLionel Sambuc   if (Entry) {
1542f4a2713aSLionel Sambuc     if (WeakRefReferences.erase(Entry)) {
1543f4a2713aSLionel Sambuc       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
1544f4a2713aSLionel Sambuc       if (FD && !FD->hasAttr<WeakAttr>())
1545f4a2713aSLionel Sambuc         Entry->setLinkage(llvm::Function::ExternalLinkage);
1546f4a2713aSLionel Sambuc     }
1547f4a2713aSLionel Sambuc 
1548*0a6a1f1dSLionel Sambuc     // Handle dropped DLL attributes.
1549*0a6a1f1dSLionel Sambuc     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
1550*0a6a1f1dSLionel Sambuc       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1551*0a6a1f1dSLionel Sambuc 
1552f4a2713aSLionel Sambuc     if (Entry->getType()->getElementType() == Ty)
1553f4a2713aSLionel Sambuc       return Entry;
1554f4a2713aSLionel Sambuc 
1555f4a2713aSLionel Sambuc     // Make sure the result is of the correct type.
1556f4a2713aSLionel Sambuc     return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1557f4a2713aSLionel Sambuc   }
1558f4a2713aSLionel Sambuc 
1559f4a2713aSLionel Sambuc   // This function doesn't have a complete type (for example, the return
1560f4a2713aSLionel Sambuc   // type is an incomplete struct). Use a fake type instead, and make
1561f4a2713aSLionel Sambuc   // sure not to try to set attributes.
1562f4a2713aSLionel Sambuc   bool IsIncompleteFunction = false;
1563f4a2713aSLionel Sambuc 
1564f4a2713aSLionel Sambuc   llvm::FunctionType *FTy;
1565f4a2713aSLionel Sambuc   if (isa<llvm::FunctionType>(Ty)) {
1566f4a2713aSLionel Sambuc     FTy = cast<llvm::FunctionType>(Ty);
1567f4a2713aSLionel Sambuc   } else {
1568f4a2713aSLionel Sambuc     FTy = llvm::FunctionType::get(VoidTy, false);
1569f4a2713aSLionel Sambuc     IsIncompleteFunction = true;
1570f4a2713aSLionel Sambuc   }
1571f4a2713aSLionel Sambuc 
1572f4a2713aSLionel Sambuc   llvm::Function *F = llvm::Function::Create(FTy,
1573f4a2713aSLionel Sambuc                                              llvm::Function::ExternalLinkage,
1574f4a2713aSLionel Sambuc                                              MangledName, &getModule());
1575f4a2713aSLionel Sambuc   assert(F->getName() == MangledName && "name was uniqued!");
1576f4a2713aSLionel Sambuc   if (D)
1577*0a6a1f1dSLionel Sambuc     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
1578f4a2713aSLionel Sambuc   if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1579f4a2713aSLionel Sambuc     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
1580f4a2713aSLionel Sambuc     F->addAttributes(llvm::AttributeSet::FunctionIndex,
1581f4a2713aSLionel Sambuc                      llvm::AttributeSet::get(VMContext,
1582f4a2713aSLionel Sambuc                                              llvm::AttributeSet::FunctionIndex,
1583f4a2713aSLionel Sambuc                                              B));
1584f4a2713aSLionel Sambuc   }
1585f4a2713aSLionel Sambuc 
1586*0a6a1f1dSLionel Sambuc   if (!DontDefer) {
1587*0a6a1f1dSLionel Sambuc     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
1588*0a6a1f1dSLionel Sambuc     // each other bottoming out with the base dtor.  Therefore we emit non-base
1589*0a6a1f1dSLionel Sambuc     // dtors on usage, even if there is no dtor definition in the TU.
1590*0a6a1f1dSLionel Sambuc     if (D && isa<CXXDestructorDecl>(D) &&
1591*0a6a1f1dSLionel Sambuc         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
1592*0a6a1f1dSLionel Sambuc                                            GD.getDtorType()))
1593*0a6a1f1dSLionel Sambuc       addDeferredDeclToEmit(F, GD);
1594*0a6a1f1dSLionel Sambuc 
1595f4a2713aSLionel Sambuc     // This is the first use or definition of a mangled name.  If there is a
1596f4a2713aSLionel Sambuc     // deferred decl with this name, remember that we need to emit it at the end
1597f4a2713aSLionel Sambuc     // of the file.
1598*0a6a1f1dSLionel Sambuc     auto DDI = DeferredDecls.find(MangledName);
1599f4a2713aSLionel Sambuc     if (DDI != DeferredDecls.end()) {
1600*0a6a1f1dSLionel Sambuc       // Move the potentially referenced deferred decl to the
1601*0a6a1f1dSLionel Sambuc       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
1602*0a6a1f1dSLionel Sambuc       // don't need it anymore).
1603*0a6a1f1dSLionel Sambuc       addDeferredDeclToEmit(F, DDI->second);
1604f4a2713aSLionel Sambuc       DeferredDecls.erase(DDI);
1605f4a2713aSLionel Sambuc 
1606*0a6a1f1dSLionel Sambuc       // Otherwise, if this is a sized deallocation function, emit a weak
1607*0a6a1f1dSLionel Sambuc       // definition
1608f4a2713aSLionel Sambuc       // for it at the end of the translation unit.
1609f4a2713aSLionel Sambuc     } else if (D && cast<FunctionDecl>(D)
1610f4a2713aSLionel Sambuc                         ->getCorrespondingUnsizedGlobalDeallocationFunction()) {
1611*0a6a1f1dSLionel Sambuc       addDeferredDeclToEmit(F, GD);
1612f4a2713aSLionel Sambuc 
1613f4a2713aSLionel Sambuc       // Otherwise, there are cases we have to worry about where we're
1614f4a2713aSLionel Sambuc       // using a declaration for which we must emit a definition but where
1615f4a2713aSLionel Sambuc       // we might not find a top-level definition:
1616f4a2713aSLionel Sambuc       //   - member functions defined inline in their classes
1617f4a2713aSLionel Sambuc       //   - friend functions defined inline in some class
1618f4a2713aSLionel Sambuc       //   - special member functions with implicit definitions
1619f4a2713aSLionel Sambuc       // If we ever change our AST traversal to walk into class methods,
1620f4a2713aSLionel Sambuc       // this will be unnecessary.
1621f4a2713aSLionel Sambuc       //
1622*0a6a1f1dSLionel Sambuc       // We also don't emit a definition for a function if it's going to be an
1623*0a6a1f1dSLionel Sambuc       // entry in a vtable, unless it's already marked as used.
1624f4a2713aSLionel Sambuc     } else if (getLangOpts().CPlusPlus && D) {
1625f4a2713aSLionel Sambuc       // Look for a declaration that's lexically in a record.
1626*0a6a1f1dSLionel Sambuc       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
1627*0a6a1f1dSLionel Sambuc            FD = FD->getPreviousDecl()) {
1628f4a2713aSLionel Sambuc         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
1629*0a6a1f1dSLionel Sambuc           if (FD->doesThisDeclarationHaveABody()) {
1630*0a6a1f1dSLionel Sambuc             addDeferredDeclToEmit(F, GD.getWithDecl(FD));
1631f4a2713aSLionel Sambuc             break;
1632f4a2713aSLionel Sambuc           }
1633f4a2713aSLionel Sambuc         }
1634*0a6a1f1dSLionel Sambuc       }
1635*0a6a1f1dSLionel Sambuc     }
1636f4a2713aSLionel Sambuc   }
1637f4a2713aSLionel Sambuc 
1638f4a2713aSLionel Sambuc   // Make sure the result is of the requested type.
1639f4a2713aSLionel Sambuc   if (!IsIncompleteFunction) {
1640f4a2713aSLionel Sambuc     assert(F->getType()->getElementType() == Ty);
1641f4a2713aSLionel Sambuc     return F;
1642f4a2713aSLionel Sambuc   }
1643f4a2713aSLionel Sambuc 
1644f4a2713aSLionel Sambuc   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1645f4a2713aSLionel Sambuc   return llvm::ConstantExpr::getBitCast(F, PTy);
1646f4a2713aSLionel Sambuc }
1647f4a2713aSLionel Sambuc 
1648f4a2713aSLionel Sambuc /// GetAddrOfFunction - Return the address of the given function.  If Ty is
1649f4a2713aSLionel Sambuc /// non-null, then this function will use the specified type if it has to
1650f4a2713aSLionel Sambuc /// create it (this occurs when we see a definition of the function).
GetAddrOfFunction(GlobalDecl GD,llvm::Type * Ty,bool ForVTable,bool DontDefer)1651f4a2713aSLionel Sambuc llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
1652f4a2713aSLionel Sambuc                                                  llvm::Type *Ty,
1653*0a6a1f1dSLionel Sambuc                                                  bool ForVTable,
1654*0a6a1f1dSLionel Sambuc                                                  bool DontDefer) {
1655f4a2713aSLionel Sambuc   // If there was no specific requested type, just convert it now.
1656f4a2713aSLionel Sambuc   if (!Ty)
1657f4a2713aSLionel Sambuc     Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
1658f4a2713aSLionel Sambuc 
1659f4a2713aSLionel Sambuc   StringRef MangledName = getMangledName(GD);
1660*0a6a1f1dSLionel Sambuc   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer);
1661f4a2713aSLionel Sambuc }
1662f4a2713aSLionel Sambuc 
1663f4a2713aSLionel Sambuc /// CreateRuntimeFunction - Create a new runtime function with the specified
1664f4a2713aSLionel Sambuc /// type and name.
1665f4a2713aSLionel Sambuc llvm::Constant *
CreateRuntimeFunction(llvm::FunctionType * FTy,StringRef Name,llvm::AttributeSet ExtraAttrs)1666f4a2713aSLionel Sambuc CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
1667f4a2713aSLionel Sambuc                                      StringRef Name,
1668f4a2713aSLionel Sambuc                                      llvm::AttributeSet ExtraAttrs) {
1669*0a6a1f1dSLionel Sambuc   llvm::Constant *C =
1670*0a6a1f1dSLionel Sambuc       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1671*0a6a1f1dSLionel Sambuc                               /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
1672*0a6a1f1dSLionel Sambuc   if (auto *F = dyn_cast<llvm::Function>(C))
1673f4a2713aSLionel Sambuc     if (F->empty())
1674f4a2713aSLionel Sambuc       F->setCallingConv(getRuntimeCC());
1675f4a2713aSLionel Sambuc   return C;
1676f4a2713aSLionel Sambuc }
1677f4a2713aSLionel Sambuc 
1678*0a6a1f1dSLionel Sambuc /// CreateBuiltinFunction - Create a new builtin function with the specified
1679*0a6a1f1dSLionel Sambuc /// type and name.
1680*0a6a1f1dSLionel Sambuc llvm::Constant *
CreateBuiltinFunction(llvm::FunctionType * FTy,StringRef Name,llvm::AttributeSet ExtraAttrs)1681*0a6a1f1dSLionel Sambuc CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy,
1682*0a6a1f1dSLionel Sambuc                                      StringRef Name,
1683*0a6a1f1dSLionel Sambuc                                      llvm::AttributeSet ExtraAttrs) {
1684*0a6a1f1dSLionel Sambuc   llvm::Constant *C =
1685*0a6a1f1dSLionel Sambuc       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1686*0a6a1f1dSLionel Sambuc                               /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
1687*0a6a1f1dSLionel Sambuc   if (auto *F = dyn_cast<llvm::Function>(C))
1688*0a6a1f1dSLionel Sambuc     if (F->empty())
1689*0a6a1f1dSLionel Sambuc       F->setCallingConv(getBuiltinCC());
1690*0a6a1f1dSLionel Sambuc   return C;
1691*0a6a1f1dSLionel Sambuc }
1692*0a6a1f1dSLionel Sambuc 
1693f4a2713aSLionel Sambuc /// isTypeConstant - Determine whether an object of this type can be emitted
1694f4a2713aSLionel Sambuc /// as a constant.
1695f4a2713aSLionel Sambuc ///
1696f4a2713aSLionel Sambuc /// If ExcludeCtor is true, the duration when the object's constructor runs
1697f4a2713aSLionel Sambuc /// will not be considered. The caller will need to verify that the object is
1698f4a2713aSLionel Sambuc /// not written to during its construction.
isTypeConstant(QualType Ty,bool ExcludeCtor)1699f4a2713aSLionel Sambuc bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1700f4a2713aSLionel Sambuc   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
1701f4a2713aSLionel Sambuc     return false;
1702f4a2713aSLionel Sambuc 
1703f4a2713aSLionel Sambuc   if (Context.getLangOpts().CPlusPlus) {
1704f4a2713aSLionel Sambuc     if (const CXXRecordDecl *Record
1705f4a2713aSLionel Sambuc           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1706f4a2713aSLionel Sambuc       return ExcludeCtor && !Record->hasMutableFields() &&
1707f4a2713aSLionel Sambuc              Record->hasTrivialDestructor();
1708f4a2713aSLionel Sambuc   }
1709f4a2713aSLionel Sambuc 
1710f4a2713aSLionel Sambuc   return true;
1711f4a2713aSLionel Sambuc }
1712f4a2713aSLionel Sambuc 
1713f4a2713aSLionel Sambuc /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1714f4a2713aSLionel Sambuc /// create and return an llvm GlobalVariable with the specified type.  If there
1715f4a2713aSLionel Sambuc /// is something in the module with the specified name, return it potentially
1716f4a2713aSLionel Sambuc /// bitcasted to the right type.
1717f4a2713aSLionel Sambuc ///
1718f4a2713aSLionel Sambuc /// If D is non-null, it specifies a decl that correspond to this.  This is used
1719f4a2713aSLionel Sambuc /// to set the attributes on the global when it is first created.
1720f4a2713aSLionel Sambuc llvm::Constant *
GetOrCreateLLVMGlobal(StringRef MangledName,llvm::PointerType * Ty,const VarDecl * D)1721f4a2713aSLionel Sambuc CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
1722f4a2713aSLionel Sambuc                                      llvm::PointerType *Ty,
1723*0a6a1f1dSLionel Sambuc                                      const VarDecl *D) {
1724f4a2713aSLionel Sambuc   // Lookup the entry, lazily creating it if necessary.
1725f4a2713aSLionel Sambuc   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1726f4a2713aSLionel Sambuc   if (Entry) {
1727f4a2713aSLionel Sambuc     if (WeakRefReferences.erase(Entry)) {
1728f4a2713aSLionel Sambuc       if (D && !D->hasAttr<WeakAttr>())
1729f4a2713aSLionel Sambuc         Entry->setLinkage(llvm::Function::ExternalLinkage);
1730f4a2713aSLionel Sambuc     }
1731f4a2713aSLionel Sambuc 
1732*0a6a1f1dSLionel Sambuc     // Handle dropped DLL attributes.
1733*0a6a1f1dSLionel Sambuc     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
1734*0a6a1f1dSLionel Sambuc       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1735f4a2713aSLionel Sambuc 
1736f4a2713aSLionel Sambuc     if (Entry->getType() == Ty)
1737f4a2713aSLionel Sambuc       return Entry;
1738f4a2713aSLionel Sambuc 
1739f4a2713aSLionel Sambuc     // Make sure the result is of the correct type.
1740f4a2713aSLionel Sambuc     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
1741f4a2713aSLionel Sambuc       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
1742f4a2713aSLionel Sambuc 
1743f4a2713aSLionel Sambuc     return llvm::ConstantExpr::getBitCast(Entry, Ty);
1744f4a2713aSLionel Sambuc   }
1745f4a2713aSLionel Sambuc 
1746*0a6a1f1dSLionel Sambuc   unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
1747*0a6a1f1dSLionel Sambuc   auto *GV = new llvm::GlobalVariable(
1748*0a6a1f1dSLionel Sambuc       getModule(), Ty->getElementType(), false,
1749*0a6a1f1dSLionel Sambuc       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
1750*0a6a1f1dSLionel Sambuc       llvm::GlobalVariable::NotThreadLocal, AddrSpace);
1751*0a6a1f1dSLionel Sambuc 
1752f4a2713aSLionel Sambuc   // This is the first use or definition of a mangled name.  If there is a
1753f4a2713aSLionel Sambuc   // deferred decl with this name, remember that we need to emit it at the end
1754f4a2713aSLionel Sambuc   // of the file.
1755*0a6a1f1dSLionel Sambuc   auto DDI = DeferredDecls.find(MangledName);
1756f4a2713aSLionel Sambuc   if (DDI != DeferredDecls.end()) {
1757f4a2713aSLionel Sambuc     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1758f4a2713aSLionel Sambuc     // list, and remove it from DeferredDecls (since we don't need it anymore).
1759*0a6a1f1dSLionel Sambuc     addDeferredDeclToEmit(GV, DDI->second);
1760f4a2713aSLionel Sambuc     DeferredDecls.erase(DDI);
1761f4a2713aSLionel Sambuc   }
1762f4a2713aSLionel Sambuc 
1763f4a2713aSLionel Sambuc   // Handle things which are present even on external declarations.
1764f4a2713aSLionel Sambuc   if (D) {
1765f4a2713aSLionel Sambuc     // FIXME: This code is overly simple and should be merged with other global
1766f4a2713aSLionel Sambuc     // handling.
1767f4a2713aSLionel Sambuc     GV->setConstant(isTypeConstant(D->getType(), false));
1768f4a2713aSLionel Sambuc 
1769*0a6a1f1dSLionel Sambuc     setLinkageAndVisibilityForGV(GV, D);
1770f4a2713aSLionel Sambuc 
1771f4a2713aSLionel Sambuc     if (D->getTLSKind()) {
1772f4a2713aSLionel Sambuc       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
1773f4a2713aSLionel Sambuc         CXXThreadLocals.push_back(std::make_pair(D, GV));
1774f4a2713aSLionel Sambuc       setTLSMode(GV, *D);
1775f4a2713aSLionel Sambuc     }
1776f4a2713aSLionel Sambuc 
1777f4a2713aSLionel Sambuc     // If required by the ABI, treat declarations of static data members with
1778f4a2713aSLionel Sambuc     // inline initializers as definitions.
1779*0a6a1f1dSLionel Sambuc     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
1780f4a2713aSLionel Sambuc       EmitGlobalVarDefinition(D);
1781f4a2713aSLionel Sambuc     }
1782f4a2713aSLionel Sambuc 
1783*0a6a1f1dSLionel Sambuc     // Handle XCore specific ABI requirements.
1784*0a6a1f1dSLionel Sambuc     if (getTarget().getTriple().getArch() == llvm::Triple::xcore &&
1785*0a6a1f1dSLionel Sambuc         D->getLanguageLinkage() == CLanguageLinkage &&
1786*0a6a1f1dSLionel Sambuc         D->getType().isConstant(Context) &&
1787*0a6a1f1dSLionel Sambuc         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
1788*0a6a1f1dSLionel Sambuc       GV->setSection(".cp.rodata");
1789*0a6a1f1dSLionel Sambuc   }
1790*0a6a1f1dSLionel Sambuc 
1791f4a2713aSLionel Sambuc   if (AddrSpace != Ty->getAddressSpace())
1792f4a2713aSLionel Sambuc     return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
1793f4a2713aSLionel Sambuc 
1794f4a2713aSLionel Sambuc   return GV;
1795f4a2713aSLionel Sambuc }
1796f4a2713aSLionel Sambuc 
1797f4a2713aSLionel Sambuc 
1798f4a2713aSLionel Sambuc llvm::GlobalVariable *
CreateOrReplaceCXXRuntimeVariable(StringRef Name,llvm::Type * Ty,llvm::GlobalValue::LinkageTypes Linkage)1799f4a2713aSLionel Sambuc CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
1800f4a2713aSLionel Sambuc                                       llvm::Type *Ty,
1801f4a2713aSLionel Sambuc                                       llvm::GlobalValue::LinkageTypes Linkage) {
1802f4a2713aSLionel Sambuc   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1803*0a6a1f1dSLionel Sambuc   llvm::GlobalVariable *OldGV = nullptr;
1804f4a2713aSLionel Sambuc 
1805f4a2713aSLionel Sambuc   if (GV) {
1806f4a2713aSLionel Sambuc     // Check if the variable has the right type.
1807f4a2713aSLionel Sambuc     if (GV->getType()->getElementType() == Ty)
1808f4a2713aSLionel Sambuc       return GV;
1809f4a2713aSLionel Sambuc 
1810f4a2713aSLionel Sambuc     // Because C++ name mangling, the only way we can end up with an already
1811f4a2713aSLionel Sambuc     // existing global with the same name is if it has been declared extern "C".
1812f4a2713aSLionel Sambuc     assert(GV->isDeclaration() && "Declaration has wrong type!");
1813f4a2713aSLionel Sambuc     OldGV = GV;
1814f4a2713aSLionel Sambuc   }
1815f4a2713aSLionel Sambuc 
1816f4a2713aSLionel Sambuc   // Create a new variable.
1817f4a2713aSLionel Sambuc   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1818*0a6a1f1dSLionel Sambuc                                 Linkage, nullptr, Name);
1819f4a2713aSLionel Sambuc 
1820f4a2713aSLionel Sambuc   if (OldGV) {
1821f4a2713aSLionel Sambuc     // Replace occurrences of the old variable if needed.
1822f4a2713aSLionel Sambuc     GV->takeName(OldGV);
1823f4a2713aSLionel Sambuc 
1824f4a2713aSLionel Sambuc     if (!OldGV->use_empty()) {
1825f4a2713aSLionel Sambuc       llvm::Constant *NewPtrForOldDecl =
1826f4a2713aSLionel Sambuc       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1827f4a2713aSLionel Sambuc       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1828f4a2713aSLionel Sambuc     }
1829f4a2713aSLionel Sambuc 
1830f4a2713aSLionel Sambuc     OldGV->eraseFromParent();
1831f4a2713aSLionel Sambuc   }
1832f4a2713aSLionel Sambuc 
1833f4a2713aSLionel Sambuc   return GV;
1834f4a2713aSLionel Sambuc }
1835f4a2713aSLionel Sambuc 
1836f4a2713aSLionel Sambuc /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1837f4a2713aSLionel Sambuc /// given global variable.  If Ty is non-null and if the global doesn't exist,
1838f4a2713aSLionel Sambuc /// then it will be created with the specified type instead of whatever the
1839f4a2713aSLionel Sambuc /// normal requested type would be.
GetAddrOfGlobalVar(const VarDecl * D,llvm::Type * Ty)1840f4a2713aSLionel Sambuc llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1841f4a2713aSLionel Sambuc                                                   llvm::Type *Ty) {
1842f4a2713aSLionel Sambuc   assert(D->hasGlobalStorage() && "Not a global variable");
1843f4a2713aSLionel Sambuc   QualType ASTTy = D->getType();
1844*0a6a1f1dSLionel Sambuc   if (!Ty)
1845f4a2713aSLionel Sambuc     Ty = getTypes().ConvertTypeForMem(ASTTy);
1846f4a2713aSLionel Sambuc 
1847f4a2713aSLionel Sambuc   llvm::PointerType *PTy =
1848f4a2713aSLionel Sambuc     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1849f4a2713aSLionel Sambuc 
1850f4a2713aSLionel Sambuc   StringRef MangledName = getMangledName(D);
1851f4a2713aSLionel Sambuc   return GetOrCreateLLVMGlobal(MangledName, PTy, D);
1852f4a2713aSLionel Sambuc }
1853f4a2713aSLionel Sambuc 
1854f4a2713aSLionel Sambuc /// CreateRuntimeVariable - Create a new runtime global variable with the
1855f4a2713aSLionel Sambuc /// specified type and name.
1856f4a2713aSLionel Sambuc llvm::Constant *
CreateRuntimeVariable(llvm::Type * Ty,StringRef Name)1857f4a2713aSLionel Sambuc CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
1858f4a2713aSLionel Sambuc                                      StringRef Name) {
1859*0a6a1f1dSLionel Sambuc   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
1860f4a2713aSLionel Sambuc }
1861f4a2713aSLionel Sambuc 
EmitTentativeDefinition(const VarDecl * D)1862f4a2713aSLionel Sambuc void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1863f4a2713aSLionel Sambuc   assert(!D->getInit() && "Cannot emit definite definitions here!");
1864f4a2713aSLionel Sambuc 
1865*0a6a1f1dSLionel Sambuc   if (!MustBeEmitted(D)) {
1866f4a2713aSLionel Sambuc     // If we have not seen a reference to this variable yet, place it
1867f4a2713aSLionel Sambuc     // into the deferred declarations table to be emitted if needed
1868f4a2713aSLionel Sambuc     // later.
1869f4a2713aSLionel Sambuc     StringRef MangledName = getMangledName(D);
1870f4a2713aSLionel Sambuc     if (!GetGlobalValue(MangledName)) {
1871f4a2713aSLionel Sambuc       DeferredDecls[MangledName] = D;
1872f4a2713aSLionel Sambuc       return;
1873f4a2713aSLionel Sambuc     }
1874f4a2713aSLionel Sambuc   }
1875f4a2713aSLionel Sambuc 
1876f4a2713aSLionel Sambuc   // The tentative definition is the only definition.
1877f4a2713aSLionel Sambuc   EmitGlobalVarDefinition(D);
1878f4a2713aSLionel Sambuc }
1879f4a2713aSLionel Sambuc 
GetTargetTypeStoreSize(llvm::Type * Ty) const1880f4a2713aSLionel Sambuc CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
1881f4a2713aSLionel Sambuc     return Context.toCharUnitsFromBits(
1882f4a2713aSLionel Sambuc       TheDataLayout.getTypeStoreSizeInBits(Ty));
1883f4a2713aSLionel Sambuc }
1884f4a2713aSLionel Sambuc 
GetGlobalVarAddressSpace(const VarDecl * D,unsigned AddrSpace)1885f4a2713aSLionel Sambuc unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
1886f4a2713aSLionel Sambuc                                                  unsigned AddrSpace) {
1887f4a2713aSLionel Sambuc   if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
1888f4a2713aSLionel Sambuc     if (D->hasAttr<CUDAConstantAttr>())
1889f4a2713aSLionel Sambuc       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
1890f4a2713aSLionel Sambuc     else if (D->hasAttr<CUDASharedAttr>())
1891f4a2713aSLionel Sambuc       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
1892f4a2713aSLionel Sambuc     else
1893f4a2713aSLionel Sambuc       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
1894f4a2713aSLionel Sambuc   }
1895f4a2713aSLionel Sambuc 
1896f4a2713aSLionel Sambuc   return AddrSpace;
1897f4a2713aSLionel Sambuc }
1898f4a2713aSLionel Sambuc 
1899f4a2713aSLionel Sambuc template<typename SomeDecl>
MaybeHandleStaticInExternC(const SomeDecl * D,llvm::GlobalValue * GV)1900f4a2713aSLionel Sambuc void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
1901f4a2713aSLionel Sambuc                                                llvm::GlobalValue *GV) {
1902f4a2713aSLionel Sambuc   if (!getLangOpts().CPlusPlus)
1903f4a2713aSLionel Sambuc     return;
1904f4a2713aSLionel Sambuc 
1905f4a2713aSLionel Sambuc   // Must have 'used' attribute, or else inline assembly can't rely on
1906f4a2713aSLionel Sambuc   // the name existing.
1907f4a2713aSLionel Sambuc   if (!D->template hasAttr<UsedAttr>())
1908f4a2713aSLionel Sambuc     return;
1909f4a2713aSLionel Sambuc 
1910f4a2713aSLionel Sambuc   // Must have internal linkage and an ordinary name.
1911f4a2713aSLionel Sambuc   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
1912f4a2713aSLionel Sambuc     return;
1913f4a2713aSLionel Sambuc 
1914f4a2713aSLionel Sambuc   // Must be in an extern "C" context. Entities declared directly within
1915f4a2713aSLionel Sambuc   // a record are not extern "C" even if the record is in such a context.
1916f4a2713aSLionel Sambuc   const SomeDecl *First = D->getFirstDecl();
1917f4a2713aSLionel Sambuc   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
1918f4a2713aSLionel Sambuc     return;
1919f4a2713aSLionel Sambuc 
1920f4a2713aSLionel Sambuc   // OK, this is an internal linkage entity inside an extern "C" linkage
1921f4a2713aSLionel Sambuc   // specification. Make a note of that so we can give it the "expected"
1922f4a2713aSLionel Sambuc   // mangled name if nothing else is using that name.
1923f4a2713aSLionel Sambuc   std::pair<StaticExternCMap::iterator, bool> R =
1924f4a2713aSLionel Sambuc       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
1925f4a2713aSLionel Sambuc 
1926f4a2713aSLionel Sambuc   // If we have multiple internal linkage entities with the same name
1927f4a2713aSLionel Sambuc   // in extern "C" regions, none of them gets that name.
1928f4a2713aSLionel Sambuc   if (!R.second)
1929*0a6a1f1dSLionel Sambuc     R.first->second = nullptr;
1930f4a2713aSLionel Sambuc }
1931f4a2713aSLionel Sambuc 
EmitGlobalVarDefinition(const VarDecl * D)1932f4a2713aSLionel Sambuc void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1933*0a6a1f1dSLionel Sambuc   llvm::Constant *Init = nullptr;
1934f4a2713aSLionel Sambuc   QualType ASTTy = D->getType();
1935f4a2713aSLionel Sambuc   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1936f4a2713aSLionel Sambuc   bool NeedsGlobalCtor = false;
1937f4a2713aSLionel Sambuc   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
1938f4a2713aSLionel Sambuc 
1939f4a2713aSLionel Sambuc   const VarDecl *InitDecl;
1940f4a2713aSLionel Sambuc   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
1941f4a2713aSLionel Sambuc 
1942f4a2713aSLionel Sambuc   if (!InitExpr) {
1943f4a2713aSLionel Sambuc     // This is a tentative definition; tentative definitions are
1944f4a2713aSLionel Sambuc     // implicitly initialized with { 0 }.
1945f4a2713aSLionel Sambuc     //
1946f4a2713aSLionel Sambuc     // Note that tentative definitions are only emitted at the end of
1947f4a2713aSLionel Sambuc     // a translation unit, so they should never have incomplete
1948f4a2713aSLionel Sambuc     // type. In addition, EmitTentativeDefinition makes sure that we
1949f4a2713aSLionel Sambuc     // never attempt to emit a tentative definition if a real one
1950f4a2713aSLionel Sambuc     // exists. A use may still exists, however, so we still may need
1951f4a2713aSLionel Sambuc     // to do a RAUW.
1952f4a2713aSLionel Sambuc     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1953f4a2713aSLionel Sambuc     Init = EmitNullConstant(D->getType());
1954f4a2713aSLionel Sambuc   } else {
1955f4a2713aSLionel Sambuc     initializedGlobalDecl = GlobalDecl(D);
1956f4a2713aSLionel Sambuc     Init = EmitConstantInit(*InitDecl);
1957f4a2713aSLionel Sambuc 
1958f4a2713aSLionel Sambuc     if (!Init) {
1959f4a2713aSLionel Sambuc       QualType T = InitExpr->getType();
1960f4a2713aSLionel Sambuc       if (D->getType()->isReferenceType())
1961f4a2713aSLionel Sambuc         T = D->getType();
1962f4a2713aSLionel Sambuc 
1963f4a2713aSLionel Sambuc       if (getLangOpts().CPlusPlus) {
1964f4a2713aSLionel Sambuc         Init = EmitNullConstant(T);
1965f4a2713aSLionel Sambuc         NeedsGlobalCtor = true;
1966f4a2713aSLionel Sambuc       } else {
1967f4a2713aSLionel Sambuc         ErrorUnsupported(D, "static initializer");
1968f4a2713aSLionel Sambuc         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1969f4a2713aSLionel Sambuc       }
1970f4a2713aSLionel Sambuc     } else {
1971f4a2713aSLionel Sambuc       // We don't need an initializer, so remove the entry for the delayed
1972f4a2713aSLionel Sambuc       // initializer position (just in case this entry was delayed) if we
1973f4a2713aSLionel Sambuc       // also don't need to register a destructor.
1974f4a2713aSLionel Sambuc       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
1975f4a2713aSLionel Sambuc         DelayedCXXInitPosition.erase(D);
1976f4a2713aSLionel Sambuc     }
1977f4a2713aSLionel Sambuc   }
1978f4a2713aSLionel Sambuc 
1979f4a2713aSLionel Sambuc   llvm::Type* InitType = Init->getType();
1980f4a2713aSLionel Sambuc   llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1981f4a2713aSLionel Sambuc 
1982f4a2713aSLionel Sambuc   // Strip off a bitcast if we got one back.
1983*0a6a1f1dSLionel Sambuc   if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1984f4a2713aSLionel Sambuc     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1985f4a2713aSLionel Sambuc            CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
1986f4a2713aSLionel Sambuc            // All zero index gep.
1987f4a2713aSLionel Sambuc            CE->getOpcode() == llvm::Instruction::GetElementPtr);
1988f4a2713aSLionel Sambuc     Entry = CE->getOperand(0);
1989f4a2713aSLionel Sambuc   }
1990f4a2713aSLionel Sambuc 
1991f4a2713aSLionel Sambuc   // Entry is now either a Function or GlobalVariable.
1992*0a6a1f1dSLionel Sambuc   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1993f4a2713aSLionel Sambuc 
1994f4a2713aSLionel Sambuc   // We have a definition after a declaration with the wrong type.
1995f4a2713aSLionel Sambuc   // We must make a new GlobalVariable* and update everything that used OldGV
1996f4a2713aSLionel Sambuc   // (a declaration or tentative definition) with the new GlobalVariable*
1997f4a2713aSLionel Sambuc   // (which will be a definition).
1998f4a2713aSLionel Sambuc   //
1999f4a2713aSLionel Sambuc   // This happens if there is a prototype for a global (e.g.
2000f4a2713aSLionel Sambuc   // "extern int x[];") and then a definition of a different type (e.g.
2001f4a2713aSLionel Sambuc   // "int x[10];"). This also happens when an initializer has a different type
2002f4a2713aSLionel Sambuc   // from the type of the global (this happens with unions).
2003*0a6a1f1dSLionel Sambuc   if (!GV ||
2004f4a2713aSLionel Sambuc       GV->getType()->getElementType() != InitType ||
2005f4a2713aSLionel Sambuc       GV->getType()->getAddressSpace() !=
2006f4a2713aSLionel Sambuc        GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
2007f4a2713aSLionel Sambuc 
2008f4a2713aSLionel Sambuc     // Move the old entry aside so that we'll create a new one.
2009f4a2713aSLionel Sambuc     Entry->setName(StringRef());
2010f4a2713aSLionel Sambuc 
2011f4a2713aSLionel Sambuc     // Make a new global with the correct type, this is now guaranteed to work.
2012f4a2713aSLionel Sambuc     GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
2013f4a2713aSLionel Sambuc 
2014f4a2713aSLionel Sambuc     // Replace all uses of the old global with the new global
2015f4a2713aSLionel Sambuc     llvm::Constant *NewPtrForOldDecl =
2016f4a2713aSLionel Sambuc         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2017f4a2713aSLionel Sambuc     Entry->replaceAllUsesWith(NewPtrForOldDecl);
2018f4a2713aSLionel Sambuc 
2019f4a2713aSLionel Sambuc     // Erase the old global, since it is no longer used.
2020f4a2713aSLionel Sambuc     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2021f4a2713aSLionel Sambuc   }
2022f4a2713aSLionel Sambuc 
2023f4a2713aSLionel Sambuc   MaybeHandleStaticInExternC(D, GV);
2024f4a2713aSLionel Sambuc 
2025f4a2713aSLionel Sambuc   if (D->hasAttr<AnnotateAttr>())
2026f4a2713aSLionel Sambuc     AddGlobalAnnotations(D, GV);
2027f4a2713aSLionel Sambuc 
2028f4a2713aSLionel Sambuc   GV->setInitializer(Init);
2029f4a2713aSLionel Sambuc 
2030f4a2713aSLionel Sambuc   // If it is safe to mark the global 'constant', do so now.
2031f4a2713aSLionel Sambuc   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2032f4a2713aSLionel Sambuc                   isTypeConstant(D->getType(), true));
2033f4a2713aSLionel Sambuc 
2034*0a6a1f1dSLionel Sambuc   // If it is in a read-only section, mark it 'constant'.
2035*0a6a1f1dSLionel Sambuc   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
2036*0a6a1f1dSLionel Sambuc     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
2037*0a6a1f1dSLionel Sambuc     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
2038*0a6a1f1dSLionel Sambuc       GV->setConstant(true);
2039*0a6a1f1dSLionel Sambuc   }
2040*0a6a1f1dSLionel Sambuc 
2041f4a2713aSLionel Sambuc   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2042f4a2713aSLionel Sambuc 
2043f4a2713aSLionel Sambuc   // Set the llvm linkage type as appropriate.
2044f4a2713aSLionel Sambuc   llvm::GlobalValue::LinkageTypes Linkage =
2045*0a6a1f1dSLionel Sambuc       getLLVMLinkageVarDefinition(D, GV->isConstant());
2046f4a2713aSLionel Sambuc 
2047*0a6a1f1dSLionel Sambuc   // On Darwin, the backing variable for a C++11 thread_local variable always
2048*0a6a1f1dSLionel Sambuc   // has internal linkage; all accesses should just be calls to the
2049*0a6a1f1dSLionel Sambuc   // Itanium-specified entry point, which has the normal linkage of the
2050*0a6a1f1dSLionel Sambuc   // variable.
2051*0a6a1f1dSLionel Sambuc   if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
2052*0a6a1f1dSLionel Sambuc       Context.getTargetInfo().getTriple().isMacOSX())
2053*0a6a1f1dSLionel Sambuc     Linkage = llvm::GlobalValue::InternalLinkage;
2054*0a6a1f1dSLionel Sambuc 
2055*0a6a1f1dSLionel Sambuc   GV->setLinkage(Linkage);
2056*0a6a1f1dSLionel Sambuc   if (D->hasAttr<DLLImportAttr>())
2057*0a6a1f1dSLionel Sambuc     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2058*0a6a1f1dSLionel Sambuc   else if (D->hasAttr<DLLExportAttr>())
2059*0a6a1f1dSLionel Sambuc     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2060*0a6a1f1dSLionel Sambuc   else
2061*0a6a1f1dSLionel Sambuc     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2062f4a2713aSLionel Sambuc 
2063f4a2713aSLionel Sambuc   if (Linkage == llvm::GlobalVariable::CommonLinkage)
2064f4a2713aSLionel Sambuc     // common vars aren't constant even if declared const.
2065f4a2713aSLionel Sambuc     GV->setConstant(false);
2066f4a2713aSLionel Sambuc 
2067*0a6a1f1dSLionel Sambuc   setNonAliasAttributes(D, GV);
2068*0a6a1f1dSLionel Sambuc 
2069*0a6a1f1dSLionel Sambuc   if (D->getTLSKind() && !GV->isThreadLocal()) {
2070*0a6a1f1dSLionel Sambuc     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2071*0a6a1f1dSLionel Sambuc       CXXThreadLocals.push_back(std::make_pair(D, GV));
2072*0a6a1f1dSLionel Sambuc     setTLSMode(GV, *D);
2073*0a6a1f1dSLionel Sambuc   }
2074f4a2713aSLionel Sambuc 
2075f4a2713aSLionel Sambuc   // Emit the initializer function if necessary.
2076f4a2713aSLionel Sambuc   if (NeedsGlobalCtor || NeedsGlobalDtor)
2077f4a2713aSLionel Sambuc     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
2078f4a2713aSLionel Sambuc 
2079*0a6a1f1dSLionel Sambuc   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
2080f4a2713aSLionel Sambuc 
2081f4a2713aSLionel Sambuc   // Emit global variable debug information.
2082f4a2713aSLionel Sambuc   if (CGDebugInfo *DI = getModuleDebugInfo())
2083f4a2713aSLionel Sambuc     if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
2084f4a2713aSLionel Sambuc       DI->EmitGlobalVariable(GV, D);
2085f4a2713aSLionel Sambuc }
2086f4a2713aSLionel Sambuc 
isVarDeclStrongDefinition(const ASTContext & Context,const VarDecl * D,bool NoCommon)2087*0a6a1f1dSLionel Sambuc static bool isVarDeclStrongDefinition(const ASTContext &Context,
2088*0a6a1f1dSLionel Sambuc                                       const VarDecl *D, bool NoCommon) {
2089*0a6a1f1dSLionel Sambuc   // Don't give variables common linkage if -fno-common was specified unless it
2090*0a6a1f1dSLionel Sambuc   // was overridden by a NoCommon attribute.
2091*0a6a1f1dSLionel Sambuc   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
2092*0a6a1f1dSLionel Sambuc     return true;
2093*0a6a1f1dSLionel Sambuc 
2094*0a6a1f1dSLionel Sambuc   // C11 6.9.2/2:
2095*0a6a1f1dSLionel Sambuc   //   A declaration of an identifier for an object that has file scope without
2096*0a6a1f1dSLionel Sambuc   //   an initializer, and without a storage-class specifier or with the
2097*0a6a1f1dSLionel Sambuc   //   storage-class specifier static, constitutes a tentative definition.
2098*0a6a1f1dSLionel Sambuc   if (D->getInit() || D->hasExternalStorage())
2099*0a6a1f1dSLionel Sambuc     return true;
2100*0a6a1f1dSLionel Sambuc 
2101*0a6a1f1dSLionel Sambuc   // A variable cannot be both common and exist in a section.
2102*0a6a1f1dSLionel Sambuc   if (D->hasAttr<SectionAttr>())
2103*0a6a1f1dSLionel Sambuc     return true;
2104*0a6a1f1dSLionel Sambuc 
2105*0a6a1f1dSLionel Sambuc   // Thread local vars aren't considered common linkage.
2106*0a6a1f1dSLionel Sambuc   if (D->getTLSKind())
2107*0a6a1f1dSLionel Sambuc     return true;
2108*0a6a1f1dSLionel Sambuc 
2109*0a6a1f1dSLionel Sambuc   // Tentative definitions marked with WeakImportAttr are true definitions.
2110*0a6a1f1dSLionel Sambuc   if (D->hasAttr<WeakImportAttr>())
2111*0a6a1f1dSLionel Sambuc     return true;
2112*0a6a1f1dSLionel Sambuc 
2113*0a6a1f1dSLionel Sambuc   // Declarations with a required alignment do not have common linakge in MSVC
2114*0a6a1f1dSLionel Sambuc   // mode.
2115*0a6a1f1dSLionel Sambuc   if (Context.getLangOpts().MSVCCompat &&
2116*0a6a1f1dSLionel Sambuc       (Context.isAlignmentRequired(D->getType()) || D->hasAttr<AlignedAttr>()))
2117*0a6a1f1dSLionel Sambuc     return true;
2118*0a6a1f1dSLionel Sambuc 
2119*0a6a1f1dSLionel Sambuc   return false;
2120*0a6a1f1dSLionel Sambuc }
2121*0a6a1f1dSLionel Sambuc 
getLLVMLinkageForDeclarator(const DeclaratorDecl * D,GVALinkage Linkage,bool IsConstantVariable)2122*0a6a1f1dSLionel Sambuc llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
2123*0a6a1f1dSLionel Sambuc     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
2124f4a2713aSLionel Sambuc   if (Linkage == GVA_Internal)
2125f4a2713aSLionel Sambuc     return llvm::Function::InternalLinkage;
2126*0a6a1f1dSLionel Sambuc 
2127*0a6a1f1dSLionel Sambuc   if (D->hasAttr<WeakAttr>()) {
2128*0a6a1f1dSLionel Sambuc     if (IsConstantVariable)
2129*0a6a1f1dSLionel Sambuc       return llvm::GlobalVariable::WeakODRLinkage;
2130*0a6a1f1dSLionel Sambuc     else
2131*0a6a1f1dSLionel Sambuc       return llvm::GlobalVariable::WeakAnyLinkage;
2132*0a6a1f1dSLionel Sambuc   }
2133*0a6a1f1dSLionel Sambuc 
2134*0a6a1f1dSLionel Sambuc   // We are guaranteed to have a strong definition somewhere else,
2135*0a6a1f1dSLionel Sambuc   // so we can use available_externally linkage.
2136*0a6a1f1dSLionel Sambuc   if (Linkage == GVA_AvailableExternally)
2137*0a6a1f1dSLionel Sambuc     return llvm::Function::AvailableExternallyLinkage;
2138*0a6a1f1dSLionel Sambuc 
2139*0a6a1f1dSLionel Sambuc   // Note that Apple's kernel linker doesn't support symbol
2140*0a6a1f1dSLionel Sambuc   // coalescing, so we need to avoid linkonce and weak linkages there.
2141*0a6a1f1dSLionel Sambuc   // Normally, this means we just map to internal, but for explicit
2142*0a6a1f1dSLionel Sambuc   // instantiations we'll map to external.
2143*0a6a1f1dSLionel Sambuc 
2144*0a6a1f1dSLionel Sambuc   // In C++, the compiler has to emit a definition in every translation unit
2145*0a6a1f1dSLionel Sambuc   // that references the function.  We should use linkonce_odr because
2146*0a6a1f1dSLionel Sambuc   // a) if all references in this translation unit are optimized away, we
2147*0a6a1f1dSLionel Sambuc   // don't need to codegen it.  b) if the function persists, it needs to be
2148*0a6a1f1dSLionel Sambuc   // merged with other definitions. c) C++ has the ODR, so we know the
2149*0a6a1f1dSLionel Sambuc   // definition is dependable.
2150*0a6a1f1dSLionel Sambuc   if (Linkage == GVA_DiscardableODR)
2151*0a6a1f1dSLionel Sambuc     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
2152*0a6a1f1dSLionel Sambuc                                             : llvm::Function::InternalLinkage;
2153*0a6a1f1dSLionel Sambuc 
2154*0a6a1f1dSLionel Sambuc   // An explicit instantiation of a template has weak linkage, since
2155*0a6a1f1dSLionel Sambuc   // explicit instantiations can occur in multiple translation units
2156*0a6a1f1dSLionel Sambuc   // and must all be equivalent. However, we are not allowed to
2157*0a6a1f1dSLionel Sambuc   // throw away these explicit instantiations.
2158*0a6a1f1dSLionel Sambuc   if (Linkage == GVA_StrongODR)
2159*0a6a1f1dSLionel Sambuc     return !Context.getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage
2160*0a6a1f1dSLionel Sambuc                                             : llvm::Function::ExternalLinkage;
2161*0a6a1f1dSLionel Sambuc 
2162*0a6a1f1dSLionel Sambuc   // C++ doesn't have tentative definitions and thus cannot have common
2163*0a6a1f1dSLionel Sambuc   // linkage.
2164*0a6a1f1dSLionel Sambuc   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
2165*0a6a1f1dSLionel Sambuc       !isVarDeclStrongDefinition(Context, cast<VarDecl>(D),
2166*0a6a1f1dSLionel Sambuc                                  CodeGenOpts.NoCommon))
2167*0a6a1f1dSLionel Sambuc     return llvm::GlobalVariable::CommonLinkage;
2168*0a6a1f1dSLionel Sambuc 
2169f4a2713aSLionel Sambuc   // selectany symbols are externally visible, so use weak instead of
2170f4a2713aSLionel Sambuc   // linkonce.  MSVC optimizes away references to const selectany globals, so
2171f4a2713aSLionel Sambuc   // all definitions should be the same and ODR linkage should be used.
2172f4a2713aSLionel Sambuc   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
2173*0a6a1f1dSLionel Sambuc   if (D->hasAttr<SelectAnyAttr>())
2174f4a2713aSLionel Sambuc     return llvm::GlobalVariable::WeakODRLinkage;
2175*0a6a1f1dSLionel Sambuc 
2176*0a6a1f1dSLionel Sambuc   // Otherwise, we have strong external linkage.
2177*0a6a1f1dSLionel Sambuc   assert(Linkage == GVA_StrongExternal);
2178f4a2713aSLionel Sambuc   return llvm::GlobalVariable::ExternalLinkage;
2179f4a2713aSLionel Sambuc }
2180f4a2713aSLionel Sambuc 
getLLVMLinkageVarDefinition(const VarDecl * VD,bool IsConstant)2181*0a6a1f1dSLionel Sambuc llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
2182*0a6a1f1dSLionel Sambuc     const VarDecl *VD, bool IsConstant) {
2183*0a6a1f1dSLionel Sambuc   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
2184*0a6a1f1dSLionel Sambuc   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
2185*0a6a1f1dSLionel Sambuc }
2186*0a6a1f1dSLionel Sambuc 
2187f4a2713aSLionel Sambuc /// Replace the uses of a function that was declared with a non-proto type.
2188f4a2713aSLionel Sambuc /// We want to silently drop extra arguments from call sites
replaceUsesOfNonProtoConstant(llvm::Constant * old,llvm::Function * newFn)2189f4a2713aSLionel Sambuc static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2190f4a2713aSLionel Sambuc                                           llvm::Function *newFn) {
2191f4a2713aSLionel Sambuc   // Fast path.
2192f4a2713aSLionel Sambuc   if (old->use_empty()) return;
2193f4a2713aSLionel Sambuc 
2194f4a2713aSLionel Sambuc   llvm::Type *newRetTy = newFn->getReturnType();
2195f4a2713aSLionel Sambuc   SmallVector<llvm::Value*, 4> newArgs;
2196f4a2713aSLionel Sambuc 
2197f4a2713aSLionel Sambuc   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2198f4a2713aSLionel Sambuc          ui != ue; ) {
2199f4a2713aSLionel Sambuc     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
2200*0a6a1f1dSLionel Sambuc     llvm::User *user = use->getUser();
2201f4a2713aSLionel Sambuc 
2202f4a2713aSLionel Sambuc     // Recognize and replace uses of bitcasts.  Most calls to
2203f4a2713aSLionel Sambuc     // unprototyped functions will use bitcasts.
2204*0a6a1f1dSLionel Sambuc     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
2205f4a2713aSLionel Sambuc       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2206f4a2713aSLionel Sambuc         replaceUsesOfNonProtoConstant(bitcast, newFn);
2207f4a2713aSLionel Sambuc       continue;
2208f4a2713aSLionel Sambuc     }
2209f4a2713aSLionel Sambuc 
2210f4a2713aSLionel Sambuc     // Recognize calls to the function.
2211f4a2713aSLionel Sambuc     llvm::CallSite callSite(user);
2212f4a2713aSLionel Sambuc     if (!callSite) continue;
2213*0a6a1f1dSLionel Sambuc     if (!callSite.isCallee(&*use)) continue;
2214f4a2713aSLionel Sambuc 
2215f4a2713aSLionel Sambuc     // If the return types don't match exactly, then we can't
2216f4a2713aSLionel Sambuc     // transform this call unless it's dead.
2217f4a2713aSLionel Sambuc     if (callSite->getType() != newRetTy && !callSite->use_empty())
2218f4a2713aSLionel Sambuc       continue;
2219f4a2713aSLionel Sambuc 
2220f4a2713aSLionel Sambuc     // Get the call site's attribute list.
2221f4a2713aSLionel Sambuc     SmallVector<llvm::AttributeSet, 8> newAttrs;
2222f4a2713aSLionel Sambuc     llvm::AttributeSet oldAttrs = callSite.getAttributes();
2223f4a2713aSLionel Sambuc 
2224f4a2713aSLionel Sambuc     // Collect any return attributes from the call.
2225f4a2713aSLionel Sambuc     if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
2226f4a2713aSLionel Sambuc       newAttrs.push_back(
2227f4a2713aSLionel Sambuc         llvm::AttributeSet::get(newFn->getContext(),
2228f4a2713aSLionel Sambuc                                 oldAttrs.getRetAttributes()));
2229f4a2713aSLionel Sambuc 
2230f4a2713aSLionel Sambuc     // If the function was passed too few arguments, don't transform.
2231f4a2713aSLionel Sambuc     unsigned newNumArgs = newFn->arg_size();
2232f4a2713aSLionel Sambuc     if (callSite.arg_size() < newNumArgs) continue;
2233f4a2713aSLionel Sambuc 
2234f4a2713aSLionel Sambuc     // If extra arguments were passed, we silently drop them.
2235f4a2713aSLionel Sambuc     // If any of the types mismatch, we don't transform.
2236f4a2713aSLionel Sambuc     unsigned argNo = 0;
2237f4a2713aSLionel Sambuc     bool dontTransform = false;
2238f4a2713aSLionel Sambuc     for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
2239f4a2713aSLionel Sambuc            ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
2240f4a2713aSLionel Sambuc       if (callSite.getArgument(argNo)->getType() != ai->getType()) {
2241f4a2713aSLionel Sambuc         dontTransform = true;
2242f4a2713aSLionel Sambuc         break;
2243f4a2713aSLionel Sambuc       }
2244f4a2713aSLionel Sambuc 
2245f4a2713aSLionel Sambuc       // Add any parameter attributes.
2246f4a2713aSLionel Sambuc       if (oldAttrs.hasAttributes(argNo + 1))
2247f4a2713aSLionel Sambuc         newAttrs.
2248f4a2713aSLionel Sambuc           push_back(llvm::
2249f4a2713aSLionel Sambuc                     AttributeSet::get(newFn->getContext(),
2250f4a2713aSLionel Sambuc                                       oldAttrs.getParamAttributes(argNo + 1)));
2251f4a2713aSLionel Sambuc     }
2252f4a2713aSLionel Sambuc     if (dontTransform)
2253f4a2713aSLionel Sambuc       continue;
2254f4a2713aSLionel Sambuc 
2255f4a2713aSLionel Sambuc     if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
2256f4a2713aSLionel Sambuc       newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
2257f4a2713aSLionel Sambuc                                                  oldAttrs.getFnAttributes()));
2258f4a2713aSLionel Sambuc 
2259f4a2713aSLionel Sambuc     // Okay, we can transform this.  Create the new call instruction and copy
2260f4a2713aSLionel Sambuc     // over the required information.
2261f4a2713aSLionel Sambuc     newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2262f4a2713aSLionel Sambuc 
2263f4a2713aSLionel Sambuc     llvm::CallSite newCall;
2264f4a2713aSLionel Sambuc     if (callSite.isCall()) {
2265f4a2713aSLionel Sambuc       newCall = llvm::CallInst::Create(newFn, newArgs, "",
2266f4a2713aSLionel Sambuc                                        callSite.getInstruction());
2267f4a2713aSLionel Sambuc     } else {
2268*0a6a1f1dSLionel Sambuc       auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
2269f4a2713aSLionel Sambuc       newCall = llvm::InvokeInst::Create(newFn,
2270f4a2713aSLionel Sambuc                                          oldInvoke->getNormalDest(),
2271f4a2713aSLionel Sambuc                                          oldInvoke->getUnwindDest(),
2272f4a2713aSLionel Sambuc                                          newArgs, "",
2273f4a2713aSLionel Sambuc                                          callSite.getInstruction());
2274f4a2713aSLionel Sambuc     }
2275f4a2713aSLionel Sambuc     newArgs.clear(); // for the next iteration
2276f4a2713aSLionel Sambuc 
2277f4a2713aSLionel Sambuc     if (!newCall->getType()->isVoidTy())
2278f4a2713aSLionel Sambuc       newCall->takeName(callSite.getInstruction());
2279f4a2713aSLionel Sambuc     newCall.setAttributes(
2280f4a2713aSLionel Sambuc                      llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2281f4a2713aSLionel Sambuc     newCall.setCallingConv(callSite.getCallingConv());
2282f4a2713aSLionel Sambuc 
2283f4a2713aSLionel Sambuc     // Finally, remove the old call, replacing any uses with the new one.
2284f4a2713aSLionel Sambuc     if (!callSite->use_empty())
2285f4a2713aSLionel Sambuc       callSite->replaceAllUsesWith(newCall.getInstruction());
2286f4a2713aSLionel Sambuc 
2287f4a2713aSLionel Sambuc     // Copy debug location attached to CI.
2288f4a2713aSLionel Sambuc     if (!callSite->getDebugLoc().isUnknown())
2289f4a2713aSLionel Sambuc       newCall->setDebugLoc(callSite->getDebugLoc());
2290f4a2713aSLionel Sambuc     callSite->eraseFromParent();
2291f4a2713aSLionel Sambuc   }
2292f4a2713aSLionel Sambuc }
2293f4a2713aSLionel Sambuc 
2294f4a2713aSLionel Sambuc /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2295f4a2713aSLionel Sambuc /// implement a function with no prototype, e.g. "int foo() {}".  If there are
2296f4a2713aSLionel Sambuc /// existing call uses of the old function in the module, this adjusts them to
2297f4a2713aSLionel Sambuc /// call the new function directly.
2298f4a2713aSLionel Sambuc ///
2299f4a2713aSLionel Sambuc /// This is not just a cleanup: the always_inline pass requires direct calls to
2300f4a2713aSLionel Sambuc /// functions to be able to inline them.  If there is a bitcast in the way, it
2301f4a2713aSLionel Sambuc /// won't inline them.  Instcombine normally deletes these calls, but it isn't
2302f4a2713aSLionel Sambuc /// run at -O0.
ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue * Old,llvm::Function * NewFn)2303f4a2713aSLionel Sambuc static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2304f4a2713aSLionel Sambuc                                                       llvm::Function *NewFn) {
2305f4a2713aSLionel Sambuc   // If we're redefining a global as a function, don't transform it.
2306f4a2713aSLionel Sambuc   if (!isa<llvm::Function>(Old)) return;
2307f4a2713aSLionel Sambuc 
2308f4a2713aSLionel Sambuc   replaceUsesOfNonProtoConstant(Old, NewFn);
2309f4a2713aSLionel Sambuc }
2310f4a2713aSLionel Sambuc 
HandleCXXStaticMemberVarInstantiation(VarDecl * VD)2311f4a2713aSLionel Sambuc void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2312f4a2713aSLionel Sambuc   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2313f4a2713aSLionel Sambuc   // If we have a definition, this might be a deferred decl. If the
2314f4a2713aSLionel Sambuc   // instantiation is explicit, make sure we emit it at the end.
2315f4a2713aSLionel Sambuc   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2316f4a2713aSLionel Sambuc     GetAddrOfGlobalVar(VD);
2317f4a2713aSLionel Sambuc 
2318f4a2713aSLionel Sambuc   EmitTopLevelDecl(VD);
2319f4a2713aSLionel Sambuc }
2320f4a2713aSLionel Sambuc 
EmitGlobalFunctionDefinition(GlobalDecl GD,llvm::GlobalValue * GV)2321*0a6a1f1dSLionel Sambuc void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
2322*0a6a1f1dSLionel Sambuc                                                  llvm::GlobalValue *GV) {
2323*0a6a1f1dSLionel Sambuc   const auto *D = cast<FunctionDecl>(GD.getDecl());
2324f4a2713aSLionel Sambuc 
2325f4a2713aSLionel Sambuc   // Compute the function info and LLVM type.
2326f4a2713aSLionel Sambuc   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2327f4a2713aSLionel Sambuc   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2328f4a2713aSLionel Sambuc 
2329f4a2713aSLionel Sambuc   // Get or create the prototype for the function.
2330*0a6a1f1dSLionel Sambuc   if (!GV) {
2331*0a6a1f1dSLionel Sambuc     llvm::Constant *C =
2332*0a6a1f1dSLionel Sambuc         GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer*/ true);
2333f4a2713aSLionel Sambuc 
2334f4a2713aSLionel Sambuc     // Strip off a bitcast if we got one back.
2335*0a6a1f1dSLionel Sambuc     if (auto *CE = dyn_cast<llvm::ConstantExpr>(C)) {
2336f4a2713aSLionel Sambuc       assert(CE->getOpcode() == llvm::Instruction::BitCast);
2337*0a6a1f1dSLionel Sambuc       GV = cast<llvm::GlobalValue>(CE->getOperand(0));
2338*0a6a1f1dSLionel Sambuc     } else {
2339*0a6a1f1dSLionel Sambuc       GV = cast<llvm::GlobalValue>(C);
2340*0a6a1f1dSLionel Sambuc     }
2341f4a2713aSLionel Sambuc   }
2342f4a2713aSLionel Sambuc 
2343*0a6a1f1dSLionel Sambuc   if (!GV->isDeclaration()) {
2344f4a2713aSLionel Sambuc     getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name);
2345*0a6a1f1dSLionel Sambuc     GlobalDecl OldGD = Manglings.lookup(GV->getName());
2346*0a6a1f1dSLionel Sambuc     if (auto *Prev = OldGD.getDecl())
2347*0a6a1f1dSLionel Sambuc       getDiags().Report(Prev->getLocation(), diag::note_previous_definition);
2348f4a2713aSLionel Sambuc     return;
2349f4a2713aSLionel Sambuc   }
2350f4a2713aSLionel Sambuc 
2351*0a6a1f1dSLionel Sambuc   if (GV->getType()->getElementType() != Ty) {
2352f4a2713aSLionel Sambuc     // If the types mismatch then we have to rewrite the definition.
2353*0a6a1f1dSLionel Sambuc     assert(GV->isDeclaration() && "Shouldn't replace non-declaration");
2354f4a2713aSLionel Sambuc 
2355f4a2713aSLionel Sambuc     // F is the Function* for the one with the wrong type, we must make a new
2356f4a2713aSLionel Sambuc     // Function* and update everything that used F (a declaration) with the new
2357f4a2713aSLionel Sambuc     // Function* (which will be a definition).
2358f4a2713aSLionel Sambuc     //
2359f4a2713aSLionel Sambuc     // This happens if there is a prototype for a function
2360f4a2713aSLionel Sambuc     // (e.g. "int f()") and then a definition of a different type
2361f4a2713aSLionel Sambuc     // (e.g. "int f(int x)").  Move the old function aside so that it
2362f4a2713aSLionel Sambuc     // doesn't interfere with GetAddrOfFunction.
2363*0a6a1f1dSLionel Sambuc     GV->setName(StringRef());
2364*0a6a1f1dSLionel Sambuc     auto *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
2365f4a2713aSLionel Sambuc 
2366f4a2713aSLionel Sambuc     // This might be an implementation of a function without a
2367f4a2713aSLionel Sambuc     // prototype, in which case, try to do special replacement of
2368f4a2713aSLionel Sambuc     // calls which match the new prototype.  The really key thing here
2369f4a2713aSLionel Sambuc     // is that we also potentially drop arguments from the call site
2370f4a2713aSLionel Sambuc     // so as to make a direct call, which makes the inliner happier
2371f4a2713aSLionel Sambuc     // and suppresses a number of optimizer warnings (!) about
2372f4a2713aSLionel Sambuc     // dropping arguments.
2373*0a6a1f1dSLionel Sambuc     if (!GV->use_empty()) {
2374*0a6a1f1dSLionel Sambuc       ReplaceUsesOfNonProtoTypeWithRealFunction(GV, NewFn);
2375*0a6a1f1dSLionel Sambuc       GV->removeDeadConstantUsers();
2376f4a2713aSLionel Sambuc     }
2377f4a2713aSLionel Sambuc 
2378f4a2713aSLionel Sambuc     // Replace uses of F with the Function we will endow with a body.
2379*0a6a1f1dSLionel Sambuc     if (!GV->use_empty()) {
2380f4a2713aSLionel Sambuc       llvm::Constant *NewPtrForOldDecl =
2381*0a6a1f1dSLionel Sambuc           llvm::ConstantExpr::getBitCast(NewFn, GV->getType());
2382*0a6a1f1dSLionel Sambuc       GV->replaceAllUsesWith(NewPtrForOldDecl);
2383f4a2713aSLionel Sambuc     }
2384f4a2713aSLionel Sambuc 
2385f4a2713aSLionel Sambuc     // Ok, delete the old function now, which is dead.
2386*0a6a1f1dSLionel Sambuc     GV->eraseFromParent();
2387f4a2713aSLionel Sambuc 
2388*0a6a1f1dSLionel Sambuc     GV = NewFn;
2389f4a2713aSLionel Sambuc   }
2390f4a2713aSLionel Sambuc 
2391f4a2713aSLionel Sambuc   // We need to set linkage and visibility on the function before
2392f4a2713aSLionel Sambuc   // generating code for it because various parts of IR generation
2393f4a2713aSLionel Sambuc   // want to propagate this information down (e.g. to local static
2394f4a2713aSLionel Sambuc   // declarations).
2395*0a6a1f1dSLionel Sambuc   auto *Fn = cast<llvm::Function>(GV);
2396f4a2713aSLionel Sambuc   setFunctionLinkage(GD, Fn);
2397*0a6a1f1dSLionel Sambuc   if (D->hasAttr<DLLImportAttr>())
2398*0a6a1f1dSLionel Sambuc     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2399*0a6a1f1dSLionel Sambuc   else if (D->hasAttr<DLLExportAttr>())
2400*0a6a1f1dSLionel Sambuc     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2401*0a6a1f1dSLionel Sambuc   else
2402*0a6a1f1dSLionel Sambuc     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2403f4a2713aSLionel Sambuc 
2404*0a6a1f1dSLionel Sambuc   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
2405f4a2713aSLionel Sambuc   setGlobalVisibility(Fn, D);
2406f4a2713aSLionel Sambuc 
2407f4a2713aSLionel Sambuc   MaybeHandleStaticInExternC(D, Fn);
2408f4a2713aSLionel Sambuc 
2409f4a2713aSLionel Sambuc   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
2410f4a2713aSLionel Sambuc 
2411*0a6a1f1dSLionel Sambuc   setFunctionDefinitionAttributes(D, Fn);
2412f4a2713aSLionel Sambuc   SetLLVMFunctionAttributesForDefinition(D, Fn);
2413f4a2713aSLionel Sambuc 
2414f4a2713aSLionel Sambuc   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
2415f4a2713aSLionel Sambuc     AddGlobalCtor(Fn, CA->getPriority());
2416f4a2713aSLionel Sambuc   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
2417f4a2713aSLionel Sambuc     AddGlobalDtor(Fn, DA->getPriority());
2418f4a2713aSLionel Sambuc   if (D->hasAttr<AnnotateAttr>())
2419f4a2713aSLionel Sambuc     AddGlobalAnnotations(D, Fn);
2420f4a2713aSLionel Sambuc }
2421f4a2713aSLionel Sambuc 
EmitAliasDefinition(GlobalDecl GD)2422f4a2713aSLionel Sambuc void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
2423*0a6a1f1dSLionel Sambuc   const auto *D = cast<ValueDecl>(GD.getDecl());
2424f4a2713aSLionel Sambuc   const AliasAttr *AA = D->getAttr<AliasAttr>();
2425f4a2713aSLionel Sambuc   assert(AA && "Not an alias?");
2426f4a2713aSLionel Sambuc 
2427f4a2713aSLionel Sambuc   StringRef MangledName = getMangledName(GD);
2428f4a2713aSLionel Sambuc 
2429f4a2713aSLionel Sambuc   // If there is a definition in the module, then it wins over the alias.
2430f4a2713aSLionel Sambuc   // This is dubious, but allow it to be safe.  Just ignore the alias.
2431f4a2713aSLionel Sambuc   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2432f4a2713aSLionel Sambuc   if (Entry && !Entry->isDeclaration())
2433f4a2713aSLionel Sambuc     return;
2434f4a2713aSLionel Sambuc 
2435f4a2713aSLionel Sambuc   Aliases.push_back(GD);
2436f4a2713aSLionel Sambuc 
2437f4a2713aSLionel Sambuc   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
2438f4a2713aSLionel Sambuc 
2439f4a2713aSLionel Sambuc   // Create a reference to the named value.  This ensures that it is emitted
2440f4a2713aSLionel Sambuc   // if a deferred decl.
2441f4a2713aSLionel Sambuc   llvm::Constant *Aliasee;
2442f4a2713aSLionel Sambuc   if (isa<llvm::FunctionType>(DeclTy))
2443f4a2713aSLionel Sambuc     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
2444f4a2713aSLionel Sambuc                                       /*ForVTable=*/false);
2445f4a2713aSLionel Sambuc   else
2446f4a2713aSLionel Sambuc     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2447*0a6a1f1dSLionel Sambuc                                     llvm::PointerType::getUnqual(DeclTy),
2448*0a6a1f1dSLionel Sambuc                                     /*D=*/nullptr);
2449f4a2713aSLionel Sambuc 
2450f4a2713aSLionel Sambuc   // Create the new alias itself, but don't set a name yet.
2451*0a6a1f1dSLionel Sambuc   auto *GA = llvm::GlobalAlias::create(
2452*0a6a1f1dSLionel Sambuc       cast<llvm::PointerType>(Aliasee->getType())->getElementType(), 0,
2453*0a6a1f1dSLionel Sambuc       llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
2454f4a2713aSLionel Sambuc 
2455f4a2713aSLionel Sambuc   if (Entry) {
2456*0a6a1f1dSLionel Sambuc     if (GA->getAliasee() == Entry) {
2457*0a6a1f1dSLionel Sambuc       Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
2458*0a6a1f1dSLionel Sambuc       return;
2459*0a6a1f1dSLionel Sambuc     }
2460*0a6a1f1dSLionel Sambuc 
2461f4a2713aSLionel Sambuc     assert(Entry->isDeclaration());
2462f4a2713aSLionel Sambuc 
2463f4a2713aSLionel Sambuc     // If there is a declaration in the module, then we had an extern followed
2464f4a2713aSLionel Sambuc     // by the alias, as in:
2465f4a2713aSLionel Sambuc     //   extern int test6();
2466f4a2713aSLionel Sambuc     //   ...
2467f4a2713aSLionel Sambuc     //   int test6() __attribute__((alias("test7")));
2468f4a2713aSLionel Sambuc     //
2469f4a2713aSLionel Sambuc     // Remove it and replace uses of it with the alias.
2470f4a2713aSLionel Sambuc     GA->takeName(Entry);
2471f4a2713aSLionel Sambuc 
2472f4a2713aSLionel Sambuc     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
2473f4a2713aSLionel Sambuc                                                           Entry->getType()));
2474f4a2713aSLionel Sambuc     Entry->eraseFromParent();
2475f4a2713aSLionel Sambuc   } else {
2476f4a2713aSLionel Sambuc     GA->setName(MangledName);
2477f4a2713aSLionel Sambuc   }
2478f4a2713aSLionel Sambuc 
2479f4a2713aSLionel Sambuc   // Set attributes which are particular to an alias; this is a
2480f4a2713aSLionel Sambuc   // specialization of the attributes which may be set on a global
2481f4a2713aSLionel Sambuc   // variable/function.
2482*0a6a1f1dSLionel Sambuc   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
2483f4a2713aSLionel Sambuc       D->isWeakImported()) {
2484f4a2713aSLionel Sambuc     GA->setLinkage(llvm::Function::WeakAnyLinkage);
2485f4a2713aSLionel Sambuc   }
2486f4a2713aSLionel Sambuc 
2487*0a6a1f1dSLionel Sambuc   if (const auto *VD = dyn_cast<VarDecl>(D))
2488*0a6a1f1dSLionel Sambuc     if (VD->getTLSKind())
2489*0a6a1f1dSLionel Sambuc       setTLSMode(GA, *VD);
2490*0a6a1f1dSLionel Sambuc 
2491*0a6a1f1dSLionel Sambuc   setAliasAttributes(D, GA);
2492f4a2713aSLionel Sambuc }
2493f4a2713aSLionel Sambuc 
getIntrinsic(unsigned IID,ArrayRef<llvm::Type * > Tys)2494f4a2713aSLionel Sambuc llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
2495f4a2713aSLionel Sambuc                                             ArrayRef<llvm::Type*> Tys) {
2496f4a2713aSLionel Sambuc   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
2497f4a2713aSLionel Sambuc                                          Tys);
2498f4a2713aSLionel Sambuc }
2499f4a2713aSLionel Sambuc 
2500f4a2713aSLionel Sambuc static llvm::StringMapEntry<llvm::Constant*> &
GetConstantCFStringEntry(llvm::StringMap<llvm::Constant * > & Map,const StringLiteral * Literal,bool TargetIsLSB,bool & IsUTF16,unsigned & StringLength)2501f4a2713aSLionel Sambuc GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2502f4a2713aSLionel Sambuc                          const StringLiteral *Literal,
2503f4a2713aSLionel Sambuc                          bool TargetIsLSB,
2504f4a2713aSLionel Sambuc                          bool &IsUTF16,
2505f4a2713aSLionel Sambuc                          unsigned &StringLength) {
2506f4a2713aSLionel Sambuc   StringRef String = Literal->getString();
2507f4a2713aSLionel Sambuc   unsigned NumBytes = String.size();
2508f4a2713aSLionel Sambuc 
2509f4a2713aSLionel Sambuc   // Check for simple case.
2510f4a2713aSLionel Sambuc   if (!Literal->containsNonAsciiOrNull()) {
2511f4a2713aSLionel Sambuc     StringLength = NumBytes;
2512*0a6a1f1dSLionel Sambuc     return *Map.insert(std::make_pair(String, nullptr)).first;
2513f4a2713aSLionel Sambuc   }
2514f4a2713aSLionel Sambuc 
2515f4a2713aSLionel Sambuc   // Otherwise, convert the UTF8 literals into a string of shorts.
2516f4a2713aSLionel Sambuc   IsUTF16 = true;
2517f4a2713aSLionel Sambuc 
2518f4a2713aSLionel Sambuc   SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
2519f4a2713aSLionel Sambuc   const UTF8 *FromPtr = (const UTF8 *)String.data();
2520f4a2713aSLionel Sambuc   UTF16 *ToPtr = &ToBuf[0];
2521f4a2713aSLionel Sambuc 
2522f4a2713aSLionel Sambuc   (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2523f4a2713aSLionel Sambuc                            &ToPtr, ToPtr + NumBytes,
2524f4a2713aSLionel Sambuc                            strictConversion);
2525f4a2713aSLionel Sambuc 
2526f4a2713aSLionel Sambuc   // ConvertUTF8toUTF16 returns the length in ToPtr.
2527f4a2713aSLionel Sambuc   StringLength = ToPtr - &ToBuf[0];
2528f4a2713aSLionel Sambuc 
2529f4a2713aSLionel Sambuc   // Add an explicit null.
2530f4a2713aSLionel Sambuc   *ToPtr = 0;
2531*0a6a1f1dSLionel Sambuc   return *Map.insert(std::make_pair(
2532*0a6a1f1dSLionel Sambuc                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2533*0a6a1f1dSLionel Sambuc                                    (StringLength + 1) * 2),
2534*0a6a1f1dSLionel Sambuc                          nullptr)).first;
2535f4a2713aSLionel Sambuc }
2536f4a2713aSLionel Sambuc 
2537f4a2713aSLionel Sambuc static llvm::StringMapEntry<llvm::Constant*> &
GetConstantStringEntry(llvm::StringMap<llvm::Constant * > & Map,const StringLiteral * Literal,unsigned & StringLength)2538f4a2713aSLionel Sambuc GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2539f4a2713aSLionel Sambuc                        const StringLiteral *Literal,
2540f4a2713aSLionel Sambuc                        unsigned &StringLength) {
2541f4a2713aSLionel Sambuc   StringRef String = Literal->getString();
2542f4a2713aSLionel Sambuc   StringLength = String.size();
2543*0a6a1f1dSLionel Sambuc   return *Map.insert(std::make_pair(String, nullptr)).first;
2544f4a2713aSLionel Sambuc }
2545f4a2713aSLionel Sambuc 
2546f4a2713aSLionel Sambuc llvm::Constant *
GetAddrOfConstantCFString(const StringLiteral * Literal)2547f4a2713aSLionel Sambuc CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2548f4a2713aSLionel Sambuc   unsigned StringLength = 0;
2549f4a2713aSLionel Sambuc   bool isUTF16 = false;
2550f4a2713aSLionel Sambuc   llvm::StringMapEntry<llvm::Constant*> &Entry =
2551f4a2713aSLionel Sambuc     GetConstantCFStringEntry(CFConstantStringMap, Literal,
2552f4a2713aSLionel Sambuc                              getDataLayout().isLittleEndian(),
2553f4a2713aSLionel Sambuc                              isUTF16, StringLength);
2554f4a2713aSLionel Sambuc 
2555*0a6a1f1dSLionel Sambuc   if (auto *C = Entry.second)
2556f4a2713aSLionel Sambuc     return C;
2557f4a2713aSLionel Sambuc 
2558f4a2713aSLionel Sambuc   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2559f4a2713aSLionel Sambuc   llvm::Constant *Zeros[] = { Zero, Zero };
2560f4a2713aSLionel Sambuc   llvm::Value *V;
2561f4a2713aSLionel Sambuc 
2562f4a2713aSLionel Sambuc   // If we don't already have it, get __CFConstantStringClassReference.
2563f4a2713aSLionel Sambuc   if (!CFConstantStringClassRef) {
2564f4a2713aSLionel Sambuc     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2565f4a2713aSLionel Sambuc     Ty = llvm::ArrayType::get(Ty, 0);
2566f4a2713aSLionel Sambuc     llvm::Constant *GV = CreateRuntimeVariable(Ty,
2567f4a2713aSLionel Sambuc                                            "__CFConstantStringClassReference");
2568f4a2713aSLionel Sambuc     // Decay array -> ptr
2569f4a2713aSLionel Sambuc     V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2570f4a2713aSLionel Sambuc     CFConstantStringClassRef = V;
2571f4a2713aSLionel Sambuc   }
2572f4a2713aSLionel Sambuc   else
2573f4a2713aSLionel Sambuc     V = CFConstantStringClassRef;
2574f4a2713aSLionel Sambuc 
2575f4a2713aSLionel Sambuc   QualType CFTy = getContext().getCFConstantStringType();
2576f4a2713aSLionel Sambuc 
2577*0a6a1f1dSLionel Sambuc   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2578f4a2713aSLionel Sambuc 
2579f4a2713aSLionel Sambuc   llvm::Constant *Fields[4];
2580f4a2713aSLionel Sambuc 
2581f4a2713aSLionel Sambuc   // Class pointer.
2582f4a2713aSLionel Sambuc   Fields[0] = cast<llvm::ConstantExpr>(V);
2583f4a2713aSLionel Sambuc 
2584f4a2713aSLionel Sambuc   // Flags.
2585f4a2713aSLionel Sambuc   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2586f4a2713aSLionel Sambuc   Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
2587f4a2713aSLionel Sambuc     llvm::ConstantInt::get(Ty, 0x07C8);
2588f4a2713aSLionel Sambuc 
2589f4a2713aSLionel Sambuc   // String pointer.
2590*0a6a1f1dSLionel Sambuc   llvm::Constant *C = nullptr;
2591f4a2713aSLionel Sambuc   if (isUTF16) {
2592*0a6a1f1dSLionel Sambuc     ArrayRef<uint16_t> Arr = llvm::makeArrayRef<uint16_t>(
2593*0a6a1f1dSLionel Sambuc         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
2594*0a6a1f1dSLionel Sambuc         Entry.first().size() / 2);
2595f4a2713aSLionel Sambuc     C = llvm::ConstantDataArray::get(VMContext, Arr);
2596f4a2713aSLionel Sambuc   } else {
2597*0a6a1f1dSLionel Sambuc     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
2598f4a2713aSLionel Sambuc   }
2599f4a2713aSLionel Sambuc 
2600f4a2713aSLionel Sambuc   // Note: -fwritable-strings doesn't make the backing store strings of
2601f4a2713aSLionel Sambuc   // CFStrings writable. (See <rdar://problem/10657500>)
2602*0a6a1f1dSLionel Sambuc   auto *GV =
2603f4a2713aSLionel Sambuc       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2604*0a6a1f1dSLionel Sambuc                                llvm::GlobalValue::PrivateLinkage, C, ".str");
2605f4a2713aSLionel Sambuc   GV->setUnnamedAddr(true);
2606f4a2713aSLionel Sambuc   // Don't enforce the target's minimum global alignment, since the only use
2607f4a2713aSLionel Sambuc   // of the string is via this class initializer.
2608*0a6a1f1dSLionel Sambuc   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without
2609*0a6a1f1dSLionel Sambuc   // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing
2610*0a6a1f1dSLionel Sambuc   // that changes the section it ends in, which surprises ld64.
2611f4a2713aSLionel Sambuc   if (isUTF16) {
2612f4a2713aSLionel Sambuc     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2613f4a2713aSLionel Sambuc     GV->setAlignment(Align.getQuantity());
2614*0a6a1f1dSLionel Sambuc     GV->setSection("__TEXT,__ustring");
2615f4a2713aSLionel Sambuc   } else {
2616f4a2713aSLionel Sambuc     CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2617f4a2713aSLionel Sambuc     GV->setAlignment(Align.getQuantity());
2618*0a6a1f1dSLionel Sambuc     GV->setSection("__TEXT,__cstring,cstring_literals");
2619f4a2713aSLionel Sambuc   }
2620f4a2713aSLionel Sambuc 
2621f4a2713aSLionel Sambuc   // String.
2622f4a2713aSLionel Sambuc   Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2623f4a2713aSLionel Sambuc 
2624f4a2713aSLionel Sambuc   if (isUTF16)
2625f4a2713aSLionel Sambuc     // Cast the UTF16 string to the correct type.
2626f4a2713aSLionel Sambuc     Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2627f4a2713aSLionel Sambuc 
2628f4a2713aSLionel Sambuc   // String length.
2629f4a2713aSLionel Sambuc   Ty = getTypes().ConvertType(getContext().LongTy);
2630f4a2713aSLionel Sambuc   Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
2631f4a2713aSLionel Sambuc 
2632f4a2713aSLionel Sambuc   // The struct.
2633f4a2713aSLionel Sambuc   C = llvm::ConstantStruct::get(STy, Fields);
2634f4a2713aSLionel Sambuc   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2635f4a2713aSLionel Sambuc                                 llvm::GlobalVariable::PrivateLinkage, C,
2636f4a2713aSLionel Sambuc                                 "_unnamed_cfstring_");
2637*0a6a1f1dSLionel Sambuc   GV->setSection("__DATA,__cfstring");
2638*0a6a1f1dSLionel Sambuc   Entry.second = GV;
2639f4a2713aSLionel Sambuc 
2640f4a2713aSLionel Sambuc   return GV;
2641f4a2713aSLionel Sambuc }
2642f4a2713aSLionel Sambuc 
2643f4a2713aSLionel Sambuc llvm::Constant *
GetAddrOfConstantString(const StringLiteral * Literal)2644f4a2713aSLionel Sambuc CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
2645f4a2713aSLionel Sambuc   unsigned StringLength = 0;
2646f4a2713aSLionel Sambuc   llvm::StringMapEntry<llvm::Constant*> &Entry =
2647f4a2713aSLionel Sambuc     GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
2648f4a2713aSLionel Sambuc 
2649*0a6a1f1dSLionel Sambuc   if (auto *C = Entry.second)
2650f4a2713aSLionel Sambuc     return C;
2651f4a2713aSLionel Sambuc 
2652f4a2713aSLionel Sambuc   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2653f4a2713aSLionel Sambuc   llvm::Constant *Zeros[] = { Zero, Zero };
2654f4a2713aSLionel Sambuc   llvm::Value *V;
2655f4a2713aSLionel Sambuc   // If we don't already have it, get _NSConstantStringClassReference.
2656f4a2713aSLionel Sambuc   if (!ConstantStringClassRef) {
2657f4a2713aSLionel Sambuc     std::string StringClass(getLangOpts().ObjCConstantStringClass);
2658f4a2713aSLionel Sambuc     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2659f4a2713aSLionel Sambuc     llvm::Constant *GV;
2660f4a2713aSLionel Sambuc     if (LangOpts.ObjCRuntime.isNonFragile()) {
2661f4a2713aSLionel Sambuc       std::string str =
2662f4a2713aSLionel Sambuc         StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2663f4a2713aSLionel Sambuc                             : "OBJC_CLASS_$_" + StringClass;
2664f4a2713aSLionel Sambuc       GV = getObjCRuntime().GetClassGlobal(str);
2665f4a2713aSLionel Sambuc       // Make sure the result is of the correct type.
2666f4a2713aSLionel Sambuc       llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2667f4a2713aSLionel Sambuc       V = llvm::ConstantExpr::getBitCast(GV, PTy);
2668f4a2713aSLionel Sambuc       ConstantStringClassRef = V;
2669f4a2713aSLionel Sambuc     } else {
2670f4a2713aSLionel Sambuc       std::string str =
2671f4a2713aSLionel Sambuc         StringClass.empty() ? "_NSConstantStringClassReference"
2672f4a2713aSLionel Sambuc                             : "_" + StringClass + "ClassReference";
2673f4a2713aSLionel Sambuc       llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
2674f4a2713aSLionel Sambuc       GV = CreateRuntimeVariable(PTy, str);
2675f4a2713aSLionel Sambuc       // Decay array -> ptr
2676f4a2713aSLionel Sambuc       V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2677f4a2713aSLionel Sambuc       ConstantStringClassRef = V;
2678f4a2713aSLionel Sambuc     }
2679f4a2713aSLionel Sambuc   }
2680f4a2713aSLionel Sambuc   else
2681f4a2713aSLionel Sambuc     V = ConstantStringClassRef;
2682f4a2713aSLionel Sambuc 
2683f4a2713aSLionel Sambuc   if (!NSConstantStringType) {
2684f4a2713aSLionel Sambuc     // Construct the type for a constant NSString.
2685*0a6a1f1dSLionel Sambuc     RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString");
2686f4a2713aSLionel Sambuc     D->startDefinition();
2687f4a2713aSLionel Sambuc 
2688f4a2713aSLionel Sambuc     QualType FieldTypes[3];
2689f4a2713aSLionel Sambuc 
2690f4a2713aSLionel Sambuc     // const int *isa;
2691f4a2713aSLionel Sambuc     FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2692f4a2713aSLionel Sambuc     // const char *str;
2693f4a2713aSLionel Sambuc     FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2694f4a2713aSLionel Sambuc     // unsigned int length;
2695f4a2713aSLionel Sambuc     FieldTypes[2] = Context.UnsignedIntTy;
2696f4a2713aSLionel Sambuc 
2697f4a2713aSLionel Sambuc     // Create fields
2698f4a2713aSLionel Sambuc     for (unsigned i = 0; i < 3; ++i) {
2699f4a2713aSLionel Sambuc       FieldDecl *Field = FieldDecl::Create(Context, D,
2700f4a2713aSLionel Sambuc                                            SourceLocation(),
2701*0a6a1f1dSLionel Sambuc                                            SourceLocation(), nullptr,
2702*0a6a1f1dSLionel Sambuc                                            FieldTypes[i], /*TInfo=*/nullptr,
2703*0a6a1f1dSLionel Sambuc                                            /*BitWidth=*/nullptr,
2704f4a2713aSLionel Sambuc                                            /*Mutable=*/false,
2705f4a2713aSLionel Sambuc                                            ICIS_NoInit);
2706f4a2713aSLionel Sambuc       Field->setAccess(AS_public);
2707f4a2713aSLionel Sambuc       D->addDecl(Field);
2708f4a2713aSLionel Sambuc     }
2709f4a2713aSLionel Sambuc 
2710f4a2713aSLionel Sambuc     D->completeDefinition();
2711f4a2713aSLionel Sambuc     QualType NSTy = Context.getTagDeclType(D);
2712f4a2713aSLionel Sambuc     NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2713f4a2713aSLionel Sambuc   }
2714f4a2713aSLionel Sambuc 
2715f4a2713aSLionel Sambuc   llvm::Constant *Fields[3];
2716f4a2713aSLionel Sambuc 
2717f4a2713aSLionel Sambuc   // Class pointer.
2718f4a2713aSLionel Sambuc   Fields[0] = cast<llvm::ConstantExpr>(V);
2719f4a2713aSLionel Sambuc 
2720f4a2713aSLionel Sambuc   // String pointer.
2721f4a2713aSLionel Sambuc   llvm::Constant *C =
2722*0a6a1f1dSLionel Sambuc       llvm::ConstantDataArray::getString(VMContext, Entry.first());
2723f4a2713aSLionel Sambuc 
2724f4a2713aSLionel Sambuc   llvm::GlobalValue::LinkageTypes Linkage;
2725f4a2713aSLionel Sambuc   bool isConstant;
2726f4a2713aSLionel Sambuc   Linkage = llvm::GlobalValue::PrivateLinkage;
2727f4a2713aSLionel Sambuc   isConstant = !LangOpts.WritableStrings;
2728f4a2713aSLionel Sambuc 
2729*0a6a1f1dSLionel Sambuc   auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant,
2730*0a6a1f1dSLionel Sambuc                                       Linkage, C, ".str");
2731f4a2713aSLionel Sambuc   GV->setUnnamedAddr(true);
2732f4a2713aSLionel Sambuc   // Don't enforce the target's minimum global alignment, since the only use
2733f4a2713aSLionel Sambuc   // of the string is via this class initializer.
2734f4a2713aSLionel Sambuc   CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2735f4a2713aSLionel Sambuc   GV->setAlignment(Align.getQuantity());
2736f4a2713aSLionel Sambuc   Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2737f4a2713aSLionel Sambuc 
2738f4a2713aSLionel Sambuc   // String length.
2739f4a2713aSLionel Sambuc   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2740f4a2713aSLionel Sambuc   Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2741f4a2713aSLionel Sambuc 
2742f4a2713aSLionel Sambuc   // The struct.
2743f4a2713aSLionel Sambuc   C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
2744f4a2713aSLionel Sambuc   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2745f4a2713aSLionel Sambuc                                 llvm::GlobalVariable::PrivateLinkage, C,
2746f4a2713aSLionel Sambuc                                 "_unnamed_nsstring_");
2747*0a6a1f1dSLionel Sambuc   const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";
2748*0a6a1f1dSLionel Sambuc   const char *NSStringNonFragileABISection =
2749*0a6a1f1dSLionel Sambuc       "__DATA,__objc_stringobj,regular,no_dead_strip";
2750f4a2713aSLionel Sambuc   // FIXME. Fix section.
2751*0a6a1f1dSLionel Sambuc   GV->setSection(LangOpts.ObjCRuntime.isNonFragile()
2752*0a6a1f1dSLionel Sambuc                      ? NSStringNonFragileABISection
2753*0a6a1f1dSLionel Sambuc                      : NSStringSection);
2754*0a6a1f1dSLionel Sambuc   Entry.second = GV;
2755f4a2713aSLionel Sambuc 
2756f4a2713aSLionel Sambuc   return GV;
2757f4a2713aSLionel Sambuc }
2758f4a2713aSLionel Sambuc 
getObjCFastEnumerationStateType()2759f4a2713aSLionel Sambuc QualType CodeGenModule::getObjCFastEnumerationStateType() {
2760f4a2713aSLionel Sambuc   if (ObjCFastEnumerationStateType.isNull()) {
2761*0a6a1f1dSLionel Sambuc     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
2762f4a2713aSLionel Sambuc     D->startDefinition();
2763f4a2713aSLionel Sambuc 
2764f4a2713aSLionel Sambuc     QualType FieldTypes[] = {
2765f4a2713aSLionel Sambuc       Context.UnsignedLongTy,
2766f4a2713aSLionel Sambuc       Context.getPointerType(Context.getObjCIdType()),
2767f4a2713aSLionel Sambuc       Context.getPointerType(Context.UnsignedLongTy),
2768f4a2713aSLionel Sambuc       Context.getConstantArrayType(Context.UnsignedLongTy,
2769f4a2713aSLionel Sambuc                            llvm::APInt(32, 5), ArrayType::Normal, 0)
2770f4a2713aSLionel Sambuc     };
2771f4a2713aSLionel Sambuc 
2772f4a2713aSLionel Sambuc     for (size_t i = 0; i < 4; ++i) {
2773f4a2713aSLionel Sambuc       FieldDecl *Field = FieldDecl::Create(Context,
2774f4a2713aSLionel Sambuc                                            D,
2775f4a2713aSLionel Sambuc                                            SourceLocation(),
2776*0a6a1f1dSLionel Sambuc                                            SourceLocation(), nullptr,
2777*0a6a1f1dSLionel Sambuc                                            FieldTypes[i], /*TInfo=*/nullptr,
2778*0a6a1f1dSLionel Sambuc                                            /*BitWidth=*/nullptr,
2779f4a2713aSLionel Sambuc                                            /*Mutable=*/false,
2780f4a2713aSLionel Sambuc                                            ICIS_NoInit);
2781f4a2713aSLionel Sambuc       Field->setAccess(AS_public);
2782f4a2713aSLionel Sambuc       D->addDecl(Field);
2783f4a2713aSLionel Sambuc     }
2784f4a2713aSLionel Sambuc 
2785f4a2713aSLionel Sambuc     D->completeDefinition();
2786f4a2713aSLionel Sambuc     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2787f4a2713aSLionel Sambuc   }
2788f4a2713aSLionel Sambuc 
2789f4a2713aSLionel Sambuc   return ObjCFastEnumerationStateType;
2790f4a2713aSLionel Sambuc }
2791f4a2713aSLionel Sambuc 
2792f4a2713aSLionel Sambuc llvm::Constant *
GetConstantArrayFromStringLiteral(const StringLiteral * E)2793f4a2713aSLionel Sambuc CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2794f4a2713aSLionel Sambuc   assert(!E->getType()->isPointerType() && "Strings are always arrays");
2795f4a2713aSLionel Sambuc 
2796f4a2713aSLionel Sambuc   // Don't emit it as the address of the string, emit the string data itself
2797f4a2713aSLionel Sambuc   // as an inline array.
2798f4a2713aSLionel Sambuc   if (E->getCharByteWidth() == 1) {
2799f4a2713aSLionel Sambuc     SmallString<64> Str(E->getString());
2800f4a2713aSLionel Sambuc 
2801f4a2713aSLionel Sambuc     // Resize the string to the right size, which is indicated by its type.
2802f4a2713aSLionel Sambuc     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2803f4a2713aSLionel Sambuc     Str.resize(CAT->getSize().getZExtValue());
2804f4a2713aSLionel Sambuc     return llvm::ConstantDataArray::getString(VMContext, Str, false);
2805f4a2713aSLionel Sambuc   }
2806f4a2713aSLionel Sambuc 
2807*0a6a1f1dSLionel Sambuc   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
2808f4a2713aSLionel Sambuc   llvm::Type *ElemTy = AType->getElementType();
2809f4a2713aSLionel Sambuc   unsigned NumElements = AType->getNumElements();
2810f4a2713aSLionel Sambuc 
2811f4a2713aSLionel Sambuc   // Wide strings have either 2-byte or 4-byte elements.
2812f4a2713aSLionel Sambuc   if (ElemTy->getPrimitiveSizeInBits() == 16) {
2813f4a2713aSLionel Sambuc     SmallVector<uint16_t, 32> Elements;
2814f4a2713aSLionel Sambuc     Elements.reserve(NumElements);
2815f4a2713aSLionel Sambuc 
2816f4a2713aSLionel Sambuc     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2817f4a2713aSLionel Sambuc       Elements.push_back(E->getCodeUnit(i));
2818f4a2713aSLionel Sambuc     Elements.resize(NumElements);
2819f4a2713aSLionel Sambuc     return llvm::ConstantDataArray::get(VMContext, Elements);
2820f4a2713aSLionel Sambuc   }
2821f4a2713aSLionel Sambuc 
2822f4a2713aSLionel Sambuc   assert(ElemTy->getPrimitiveSizeInBits() == 32);
2823f4a2713aSLionel Sambuc   SmallVector<uint32_t, 32> Elements;
2824f4a2713aSLionel Sambuc   Elements.reserve(NumElements);
2825f4a2713aSLionel Sambuc 
2826f4a2713aSLionel Sambuc   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2827f4a2713aSLionel Sambuc     Elements.push_back(E->getCodeUnit(i));
2828f4a2713aSLionel Sambuc   Elements.resize(NumElements);
2829f4a2713aSLionel Sambuc   return llvm::ConstantDataArray::get(VMContext, Elements);
2830f4a2713aSLionel Sambuc }
2831f4a2713aSLionel Sambuc 
2832*0a6a1f1dSLionel Sambuc static llvm::GlobalVariable *
GenerateStringLiteral(llvm::Constant * C,llvm::GlobalValue::LinkageTypes LT,CodeGenModule & CGM,StringRef GlobalName,unsigned Alignment)2833*0a6a1f1dSLionel Sambuc GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
2834*0a6a1f1dSLionel Sambuc                       CodeGenModule &CGM, StringRef GlobalName,
2835*0a6a1f1dSLionel Sambuc                       unsigned Alignment) {
2836*0a6a1f1dSLionel Sambuc   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
2837*0a6a1f1dSLionel Sambuc   unsigned AddrSpace = 0;
2838*0a6a1f1dSLionel Sambuc   if (CGM.getLangOpts().OpenCL)
2839*0a6a1f1dSLionel Sambuc     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
2840f4a2713aSLionel Sambuc 
2841*0a6a1f1dSLionel Sambuc   // Create a global variable for this string
2842*0a6a1f1dSLionel Sambuc   auto *GV = new llvm::GlobalVariable(
2843*0a6a1f1dSLionel Sambuc       CGM.getModule(), C->getType(), !CGM.getLangOpts().WritableStrings, LT, C,
2844*0a6a1f1dSLionel Sambuc       GlobalName, nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
2845*0a6a1f1dSLionel Sambuc   GV->setAlignment(Alignment);
2846*0a6a1f1dSLionel Sambuc   GV->setUnnamedAddr(true);
2847*0a6a1f1dSLionel Sambuc   return GV;
2848f4a2713aSLionel Sambuc }
2849f4a2713aSLionel Sambuc 
2850*0a6a1f1dSLionel Sambuc /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2851*0a6a1f1dSLionel Sambuc /// constant array for the given string literal.
2852*0a6a1f1dSLionel Sambuc llvm::GlobalVariable *
GetAddrOfConstantStringFromLiteral(const StringLiteral * S,StringRef Name)2853*0a6a1f1dSLionel Sambuc CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
2854*0a6a1f1dSLionel Sambuc                                                   StringRef Name) {
2855*0a6a1f1dSLionel Sambuc   auto Alignment =
2856*0a6a1f1dSLionel Sambuc       getContext().getAlignOfGlobalVarInChars(S->getType()).getQuantity();
2857f4a2713aSLionel Sambuc 
2858*0a6a1f1dSLionel Sambuc   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2859*0a6a1f1dSLionel Sambuc   llvm::GlobalVariable **Entry = nullptr;
2860*0a6a1f1dSLionel Sambuc   if (!LangOpts.WritableStrings) {
2861*0a6a1f1dSLionel Sambuc     Entry = &ConstantStringMap[C];
2862*0a6a1f1dSLionel Sambuc     if (auto GV = *Entry) {
2863*0a6a1f1dSLionel Sambuc       if (Alignment > GV->getAlignment())
2864*0a6a1f1dSLionel Sambuc         GV->setAlignment(Alignment);
2865*0a6a1f1dSLionel Sambuc       return GV;
2866*0a6a1f1dSLionel Sambuc     }
2867*0a6a1f1dSLionel Sambuc   }
2868*0a6a1f1dSLionel Sambuc 
2869*0a6a1f1dSLionel Sambuc   SmallString<256> MangledNameBuffer;
2870*0a6a1f1dSLionel Sambuc   StringRef GlobalVariableName;
2871*0a6a1f1dSLionel Sambuc   llvm::GlobalValue::LinkageTypes LT;
2872*0a6a1f1dSLionel Sambuc 
2873*0a6a1f1dSLionel Sambuc   // Mangle the string literal if the ABI allows for it.  However, we cannot
2874*0a6a1f1dSLionel Sambuc   // do this if  we are compiling with ASan or -fwritable-strings because they
2875*0a6a1f1dSLionel Sambuc   // rely on strings having normal linkage.
2876*0a6a1f1dSLionel Sambuc   if (!LangOpts.WritableStrings &&
2877*0a6a1f1dSLionel Sambuc       !LangOpts.Sanitize.has(SanitizerKind::Address) &&
2878*0a6a1f1dSLionel Sambuc       getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
2879*0a6a1f1dSLionel Sambuc     llvm::raw_svector_ostream Out(MangledNameBuffer);
2880*0a6a1f1dSLionel Sambuc     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
2881*0a6a1f1dSLionel Sambuc     Out.flush();
2882*0a6a1f1dSLionel Sambuc 
2883*0a6a1f1dSLionel Sambuc     LT = llvm::GlobalValue::LinkOnceODRLinkage;
2884*0a6a1f1dSLionel Sambuc     GlobalVariableName = MangledNameBuffer;
2885*0a6a1f1dSLionel Sambuc   } else {
2886*0a6a1f1dSLionel Sambuc     LT = llvm::GlobalValue::PrivateLinkage;
2887*0a6a1f1dSLionel Sambuc     GlobalVariableName = Name;
2888*0a6a1f1dSLionel Sambuc   }
2889*0a6a1f1dSLionel Sambuc 
2890*0a6a1f1dSLionel Sambuc   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
2891*0a6a1f1dSLionel Sambuc   if (Entry)
2892*0a6a1f1dSLionel Sambuc     *Entry = GV;
2893*0a6a1f1dSLionel Sambuc 
2894*0a6a1f1dSLionel Sambuc   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
2895*0a6a1f1dSLionel Sambuc                                   QualType());
2896f4a2713aSLionel Sambuc   return GV;
2897f4a2713aSLionel Sambuc }
2898f4a2713aSLionel Sambuc 
2899f4a2713aSLionel Sambuc /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2900f4a2713aSLionel Sambuc /// array for the given ObjCEncodeExpr node.
2901*0a6a1f1dSLionel Sambuc llvm::GlobalVariable *
GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr * E)2902f4a2713aSLionel Sambuc CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2903f4a2713aSLionel Sambuc   std::string Str;
2904f4a2713aSLionel Sambuc   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
2905f4a2713aSLionel Sambuc 
2906f4a2713aSLionel Sambuc   return GetAddrOfConstantCString(Str);
2907f4a2713aSLionel Sambuc }
2908f4a2713aSLionel Sambuc 
2909*0a6a1f1dSLionel Sambuc /// GetAddrOfConstantCString - Returns a pointer to a character array containing
2910*0a6a1f1dSLionel Sambuc /// the literal and a terminating '\0' character.
2911*0a6a1f1dSLionel Sambuc /// The result has pointer to array type.
GetAddrOfConstantCString(const std::string & Str,const char * GlobalName,unsigned Alignment)2912*0a6a1f1dSLionel Sambuc llvm::GlobalVariable *CodeGenModule::GetAddrOfConstantCString(
2913*0a6a1f1dSLionel Sambuc     const std::string &Str, const char *GlobalName, unsigned Alignment) {
2914*0a6a1f1dSLionel Sambuc   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
2915*0a6a1f1dSLionel Sambuc   if (Alignment == 0) {
2916*0a6a1f1dSLionel Sambuc     Alignment = getContext()
2917*0a6a1f1dSLionel Sambuc                     .getAlignOfGlobalVarInChars(getContext().CharTy)
2918*0a6a1f1dSLionel Sambuc                     .getQuantity();
2919f4a2713aSLionel Sambuc   }
2920f4a2713aSLionel Sambuc 
2921*0a6a1f1dSLionel Sambuc   llvm::Constant *C =
2922*0a6a1f1dSLionel Sambuc       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
2923*0a6a1f1dSLionel Sambuc 
2924*0a6a1f1dSLionel Sambuc   // Don't share any string literals if strings aren't constant.
2925*0a6a1f1dSLionel Sambuc   llvm::GlobalVariable **Entry = nullptr;
2926*0a6a1f1dSLionel Sambuc   if (!LangOpts.WritableStrings) {
2927*0a6a1f1dSLionel Sambuc     Entry = &ConstantStringMap[C];
2928*0a6a1f1dSLionel Sambuc     if (auto GV = *Entry) {
2929*0a6a1f1dSLionel Sambuc       if (Alignment > GV->getAlignment())
2930*0a6a1f1dSLionel Sambuc         GV->setAlignment(Alignment);
2931*0a6a1f1dSLionel Sambuc       return GV;
2932*0a6a1f1dSLionel Sambuc     }
2933*0a6a1f1dSLionel Sambuc   }
2934*0a6a1f1dSLionel Sambuc 
2935f4a2713aSLionel Sambuc   // Get the default prefix if a name wasn't specified.
2936f4a2713aSLionel Sambuc   if (!GlobalName)
2937f4a2713aSLionel Sambuc     GlobalName = ".str";
2938f4a2713aSLionel Sambuc   // Create a global variable for this.
2939*0a6a1f1dSLionel Sambuc   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
2940*0a6a1f1dSLionel Sambuc                                   GlobalName, Alignment);
2941*0a6a1f1dSLionel Sambuc   if (Entry)
2942*0a6a1f1dSLionel Sambuc     *Entry = GV;
2943f4a2713aSLionel Sambuc   return GV;
2944f4a2713aSLionel Sambuc }
2945f4a2713aSLionel Sambuc 
GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr * E,const Expr * Init)2946f4a2713aSLionel Sambuc llvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary(
2947f4a2713aSLionel Sambuc     const MaterializeTemporaryExpr *E, const Expr *Init) {
2948f4a2713aSLionel Sambuc   assert((E->getStorageDuration() == SD_Static ||
2949f4a2713aSLionel Sambuc           E->getStorageDuration() == SD_Thread) && "not a global temporary");
2950*0a6a1f1dSLionel Sambuc   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
2951f4a2713aSLionel Sambuc 
2952f4a2713aSLionel Sambuc   // If we're not materializing a subobject of the temporary, keep the
2953f4a2713aSLionel Sambuc   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
2954f4a2713aSLionel Sambuc   QualType MaterializedType = Init->getType();
2955f4a2713aSLionel Sambuc   if (Init == E->GetTemporaryExpr())
2956f4a2713aSLionel Sambuc     MaterializedType = E->getType();
2957f4a2713aSLionel Sambuc 
2958f4a2713aSLionel Sambuc   llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E];
2959f4a2713aSLionel Sambuc   if (Slot)
2960f4a2713aSLionel Sambuc     return Slot;
2961f4a2713aSLionel Sambuc 
2962f4a2713aSLionel Sambuc   // FIXME: If an externally-visible declaration extends multiple temporaries,
2963f4a2713aSLionel Sambuc   // we need to give each temporary the same name in every translation unit (and
2964f4a2713aSLionel Sambuc   // we also need to make the temporaries externally-visible).
2965f4a2713aSLionel Sambuc   SmallString<256> Name;
2966f4a2713aSLionel Sambuc   llvm::raw_svector_ostream Out(Name);
2967*0a6a1f1dSLionel Sambuc   getCXXABI().getMangleContext().mangleReferenceTemporary(
2968*0a6a1f1dSLionel Sambuc       VD, E->getManglingNumber(), Out);
2969f4a2713aSLionel Sambuc   Out.flush();
2970f4a2713aSLionel Sambuc 
2971*0a6a1f1dSLionel Sambuc   APValue *Value = nullptr;
2972f4a2713aSLionel Sambuc   if (E->getStorageDuration() == SD_Static) {
2973f4a2713aSLionel Sambuc     // We might have a cached constant initializer for this temporary. Note
2974f4a2713aSLionel Sambuc     // that this might have a different value from the value computed by
2975f4a2713aSLionel Sambuc     // evaluating the initializer if the surrounding constant expression
2976f4a2713aSLionel Sambuc     // modifies the temporary.
2977f4a2713aSLionel Sambuc     Value = getContext().getMaterializedTemporaryValue(E, false);
2978f4a2713aSLionel Sambuc     if (Value && Value->isUninit())
2979*0a6a1f1dSLionel Sambuc       Value = nullptr;
2980f4a2713aSLionel Sambuc   }
2981f4a2713aSLionel Sambuc 
2982f4a2713aSLionel Sambuc   // Try evaluating it now, it might have a constant initializer.
2983f4a2713aSLionel Sambuc   Expr::EvalResult EvalResult;
2984f4a2713aSLionel Sambuc   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
2985f4a2713aSLionel Sambuc       !EvalResult.hasSideEffects())
2986f4a2713aSLionel Sambuc     Value = &EvalResult.Val;
2987f4a2713aSLionel Sambuc 
2988*0a6a1f1dSLionel Sambuc   llvm::Constant *InitialValue = nullptr;
2989f4a2713aSLionel Sambuc   bool Constant = false;
2990f4a2713aSLionel Sambuc   llvm::Type *Type;
2991f4a2713aSLionel Sambuc   if (Value) {
2992f4a2713aSLionel Sambuc     // The temporary has a constant initializer, use it.
2993*0a6a1f1dSLionel Sambuc     InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
2994f4a2713aSLionel Sambuc     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
2995f4a2713aSLionel Sambuc     Type = InitialValue->getType();
2996f4a2713aSLionel Sambuc   } else {
2997f4a2713aSLionel Sambuc     // No initializer, the initialization will be provided when we
2998f4a2713aSLionel Sambuc     // initialize the declaration which performed lifetime extension.
2999f4a2713aSLionel Sambuc     Type = getTypes().ConvertTypeForMem(MaterializedType);
3000f4a2713aSLionel Sambuc   }
3001f4a2713aSLionel Sambuc 
3002f4a2713aSLionel Sambuc   // Create a global variable for this lifetime-extended temporary.
3003*0a6a1f1dSLionel Sambuc   llvm::GlobalValue::LinkageTypes Linkage =
3004*0a6a1f1dSLionel Sambuc       getLLVMLinkageVarDefinition(VD, Constant);
3005*0a6a1f1dSLionel Sambuc   // There is no need for this temporary to have global linkage if the global
3006*0a6a1f1dSLionel Sambuc   // variable has external linkage.
3007*0a6a1f1dSLionel Sambuc   if (Linkage == llvm::GlobalVariable::ExternalLinkage)
3008*0a6a1f1dSLionel Sambuc     Linkage = llvm::GlobalVariable::PrivateLinkage;
3009*0a6a1f1dSLionel Sambuc   unsigned AddrSpace = GetGlobalVarAddressSpace(
3010*0a6a1f1dSLionel Sambuc       VD, getContext().getTargetAddressSpace(MaterializedType));
3011*0a6a1f1dSLionel Sambuc   auto *GV = new llvm::GlobalVariable(
3012*0a6a1f1dSLionel Sambuc       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
3013*0a6a1f1dSLionel Sambuc       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3014*0a6a1f1dSLionel Sambuc       AddrSpace);
3015*0a6a1f1dSLionel Sambuc   setGlobalVisibility(GV, VD);
3016f4a2713aSLionel Sambuc   GV->setAlignment(
3017f4a2713aSLionel Sambuc       getContext().getTypeAlignInChars(MaterializedType).getQuantity());
3018f4a2713aSLionel Sambuc   if (VD->getTLSKind())
3019f4a2713aSLionel Sambuc     setTLSMode(GV, *VD);
3020f4a2713aSLionel Sambuc   Slot = GV;
3021f4a2713aSLionel Sambuc   return GV;
3022f4a2713aSLionel Sambuc }
3023f4a2713aSLionel Sambuc 
3024f4a2713aSLionel Sambuc /// EmitObjCPropertyImplementations - Emit information for synthesized
3025f4a2713aSLionel Sambuc /// properties for an implementation.
EmitObjCPropertyImplementations(const ObjCImplementationDecl * D)3026f4a2713aSLionel Sambuc void CodeGenModule::EmitObjCPropertyImplementations(const
3027f4a2713aSLionel Sambuc                                                     ObjCImplementationDecl *D) {
3028*0a6a1f1dSLionel Sambuc   for (const auto *PID : D->property_impls()) {
3029f4a2713aSLionel Sambuc     // Dynamic is just for type-checking.
3030f4a2713aSLionel Sambuc     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3031f4a2713aSLionel Sambuc       ObjCPropertyDecl *PD = PID->getPropertyDecl();
3032f4a2713aSLionel Sambuc 
3033f4a2713aSLionel Sambuc       // Determine which methods need to be implemented, some may have
3034f4a2713aSLionel Sambuc       // been overridden. Note that ::isPropertyAccessor is not the method
3035f4a2713aSLionel Sambuc       // we want, that just indicates if the decl came from a
3036f4a2713aSLionel Sambuc       // property. What we want to know is if the method is defined in
3037f4a2713aSLionel Sambuc       // this implementation.
3038f4a2713aSLionel Sambuc       if (!D->getInstanceMethod(PD->getGetterName()))
3039f4a2713aSLionel Sambuc         CodeGenFunction(*this).GenerateObjCGetter(
3040f4a2713aSLionel Sambuc                                  const_cast<ObjCImplementationDecl *>(D), PID);
3041f4a2713aSLionel Sambuc       if (!PD->isReadOnly() &&
3042f4a2713aSLionel Sambuc           !D->getInstanceMethod(PD->getSetterName()))
3043f4a2713aSLionel Sambuc         CodeGenFunction(*this).GenerateObjCSetter(
3044f4a2713aSLionel Sambuc                                  const_cast<ObjCImplementationDecl *>(D), PID);
3045f4a2713aSLionel Sambuc     }
3046f4a2713aSLionel Sambuc   }
3047f4a2713aSLionel Sambuc }
3048f4a2713aSLionel Sambuc 
needsDestructMethod(ObjCImplementationDecl * impl)3049f4a2713aSLionel Sambuc static bool needsDestructMethod(ObjCImplementationDecl *impl) {
3050f4a2713aSLionel Sambuc   const ObjCInterfaceDecl *iface = impl->getClassInterface();
3051f4a2713aSLionel Sambuc   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
3052f4a2713aSLionel Sambuc        ivar; ivar = ivar->getNextIvar())
3053f4a2713aSLionel Sambuc     if (ivar->getType().isDestructedType())
3054f4a2713aSLionel Sambuc       return true;
3055f4a2713aSLionel Sambuc 
3056f4a2713aSLionel Sambuc   return false;
3057f4a2713aSLionel Sambuc }
3058f4a2713aSLionel Sambuc 
AllTrivialInitializers(CodeGenModule & CGM,ObjCImplementationDecl * D)3059*0a6a1f1dSLionel Sambuc static bool AllTrivialInitializers(CodeGenModule &CGM,
3060*0a6a1f1dSLionel Sambuc                                    ObjCImplementationDecl *D) {
3061*0a6a1f1dSLionel Sambuc   CodeGenFunction CGF(CGM);
3062*0a6a1f1dSLionel Sambuc   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
3063*0a6a1f1dSLionel Sambuc        E = D->init_end(); B != E; ++B) {
3064*0a6a1f1dSLionel Sambuc     CXXCtorInitializer *CtorInitExp = *B;
3065*0a6a1f1dSLionel Sambuc     Expr *Init = CtorInitExp->getInit();
3066*0a6a1f1dSLionel Sambuc     if (!CGF.isTrivialInitializer(Init))
3067*0a6a1f1dSLionel Sambuc       return false;
3068*0a6a1f1dSLionel Sambuc   }
3069*0a6a1f1dSLionel Sambuc   return true;
3070*0a6a1f1dSLionel Sambuc }
3071*0a6a1f1dSLionel Sambuc 
3072f4a2713aSLionel Sambuc /// EmitObjCIvarInitializations - Emit information for ivar initialization
3073f4a2713aSLionel Sambuc /// for an implementation.
EmitObjCIvarInitializations(ObjCImplementationDecl * D)3074f4a2713aSLionel Sambuc void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
3075f4a2713aSLionel Sambuc   // We might need a .cxx_destruct even if we don't have any ivar initializers.
3076f4a2713aSLionel Sambuc   if (needsDestructMethod(D)) {
3077f4a2713aSLionel Sambuc     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3078f4a2713aSLionel Sambuc     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3079f4a2713aSLionel Sambuc     ObjCMethodDecl *DTORMethod =
3080f4a2713aSLionel Sambuc       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
3081*0a6a1f1dSLionel Sambuc                              cxxSelector, getContext().VoidTy, nullptr, D,
3082f4a2713aSLionel Sambuc                              /*isInstance=*/true, /*isVariadic=*/false,
3083f4a2713aSLionel Sambuc                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
3084f4a2713aSLionel Sambuc                              /*isDefined=*/false, ObjCMethodDecl::Required);
3085f4a2713aSLionel Sambuc     D->addInstanceMethod(DTORMethod);
3086f4a2713aSLionel Sambuc     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
3087f4a2713aSLionel Sambuc     D->setHasDestructors(true);
3088f4a2713aSLionel Sambuc   }
3089f4a2713aSLionel Sambuc 
3090f4a2713aSLionel Sambuc   // If the implementation doesn't have any ivar initializers, we don't need
3091f4a2713aSLionel Sambuc   // a .cxx_construct.
3092*0a6a1f1dSLionel Sambuc   if (D->getNumIvarInitializers() == 0 ||
3093*0a6a1f1dSLionel Sambuc       AllTrivialInitializers(*this, D))
3094f4a2713aSLionel Sambuc     return;
3095f4a2713aSLionel Sambuc 
3096f4a2713aSLionel Sambuc   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
3097f4a2713aSLionel Sambuc   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3098f4a2713aSLionel Sambuc   // The constructor returns 'self'.
3099f4a2713aSLionel Sambuc   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3100f4a2713aSLionel Sambuc                                                 D->getLocation(),
3101f4a2713aSLionel Sambuc                                                 D->getLocation(),
3102f4a2713aSLionel Sambuc                                                 cxxSelector,
3103*0a6a1f1dSLionel Sambuc                                                 getContext().getObjCIdType(),
3104*0a6a1f1dSLionel Sambuc                                                 nullptr, D, /*isInstance=*/true,
3105f4a2713aSLionel Sambuc                                                 /*isVariadic=*/false,
3106f4a2713aSLionel Sambuc                                                 /*isPropertyAccessor=*/true,
3107f4a2713aSLionel Sambuc                                                 /*isImplicitlyDeclared=*/true,
3108f4a2713aSLionel Sambuc                                                 /*isDefined=*/false,
3109f4a2713aSLionel Sambuc                                                 ObjCMethodDecl::Required);
3110f4a2713aSLionel Sambuc   D->addInstanceMethod(CTORMethod);
3111f4a2713aSLionel Sambuc   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
3112f4a2713aSLionel Sambuc   D->setHasNonZeroConstructors(true);
3113f4a2713aSLionel Sambuc }
3114f4a2713aSLionel Sambuc 
3115f4a2713aSLionel Sambuc /// EmitNamespace - Emit all declarations in a namespace.
EmitNamespace(const NamespaceDecl * ND)3116f4a2713aSLionel Sambuc void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
3117*0a6a1f1dSLionel Sambuc   for (auto *I : ND->decls()) {
3118*0a6a1f1dSLionel Sambuc     if (const auto *VD = dyn_cast<VarDecl>(I))
3119f4a2713aSLionel Sambuc       if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
3120f4a2713aSLionel Sambuc           VD->getTemplateSpecializationKind() != TSK_Undeclared)
3121f4a2713aSLionel Sambuc         continue;
3122*0a6a1f1dSLionel Sambuc     EmitTopLevelDecl(I);
3123f4a2713aSLionel Sambuc   }
3124f4a2713aSLionel Sambuc }
3125f4a2713aSLionel Sambuc 
3126f4a2713aSLionel Sambuc // EmitLinkageSpec - Emit all declarations in a linkage spec.
EmitLinkageSpec(const LinkageSpecDecl * LSD)3127f4a2713aSLionel Sambuc void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
3128f4a2713aSLionel Sambuc   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3129f4a2713aSLionel Sambuc       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
3130f4a2713aSLionel Sambuc     ErrorUnsupported(LSD, "linkage spec");
3131f4a2713aSLionel Sambuc     return;
3132f4a2713aSLionel Sambuc   }
3133f4a2713aSLionel Sambuc 
3134*0a6a1f1dSLionel Sambuc   for (auto *I : LSD->decls()) {
3135f4a2713aSLionel Sambuc     // Meta-data for ObjC class includes references to implemented methods.
3136f4a2713aSLionel Sambuc     // Generate class's method definitions first.
3137*0a6a1f1dSLionel Sambuc     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
3138*0a6a1f1dSLionel Sambuc       for (auto *M : OID->methods())
3139*0a6a1f1dSLionel Sambuc         EmitTopLevelDecl(M);
3140f4a2713aSLionel Sambuc     }
3141*0a6a1f1dSLionel Sambuc     EmitTopLevelDecl(I);
3142f4a2713aSLionel Sambuc   }
3143f4a2713aSLionel Sambuc }
3144f4a2713aSLionel Sambuc 
3145f4a2713aSLionel Sambuc /// EmitTopLevelDecl - Emit code for a single top level declaration.
EmitTopLevelDecl(Decl * D)3146f4a2713aSLionel Sambuc void CodeGenModule::EmitTopLevelDecl(Decl *D) {
3147f4a2713aSLionel Sambuc   // Ignore dependent declarations.
3148f4a2713aSLionel Sambuc   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3149f4a2713aSLionel Sambuc     return;
3150f4a2713aSLionel Sambuc 
3151f4a2713aSLionel Sambuc   switch (D->getKind()) {
3152f4a2713aSLionel Sambuc   case Decl::CXXConversion:
3153f4a2713aSLionel Sambuc   case Decl::CXXMethod:
3154f4a2713aSLionel Sambuc   case Decl::Function:
3155f4a2713aSLionel Sambuc     // Skip function templates
3156f4a2713aSLionel Sambuc     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3157f4a2713aSLionel Sambuc         cast<FunctionDecl>(D)->isLateTemplateParsed())
3158f4a2713aSLionel Sambuc       return;
3159f4a2713aSLionel Sambuc 
3160f4a2713aSLionel Sambuc     EmitGlobal(cast<FunctionDecl>(D));
3161*0a6a1f1dSLionel Sambuc     // Always provide some coverage mapping
3162*0a6a1f1dSLionel Sambuc     // even for the functions that aren't emitted.
3163*0a6a1f1dSLionel Sambuc     AddDeferredUnusedCoverageMapping(D);
3164f4a2713aSLionel Sambuc     break;
3165f4a2713aSLionel Sambuc 
3166f4a2713aSLionel Sambuc   case Decl::Var:
3167f4a2713aSLionel Sambuc     // Skip variable templates
3168f4a2713aSLionel Sambuc     if (cast<VarDecl>(D)->getDescribedVarTemplate())
3169f4a2713aSLionel Sambuc       return;
3170f4a2713aSLionel Sambuc   case Decl::VarTemplateSpecialization:
3171f4a2713aSLionel Sambuc     EmitGlobal(cast<VarDecl>(D));
3172f4a2713aSLionel Sambuc     break;
3173f4a2713aSLionel Sambuc 
3174f4a2713aSLionel Sambuc   // Indirect fields from global anonymous structs and unions can be
3175f4a2713aSLionel Sambuc   // ignored; only the actual variable requires IR gen support.
3176f4a2713aSLionel Sambuc   case Decl::IndirectField:
3177f4a2713aSLionel Sambuc     break;
3178f4a2713aSLionel Sambuc 
3179f4a2713aSLionel Sambuc   // C++ Decls
3180f4a2713aSLionel Sambuc   case Decl::Namespace:
3181f4a2713aSLionel Sambuc     EmitNamespace(cast<NamespaceDecl>(D));
3182f4a2713aSLionel Sambuc     break;
3183f4a2713aSLionel Sambuc     // No code generation needed.
3184f4a2713aSLionel Sambuc   case Decl::UsingShadow:
3185f4a2713aSLionel Sambuc   case Decl::ClassTemplate:
3186f4a2713aSLionel Sambuc   case Decl::VarTemplate:
3187f4a2713aSLionel Sambuc   case Decl::VarTemplatePartialSpecialization:
3188f4a2713aSLionel Sambuc   case Decl::FunctionTemplate:
3189f4a2713aSLionel Sambuc   case Decl::TypeAliasTemplate:
3190f4a2713aSLionel Sambuc   case Decl::Block:
3191f4a2713aSLionel Sambuc   case Decl::Empty:
3192f4a2713aSLionel Sambuc     break;
3193*0a6a1f1dSLionel Sambuc   case Decl::Using:          // using X; [C++]
3194*0a6a1f1dSLionel Sambuc     if (CGDebugInfo *DI = getModuleDebugInfo())
3195*0a6a1f1dSLionel Sambuc         DI->EmitUsingDecl(cast<UsingDecl>(*D));
3196*0a6a1f1dSLionel Sambuc     return;
3197f4a2713aSLionel Sambuc   case Decl::NamespaceAlias:
3198f4a2713aSLionel Sambuc     if (CGDebugInfo *DI = getModuleDebugInfo())
3199f4a2713aSLionel Sambuc         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3200f4a2713aSLionel Sambuc     return;
3201f4a2713aSLionel Sambuc   case Decl::UsingDirective: // using namespace X; [C++]
3202f4a2713aSLionel Sambuc     if (CGDebugInfo *DI = getModuleDebugInfo())
3203f4a2713aSLionel Sambuc       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3204f4a2713aSLionel Sambuc     return;
3205f4a2713aSLionel Sambuc   case Decl::CXXConstructor:
3206f4a2713aSLionel Sambuc     // Skip function templates
3207f4a2713aSLionel Sambuc     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3208f4a2713aSLionel Sambuc         cast<FunctionDecl>(D)->isLateTemplateParsed())
3209f4a2713aSLionel Sambuc       return;
3210f4a2713aSLionel Sambuc 
3211f4a2713aSLionel Sambuc     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
3212f4a2713aSLionel Sambuc     break;
3213f4a2713aSLionel Sambuc   case Decl::CXXDestructor:
3214f4a2713aSLionel Sambuc     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3215f4a2713aSLionel Sambuc       return;
3216f4a2713aSLionel Sambuc     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
3217f4a2713aSLionel Sambuc     break;
3218f4a2713aSLionel Sambuc 
3219f4a2713aSLionel Sambuc   case Decl::StaticAssert:
3220f4a2713aSLionel Sambuc     // Nothing to do.
3221f4a2713aSLionel Sambuc     break;
3222f4a2713aSLionel Sambuc 
3223f4a2713aSLionel Sambuc   // Objective-C Decls
3224f4a2713aSLionel Sambuc 
3225f4a2713aSLionel Sambuc   // Forward declarations, no (immediate) code generation.
3226f4a2713aSLionel Sambuc   case Decl::ObjCInterface:
3227f4a2713aSLionel Sambuc   case Decl::ObjCCategory:
3228f4a2713aSLionel Sambuc     break;
3229f4a2713aSLionel Sambuc 
3230f4a2713aSLionel Sambuc   case Decl::ObjCProtocol: {
3231*0a6a1f1dSLionel Sambuc     auto *Proto = cast<ObjCProtocolDecl>(D);
3232f4a2713aSLionel Sambuc     if (Proto->isThisDeclarationADefinition())
3233f4a2713aSLionel Sambuc       ObjCRuntime->GenerateProtocol(Proto);
3234f4a2713aSLionel Sambuc     break;
3235f4a2713aSLionel Sambuc   }
3236f4a2713aSLionel Sambuc 
3237f4a2713aSLionel Sambuc   case Decl::ObjCCategoryImpl:
3238f4a2713aSLionel Sambuc     // Categories have properties but don't support synthesize so we
3239f4a2713aSLionel Sambuc     // can ignore them here.
3240f4a2713aSLionel Sambuc     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
3241f4a2713aSLionel Sambuc     break;
3242f4a2713aSLionel Sambuc 
3243f4a2713aSLionel Sambuc   case Decl::ObjCImplementation: {
3244*0a6a1f1dSLionel Sambuc     auto *OMD = cast<ObjCImplementationDecl>(D);
3245f4a2713aSLionel Sambuc     EmitObjCPropertyImplementations(OMD);
3246f4a2713aSLionel Sambuc     EmitObjCIvarInitializations(OMD);
3247f4a2713aSLionel Sambuc     ObjCRuntime->GenerateClass(OMD);
3248f4a2713aSLionel Sambuc     // Emit global variable debug information.
3249f4a2713aSLionel Sambuc     if (CGDebugInfo *DI = getModuleDebugInfo())
3250f4a2713aSLionel Sambuc       if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
3251f4a2713aSLionel Sambuc         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3252f4a2713aSLionel Sambuc             OMD->getClassInterface()), OMD->getLocation());
3253f4a2713aSLionel Sambuc     break;
3254f4a2713aSLionel Sambuc   }
3255f4a2713aSLionel Sambuc   case Decl::ObjCMethod: {
3256*0a6a1f1dSLionel Sambuc     auto *OMD = cast<ObjCMethodDecl>(D);
3257f4a2713aSLionel Sambuc     // If this is not a prototype, emit the body.
3258f4a2713aSLionel Sambuc     if (OMD->getBody())
3259f4a2713aSLionel Sambuc       CodeGenFunction(*this).GenerateObjCMethod(OMD);
3260f4a2713aSLionel Sambuc     break;
3261f4a2713aSLionel Sambuc   }
3262f4a2713aSLionel Sambuc   case Decl::ObjCCompatibleAlias:
3263f4a2713aSLionel Sambuc     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3264f4a2713aSLionel Sambuc     break;
3265f4a2713aSLionel Sambuc 
3266f4a2713aSLionel Sambuc   case Decl::LinkageSpec:
3267f4a2713aSLionel Sambuc     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
3268f4a2713aSLionel Sambuc     break;
3269f4a2713aSLionel Sambuc 
3270f4a2713aSLionel Sambuc   case Decl::FileScopeAsm: {
3271*0a6a1f1dSLionel Sambuc     auto *AD = cast<FileScopeAsmDecl>(D);
3272f4a2713aSLionel Sambuc     StringRef AsmString = AD->getAsmString()->getString();
3273f4a2713aSLionel Sambuc 
3274f4a2713aSLionel Sambuc     const std::string &S = getModule().getModuleInlineAsm();
3275f4a2713aSLionel Sambuc     if (S.empty())
3276f4a2713aSLionel Sambuc       getModule().setModuleInlineAsm(AsmString);
3277f4a2713aSLionel Sambuc     else if (S.end()[-1] == '\n')
3278f4a2713aSLionel Sambuc       getModule().setModuleInlineAsm(S + AsmString.str());
3279f4a2713aSLionel Sambuc     else
3280f4a2713aSLionel Sambuc       getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
3281f4a2713aSLionel Sambuc     break;
3282f4a2713aSLionel Sambuc   }
3283f4a2713aSLionel Sambuc 
3284f4a2713aSLionel Sambuc   case Decl::Import: {
3285*0a6a1f1dSLionel Sambuc     auto *Import = cast<ImportDecl>(D);
3286f4a2713aSLionel Sambuc 
3287f4a2713aSLionel Sambuc     // Ignore import declarations that come from imported modules.
3288f4a2713aSLionel Sambuc     if (clang::Module *Owner = Import->getOwningModule()) {
3289f4a2713aSLionel Sambuc       if (getLangOpts().CurrentModule.empty() ||
3290f4a2713aSLionel Sambuc           Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
3291f4a2713aSLionel Sambuc         break;
3292f4a2713aSLionel Sambuc     }
3293f4a2713aSLionel Sambuc 
3294f4a2713aSLionel Sambuc     ImportedModules.insert(Import->getImportedModule());
3295f4a2713aSLionel Sambuc     break;
3296f4a2713aSLionel Sambuc   }
3297f4a2713aSLionel Sambuc 
3298*0a6a1f1dSLionel Sambuc   case Decl::OMPThreadPrivate:
3299*0a6a1f1dSLionel Sambuc     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
3300*0a6a1f1dSLionel Sambuc     break;
3301*0a6a1f1dSLionel Sambuc 
3302*0a6a1f1dSLionel Sambuc   case Decl::ClassTemplateSpecialization: {
3303*0a6a1f1dSLionel Sambuc     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
3304*0a6a1f1dSLionel Sambuc     if (DebugInfo &&
3305*0a6a1f1dSLionel Sambuc         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
3306*0a6a1f1dSLionel Sambuc         Spec->hasDefinition())
3307*0a6a1f1dSLionel Sambuc       DebugInfo->completeTemplateDefinition(*Spec);
3308*0a6a1f1dSLionel Sambuc     break;
3309*0a6a1f1dSLionel Sambuc   }
3310*0a6a1f1dSLionel Sambuc 
3311f4a2713aSLionel Sambuc   default:
3312f4a2713aSLionel Sambuc     // Make sure we handled everything we should, every other kind is a
3313f4a2713aSLionel Sambuc     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
3314f4a2713aSLionel Sambuc     // function. Need to recode Decl::Kind to do that easily.
3315f4a2713aSLionel Sambuc     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
3316*0a6a1f1dSLionel Sambuc     break;
3317*0a6a1f1dSLionel Sambuc   }
3318*0a6a1f1dSLionel Sambuc }
3319*0a6a1f1dSLionel Sambuc 
AddDeferredUnusedCoverageMapping(Decl * D)3320*0a6a1f1dSLionel Sambuc void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
3321*0a6a1f1dSLionel Sambuc   // Do we need to generate coverage mapping?
3322*0a6a1f1dSLionel Sambuc   if (!CodeGenOpts.CoverageMapping)
3323*0a6a1f1dSLionel Sambuc     return;
3324*0a6a1f1dSLionel Sambuc   switch (D->getKind()) {
3325*0a6a1f1dSLionel Sambuc   case Decl::CXXConversion:
3326*0a6a1f1dSLionel Sambuc   case Decl::CXXMethod:
3327*0a6a1f1dSLionel Sambuc   case Decl::Function:
3328*0a6a1f1dSLionel Sambuc   case Decl::ObjCMethod:
3329*0a6a1f1dSLionel Sambuc   case Decl::CXXConstructor:
3330*0a6a1f1dSLionel Sambuc   case Decl::CXXDestructor: {
3331*0a6a1f1dSLionel Sambuc     if (!cast<FunctionDecl>(D)->hasBody())
3332*0a6a1f1dSLionel Sambuc       return;
3333*0a6a1f1dSLionel Sambuc     auto I = DeferredEmptyCoverageMappingDecls.find(D);
3334*0a6a1f1dSLionel Sambuc     if (I == DeferredEmptyCoverageMappingDecls.end())
3335*0a6a1f1dSLionel Sambuc       DeferredEmptyCoverageMappingDecls[D] = true;
3336*0a6a1f1dSLionel Sambuc     break;
3337*0a6a1f1dSLionel Sambuc   }
3338*0a6a1f1dSLionel Sambuc   default:
3339*0a6a1f1dSLionel Sambuc     break;
3340*0a6a1f1dSLionel Sambuc   };
3341*0a6a1f1dSLionel Sambuc }
3342*0a6a1f1dSLionel Sambuc 
ClearUnusedCoverageMapping(const Decl * D)3343*0a6a1f1dSLionel Sambuc void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
3344*0a6a1f1dSLionel Sambuc   // Do we need to generate coverage mapping?
3345*0a6a1f1dSLionel Sambuc   if (!CodeGenOpts.CoverageMapping)
3346*0a6a1f1dSLionel Sambuc     return;
3347*0a6a1f1dSLionel Sambuc   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
3348*0a6a1f1dSLionel Sambuc     if (Fn->isTemplateInstantiation())
3349*0a6a1f1dSLionel Sambuc       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
3350*0a6a1f1dSLionel Sambuc   }
3351*0a6a1f1dSLionel Sambuc   auto I = DeferredEmptyCoverageMappingDecls.find(D);
3352*0a6a1f1dSLionel Sambuc   if (I == DeferredEmptyCoverageMappingDecls.end())
3353*0a6a1f1dSLionel Sambuc     DeferredEmptyCoverageMappingDecls[D] = false;
3354*0a6a1f1dSLionel Sambuc   else
3355*0a6a1f1dSLionel Sambuc     I->second = false;
3356*0a6a1f1dSLionel Sambuc }
3357*0a6a1f1dSLionel Sambuc 
EmitDeferredUnusedCoverageMappings()3358*0a6a1f1dSLionel Sambuc void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
3359*0a6a1f1dSLionel Sambuc   std::vector<const Decl *> DeferredDecls;
3360*0a6a1f1dSLionel Sambuc   for (const auto I : DeferredEmptyCoverageMappingDecls) {
3361*0a6a1f1dSLionel Sambuc     if (!I.second)
3362*0a6a1f1dSLionel Sambuc       continue;
3363*0a6a1f1dSLionel Sambuc     DeferredDecls.push_back(I.first);
3364*0a6a1f1dSLionel Sambuc   }
3365*0a6a1f1dSLionel Sambuc   // Sort the declarations by their location to make sure that the tests get a
3366*0a6a1f1dSLionel Sambuc   // predictable order for the coverage mapping for the unused declarations.
3367*0a6a1f1dSLionel Sambuc   if (CodeGenOpts.DumpCoverageMapping)
3368*0a6a1f1dSLionel Sambuc     std::sort(DeferredDecls.begin(), DeferredDecls.end(),
3369*0a6a1f1dSLionel Sambuc               [] (const Decl *LHS, const Decl *RHS) {
3370*0a6a1f1dSLionel Sambuc       return LHS->getLocStart() < RHS->getLocStart();
3371*0a6a1f1dSLionel Sambuc     });
3372*0a6a1f1dSLionel Sambuc   for (const auto *D : DeferredDecls) {
3373*0a6a1f1dSLionel Sambuc     switch (D->getKind()) {
3374*0a6a1f1dSLionel Sambuc     case Decl::CXXConversion:
3375*0a6a1f1dSLionel Sambuc     case Decl::CXXMethod:
3376*0a6a1f1dSLionel Sambuc     case Decl::Function:
3377*0a6a1f1dSLionel Sambuc     case Decl::ObjCMethod: {
3378*0a6a1f1dSLionel Sambuc       CodeGenPGO PGO(*this);
3379*0a6a1f1dSLionel Sambuc       GlobalDecl GD(cast<FunctionDecl>(D));
3380*0a6a1f1dSLionel Sambuc       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3381*0a6a1f1dSLionel Sambuc                                   getFunctionLinkage(GD));
3382*0a6a1f1dSLionel Sambuc       break;
3383*0a6a1f1dSLionel Sambuc     }
3384*0a6a1f1dSLionel Sambuc     case Decl::CXXConstructor: {
3385*0a6a1f1dSLionel Sambuc       CodeGenPGO PGO(*this);
3386*0a6a1f1dSLionel Sambuc       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
3387*0a6a1f1dSLionel Sambuc       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3388*0a6a1f1dSLionel Sambuc                                   getFunctionLinkage(GD));
3389*0a6a1f1dSLionel Sambuc       break;
3390*0a6a1f1dSLionel Sambuc     }
3391*0a6a1f1dSLionel Sambuc     case Decl::CXXDestructor: {
3392*0a6a1f1dSLionel Sambuc       CodeGenPGO PGO(*this);
3393*0a6a1f1dSLionel Sambuc       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
3394*0a6a1f1dSLionel Sambuc       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3395*0a6a1f1dSLionel Sambuc                                   getFunctionLinkage(GD));
3396*0a6a1f1dSLionel Sambuc       break;
3397*0a6a1f1dSLionel Sambuc     }
3398*0a6a1f1dSLionel Sambuc     default:
3399*0a6a1f1dSLionel Sambuc       break;
3400*0a6a1f1dSLionel Sambuc     };
3401f4a2713aSLionel Sambuc   }
3402f4a2713aSLionel Sambuc }
3403f4a2713aSLionel Sambuc 
3404f4a2713aSLionel Sambuc /// Turns the given pointer into a constant.
GetPointerConstant(llvm::LLVMContext & Context,const void * Ptr)3405f4a2713aSLionel Sambuc static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
3406f4a2713aSLionel Sambuc                                           const void *Ptr) {
3407f4a2713aSLionel Sambuc   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
3408f4a2713aSLionel Sambuc   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
3409f4a2713aSLionel Sambuc   return llvm::ConstantInt::get(i64, PtrInt);
3410f4a2713aSLionel Sambuc }
3411f4a2713aSLionel Sambuc 
EmitGlobalDeclMetadata(CodeGenModule & CGM,llvm::NamedMDNode * & GlobalMetadata,GlobalDecl D,llvm::GlobalValue * Addr)3412f4a2713aSLionel Sambuc static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
3413f4a2713aSLionel Sambuc                                    llvm::NamedMDNode *&GlobalMetadata,
3414f4a2713aSLionel Sambuc                                    GlobalDecl D,
3415f4a2713aSLionel Sambuc                                    llvm::GlobalValue *Addr) {
3416f4a2713aSLionel Sambuc   if (!GlobalMetadata)
3417f4a2713aSLionel Sambuc     GlobalMetadata =
3418f4a2713aSLionel Sambuc       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
3419f4a2713aSLionel Sambuc 
3420f4a2713aSLionel Sambuc   // TODO: should we report variant information for ctors/dtors?
3421*0a6a1f1dSLionel Sambuc   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
3422*0a6a1f1dSLionel Sambuc                            llvm::ConstantAsMetadata::get(GetPointerConstant(
3423*0a6a1f1dSLionel Sambuc                                CGM.getLLVMContext(), D.getDecl()))};
3424f4a2713aSLionel Sambuc   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
3425f4a2713aSLionel Sambuc }
3426f4a2713aSLionel Sambuc 
3427f4a2713aSLionel Sambuc /// For each function which is declared within an extern "C" region and marked
3428f4a2713aSLionel Sambuc /// as 'used', but has internal linkage, create an alias from the unmangled
3429f4a2713aSLionel Sambuc /// name to the mangled name if possible. People expect to be able to refer
3430f4a2713aSLionel Sambuc /// to such functions with an unmangled name from inline assembly within the
3431f4a2713aSLionel Sambuc /// same translation unit.
EmitStaticExternCAliases()3432f4a2713aSLionel Sambuc void CodeGenModule::EmitStaticExternCAliases() {
3433f4a2713aSLionel Sambuc   for (StaticExternCMap::iterator I = StaticExternCValues.begin(),
3434f4a2713aSLionel Sambuc                                   E = StaticExternCValues.end();
3435f4a2713aSLionel Sambuc        I != E; ++I) {
3436f4a2713aSLionel Sambuc     IdentifierInfo *Name = I->first;
3437f4a2713aSLionel Sambuc     llvm::GlobalValue *Val = I->second;
3438f4a2713aSLionel Sambuc     if (Val && !getModule().getNamedValue(Name->getName()))
3439*0a6a1f1dSLionel Sambuc       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
3440f4a2713aSLionel Sambuc   }
3441f4a2713aSLionel Sambuc }
3442f4a2713aSLionel Sambuc 
lookupRepresentativeDecl(StringRef MangledName,GlobalDecl & Result) const3443*0a6a1f1dSLionel Sambuc bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
3444*0a6a1f1dSLionel Sambuc                                              GlobalDecl &Result) const {
3445*0a6a1f1dSLionel Sambuc   auto Res = Manglings.find(MangledName);
3446*0a6a1f1dSLionel Sambuc   if (Res == Manglings.end())
3447*0a6a1f1dSLionel Sambuc     return false;
3448*0a6a1f1dSLionel Sambuc   Result = Res->getValue();
3449*0a6a1f1dSLionel Sambuc   return true;
3450*0a6a1f1dSLionel Sambuc }
3451*0a6a1f1dSLionel Sambuc 
3452f4a2713aSLionel Sambuc /// Emits metadata nodes associating all the global values in the
3453f4a2713aSLionel Sambuc /// current module with the Decls they came from.  This is useful for
3454f4a2713aSLionel Sambuc /// projects using IR gen as a subroutine.
3455f4a2713aSLionel Sambuc ///
3456f4a2713aSLionel Sambuc /// Since there's currently no way to associate an MDNode directly
3457f4a2713aSLionel Sambuc /// with an llvm::GlobalValue, we create a global named metadata
3458f4a2713aSLionel Sambuc /// with the name 'clang.global.decl.ptrs'.
EmitDeclMetadata()3459f4a2713aSLionel Sambuc void CodeGenModule::EmitDeclMetadata() {
3460*0a6a1f1dSLionel Sambuc   llvm::NamedMDNode *GlobalMetadata = nullptr;
3461f4a2713aSLionel Sambuc 
3462f4a2713aSLionel Sambuc   // StaticLocalDeclMap
3463*0a6a1f1dSLionel Sambuc   for (auto &I : MangledDeclNames) {
3464*0a6a1f1dSLionel Sambuc     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
3465*0a6a1f1dSLionel Sambuc     EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
3466f4a2713aSLionel Sambuc   }
3467f4a2713aSLionel Sambuc }
3468f4a2713aSLionel Sambuc 
3469f4a2713aSLionel Sambuc /// Emits metadata nodes for all the local variables in the current
3470f4a2713aSLionel Sambuc /// function.
EmitDeclMetadata()3471f4a2713aSLionel Sambuc void CodeGenFunction::EmitDeclMetadata() {
3472f4a2713aSLionel Sambuc   if (LocalDeclMap.empty()) return;
3473f4a2713aSLionel Sambuc 
3474f4a2713aSLionel Sambuc   llvm::LLVMContext &Context = getLLVMContext();
3475f4a2713aSLionel Sambuc 
3476f4a2713aSLionel Sambuc   // Find the unique metadata ID for this name.
3477f4a2713aSLionel Sambuc   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
3478f4a2713aSLionel Sambuc 
3479*0a6a1f1dSLionel Sambuc   llvm::NamedMDNode *GlobalMetadata = nullptr;
3480f4a2713aSLionel Sambuc 
3481*0a6a1f1dSLionel Sambuc   for (auto &I : LocalDeclMap) {
3482*0a6a1f1dSLionel Sambuc     const Decl *D = I.first;
3483*0a6a1f1dSLionel Sambuc     llvm::Value *Addr = I.second;
3484*0a6a1f1dSLionel Sambuc     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
3485f4a2713aSLionel Sambuc       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
3486*0a6a1f1dSLionel Sambuc       Alloca->setMetadata(
3487*0a6a1f1dSLionel Sambuc           DeclPtrKind, llvm::MDNode::get(
3488*0a6a1f1dSLionel Sambuc                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
3489*0a6a1f1dSLionel Sambuc     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
3490f4a2713aSLionel Sambuc       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
3491f4a2713aSLionel Sambuc       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
3492f4a2713aSLionel Sambuc     }
3493f4a2713aSLionel Sambuc   }
3494f4a2713aSLionel Sambuc }
3495f4a2713aSLionel Sambuc 
EmitVersionIdentMetadata()3496f4a2713aSLionel Sambuc void CodeGenModule::EmitVersionIdentMetadata() {
3497f4a2713aSLionel Sambuc   llvm::NamedMDNode *IdentMetadata =
3498f4a2713aSLionel Sambuc     TheModule.getOrInsertNamedMetadata("llvm.ident");
3499f4a2713aSLionel Sambuc   std::string Version = getClangFullVersion();
3500f4a2713aSLionel Sambuc   llvm::LLVMContext &Ctx = TheModule.getContext();
3501f4a2713aSLionel Sambuc 
3502*0a6a1f1dSLionel Sambuc   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
3503f4a2713aSLionel Sambuc   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
3504f4a2713aSLionel Sambuc }
3505f4a2713aSLionel Sambuc 
EmitTargetMetadata()3506*0a6a1f1dSLionel Sambuc void CodeGenModule::EmitTargetMetadata() {
3507*0a6a1f1dSLionel Sambuc   // Warning, new MangledDeclNames may be appended within this loop.
3508*0a6a1f1dSLionel Sambuc   // We rely on MapVector insertions adding new elements to the end
3509*0a6a1f1dSLionel Sambuc   // of the container.
3510*0a6a1f1dSLionel Sambuc   // FIXME: Move this loop into the one target that needs it, and only
3511*0a6a1f1dSLionel Sambuc   // loop over those declarations for which we couldn't emit the target
3512*0a6a1f1dSLionel Sambuc   // metadata when we emitted the declaration.
3513*0a6a1f1dSLionel Sambuc   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
3514*0a6a1f1dSLionel Sambuc     auto Val = *(MangledDeclNames.begin() + I);
3515*0a6a1f1dSLionel Sambuc     const Decl *D = Val.first.getDecl()->getMostRecentDecl();
3516*0a6a1f1dSLionel Sambuc     llvm::GlobalValue *GV = GetGlobalValue(Val.second);
3517*0a6a1f1dSLionel Sambuc     getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
3518*0a6a1f1dSLionel Sambuc   }
3519*0a6a1f1dSLionel Sambuc }
3520*0a6a1f1dSLionel Sambuc 
EmitCoverageFile()3521f4a2713aSLionel Sambuc void CodeGenModule::EmitCoverageFile() {
3522f4a2713aSLionel Sambuc   if (!getCodeGenOpts().CoverageFile.empty()) {
3523f4a2713aSLionel Sambuc     if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
3524f4a2713aSLionel Sambuc       llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
3525f4a2713aSLionel Sambuc       llvm::LLVMContext &Ctx = TheModule.getContext();
3526f4a2713aSLionel Sambuc       llvm::MDString *CoverageFile =
3527f4a2713aSLionel Sambuc           llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
3528f4a2713aSLionel Sambuc       for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
3529f4a2713aSLionel Sambuc         llvm::MDNode *CU = CUNode->getOperand(i);
3530*0a6a1f1dSLionel Sambuc         llvm::Metadata *Elts[] = {CoverageFile, CU};
3531*0a6a1f1dSLionel Sambuc         GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
3532f4a2713aSLionel Sambuc       }
3533f4a2713aSLionel Sambuc     }
3534f4a2713aSLionel Sambuc   }
3535f4a2713aSLionel Sambuc }
3536f4a2713aSLionel Sambuc 
EmitUuidofInitializer(StringRef Uuid)3537*0a6a1f1dSLionel Sambuc llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
3538f4a2713aSLionel Sambuc   // Sema has checked that all uuid strings are of the form
3539f4a2713aSLionel Sambuc   // "12345678-1234-1234-1234-1234567890ab".
3540f4a2713aSLionel Sambuc   assert(Uuid.size() == 36);
3541f4a2713aSLionel Sambuc   for (unsigned i = 0; i < 36; ++i) {
3542f4a2713aSLionel Sambuc     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
3543f4a2713aSLionel Sambuc     else                                         assert(isHexDigit(Uuid[i]));
3544f4a2713aSLionel Sambuc   }
3545f4a2713aSLionel Sambuc 
3546*0a6a1f1dSLionel Sambuc   // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
3547f4a2713aSLionel Sambuc   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
3548f4a2713aSLionel Sambuc 
3549f4a2713aSLionel Sambuc   llvm::Constant *Field3[8];
3550f4a2713aSLionel Sambuc   for (unsigned Idx = 0; Idx < 8; ++Idx)
3551f4a2713aSLionel Sambuc     Field3[Idx] = llvm::ConstantInt::get(
3552f4a2713aSLionel Sambuc         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
3553f4a2713aSLionel Sambuc 
3554f4a2713aSLionel Sambuc   llvm::Constant *Fields[4] = {
3555f4a2713aSLionel Sambuc     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
3556f4a2713aSLionel Sambuc     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
3557f4a2713aSLionel Sambuc     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
3558f4a2713aSLionel Sambuc     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
3559f4a2713aSLionel Sambuc   };
3560f4a2713aSLionel Sambuc 
3561f4a2713aSLionel Sambuc   return llvm::ConstantStruct::getAnon(Fields);
3562f4a2713aSLionel Sambuc }
3563*0a6a1f1dSLionel Sambuc 
GetAddrOfRTTIDescriptor(QualType Ty,bool ForEH)3564*0a6a1f1dSLionel Sambuc llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
3565*0a6a1f1dSLionel Sambuc                                                        bool ForEH) {
3566*0a6a1f1dSLionel Sambuc   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
3567*0a6a1f1dSLionel Sambuc   // FIXME: should we even be calling this method if RTTI is disabled
3568*0a6a1f1dSLionel Sambuc   // and it's not for EH?
3569*0a6a1f1dSLionel Sambuc   if (!ForEH && !getLangOpts().RTTI)
3570*0a6a1f1dSLionel Sambuc     return llvm::Constant::getNullValue(Int8PtrTy);
3571*0a6a1f1dSLionel Sambuc 
3572*0a6a1f1dSLionel Sambuc   if (ForEH && Ty->isObjCObjectPointerType() &&
3573*0a6a1f1dSLionel Sambuc       LangOpts.ObjCRuntime.isGNUFamily())
3574*0a6a1f1dSLionel Sambuc     return ObjCRuntime->GetEHType(Ty);
3575*0a6a1f1dSLionel Sambuc 
3576*0a6a1f1dSLionel Sambuc   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
3577*0a6a1f1dSLionel Sambuc }
3578*0a6a1f1dSLionel Sambuc 
EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl * D)3579*0a6a1f1dSLionel Sambuc void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
3580*0a6a1f1dSLionel Sambuc   for (auto RefExpr : D->varlists()) {
3581*0a6a1f1dSLionel Sambuc     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
3582*0a6a1f1dSLionel Sambuc     bool PerformInit =
3583*0a6a1f1dSLionel Sambuc         VD->getAnyInitializer() &&
3584*0a6a1f1dSLionel Sambuc         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
3585*0a6a1f1dSLionel Sambuc                                                         /*ForRef=*/false);
3586*0a6a1f1dSLionel Sambuc     if (auto InitFunction =
3587*0a6a1f1dSLionel Sambuc             getOpenMPRuntime().EmitOMPThreadPrivateVarDefinition(
3588*0a6a1f1dSLionel Sambuc                 VD, GetAddrOfGlobalVar(VD), RefExpr->getLocStart(),
3589*0a6a1f1dSLionel Sambuc                 PerformInit))
3590*0a6a1f1dSLionel Sambuc       CXXGlobalInits.push_back(InitFunction);
3591*0a6a1f1dSLionel Sambuc   }
3592*0a6a1f1dSLionel Sambuc }
3593*0a6a1f1dSLionel Sambuc 
3594