1f22ef01cSRoman Divacky //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This coordinates the per-module state used while generating code.
11f22ef01cSRoman Divacky //
12f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
13f22ef01cSRoman Divacky 
14f22ef01cSRoman Divacky #include "CodeGenModule.h"
150623d748SDimitry Andric #include "CGBlocks.h"
166122f3e6SDimitry Andric #include "CGCUDARuntime.h"
17e580952dSDimitry Andric #include "CGCXXABI.h"
18139f7f9bSDimitry Andric #include "CGCall.h"
19139f7f9bSDimitry Andric #include "CGDebugInfo.h"
20f22ef01cSRoman Divacky #include "CGObjCRuntime.h"
216122f3e6SDimitry Andric #include "CGOpenCLRuntime.h"
2259d1ed5bSDimitry Andric #include "CGOpenMPRuntime.h"
23e7145dcbSDimitry Andric #include "CGOpenMPRuntimeNVPTX.h"
24139f7f9bSDimitry Andric #include "CodeGenFunction.h"
2559d1ed5bSDimitry Andric #include "CodeGenPGO.h"
26139f7f9bSDimitry Andric #include "CodeGenTBAA.h"
2744290647SDimitry Andric #include "ConstantBuilder.h"
2839d628a0SDimitry Andric #include "CoverageMappingGen.h"
29f22ef01cSRoman Divacky #include "TargetInfo.h"
30f22ef01cSRoman Divacky #include "clang/AST/ASTContext.h"
31f22ef01cSRoman Divacky #include "clang/AST/CharUnits.h"
32f22ef01cSRoman Divacky #include "clang/AST/DeclCXX.h"
33139f7f9bSDimitry Andric #include "clang/AST/DeclObjC.h"
34ffd1746dSEd Schouten #include "clang/AST/DeclTemplate.h"
352754fe60SDimitry Andric #include "clang/AST/Mangle.h"
36f22ef01cSRoman Divacky #include "clang/AST/RecordLayout.h"
37f8254f43SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h"
38dff0c46cSDimitry Andric #include "clang/Basic/Builtins.h"
39139f7f9bSDimitry Andric #include "clang/Basic/CharInfo.h"
40f22ef01cSRoman Divacky #include "clang/Basic/Diagnostic.h"
41139f7f9bSDimitry Andric #include "clang/Basic/Module.h"
42f22ef01cSRoman Divacky #include "clang/Basic/SourceManager.h"
43f22ef01cSRoman Divacky #include "clang/Basic/TargetInfo.h"
44f785676fSDimitry Andric #include "clang/Basic/Version.h"
45139f7f9bSDimitry Andric #include "clang/Frontend/CodeGenOptions.h"
46f785676fSDimitry Andric #include "clang/Sema/SemaDiagnostic.h"
47f22ef01cSRoman Divacky #include "llvm/ADT/Triple.h"
4859d1ed5bSDimitry Andric #include "llvm/IR/CallSite.h"
49139f7f9bSDimitry Andric #include "llvm/IR/CallingConv.h"
50139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h"
51139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h"
52139f7f9bSDimitry Andric #include "llvm/IR/LLVMContext.h"
53139f7f9bSDimitry Andric #include "llvm/IR/Module.h"
5459d1ed5bSDimitry Andric #include "llvm/ProfileData/InstrProfReader.h"
55139f7f9bSDimitry Andric #include "llvm/Support/ConvertUTF.h"
56f22ef01cSRoman Divacky #include "llvm/Support/ErrorHandling.h"
570623d748SDimitry Andric #include "llvm/Support/MD5.h"
58139f7f9bSDimitry Andric 
59f22ef01cSRoman Divacky using namespace clang;
60f22ef01cSRoman Divacky using namespace CodeGen;
61f22ef01cSRoman Divacky 
626122f3e6SDimitry Andric static const char AnnotationSection[] = "llvm.metadata";
636122f3e6SDimitry Andric 
6459d1ed5bSDimitry Andric static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
65284c1978SDimitry Andric   switch (CGM.getTarget().getCXXABI().getKind()) {
66139f7f9bSDimitry Andric   case TargetCXXABI::GenericAArch64:
67139f7f9bSDimitry Andric   case TargetCXXABI::GenericARM:
68139f7f9bSDimitry Andric   case TargetCXXABI::iOS:
6959d1ed5bSDimitry Andric   case TargetCXXABI::iOS64:
700623d748SDimitry Andric   case TargetCXXABI::WatchOS:
71ef6fa9e2SDimitry Andric   case TargetCXXABI::GenericMIPS:
72139f7f9bSDimitry Andric   case TargetCXXABI::GenericItanium:
730623d748SDimitry Andric   case TargetCXXABI::WebAssembly:
7459d1ed5bSDimitry Andric     return CreateItaniumCXXABI(CGM);
75139f7f9bSDimitry Andric   case TargetCXXABI::Microsoft:
7659d1ed5bSDimitry Andric     return CreateMicrosoftCXXABI(CGM);
77e580952dSDimitry Andric   }
78e580952dSDimitry Andric 
79e580952dSDimitry Andric   llvm_unreachable("invalid C++ ABI kind");
80e580952dSDimitry Andric }
81e580952dSDimitry Andric 
823dac3a9bSDimitry Andric CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
833dac3a9bSDimitry Andric                              const PreprocessorOptions &PPO,
843dac3a9bSDimitry Andric                              const CodeGenOptions &CGO, llvm::Module &M,
8539d628a0SDimitry Andric                              DiagnosticsEngine &diags,
8639d628a0SDimitry Andric                              CoverageSourceInfo *CoverageInfo)
873dac3a9bSDimitry Andric     : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
883dac3a9bSDimitry Andric       PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
890623d748SDimitry Andric       Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
90e7145dcbSDimitry Andric       VMContext(M.getContext()), Types(*this), VTables(*this),
91e7145dcbSDimitry Andric       SanitizerMD(new SanitizerMetadata(*this)) {
92dff0c46cSDimitry Andric 
93dff0c46cSDimitry Andric   // Initialize the type cache.
94dff0c46cSDimitry Andric   llvm::LLVMContext &LLVMContext = M.getContext();
95dff0c46cSDimitry Andric   VoidTy = llvm::Type::getVoidTy(LLVMContext);
96dff0c46cSDimitry Andric   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
97dff0c46cSDimitry Andric   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
98dff0c46cSDimitry Andric   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
99dff0c46cSDimitry Andric   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
100dff0c46cSDimitry Andric   FloatTy = llvm::Type::getFloatTy(LLVMContext);
101dff0c46cSDimitry Andric   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
102dff0c46cSDimitry Andric   PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
103dff0c46cSDimitry Andric   PointerAlignInBytes =
104dff0c46cSDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
10544290647SDimitry Andric   SizeSizeInBytes =
10644290647SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
1070623d748SDimitry Andric   IntAlignInBytes =
1080623d748SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
109dff0c46cSDimitry Andric   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
11044290647SDimitry Andric   IntPtrTy = llvm::IntegerType::get(LLVMContext,
11144290647SDimitry Andric     C.getTargetInfo().getMaxPointerWidth());
112dff0c46cSDimitry Andric   Int8PtrTy = Int8Ty->getPointerTo(0);
113dff0c46cSDimitry Andric   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
114dff0c46cSDimitry Andric 
115139f7f9bSDimitry Andric   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
11639d628a0SDimitry Andric   BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
117139f7f9bSDimitry Andric 
118dff0c46cSDimitry Andric   if (LangOpts.ObjC1)
1193b0f4066SDimitry Andric     createObjCRuntime();
120dff0c46cSDimitry Andric   if (LangOpts.OpenCL)
1216122f3e6SDimitry Andric     createOpenCLRuntime();
12259d1ed5bSDimitry Andric   if (LangOpts.OpenMP)
12359d1ed5bSDimitry Andric     createOpenMPRuntime();
124dff0c46cSDimitry Andric   if (LangOpts.CUDA)
1256122f3e6SDimitry Andric     createCUDARuntime();
126f22ef01cSRoman Divacky 
1277ae0e2c9SDimitry Andric   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
12839d628a0SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
1297ae0e2c9SDimitry Andric       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
130e7145dcbSDimitry Andric     TBAA.reset(new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
131e7145dcbSDimitry Andric                                getCXXABI().getMangleContext()));
1322754fe60SDimitry Andric 
1333b0f4066SDimitry Andric   // If debug info or coverage generation is enabled, create the CGDebugInfo
1343b0f4066SDimitry Andric   // object.
135e7145dcbSDimitry Andric   if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
136e7145dcbSDimitry Andric       CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
137e7145dcbSDimitry Andric     DebugInfo.reset(new CGDebugInfo(*this));
1382754fe60SDimitry Andric 
1392754fe60SDimitry Andric   Block.GlobalUniqueCount = 0;
1402754fe60SDimitry Andric 
1410623d748SDimitry Andric   if (C.getLangOpts().ObjC1)
142e7145dcbSDimitry Andric     ObjCData.reset(new ObjCEntrypoints());
14359d1ed5bSDimitry Andric 
144e7145dcbSDimitry Andric   if (CodeGenOpts.hasProfileClangUse()) {
145e7145dcbSDimitry Andric     auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
146e7145dcbSDimitry Andric         CodeGenOpts.ProfileInstrumentUsePath);
147e7145dcbSDimitry Andric     if (auto E = ReaderOrErr.takeError()) {
14859d1ed5bSDimitry Andric       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1493dac3a9bSDimitry Andric                                               "Could not read profile %0: %1");
150e7145dcbSDimitry Andric       llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
151e7145dcbSDimitry Andric         getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
152e7145dcbSDimitry Andric                                   << EI.message();
153e7145dcbSDimitry Andric       });
15433956c43SDimitry Andric     } else
15533956c43SDimitry Andric       PGOReader = std::move(ReaderOrErr.get());
15659d1ed5bSDimitry Andric   }
15739d628a0SDimitry Andric 
15839d628a0SDimitry Andric   // If coverage mapping generation is enabled, create the
15939d628a0SDimitry Andric   // CoverageMappingModuleGen object.
16039d628a0SDimitry Andric   if (CodeGenOpts.CoverageMapping)
16139d628a0SDimitry Andric     CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
162f22ef01cSRoman Divacky }
163f22ef01cSRoman Divacky 
164e7145dcbSDimitry Andric CodeGenModule::~CodeGenModule() {}
165f22ef01cSRoman Divacky 
166f22ef01cSRoman Divacky void CodeGenModule::createObjCRuntime() {
1677ae0e2c9SDimitry Andric   // This is just isGNUFamily(), but we want to force implementors of
1687ae0e2c9SDimitry Andric   // new ABIs to decide how best to do this.
1697ae0e2c9SDimitry Andric   switch (LangOpts.ObjCRuntime.getKind()) {
1707ae0e2c9SDimitry Andric   case ObjCRuntime::GNUstep:
1717ae0e2c9SDimitry Andric   case ObjCRuntime::GCC:
1727ae0e2c9SDimitry Andric   case ObjCRuntime::ObjFW:
173e7145dcbSDimitry Andric     ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
1747ae0e2c9SDimitry Andric     return;
1757ae0e2c9SDimitry Andric 
1767ae0e2c9SDimitry Andric   case ObjCRuntime::FragileMacOSX:
1777ae0e2c9SDimitry Andric   case ObjCRuntime::MacOSX:
1787ae0e2c9SDimitry Andric   case ObjCRuntime::iOS:
1790623d748SDimitry Andric   case ObjCRuntime::WatchOS:
180e7145dcbSDimitry Andric     ObjCRuntime.reset(CreateMacObjCRuntime(*this));
1817ae0e2c9SDimitry Andric     return;
1827ae0e2c9SDimitry Andric   }
1837ae0e2c9SDimitry Andric   llvm_unreachable("bad runtime kind");
1846122f3e6SDimitry Andric }
1856122f3e6SDimitry Andric 
1866122f3e6SDimitry Andric void CodeGenModule::createOpenCLRuntime() {
187e7145dcbSDimitry Andric   OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
1886122f3e6SDimitry Andric }
1896122f3e6SDimitry Andric 
19059d1ed5bSDimitry Andric void CodeGenModule::createOpenMPRuntime() {
191e7145dcbSDimitry Andric   // Select a specialized code generation class based on the target, if any.
192e7145dcbSDimitry Andric   // If it does not exist use the default implementation.
19344290647SDimitry Andric   switch (getTriple().getArch()) {
194e7145dcbSDimitry Andric   case llvm::Triple::nvptx:
195e7145dcbSDimitry Andric   case llvm::Triple::nvptx64:
196e7145dcbSDimitry Andric     assert(getLangOpts().OpenMPIsDevice &&
197e7145dcbSDimitry Andric            "OpenMP NVPTX is only prepared to deal with device code.");
198e7145dcbSDimitry Andric     OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
199e7145dcbSDimitry Andric     break;
200e7145dcbSDimitry Andric   default:
201e7145dcbSDimitry Andric     OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
202e7145dcbSDimitry Andric     break;
203e7145dcbSDimitry Andric   }
20459d1ed5bSDimitry Andric }
20559d1ed5bSDimitry Andric 
2066122f3e6SDimitry Andric void CodeGenModule::createCUDARuntime() {
207e7145dcbSDimitry Andric   CUDARuntime.reset(CreateNVCUDARuntime(*this));
208f22ef01cSRoman Divacky }
209f22ef01cSRoman Divacky 
21039d628a0SDimitry Andric void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
21139d628a0SDimitry Andric   Replacements[Name] = C;
21239d628a0SDimitry Andric }
21339d628a0SDimitry Andric 
214f785676fSDimitry Andric void CodeGenModule::applyReplacements() {
2158f0fd8f6SDimitry Andric   for (auto &I : Replacements) {
2168f0fd8f6SDimitry Andric     StringRef MangledName = I.first();
2178f0fd8f6SDimitry Andric     llvm::Constant *Replacement = I.second;
218f785676fSDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
219f785676fSDimitry Andric     if (!Entry)
220f785676fSDimitry Andric       continue;
22159d1ed5bSDimitry Andric     auto *OldF = cast<llvm::Function>(Entry);
22259d1ed5bSDimitry Andric     auto *NewF = dyn_cast<llvm::Function>(Replacement);
223f785676fSDimitry Andric     if (!NewF) {
22459d1ed5bSDimitry Andric       if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
22559d1ed5bSDimitry Andric         NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
22659d1ed5bSDimitry Andric       } else {
22759d1ed5bSDimitry Andric         auto *CE = cast<llvm::ConstantExpr>(Replacement);
228f785676fSDimitry Andric         assert(CE->getOpcode() == llvm::Instruction::BitCast ||
229f785676fSDimitry Andric                CE->getOpcode() == llvm::Instruction::GetElementPtr);
230f785676fSDimitry Andric         NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
231f785676fSDimitry Andric       }
23259d1ed5bSDimitry Andric     }
233f785676fSDimitry Andric 
234f785676fSDimitry Andric     // Replace old with new, but keep the old order.
235f785676fSDimitry Andric     OldF->replaceAllUsesWith(Replacement);
236f785676fSDimitry Andric     if (NewF) {
237f785676fSDimitry Andric       NewF->removeFromParent();
2380623d748SDimitry Andric       OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
2390623d748SDimitry Andric                                                        NewF);
240f785676fSDimitry Andric     }
241f785676fSDimitry Andric     OldF->eraseFromParent();
242f785676fSDimitry Andric   }
243f785676fSDimitry Andric }
244f785676fSDimitry Andric 
2450623d748SDimitry Andric void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
2460623d748SDimitry Andric   GlobalValReplacements.push_back(std::make_pair(GV, C));
2470623d748SDimitry Andric }
2480623d748SDimitry Andric 
2490623d748SDimitry Andric void CodeGenModule::applyGlobalValReplacements() {
2500623d748SDimitry Andric   for (auto &I : GlobalValReplacements) {
2510623d748SDimitry Andric     llvm::GlobalValue *GV = I.first;
2520623d748SDimitry Andric     llvm::Constant *C = I.second;
2530623d748SDimitry Andric 
2540623d748SDimitry Andric     GV->replaceAllUsesWith(C);
2550623d748SDimitry Andric     GV->eraseFromParent();
2560623d748SDimitry Andric   }
2570623d748SDimitry Andric }
2580623d748SDimitry Andric 
25959d1ed5bSDimitry Andric // This is only used in aliases that we created and we know they have a
26059d1ed5bSDimitry Andric // linear structure.
261e7145dcbSDimitry Andric static const llvm::GlobalObject *getAliasedGlobal(
262e7145dcbSDimitry Andric     const llvm::GlobalIndirectSymbol &GIS) {
263e7145dcbSDimitry Andric   llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
264e7145dcbSDimitry Andric   const llvm::Constant *C = &GIS;
26559d1ed5bSDimitry Andric   for (;;) {
26659d1ed5bSDimitry Andric     C = C->stripPointerCasts();
26759d1ed5bSDimitry Andric     if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
26859d1ed5bSDimitry Andric       return GO;
26959d1ed5bSDimitry Andric     // stripPointerCasts will not walk over weak aliases.
270e7145dcbSDimitry Andric     auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
271e7145dcbSDimitry Andric     if (!GIS2)
27259d1ed5bSDimitry Andric       return nullptr;
273e7145dcbSDimitry Andric     if (!Visited.insert(GIS2).second)
27459d1ed5bSDimitry Andric       return nullptr;
275e7145dcbSDimitry Andric     C = GIS2->getIndirectSymbol();
27659d1ed5bSDimitry Andric   }
27759d1ed5bSDimitry Andric }
27859d1ed5bSDimitry Andric 
279f785676fSDimitry Andric void CodeGenModule::checkAliases() {
28059d1ed5bSDimitry Andric   // Check if the constructed aliases are well formed. It is really unfortunate
28159d1ed5bSDimitry Andric   // that we have to do this in CodeGen, but we only construct mangled names
28259d1ed5bSDimitry Andric   // and aliases during codegen.
283f785676fSDimitry Andric   bool Error = false;
28459d1ed5bSDimitry Andric   DiagnosticsEngine &Diags = getDiags();
2858f0fd8f6SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
28659d1ed5bSDimitry Andric     const auto *D = cast<ValueDecl>(GD.getDecl());
287e7145dcbSDimitry Andric     SourceLocation Location;
288e7145dcbSDimitry Andric     bool IsIFunc = D->hasAttr<IFuncAttr>();
289e7145dcbSDimitry Andric     if (const Attr *A = D->getDefiningAttr())
290e7145dcbSDimitry Andric       Location = A->getLocation();
291e7145dcbSDimitry Andric     else
292e7145dcbSDimitry Andric       llvm_unreachable("Not an alias or ifunc?");
293f785676fSDimitry Andric     StringRef MangledName = getMangledName(GD);
294f785676fSDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
295e7145dcbSDimitry Andric     auto *Alias  = cast<llvm::GlobalIndirectSymbol>(Entry);
29659d1ed5bSDimitry Andric     const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
29759d1ed5bSDimitry Andric     if (!GV) {
298f785676fSDimitry Andric       Error = true;
299e7145dcbSDimitry Andric       Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
30059d1ed5bSDimitry Andric     } else if (GV->isDeclaration()) {
301f785676fSDimitry Andric       Error = true;
302e7145dcbSDimitry Andric       Diags.Report(Location, diag::err_alias_to_undefined)
303e7145dcbSDimitry Andric           << IsIFunc << IsIFunc;
304e7145dcbSDimitry Andric     } else if (IsIFunc) {
305e7145dcbSDimitry Andric       // Check resolver function type.
306e7145dcbSDimitry Andric       llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
307e7145dcbSDimitry Andric           GV->getType()->getPointerElementType());
308e7145dcbSDimitry Andric       assert(FTy);
309e7145dcbSDimitry Andric       if (!FTy->getReturnType()->isPointerTy())
310e7145dcbSDimitry Andric         Diags.Report(Location, diag::err_ifunc_resolver_return);
311e7145dcbSDimitry Andric       if (FTy->getNumParams())
312e7145dcbSDimitry Andric         Diags.Report(Location, diag::err_ifunc_resolver_params);
31359d1ed5bSDimitry Andric     }
31459d1ed5bSDimitry Andric 
315e7145dcbSDimitry Andric     llvm::Constant *Aliasee = Alias->getIndirectSymbol();
31659d1ed5bSDimitry Andric     llvm::GlobalValue *AliaseeGV;
31759d1ed5bSDimitry Andric     if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
31859d1ed5bSDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
31959d1ed5bSDimitry Andric     else
32059d1ed5bSDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
32159d1ed5bSDimitry Andric 
32259d1ed5bSDimitry Andric     if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
32359d1ed5bSDimitry Andric       StringRef AliasSection = SA->getName();
32459d1ed5bSDimitry Andric       if (AliasSection != AliaseeGV->getSection())
32559d1ed5bSDimitry Andric         Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
326e7145dcbSDimitry Andric             << AliasSection << IsIFunc << IsIFunc;
32759d1ed5bSDimitry Andric     }
32859d1ed5bSDimitry Andric 
32959d1ed5bSDimitry Andric     // We have to handle alias to weak aliases in here. LLVM itself disallows
33059d1ed5bSDimitry Andric     // this since the object semantics would not match the IL one. For
33159d1ed5bSDimitry Andric     // compatibility with gcc we implement it by just pointing the alias
33259d1ed5bSDimitry Andric     // to its aliasee's aliasee. We also warn, since the user is probably
33359d1ed5bSDimitry Andric     // expecting the link to be weak.
334e7145dcbSDimitry Andric     if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
335e7145dcbSDimitry Andric       if (GA->isInterposable()) {
336e7145dcbSDimitry Andric         Diags.Report(Location, diag::warn_alias_to_weak_alias)
337e7145dcbSDimitry Andric             << GV->getName() << GA->getName() << IsIFunc;
33859d1ed5bSDimitry Andric         Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
339e7145dcbSDimitry Andric             GA->getIndirectSymbol(), Alias->getType());
340e7145dcbSDimitry Andric         Alias->setIndirectSymbol(Aliasee);
34159d1ed5bSDimitry Andric       }
342f785676fSDimitry Andric     }
343f785676fSDimitry Andric   }
344f785676fSDimitry Andric   if (!Error)
345f785676fSDimitry Andric     return;
346f785676fSDimitry Andric 
3478f0fd8f6SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
348f785676fSDimitry Andric     StringRef MangledName = getMangledName(GD);
349f785676fSDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
350e7145dcbSDimitry Andric     auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
351f785676fSDimitry Andric     Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
352f785676fSDimitry Andric     Alias->eraseFromParent();
353f785676fSDimitry Andric   }
354f785676fSDimitry Andric }
355f785676fSDimitry Andric 
35659d1ed5bSDimitry Andric void CodeGenModule::clear() {
35759d1ed5bSDimitry Andric   DeferredDeclsToEmit.clear();
35833956c43SDimitry Andric   if (OpenMPRuntime)
35933956c43SDimitry Andric     OpenMPRuntime->clear();
36059d1ed5bSDimitry Andric }
36159d1ed5bSDimitry Andric 
36259d1ed5bSDimitry Andric void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
36359d1ed5bSDimitry Andric                                        StringRef MainFile) {
36459d1ed5bSDimitry Andric   if (!hasDiagnostics())
36559d1ed5bSDimitry Andric     return;
36659d1ed5bSDimitry Andric   if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
36759d1ed5bSDimitry Andric     if (MainFile.empty())
36859d1ed5bSDimitry Andric       MainFile = "<stdin>";
36959d1ed5bSDimitry Andric     Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
37059d1ed5bSDimitry Andric   } else
37159d1ed5bSDimitry Andric     Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Missing
37259d1ed5bSDimitry Andric                                                       << Mismatched;
37359d1ed5bSDimitry Andric }
37459d1ed5bSDimitry Andric 
375f22ef01cSRoman Divacky void CodeGenModule::Release() {
376f22ef01cSRoman Divacky   EmitDeferred();
3770623d748SDimitry Andric   applyGlobalValReplacements();
378f785676fSDimitry Andric   applyReplacements();
379f785676fSDimitry Andric   checkAliases();
380f22ef01cSRoman Divacky   EmitCXXGlobalInitFunc();
381f22ef01cSRoman Divacky   EmitCXXGlobalDtorFunc();
382284c1978SDimitry Andric   EmitCXXThreadLocalInitFunc();
3836122f3e6SDimitry Andric   if (ObjCRuntime)
3846122f3e6SDimitry Andric     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
385f22ef01cSRoman Divacky       AddGlobalCtor(ObjCInitFunction);
38633956c43SDimitry Andric   if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
38733956c43SDimitry Andric       CUDARuntime) {
38833956c43SDimitry Andric     if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
38933956c43SDimitry Andric       AddGlobalCtor(CudaCtorFunction);
39033956c43SDimitry Andric     if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
39133956c43SDimitry Andric       AddGlobalDtor(CudaDtorFunction);
39233956c43SDimitry Andric   }
393ea942507SDimitry Andric   if (OpenMPRuntime)
394ea942507SDimitry Andric     if (llvm::Function *OpenMPRegistrationFunction =
395ea942507SDimitry Andric             OpenMPRuntime->emitRegistrationFunction())
396ea942507SDimitry Andric       AddGlobalCtor(OpenMPRegistrationFunction, 0);
3970623d748SDimitry Andric   if (PGOReader) {
398e7145dcbSDimitry Andric     getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
3990623d748SDimitry Andric     if (PGOStats.hasDiagnostics())
40059d1ed5bSDimitry Andric       PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
4010623d748SDimitry Andric   }
402f22ef01cSRoman Divacky   EmitCtorList(GlobalCtors, "llvm.global_ctors");
403f22ef01cSRoman Divacky   EmitCtorList(GlobalDtors, "llvm.global_dtors");
4046122f3e6SDimitry Andric   EmitGlobalAnnotations();
405284c1978SDimitry Andric   EmitStaticExternCAliases();
40639d628a0SDimitry Andric   EmitDeferredUnusedCoverageMappings();
40739d628a0SDimitry Andric   if (CoverageMapping)
40839d628a0SDimitry Andric     CoverageMapping->emit();
409e7145dcbSDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
410e7145dcbSDimitry Andric     CodeGenFunction(*this).EmitCfiCheckFail();
41159d1ed5bSDimitry Andric   emitLLVMUsed();
412e7145dcbSDimitry Andric   if (SanStats)
413e7145dcbSDimitry Andric     SanStats->finish();
414ffd1746dSEd Schouten 
415f785676fSDimitry Andric   if (CodeGenOpts.Autolink &&
416f785676fSDimitry Andric       (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
417139f7f9bSDimitry Andric     EmitModuleLinkOptions();
418139f7f9bSDimitry Andric   }
4190623d748SDimitry Andric   if (CodeGenOpts.DwarfVersion) {
420f785676fSDimitry Andric     // We actually want the latest version when there are conflicts.
421f785676fSDimitry Andric     // We can change from Warning to Latest if such mode is supported.
422f785676fSDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
423f785676fSDimitry Andric                               CodeGenOpts.DwarfVersion);
4240623d748SDimitry Andric   }
4250623d748SDimitry Andric   if (CodeGenOpts.EmitCodeView) {
4260623d748SDimitry Andric     // Indicate that we want CodeView in the metadata.
4270623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
4280623d748SDimitry Andric   }
4290623d748SDimitry Andric   if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
4300623d748SDimitry Andric     // We don't support LTO with 2 with different StrictVTablePointers
4310623d748SDimitry Andric     // FIXME: we could support it by stripping all the information introduced
4320623d748SDimitry Andric     // by StrictVTablePointers.
4330623d748SDimitry Andric 
4340623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
4350623d748SDimitry Andric 
4360623d748SDimitry Andric     llvm::Metadata *Ops[2] = {
4370623d748SDimitry Andric               llvm::MDString::get(VMContext, "StrictVTablePointers"),
4380623d748SDimitry Andric               llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
4390623d748SDimitry Andric                   llvm::Type::getInt32Ty(VMContext), 1))};
4400623d748SDimitry Andric 
4410623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Require,
4420623d748SDimitry Andric                               "StrictVTablePointersRequirement",
4430623d748SDimitry Andric                               llvm::MDNode::get(VMContext, Ops));
4440623d748SDimitry Andric   }
445f785676fSDimitry Andric   if (DebugInfo)
44659d1ed5bSDimitry Andric     // We support a single version in the linked module. The LLVM
44759d1ed5bSDimitry Andric     // parser will drop debug info with a different version number
44859d1ed5bSDimitry Andric     // (and warn about it, too).
44959d1ed5bSDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
450f785676fSDimitry Andric                               llvm::DEBUG_METADATA_VERSION);
451139f7f9bSDimitry Andric 
45259d1ed5bSDimitry Andric   // We need to record the widths of enums and wchar_t, so that we can generate
45359d1ed5bSDimitry Andric   // the correct build attributes in the ARM backend.
45459d1ed5bSDimitry Andric   llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
45559d1ed5bSDimitry Andric   if (   Arch == llvm::Triple::arm
45659d1ed5bSDimitry Andric       || Arch == llvm::Triple::armeb
45759d1ed5bSDimitry Andric       || Arch == llvm::Triple::thumb
45859d1ed5bSDimitry Andric       || Arch == llvm::Triple::thumbeb) {
45959d1ed5bSDimitry Andric     // Width of wchar_t in bytes
46059d1ed5bSDimitry Andric     uint64_t WCharWidth =
46159d1ed5bSDimitry Andric         Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
46259d1ed5bSDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
46359d1ed5bSDimitry Andric 
46459d1ed5bSDimitry Andric     // The minimum width of an enum in bytes
46559d1ed5bSDimitry Andric     uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
46659d1ed5bSDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
46759d1ed5bSDimitry Andric   }
46859d1ed5bSDimitry Andric 
4690623d748SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
4700623d748SDimitry Andric     // Indicate that we want cross-DSO control flow integrity checks.
4710623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
4720623d748SDimitry Andric   }
4730623d748SDimitry Andric 
47444290647SDimitry Andric   if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
475e7145dcbSDimitry Andric     // Indicate whether __nvvm_reflect should be configured to flush denormal
476e7145dcbSDimitry Andric     // floating point values to 0.  (This corresponds to its "__CUDA_FTZ"
477e7145dcbSDimitry Andric     // property.)
478e7145dcbSDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
479e7145dcbSDimitry Andric                               LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
48039d628a0SDimitry Andric   }
48139d628a0SDimitry Andric 
482e7145dcbSDimitry Andric   if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
483e7145dcbSDimitry Andric     assert(PLevel < 3 && "Invalid PIC Level");
484e7145dcbSDimitry Andric     getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
485e7145dcbSDimitry Andric     if (Context.getLangOpts().PIE)
486e7145dcbSDimitry Andric       getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
48739d628a0SDimitry Andric   }
48839d628a0SDimitry Andric 
4892754fe60SDimitry Andric   SimplifyPersonality();
4902754fe60SDimitry Andric 
491ffd1746dSEd Schouten   if (getCodeGenOpts().EmitDeclMetadata)
492ffd1746dSEd Schouten     EmitDeclMetadata();
493bd5abe19SDimitry Andric 
494bd5abe19SDimitry Andric   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
495bd5abe19SDimitry Andric     EmitCoverageFile();
4966122f3e6SDimitry Andric 
4976122f3e6SDimitry Andric   if (DebugInfo)
4986122f3e6SDimitry Andric     DebugInfo->finalize();
499f785676fSDimitry Andric 
500f785676fSDimitry Andric   EmitVersionIdentMetadata();
50159d1ed5bSDimitry Andric 
50259d1ed5bSDimitry Andric   EmitTargetMetadata();
503f22ef01cSRoman Divacky }
504f22ef01cSRoman Divacky 
5053b0f4066SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
5063b0f4066SDimitry Andric   // Make sure that this type is translated.
5073b0f4066SDimitry Andric   Types.UpdateCompletedType(TD);
5083b0f4066SDimitry Andric }
5093b0f4066SDimitry Andric 
510e7145dcbSDimitry Andric void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
511e7145dcbSDimitry Andric   // Make sure that this type is translated.
512e7145dcbSDimitry Andric   Types.RefreshTypeCacheForClass(RD);
513e7145dcbSDimitry Andric }
514e7145dcbSDimitry Andric 
5152754fe60SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
5162754fe60SDimitry Andric   if (!TBAA)
51759d1ed5bSDimitry Andric     return nullptr;
5182754fe60SDimitry Andric   return TBAA->getTBAAInfo(QTy);
5192754fe60SDimitry Andric }
5202754fe60SDimitry Andric 
521dff0c46cSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
522dff0c46cSDimitry Andric   if (!TBAA)
52359d1ed5bSDimitry Andric     return nullptr;
524dff0c46cSDimitry Andric   return TBAA->getTBAAInfoForVTablePtr();
525dff0c46cSDimitry Andric }
526dff0c46cSDimitry Andric 
5273861d79fSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
5283861d79fSDimitry Andric   if (!TBAA)
52959d1ed5bSDimitry Andric     return nullptr;
5303861d79fSDimitry Andric   return TBAA->getTBAAStructInfo(QTy);
5313861d79fSDimitry Andric }
5323861d79fSDimitry Andric 
533139f7f9bSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
534139f7f9bSDimitry Andric                                                   llvm::MDNode *AccessN,
535139f7f9bSDimitry Andric                                                   uint64_t O) {
536139f7f9bSDimitry Andric   if (!TBAA)
53759d1ed5bSDimitry Andric     return nullptr;
538139f7f9bSDimitry Andric   return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
539139f7f9bSDimitry Andric }
540139f7f9bSDimitry Andric 
541f785676fSDimitry Andric /// Decorate the instruction with a TBAA tag. For both scalar TBAA
542f785676fSDimitry Andric /// and struct-path aware TBAA, the tag has the same format:
543f785676fSDimitry Andric /// base type, access type and offset.
544284c1978SDimitry Andric /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
5450623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
546284c1978SDimitry Andric                                                 llvm::MDNode *TBAAInfo,
547284c1978SDimitry Andric                                                 bool ConvertTypeToTag) {
548f785676fSDimitry Andric   if (ConvertTypeToTag && TBAA)
549284c1978SDimitry Andric     Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
550284c1978SDimitry Andric                       TBAA->getTBAAScalarTagInfo(TBAAInfo));
551284c1978SDimitry Andric   else
5522754fe60SDimitry Andric     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
5532754fe60SDimitry Andric }
5542754fe60SDimitry Andric 
5550623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup(
5560623d748SDimitry Andric     llvm::Instruction *I, const CXXRecordDecl *RD) {
5570623d748SDimitry Andric   llvm::Metadata *MD = CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
5580623d748SDimitry Andric   auto *MetaDataNode = dyn_cast<llvm::MDNode>(MD);
5590623d748SDimitry Andric   // Check if we have to wrap MDString in MDNode.
5600623d748SDimitry Andric   if (!MetaDataNode)
5610623d748SDimitry Andric     MetaDataNode = llvm::MDNode::get(getLLVMContext(), MD);
5620623d748SDimitry Andric   I->setMetadata(llvm::LLVMContext::MD_invariant_group, MetaDataNode);
5630623d748SDimitry Andric }
5640623d748SDimitry Andric 
56559d1ed5bSDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) {
56659d1ed5bSDimitry Andric   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
56759d1ed5bSDimitry Andric   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
568f22ef01cSRoman Divacky }
569f22ef01cSRoman Divacky 
570f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
571f22ef01cSRoman Divacky /// specified stmt yet.
572f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
5736122f3e6SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
574f22ef01cSRoman Divacky                                                "cannot compile this %0 yet");
575f22ef01cSRoman Divacky   std::string Msg = Type;
576f22ef01cSRoman Divacky   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
577f22ef01cSRoman Divacky     << Msg << S->getSourceRange();
578f22ef01cSRoman Divacky }
579f22ef01cSRoman Divacky 
580f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
581f22ef01cSRoman Divacky /// specified decl yet.
582f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
5836122f3e6SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
584f22ef01cSRoman Divacky                                                "cannot compile this %0 yet");
585f22ef01cSRoman Divacky   std::string Msg = Type;
586f22ef01cSRoman Divacky   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
587f22ef01cSRoman Divacky }
588f22ef01cSRoman Divacky 
58917a519f9SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
59017a519f9SDimitry Andric   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
59117a519f9SDimitry Andric }
59217a519f9SDimitry Andric 
593f22ef01cSRoman Divacky void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
5942754fe60SDimitry Andric                                         const NamedDecl *D) const {
595f22ef01cSRoman Divacky   // Internal definitions always have default visibility.
596f22ef01cSRoman Divacky   if (GV->hasLocalLinkage()) {
597f22ef01cSRoman Divacky     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
598f22ef01cSRoman Divacky     return;
599f22ef01cSRoman Divacky   }
600f22ef01cSRoman Divacky 
6012754fe60SDimitry Andric   // Set visibility for definitions.
602139f7f9bSDimitry Andric   LinkageInfo LV = D->getLinkageAndVisibility();
603139f7f9bSDimitry Andric   if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
604139f7f9bSDimitry Andric     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
605f22ef01cSRoman Divacky }
606f22ef01cSRoman Divacky 
6077ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
6087ae0e2c9SDimitry Andric   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
6097ae0e2c9SDimitry Andric       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
6107ae0e2c9SDimitry Andric       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
6117ae0e2c9SDimitry Andric       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
6127ae0e2c9SDimitry Andric       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
6137ae0e2c9SDimitry Andric }
6147ae0e2c9SDimitry Andric 
6157ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
6167ae0e2c9SDimitry Andric     CodeGenOptions::TLSModel M) {
6177ae0e2c9SDimitry Andric   switch (M) {
6187ae0e2c9SDimitry Andric   case CodeGenOptions::GeneralDynamicTLSModel:
6197ae0e2c9SDimitry Andric     return llvm::GlobalVariable::GeneralDynamicTLSModel;
6207ae0e2c9SDimitry Andric   case CodeGenOptions::LocalDynamicTLSModel:
6217ae0e2c9SDimitry Andric     return llvm::GlobalVariable::LocalDynamicTLSModel;
6227ae0e2c9SDimitry Andric   case CodeGenOptions::InitialExecTLSModel:
6237ae0e2c9SDimitry Andric     return llvm::GlobalVariable::InitialExecTLSModel;
6247ae0e2c9SDimitry Andric   case CodeGenOptions::LocalExecTLSModel:
6257ae0e2c9SDimitry Andric     return llvm::GlobalVariable::LocalExecTLSModel;
6267ae0e2c9SDimitry Andric   }
6277ae0e2c9SDimitry Andric   llvm_unreachable("Invalid TLS model!");
6287ae0e2c9SDimitry Andric }
6297ae0e2c9SDimitry Andric 
63039d628a0SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
631284c1978SDimitry Andric   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
6327ae0e2c9SDimitry Andric 
63339d628a0SDimitry Andric   llvm::GlobalValue::ThreadLocalMode TLM;
6343861d79fSDimitry Andric   TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
6357ae0e2c9SDimitry Andric 
6367ae0e2c9SDimitry Andric   // Override the TLS model if it is explicitly specified.
63759d1ed5bSDimitry Andric   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
6387ae0e2c9SDimitry Andric     TLM = GetLLVMTLSModel(Attr->getModel());
6397ae0e2c9SDimitry Andric   }
6407ae0e2c9SDimitry Andric 
6417ae0e2c9SDimitry Andric   GV->setThreadLocalMode(TLM);
6427ae0e2c9SDimitry Andric }
6437ae0e2c9SDimitry Andric 
6446122f3e6SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
645444ed5c5SDimitry Andric   GlobalDecl CanonicalGD = GD.getCanonicalDecl();
646444ed5c5SDimitry Andric 
647444ed5c5SDimitry Andric   // Some ABIs don't have constructor variants.  Make sure that base and
648444ed5c5SDimitry Andric   // complete constructors get mangled the same.
649444ed5c5SDimitry Andric   if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
650444ed5c5SDimitry Andric     if (!getTarget().getCXXABI().hasConstructorVariants()) {
651444ed5c5SDimitry Andric       CXXCtorType OrigCtorType = GD.getCtorType();
652444ed5c5SDimitry Andric       assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
653444ed5c5SDimitry Andric       if (OrigCtorType == Ctor_Base)
654444ed5c5SDimitry Andric         CanonicalGD = GlobalDecl(CD, Ctor_Complete);
655444ed5c5SDimitry Andric     }
656444ed5c5SDimitry Andric   }
657444ed5c5SDimitry Andric 
658444ed5c5SDimitry Andric   StringRef &FoundStr = MangledDeclNames[CanonicalGD];
65959d1ed5bSDimitry Andric   if (!FoundStr.empty())
66059d1ed5bSDimitry Andric     return FoundStr;
661f22ef01cSRoman Divacky 
66259d1ed5bSDimitry Andric   const auto *ND = cast<NamedDecl>(GD.getDecl());
663dff0c46cSDimitry Andric   SmallString<256> Buffer;
66459d1ed5bSDimitry Andric   StringRef Str;
66559d1ed5bSDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
6662754fe60SDimitry Andric     llvm::raw_svector_ostream Out(Buffer);
66759d1ed5bSDimitry Andric     if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
6682754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
66959d1ed5bSDimitry Andric     else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
6702754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
671ffd1746dSEd Schouten     else
6722754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleName(ND, Out);
67359d1ed5bSDimitry Andric     Str = Out.str();
67459d1ed5bSDimitry Andric   } else {
67559d1ed5bSDimitry Andric     IdentifierInfo *II = ND->getIdentifier();
67659d1ed5bSDimitry Andric     assert(II && "Attempt to mangle unnamed decl.");
67744290647SDimitry Andric     const auto *FD = dyn_cast<FunctionDecl>(ND);
67844290647SDimitry Andric 
67944290647SDimitry Andric     if (FD &&
68044290647SDimitry Andric         FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
68144290647SDimitry Andric       llvm::raw_svector_ostream Out(Buffer);
68244290647SDimitry Andric       Out << "__regcall3__" << II->getName();
68344290647SDimitry Andric       Str = Out.str();
68444290647SDimitry Andric     } else {
68559d1ed5bSDimitry Andric       Str = II->getName();
686ffd1746dSEd Schouten     }
68744290647SDimitry Andric   }
688ffd1746dSEd Schouten 
68939d628a0SDimitry Andric   // Keep the first result in the case of a mangling collision.
69039d628a0SDimitry Andric   auto Result = Manglings.insert(std::make_pair(Str, GD));
69139d628a0SDimitry Andric   return FoundStr = Result.first->first();
69259d1ed5bSDimitry Andric }
69359d1ed5bSDimitry Andric 
69459d1ed5bSDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
695ffd1746dSEd Schouten                                              const BlockDecl *BD) {
6962754fe60SDimitry Andric   MangleContext &MangleCtx = getCXXABI().getMangleContext();
6972754fe60SDimitry Andric   const Decl *D = GD.getDecl();
69859d1ed5bSDimitry Andric 
69959d1ed5bSDimitry Andric   SmallString<256> Buffer;
70059d1ed5bSDimitry Andric   llvm::raw_svector_ostream Out(Buffer);
70159d1ed5bSDimitry Andric   if (!D)
7027ae0e2c9SDimitry Andric     MangleCtx.mangleGlobalBlock(BD,
7037ae0e2c9SDimitry Andric       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
70459d1ed5bSDimitry Andric   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
7052754fe60SDimitry Andric     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
70659d1ed5bSDimitry Andric   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
7072754fe60SDimitry Andric     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
7082754fe60SDimitry Andric   else
7092754fe60SDimitry Andric     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
71059d1ed5bSDimitry Andric 
71139d628a0SDimitry Andric   auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
71239d628a0SDimitry Andric   return Result.first->first();
713f22ef01cSRoman Divacky }
714f22ef01cSRoman Divacky 
7156122f3e6SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
716f22ef01cSRoman Divacky   return getModule().getNamedValue(Name);
717f22ef01cSRoman Divacky }
718f22ef01cSRoman Divacky 
719f22ef01cSRoman Divacky /// AddGlobalCtor - Add a function to the list that will be called before
720f22ef01cSRoman Divacky /// main() runs.
72159d1ed5bSDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
72259d1ed5bSDimitry Andric                                   llvm::Constant *AssociatedData) {
723f22ef01cSRoman Divacky   // FIXME: Type coercion of void()* types.
72459d1ed5bSDimitry Andric   GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
725f22ef01cSRoman Divacky }
726f22ef01cSRoman Divacky 
727f22ef01cSRoman Divacky /// AddGlobalDtor - Add a function to the list that will be called
728f22ef01cSRoman Divacky /// when the module is unloaded.
729f22ef01cSRoman Divacky void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
730f22ef01cSRoman Divacky   // FIXME: Type coercion of void()* types.
73159d1ed5bSDimitry Andric   GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
732f22ef01cSRoman Divacky }
733f22ef01cSRoman Divacky 
73444290647SDimitry Andric void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
73544290647SDimitry Andric   if (Fns.empty()) return;
73644290647SDimitry Andric 
737f22ef01cSRoman Divacky   // Ctor function type is void()*.
738bd5abe19SDimitry Andric   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
739f22ef01cSRoman Divacky   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
740f22ef01cSRoman Divacky 
74159d1ed5bSDimitry Andric   // Get the type of a ctor entry, { i32, void ()*, i8* }.
74259d1ed5bSDimitry Andric   llvm::StructType *CtorStructTy = llvm::StructType::get(
74339d628a0SDimitry Andric       Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr);
744f22ef01cSRoman Divacky 
745f22ef01cSRoman Divacky   // Construct the constructor and destructor arrays.
74644290647SDimitry Andric   ConstantInitBuilder builder(*this);
74744290647SDimitry Andric   auto ctors = builder.beginArray(CtorStructTy);
7488f0fd8f6SDimitry Andric   for (const auto &I : Fns) {
74944290647SDimitry Andric     auto ctor = ctors.beginStruct(CtorStructTy);
75044290647SDimitry Andric     ctor.addInt(Int32Ty, I.Priority);
75144290647SDimitry Andric     ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
75244290647SDimitry Andric     if (I.AssociatedData)
75344290647SDimitry Andric       ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
75444290647SDimitry Andric     else
75544290647SDimitry Andric       ctor.addNullPointer(VoidPtrTy);
75644290647SDimitry Andric     ctor.finishAndAddTo(ctors);
757f22ef01cSRoman Divacky   }
758f22ef01cSRoman Divacky 
75944290647SDimitry Andric   auto list =
76044290647SDimitry Andric     ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
76144290647SDimitry Andric                                 /*constant*/ false,
76244290647SDimitry Andric                                 llvm::GlobalValue::AppendingLinkage);
76344290647SDimitry Andric 
76444290647SDimitry Andric   // The LTO linker doesn't seem to like it when we set an alignment
76544290647SDimitry Andric   // on appending variables.  Take it off as a workaround.
76644290647SDimitry Andric   list->setAlignment(0);
76744290647SDimitry Andric 
76844290647SDimitry Andric   Fns.clear();
769f22ef01cSRoman Divacky }
770f22ef01cSRoman Divacky 
771f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes
772f785676fSDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
77359d1ed5bSDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
774f785676fSDimitry Andric 
775e580952dSDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
776f22ef01cSRoman Divacky 
77759d1ed5bSDimitry Andric   if (isa<CXXDestructorDecl>(D) &&
77859d1ed5bSDimitry Andric       getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
77959d1ed5bSDimitry Andric                                          GD.getDtorType())) {
78059d1ed5bSDimitry Andric     // Destructor variants in the Microsoft C++ ABI are always internal or
78159d1ed5bSDimitry Andric     // linkonce_odr thunks emitted on an as-needed basis.
78259d1ed5bSDimitry Andric     return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
78359d1ed5bSDimitry Andric                                    : llvm::GlobalValue::LinkOnceODRLinkage;
784f22ef01cSRoman Divacky   }
785f22ef01cSRoman Divacky 
786e7145dcbSDimitry Andric   if (isa<CXXConstructorDecl>(D) &&
787e7145dcbSDimitry Andric       cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
788e7145dcbSDimitry Andric       Context.getTargetInfo().getCXXABI().isMicrosoft()) {
789e7145dcbSDimitry Andric     // Our approach to inheriting constructors is fundamentally different from
790e7145dcbSDimitry Andric     // that used by the MS ABI, so keep our inheriting constructor thunks
791e7145dcbSDimitry Andric     // internal rather than trying to pick an unambiguous mangling for them.
792e7145dcbSDimitry Andric     return llvm::GlobalValue::InternalLinkage;
793e7145dcbSDimitry Andric   }
794e7145dcbSDimitry Andric 
79559d1ed5bSDimitry Andric   return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
79659d1ed5bSDimitry Andric }
797f22ef01cSRoman Divacky 
79897bc6c73SDimitry Andric void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
79997bc6c73SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
80097bc6c73SDimitry Andric 
80197bc6c73SDimitry Andric   if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
80297bc6c73SDimitry Andric     if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
80397bc6c73SDimitry Andric       // Don't dllexport/import destructor thunks.
80497bc6c73SDimitry Andric       F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
80597bc6c73SDimitry Andric       return;
80697bc6c73SDimitry Andric     }
80797bc6c73SDimitry Andric   }
80897bc6c73SDimitry Andric 
80997bc6c73SDimitry Andric   if (FD->hasAttr<DLLImportAttr>())
81097bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
81197bc6c73SDimitry Andric   else if (FD->hasAttr<DLLExportAttr>())
81297bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
81397bc6c73SDimitry Andric   else
81497bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
81597bc6c73SDimitry Andric }
81697bc6c73SDimitry Andric 
817e7145dcbSDimitry Andric llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
8180623d748SDimitry Andric   llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
8190623d748SDimitry Andric   if (!MDS) return nullptr;
8200623d748SDimitry Andric 
82144290647SDimitry Andric   return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
8220623d748SDimitry Andric }
8230623d748SDimitry Andric 
82459d1ed5bSDimitry Andric void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
82559d1ed5bSDimitry Andric                                                     llvm::Function *F) {
82659d1ed5bSDimitry Andric   setNonAliasAttributes(D, F);
827f22ef01cSRoman Divacky }
828f22ef01cSRoman Divacky 
829f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
830f22ef01cSRoman Divacky                                               const CGFunctionInfo &Info,
831f22ef01cSRoman Divacky                                               llvm::Function *F) {
832f22ef01cSRoman Divacky   unsigned CallingConv;
833f22ef01cSRoman Divacky   AttributeListType AttributeList;
834ea942507SDimitry Andric   ConstructAttributeList(F->getName(), Info, D, AttributeList, CallingConv,
835ea942507SDimitry Andric                          false);
836139f7f9bSDimitry Andric   F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
837f22ef01cSRoman Divacky   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
838f22ef01cSRoman Divacky }
839f22ef01cSRoman Divacky 
8406122f3e6SDimitry Andric /// Determines whether the language options require us to model
8416122f3e6SDimitry Andric /// unwind exceptions.  We treat -fexceptions as mandating this
8426122f3e6SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions
8436122f3e6SDimitry Andric /// enabled.  This means, for example, that C with -fexceptions
8446122f3e6SDimitry Andric /// enables this.
845dff0c46cSDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) {
8466122f3e6SDimitry Andric   // If exceptions are completely disabled, obviously this is false.
847dff0c46cSDimitry Andric   if (!LangOpts.Exceptions) return false;
8486122f3e6SDimitry Andric 
8496122f3e6SDimitry Andric   // If C++ exceptions are enabled, this is true.
850dff0c46cSDimitry Andric   if (LangOpts.CXXExceptions) return true;
8516122f3e6SDimitry Andric 
8526122f3e6SDimitry Andric   // If ObjC exceptions are enabled, this depends on the ABI.
853dff0c46cSDimitry Andric   if (LangOpts.ObjCExceptions) {
8547ae0e2c9SDimitry Andric     return LangOpts.ObjCRuntime.hasUnwindExceptions();
8556122f3e6SDimitry Andric   }
8566122f3e6SDimitry Andric 
8576122f3e6SDimitry Andric   return true;
8586122f3e6SDimitry Andric }
8596122f3e6SDimitry Andric 
860f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
861f22ef01cSRoman Divacky                                                            llvm::Function *F) {
862f785676fSDimitry Andric   llvm::AttrBuilder B;
863f785676fSDimitry Andric 
864bd5abe19SDimitry Andric   if (CodeGenOpts.UnwindTables)
865f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::UWTable);
866bd5abe19SDimitry Andric 
867dff0c46cSDimitry Andric   if (!hasUnwindExceptions(LangOpts))
868f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoUnwind);
869f22ef01cSRoman Divacky 
8700623d748SDimitry Andric   if (LangOpts.getStackProtector() == LangOptions::SSPOn)
8710623d748SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtect);
8720623d748SDimitry Andric   else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
8730623d748SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtectStrong);
8740623d748SDimitry Andric   else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
8750623d748SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtectReq);
8760623d748SDimitry Andric 
8770623d748SDimitry Andric   if (!D) {
87844290647SDimitry Andric     // If we don't have a declaration to control inlining, the function isn't
87944290647SDimitry Andric     // explicitly marked as alwaysinline for semantic reasons, and inlining is
88044290647SDimitry Andric     // disabled, mark the function as noinline.
88144290647SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
88244290647SDimitry Andric         CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
88344290647SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
88444290647SDimitry Andric 
8850623d748SDimitry Andric     F->addAttributes(llvm::AttributeSet::FunctionIndex,
8860623d748SDimitry Andric                      llvm::AttributeSet::get(
8870623d748SDimitry Andric                          F->getContext(),
8880623d748SDimitry Andric                          llvm::AttributeSet::FunctionIndex, B));
8890623d748SDimitry Andric     return;
8900623d748SDimitry Andric   }
8910623d748SDimitry Andric 
89244290647SDimitry Andric   if (D->hasAttr<OptimizeNoneAttr>()) {
89344290647SDimitry Andric     B.addAttribute(llvm::Attribute::OptimizeNone);
89444290647SDimitry Andric 
89544290647SDimitry Andric     // OptimizeNone implies noinline; we should not be inlining such functions.
89644290647SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
89744290647SDimitry Andric     assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
89844290647SDimitry Andric            "OptimizeNone and AlwaysInline on same function!");
89944290647SDimitry Andric 
90044290647SDimitry Andric     // We still need to handle naked functions even though optnone subsumes
90144290647SDimitry Andric     // much of their semantics.
90244290647SDimitry Andric     if (D->hasAttr<NakedAttr>())
90344290647SDimitry Andric       B.addAttribute(llvm::Attribute::Naked);
90444290647SDimitry Andric 
90544290647SDimitry Andric     // OptimizeNone wins over OptimizeForSize and MinSize.
90644290647SDimitry Andric     F->removeFnAttr(llvm::Attribute::OptimizeForSize);
90744290647SDimitry Andric     F->removeFnAttr(llvm::Attribute::MinSize);
90844290647SDimitry Andric   } else if (D->hasAttr<NakedAttr>()) {
9096122f3e6SDimitry Andric     // Naked implies noinline: we should not be inlining such functions.
910f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::Naked);
911f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
91259d1ed5bSDimitry Andric   } else if (D->hasAttr<NoDuplicateAttr>()) {
91359d1ed5bSDimitry Andric     B.addAttribute(llvm::Attribute::NoDuplicate);
914f785676fSDimitry Andric   } else if (D->hasAttr<NoInlineAttr>()) {
915f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
91659d1ed5bSDimitry Andric   } else if (D->hasAttr<AlwaysInlineAttr>() &&
91744290647SDimitry Andric              !F->hasFnAttribute(llvm::Attribute::NoInline)) {
918f785676fSDimitry Andric     // (noinline wins over always_inline, and we can't specify both in IR)
919f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::AlwaysInline);
92044290647SDimitry Andric   } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
92144290647SDimitry Andric     // If we're not inlining, then force everything that isn't always_inline to
92244290647SDimitry Andric     // carry an explicit noinline attribute.
92344290647SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
92444290647SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
92544290647SDimitry Andric   } else {
92644290647SDimitry Andric     // Otherwise, propagate the inline hint attribute and potentially use its
92744290647SDimitry Andric     // absence to mark things as noinline.
92844290647SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
92944290647SDimitry Andric       if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
93044290647SDimitry Andric             return Redecl->isInlineSpecified();
93144290647SDimitry Andric           })) {
93244290647SDimitry Andric         B.addAttribute(llvm::Attribute::InlineHint);
93344290647SDimitry Andric       } else if (CodeGenOpts.getInlining() ==
93444290647SDimitry Andric                      CodeGenOptions::OnlyHintInlining &&
93544290647SDimitry Andric                  !FD->isInlined() &&
93644290647SDimitry Andric                  !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
93744290647SDimitry Andric         B.addAttribute(llvm::Attribute::NoInline);
93844290647SDimitry Andric       }
93944290647SDimitry Andric     }
9406122f3e6SDimitry Andric   }
9412754fe60SDimitry Andric 
94244290647SDimitry Andric   // Add other optimization related attributes if we are optimizing this
94344290647SDimitry Andric   // function.
94444290647SDimitry Andric   if (!D->hasAttr<OptimizeNoneAttr>()) {
945f785676fSDimitry Andric     if (D->hasAttr<ColdAttr>()) {
946f785676fSDimitry Andric       B.addAttribute(llvm::Attribute::OptimizeForSize);
947f785676fSDimitry Andric       B.addAttribute(llvm::Attribute::Cold);
948f785676fSDimitry Andric     }
9493861d79fSDimitry Andric 
9503861d79fSDimitry Andric     if (D->hasAttr<MinSizeAttr>())
951f785676fSDimitry Andric       B.addAttribute(llvm::Attribute::MinSize);
95244290647SDimitry Andric   }
953f22ef01cSRoman Divacky 
954f785676fSDimitry Andric   F->addAttributes(llvm::AttributeSet::FunctionIndex,
955f785676fSDimitry Andric                    llvm::AttributeSet::get(
956f785676fSDimitry Andric                        F->getContext(), llvm::AttributeSet::FunctionIndex, B));
957f785676fSDimitry Andric 
958e580952dSDimitry Andric   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
959e580952dSDimitry Andric   if (alignment)
960e580952dSDimitry Andric     F->setAlignment(alignment);
961e580952dSDimitry Andric 
9620623d748SDimitry Andric   // Some C++ ABIs require 2-byte alignment for member functions, in order to
9630623d748SDimitry Andric   // reserve a bit for differentiating between virtual and non-virtual member
9640623d748SDimitry Andric   // functions. If the current target's C++ ABI requires this and this is a
9650623d748SDimitry Andric   // member function, set its alignment accordingly.
9660623d748SDimitry Andric   if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
967f22ef01cSRoman Divacky     if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
968f22ef01cSRoman Divacky       F->setAlignment(2);
969f22ef01cSRoman Divacky   }
97044290647SDimitry Andric 
97144290647SDimitry Andric   // In the cross-dso CFI mode, we want !type attributes on definitions only.
97244290647SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
97344290647SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D))
97444290647SDimitry Andric       CreateFunctionTypeMetadata(FD, F);
9750623d748SDimitry Andric }
976f22ef01cSRoman Divacky 
977f22ef01cSRoman Divacky void CodeGenModule::SetCommonAttributes(const Decl *D,
978f22ef01cSRoman Divacky                                         llvm::GlobalValue *GV) {
9790623d748SDimitry Andric   if (const auto *ND = dyn_cast_or_null<NamedDecl>(D))
9802754fe60SDimitry Andric     setGlobalVisibility(GV, ND);
9812754fe60SDimitry Andric   else
9822754fe60SDimitry Andric     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
983f22ef01cSRoman Divacky 
9840623d748SDimitry Andric   if (D && D->hasAttr<UsedAttr>())
98559d1ed5bSDimitry Andric     addUsedGlobal(GV);
98659d1ed5bSDimitry Andric }
98759d1ed5bSDimitry Andric 
98839d628a0SDimitry Andric void CodeGenModule::setAliasAttributes(const Decl *D,
98939d628a0SDimitry Andric                                        llvm::GlobalValue *GV) {
99039d628a0SDimitry Andric   SetCommonAttributes(D, GV);
99139d628a0SDimitry Andric 
99239d628a0SDimitry Andric   // Process the dllexport attribute based on whether the original definition
99339d628a0SDimitry Andric   // (not necessarily the aliasee) was exported.
99439d628a0SDimitry Andric   if (D->hasAttr<DLLExportAttr>())
99539d628a0SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
99639d628a0SDimitry Andric }
99739d628a0SDimitry Andric 
99859d1ed5bSDimitry Andric void CodeGenModule::setNonAliasAttributes(const Decl *D,
99959d1ed5bSDimitry Andric                                           llvm::GlobalObject *GO) {
100059d1ed5bSDimitry Andric   SetCommonAttributes(D, GO);
1001f22ef01cSRoman Divacky 
10020623d748SDimitry Andric   if (D)
1003f22ef01cSRoman Divacky     if (const SectionAttr *SA = D->getAttr<SectionAttr>())
100459d1ed5bSDimitry Andric       GO->setSection(SA->getName());
1005f22ef01cSRoman Divacky 
100697bc6c73SDimitry Andric   getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
1007f22ef01cSRoman Divacky }
1008f22ef01cSRoman Divacky 
1009f22ef01cSRoman Divacky void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
1010f22ef01cSRoman Divacky                                                   llvm::Function *F,
1011f22ef01cSRoman Divacky                                                   const CGFunctionInfo &FI) {
1012f22ef01cSRoman Divacky   SetLLVMFunctionAttributes(D, FI, F);
1013f22ef01cSRoman Divacky   SetLLVMFunctionAttributesForDefinition(D, F);
1014f22ef01cSRoman Divacky 
1015f22ef01cSRoman Divacky   F->setLinkage(llvm::Function::InternalLinkage);
1016f22ef01cSRoman Divacky 
101759d1ed5bSDimitry Andric   setNonAliasAttributes(D, F);
101859d1ed5bSDimitry Andric }
101959d1ed5bSDimitry Andric 
102059d1ed5bSDimitry Andric static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
102159d1ed5bSDimitry Andric                                          const NamedDecl *ND) {
102259d1ed5bSDimitry Andric   // Set linkage and visibility in case we never see a definition.
102359d1ed5bSDimitry Andric   LinkageInfo LV = ND->getLinkageAndVisibility();
102459d1ed5bSDimitry Andric   if (LV.getLinkage() != ExternalLinkage) {
102559d1ed5bSDimitry Andric     // Don't set internal linkage on declarations.
102659d1ed5bSDimitry Andric   } else {
102759d1ed5bSDimitry Andric     if (ND->hasAttr<DLLImportAttr>()) {
102859d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
102959d1ed5bSDimitry Andric       GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
103059d1ed5bSDimitry Andric     } else if (ND->hasAttr<DLLExportAttr>()) {
103159d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
103259d1ed5bSDimitry Andric       GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
103359d1ed5bSDimitry Andric     } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
103459d1ed5bSDimitry Andric       // "extern_weak" is overloaded in LLVM; we probably should have
103559d1ed5bSDimitry Andric       // separate linkage types for this.
103659d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
103759d1ed5bSDimitry Andric     }
103859d1ed5bSDimitry Andric 
103959d1ed5bSDimitry Andric     // Set visibility on a declaration only if it's explicit.
104059d1ed5bSDimitry Andric     if (LV.isVisibilityExplicit())
104159d1ed5bSDimitry Andric       GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
104259d1ed5bSDimitry Andric   }
1043f22ef01cSRoman Divacky }
1044f22ef01cSRoman Divacky 
1045e7145dcbSDimitry Andric void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD,
10460623d748SDimitry Andric                                                llvm::Function *F) {
10470623d748SDimitry Andric   // Only if we are checking indirect calls.
10480623d748SDimitry Andric   if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
10490623d748SDimitry Andric     return;
10500623d748SDimitry Andric 
10510623d748SDimitry Andric   // Non-static class methods are handled via vtable pointer checks elsewhere.
10520623d748SDimitry Andric   if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
10530623d748SDimitry Andric     return;
10540623d748SDimitry Andric 
10550623d748SDimitry Andric   // Additionally, if building with cross-DSO support...
10560623d748SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
10570623d748SDimitry Andric     // Skip available_externally functions. They won't be codegen'ed in the
10580623d748SDimitry Andric     // current module anyway.
10590623d748SDimitry Andric     if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
10600623d748SDimitry Andric       return;
10610623d748SDimitry Andric   }
10620623d748SDimitry Andric 
10630623d748SDimitry Andric   llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
1064e7145dcbSDimitry Andric   F->addTypeMetadata(0, MD);
10650623d748SDimitry Andric 
10660623d748SDimitry Andric   // Emit a hash-based bit set entry for cross-DSO calls.
1067e7145dcbSDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
1068e7145dcbSDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1069e7145dcbSDimitry Andric       F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
10700623d748SDimitry Andric }
10710623d748SDimitry Andric 
107239d628a0SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
107339d628a0SDimitry Andric                                           bool IsIncompleteFunction,
107439d628a0SDimitry Andric                                           bool IsThunk) {
107533956c43SDimitry Andric   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
10763b0f4066SDimitry Andric     // If this is an intrinsic function, set the function's attributes
10773b0f4066SDimitry Andric     // to the intrinsic's attributes.
107833956c43SDimitry Andric     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
10793b0f4066SDimitry Andric     return;
10803b0f4066SDimitry Andric   }
10813b0f4066SDimitry Andric 
108259d1ed5bSDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
1083f22ef01cSRoman Divacky 
1084f22ef01cSRoman Divacky   if (!IsIncompleteFunction)
1085dff0c46cSDimitry Andric     SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
1086f22ef01cSRoman Divacky 
108759d1ed5bSDimitry Andric   // Add the Returned attribute for "this", except for iOS 5 and earlier
108859d1ed5bSDimitry Andric   // where substantial code, including the libstdc++ dylib, was compiled with
108959d1ed5bSDimitry Andric   // GCC and does not actually return "this".
109039d628a0SDimitry Andric   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
109144290647SDimitry Andric       !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
1092f785676fSDimitry Andric     assert(!F->arg_empty() &&
1093f785676fSDimitry Andric            F->arg_begin()->getType()
1094f785676fSDimitry Andric              ->canLosslesslyBitCastTo(F->getReturnType()) &&
1095f785676fSDimitry Andric            "unexpected this return");
1096f785676fSDimitry Andric     F->addAttribute(1, llvm::Attribute::Returned);
1097f785676fSDimitry Andric   }
1098f785676fSDimitry Andric 
1099f22ef01cSRoman Divacky   // Only a few attributes are set on declarations; these may later be
1100f22ef01cSRoman Divacky   // overridden by a definition.
1101f22ef01cSRoman Divacky 
110259d1ed5bSDimitry Andric   setLinkageAndVisibilityForGV(F, FD);
11032754fe60SDimitry Andric 
1104f22ef01cSRoman Divacky   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
1105f22ef01cSRoman Divacky     F->setSection(SA->getName());
1106f785676fSDimitry Andric 
1107e7145dcbSDimitry Andric   if (FD->isReplaceableGlobalAllocationFunction()) {
1108f785676fSDimitry Andric     // A replaceable global allocation function does not act like a builtin by
1109f785676fSDimitry Andric     // default, only if it is invoked by a new-expression or delete-expression.
1110f785676fSDimitry Andric     F->addAttribute(llvm::AttributeSet::FunctionIndex,
1111f785676fSDimitry Andric                     llvm::Attribute::NoBuiltin);
11120623d748SDimitry Andric 
1113e7145dcbSDimitry Andric     // A sane operator new returns a non-aliasing pointer.
1114e7145dcbSDimitry Andric     // FIXME: Also add NonNull attribute to the return value
1115e7145dcbSDimitry Andric     // for the non-nothrow forms?
1116e7145dcbSDimitry Andric     auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1117e7145dcbSDimitry Andric     if (getCodeGenOpts().AssumeSaneOperatorNew &&
1118e7145dcbSDimitry Andric         (Kind == OO_New || Kind == OO_Array_New))
1119e7145dcbSDimitry Andric       F->addAttribute(llvm::AttributeSet::ReturnIndex,
1120e7145dcbSDimitry Andric                       llvm::Attribute::NoAlias);
1121e7145dcbSDimitry Andric   }
1122e7145dcbSDimitry Andric 
1123e7145dcbSDimitry Andric   if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1124e7145dcbSDimitry Andric     F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1125e7145dcbSDimitry Andric   else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1126e7145dcbSDimitry Andric     if (MD->isVirtual())
1127e7145dcbSDimitry Andric       F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1128e7145dcbSDimitry Andric 
112944290647SDimitry Andric   // Don't emit entries for function declarations in the cross-DSO mode. This
113044290647SDimitry Andric   // is handled with better precision by the receiving DSO.
113144290647SDimitry Andric   if (!CodeGenOpts.SanitizeCfiCrossDso)
1132e7145dcbSDimitry Andric     CreateFunctionTypeMetadata(FD, F);
1133f22ef01cSRoman Divacky }
1134f22ef01cSRoman Divacky 
113559d1ed5bSDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
1136f22ef01cSRoman Divacky   assert(!GV->isDeclaration() &&
1137f22ef01cSRoman Divacky          "Only globals with definition can force usage.");
113897bc6c73SDimitry Andric   LLVMUsed.emplace_back(GV);
1139f22ef01cSRoman Divacky }
1140f22ef01cSRoman Divacky 
114159d1ed5bSDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
114259d1ed5bSDimitry Andric   assert(!GV->isDeclaration() &&
114359d1ed5bSDimitry Andric          "Only globals with definition can force usage.");
114497bc6c73SDimitry Andric   LLVMCompilerUsed.emplace_back(GV);
114559d1ed5bSDimitry Andric }
114659d1ed5bSDimitry Andric 
114759d1ed5bSDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name,
114859d1ed5bSDimitry Andric                      std::vector<llvm::WeakVH> &List) {
1149f22ef01cSRoman Divacky   // Don't create llvm.used if there is no need.
115059d1ed5bSDimitry Andric   if (List.empty())
1151f22ef01cSRoman Divacky     return;
1152f22ef01cSRoman Divacky 
115359d1ed5bSDimitry Andric   // Convert List to what ConstantArray needs.
1154dff0c46cSDimitry Andric   SmallVector<llvm::Constant*, 8> UsedArray;
115559d1ed5bSDimitry Andric   UsedArray.resize(List.size());
115659d1ed5bSDimitry Andric   for (unsigned i = 0, e = List.size(); i != e; ++i) {
1157f22ef01cSRoman Divacky     UsedArray[i] =
115844f7b0dcSDimitry Andric         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
115944f7b0dcSDimitry Andric             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
1160f22ef01cSRoman Divacky   }
1161f22ef01cSRoman Divacky 
1162f22ef01cSRoman Divacky   if (UsedArray.empty())
1163f22ef01cSRoman Divacky     return;
116459d1ed5bSDimitry Andric   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
1165f22ef01cSRoman Divacky 
116659d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
116759d1ed5bSDimitry Andric       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
116859d1ed5bSDimitry Andric       llvm::ConstantArray::get(ATy, UsedArray), Name);
1169f22ef01cSRoman Divacky 
1170f22ef01cSRoman Divacky   GV->setSection("llvm.metadata");
1171f22ef01cSRoman Divacky }
1172f22ef01cSRoman Divacky 
117359d1ed5bSDimitry Andric void CodeGenModule::emitLLVMUsed() {
117459d1ed5bSDimitry Andric   emitUsed(*this, "llvm.used", LLVMUsed);
117559d1ed5bSDimitry Andric   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
117659d1ed5bSDimitry Andric }
117759d1ed5bSDimitry Andric 
1178f785676fSDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
117939d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
1180f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1181f785676fSDimitry Andric }
1182f785676fSDimitry Andric 
1183f785676fSDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1184f785676fSDimitry Andric   llvm::SmallString<32> Opt;
1185f785676fSDimitry Andric   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
118639d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1187f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1188f785676fSDimitry Andric }
1189f785676fSDimitry Andric 
1190f785676fSDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) {
1191f785676fSDimitry Andric   llvm::SmallString<24> Opt;
1192f785676fSDimitry Andric   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
119339d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1194f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1195f785676fSDimitry Andric }
1196f785676fSDimitry Andric 
1197139f7f9bSDimitry Andric /// \brief Add link options implied by the given module, including modules
1198139f7f9bSDimitry Andric /// it depends on, using a postorder walk.
119939d628a0SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
120039d628a0SDimitry Andric                                     SmallVectorImpl<llvm::Metadata *> &Metadata,
1201139f7f9bSDimitry Andric                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
1202139f7f9bSDimitry Andric   // Import this module's parent.
120339d628a0SDimitry Andric   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
1204f785676fSDimitry Andric     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
1205139f7f9bSDimitry Andric   }
1206139f7f9bSDimitry Andric 
1207139f7f9bSDimitry Andric   // Import this module's dependencies.
1208139f7f9bSDimitry Andric   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
120939d628a0SDimitry Andric     if (Visited.insert(Mod->Imports[I - 1]).second)
1210f785676fSDimitry Andric       addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
1211139f7f9bSDimitry Andric   }
1212139f7f9bSDimitry Andric 
1213139f7f9bSDimitry Andric   // Add linker options to link against the libraries/frameworks
1214139f7f9bSDimitry Andric   // described by this module.
1215f785676fSDimitry Andric   llvm::LLVMContext &Context = CGM.getLLVMContext();
1216139f7f9bSDimitry Andric   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
1217f785676fSDimitry Andric     // Link against a framework.  Frameworks are currently Darwin only, so we
1218f785676fSDimitry Andric     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
1219139f7f9bSDimitry Andric     if (Mod->LinkLibraries[I-1].IsFramework) {
122039d628a0SDimitry Andric       llvm::Metadata *Args[2] = {
1221139f7f9bSDimitry Andric           llvm::MDString::get(Context, "-framework"),
122239d628a0SDimitry Andric           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1223139f7f9bSDimitry Andric 
1224139f7f9bSDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, Args));
1225139f7f9bSDimitry Andric       continue;
1226139f7f9bSDimitry Andric     }
1227139f7f9bSDimitry Andric 
1228139f7f9bSDimitry Andric     // Link against a library.
1229f785676fSDimitry Andric     llvm::SmallString<24> Opt;
1230f785676fSDimitry Andric     CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1231f785676fSDimitry Andric       Mod->LinkLibraries[I-1].Library, Opt);
123239d628a0SDimitry Andric     auto *OptString = llvm::MDString::get(Context, Opt);
1233139f7f9bSDimitry Andric     Metadata.push_back(llvm::MDNode::get(Context, OptString));
1234139f7f9bSDimitry Andric   }
1235139f7f9bSDimitry Andric }
1236139f7f9bSDimitry Andric 
1237139f7f9bSDimitry Andric void CodeGenModule::EmitModuleLinkOptions() {
1238139f7f9bSDimitry Andric   // Collect the set of all of the modules we want to visit to emit link
1239139f7f9bSDimitry Andric   // options, which is essentially the imported modules and all of their
1240139f7f9bSDimitry Andric   // non-explicit child modules.
1241139f7f9bSDimitry Andric   llvm::SetVector<clang::Module *> LinkModules;
1242139f7f9bSDimitry Andric   llvm::SmallPtrSet<clang::Module *, 16> Visited;
1243139f7f9bSDimitry Andric   SmallVector<clang::Module *, 16> Stack;
1244139f7f9bSDimitry Andric 
1245139f7f9bSDimitry Andric   // Seed the stack with imported modules.
12468f0fd8f6SDimitry Andric   for (Module *M : ImportedModules)
12478f0fd8f6SDimitry Andric     if (Visited.insert(M).second)
12488f0fd8f6SDimitry Andric       Stack.push_back(M);
1249139f7f9bSDimitry Andric 
1250139f7f9bSDimitry Andric   // Find all of the modules to import, making a little effort to prune
1251139f7f9bSDimitry Andric   // non-leaf modules.
1252139f7f9bSDimitry Andric   while (!Stack.empty()) {
1253f785676fSDimitry Andric     clang::Module *Mod = Stack.pop_back_val();
1254139f7f9bSDimitry Andric 
1255139f7f9bSDimitry Andric     bool AnyChildren = false;
1256139f7f9bSDimitry Andric 
1257139f7f9bSDimitry Andric     // Visit the submodules of this module.
1258139f7f9bSDimitry Andric     for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1259139f7f9bSDimitry Andric                                         SubEnd = Mod->submodule_end();
1260139f7f9bSDimitry Andric          Sub != SubEnd; ++Sub) {
1261139f7f9bSDimitry Andric       // Skip explicit children; they need to be explicitly imported to be
1262139f7f9bSDimitry Andric       // linked against.
1263139f7f9bSDimitry Andric       if ((*Sub)->IsExplicit)
1264139f7f9bSDimitry Andric         continue;
1265139f7f9bSDimitry Andric 
126639d628a0SDimitry Andric       if (Visited.insert(*Sub).second) {
1267139f7f9bSDimitry Andric         Stack.push_back(*Sub);
1268139f7f9bSDimitry Andric         AnyChildren = true;
1269139f7f9bSDimitry Andric       }
1270139f7f9bSDimitry Andric     }
1271139f7f9bSDimitry Andric 
1272139f7f9bSDimitry Andric     // We didn't find any children, so add this module to the list of
1273139f7f9bSDimitry Andric     // modules to link against.
1274139f7f9bSDimitry Andric     if (!AnyChildren) {
1275139f7f9bSDimitry Andric       LinkModules.insert(Mod);
1276139f7f9bSDimitry Andric     }
1277139f7f9bSDimitry Andric   }
1278139f7f9bSDimitry Andric 
1279139f7f9bSDimitry Andric   // Add link options for all of the imported modules in reverse topological
1280f785676fSDimitry Andric   // order.  We don't do anything to try to order import link flags with respect
1281f785676fSDimitry Andric   // to linker options inserted by things like #pragma comment().
128239d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 16> MetadataArgs;
1283139f7f9bSDimitry Andric   Visited.clear();
12848f0fd8f6SDimitry Andric   for (Module *M : LinkModules)
12858f0fd8f6SDimitry Andric     if (Visited.insert(M).second)
12868f0fd8f6SDimitry Andric       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
1287139f7f9bSDimitry Andric   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1288f785676fSDimitry Andric   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1289139f7f9bSDimitry Andric 
1290139f7f9bSDimitry Andric   // Add the linker options metadata flag.
1291139f7f9bSDimitry Andric   getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
1292f785676fSDimitry Andric                             llvm::MDNode::get(getLLVMContext(),
1293f785676fSDimitry Andric                                               LinkerOptionsMetadata));
1294139f7f9bSDimitry Andric }
1295139f7f9bSDimitry Andric 
1296f22ef01cSRoman Divacky void CodeGenModule::EmitDeferred() {
1297f22ef01cSRoman Divacky   // Emit code for any potentially referenced deferred decls.  Since a
1298f22ef01cSRoman Divacky   // previously unused static decl may become used during the generation of code
1299f22ef01cSRoman Divacky   // for a static function, iterate until no changes are made.
1300f22ef01cSRoman Divacky 
1301f22ef01cSRoman Divacky   if (!DeferredVTables.empty()) {
1302139f7f9bSDimitry Andric     EmitDeferredVTables();
1303139f7f9bSDimitry Andric 
1304e7145dcbSDimitry Andric     // Emitting a vtable doesn't directly cause more vtables to
1305139f7f9bSDimitry Andric     // become deferred, although it can cause functions to be
1306e7145dcbSDimitry Andric     // emitted that then need those vtables.
1307139f7f9bSDimitry Andric     assert(DeferredVTables.empty());
1308f22ef01cSRoman Divacky   }
1309f22ef01cSRoman Divacky 
1310e7145dcbSDimitry Andric   // Stop if we're out of both deferred vtables and deferred declarations.
131133956c43SDimitry Andric   if (DeferredDeclsToEmit.empty())
131233956c43SDimitry Andric     return;
1313139f7f9bSDimitry Andric 
131433956c43SDimitry Andric   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
131533956c43SDimitry Andric   // work, it will not interfere with this.
131633956c43SDimitry Andric   std::vector<DeferredGlobal> CurDeclsToEmit;
131733956c43SDimitry Andric   CurDeclsToEmit.swap(DeferredDeclsToEmit);
131833956c43SDimitry Andric 
131933956c43SDimitry Andric   for (DeferredGlobal &G : CurDeclsToEmit) {
132059d1ed5bSDimitry Andric     GlobalDecl D = G.GD;
132133956c43SDimitry Andric     G.GV = nullptr;
1322f22ef01cSRoman Divacky 
13230623d748SDimitry Andric     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
13240623d748SDimitry Andric     // to get GlobalValue with exactly the type we need, not something that
13250623d748SDimitry Andric     // might had been created for another decl with the same mangled name but
13260623d748SDimitry Andric     // different type.
1327e7145dcbSDimitry Andric     llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
132844290647SDimitry Andric         GetAddrOfGlobal(D, ForDefinition));
1329e7145dcbSDimitry Andric 
1330e7145dcbSDimitry Andric     // In case of different address spaces, we may still get a cast, even with
1331e7145dcbSDimitry Andric     // IsForDefinition equal to true. Query mangled names table to get
1332e7145dcbSDimitry Andric     // GlobalValue.
133339d628a0SDimitry Andric     if (!GV)
133439d628a0SDimitry Andric       GV = GetGlobalValue(getMangledName(D));
133539d628a0SDimitry Andric 
1336e7145dcbSDimitry Andric     // Make sure GetGlobalValue returned non-null.
1337e7145dcbSDimitry Andric     assert(GV);
1338e7145dcbSDimitry Andric 
1339f22ef01cSRoman Divacky     // Check to see if we've already emitted this.  This is necessary
1340f22ef01cSRoman Divacky     // for a couple of reasons: first, decls can end up in the
1341f22ef01cSRoman Divacky     // deferred-decls queue multiple times, and second, decls can end
1342f22ef01cSRoman Divacky     // up with definitions in unusual ways (e.g. by an extern inline
1343f22ef01cSRoman Divacky     // function acquiring a strong function redefinition).  Just
1344f22ef01cSRoman Divacky     // ignore these cases.
1345e7145dcbSDimitry Andric     if (!GV->isDeclaration())
1346f22ef01cSRoman Divacky       continue;
1347f22ef01cSRoman Divacky 
1348f22ef01cSRoman Divacky     // Otherwise, emit the definition and move on to the next one.
134959d1ed5bSDimitry Andric     EmitGlobalDefinition(D, GV);
135033956c43SDimitry Andric 
135133956c43SDimitry Andric     // If we found out that we need to emit more decls, do that recursively.
135233956c43SDimitry Andric     // This has the advantage that the decls are emitted in a DFS and related
135333956c43SDimitry Andric     // ones are close together, which is convenient for testing.
135433956c43SDimitry Andric     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
135533956c43SDimitry Andric       EmitDeferred();
135633956c43SDimitry Andric       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
135733956c43SDimitry Andric     }
1358f22ef01cSRoman Divacky   }
1359f22ef01cSRoman Divacky }
1360f22ef01cSRoman Divacky 
13616122f3e6SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() {
13626122f3e6SDimitry Andric   if (Annotations.empty())
13636122f3e6SDimitry Andric     return;
13646122f3e6SDimitry Andric 
13656122f3e6SDimitry Andric   // Create a new global variable for the ConstantStruct in the Module.
13666122f3e6SDimitry Andric   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
13676122f3e6SDimitry Andric     Annotations[0]->getType(), Annotations.size()), Annotations);
136859d1ed5bSDimitry Andric   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
136959d1ed5bSDimitry Andric                                       llvm::GlobalValue::AppendingLinkage,
137059d1ed5bSDimitry Andric                                       Array, "llvm.global.annotations");
13716122f3e6SDimitry Andric   gv->setSection(AnnotationSection);
13726122f3e6SDimitry Andric }
13736122f3e6SDimitry Andric 
1374139f7f9bSDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1375f785676fSDimitry Andric   llvm::Constant *&AStr = AnnotationStrings[Str];
1376f785676fSDimitry Andric   if (AStr)
1377f785676fSDimitry Andric     return AStr;
13786122f3e6SDimitry Andric 
13796122f3e6SDimitry Andric   // Not found yet, create a new global.
1380dff0c46cSDimitry Andric   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
138159d1ed5bSDimitry Andric   auto *gv =
138259d1ed5bSDimitry Andric       new llvm::GlobalVariable(getModule(), s->getType(), true,
138359d1ed5bSDimitry Andric                                llvm::GlobalValue::PrivateLinkage, s, ".str");
13846122f3e6SDimitry Andric   gv->setSection(AnnotationSection);
1385e7145dcbSDimitry Andric   gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1386f785676fSDimitry Andric   AStr = gv;
13876122f3e6SDimitry Andric   return gv;
13886122f3e6SDimitry Andric }
13896122f3e6SDimitry Andric 
13906122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
13916122f3e6SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
13926122f3e6SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
13936122f3e6SDimitry Andric   if (PLoc.isValid())
13946122f3e6SDimitry Andric     return EmitAnnotationString(PLoc.getFilename());
13956122f3e6SDimitry Andric   return EmitAnnotationString(SM.getBufferName(Loc));
13966122f3e6SDimitry Andric }
13976122f3e6SDimitry Andric 
13986122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
13996122f3e6SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
14006122f3e6SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(L);
14016122f3e6SDimitry Andric   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
14026122f3e6SDimitry Andric     SM.getExpansionLineNumber(L);
14036122f3e6SDimitry Andric   return llvm::ConstantInt::get(Int32Ty, LineNo);
14046122f3e6SDimitry Andric }
14056122f3e6SDimitry Andric 
1406f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1407f22ef01cSRoman Divacky                                                 const AnnotateAttr *AA,
14086122f3e6SDimitry Andric                                                 SourceLocation L) {
14096122f3e6SDimitry Andric   // Get the globals for file name, annotation, and the line number.
14106122f3e6SDimitry Andric   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
14116122f3e6SDimitry Andric                  *UnitGV = EmitAnnotationUnit(L),
14126122f3e6SDimitry Andric                  *LineNoCst = EmitAnnotationLineNo(L);
1413f22ef01cSRoman Divacky 
1414f22ef01cSRoman Divacky   // Create the ConstantStruct for the global annotation.
1415f22ef01cSRoman Divacky   llvm::Constant *Fields[4] = {
14166122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
14176122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
14186122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
14196122f3e6SDimitry Andric     LineNoCst
1420f22ef01cSRoman Divacky   };
142117a519f9SDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
1422f22ef01cSRoman Divacky }
1423f22ef01cSRoman Divacky 
14246122f3e6SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
14256122f3e6SDimitry Andric                                          llvm::GlobalValue *GV) {
14266122f3e6SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
14276122f3e6SDimitry Andric   // Get the struct elements for these annotations.
142859d1ed5bSDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>())
142959d1ed5bSDimitry Andric     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
14306122f3e6SDimitry Andric }
14316122f3e6SDimitry Andric 
143239d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
143339d628a0SDimitry Andric                                            SourceLocation Loc) const {
143439d628a0SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
143539d628a0SDimitry Andric   // Blacklist by function name.
143639d628a0SDimitry Andric   if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
143739d628a0SDimitry Andric     return true;
143839d628a0SDimitry Andric   // Blacklist by location.
14390623d748SDimitry Andric   if (Loc.isValid())
144039d628a0SDimitry Andric     return SanitizerBL.isBlacklistedLocation(Loc);
144139d628a0SDimitry Andric   // If location is unknown, this may be a compiler-generated function. Assume
144239d628a0SDimitry Andric   // it's located in the main file.
144339d628a0SDimitry Andric   auto &SM = Context.getSourceManager();
144439d628a0SDimitry Andric   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
144539d628a0SDimitry Andric     return SanitizerBL.isBlacklistedFile(MainFile->getName());
144639d628a0SDimitry Andric   }
144739d628a0SDimitry Andric   return false;
144839d628a0SDimitry Andric }
144939d628a0SDimitry Andric 
145039d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
145139d628a0SDimitry Andric                                            SourceLocation Loc, QualType Ty,
145239d628a0SDimitry Andric                                            StringRef Category) const {
14538f0fd8f6SDimitry Andric   // For now globals can be blacklisted only in ASan and KASan.
14548f0fd8f6SDimitry Andric   if (!LangOpts.Sanitize.hasOneOf(
14558f0fd8f6SDimitry Andric           SanitizerKind::Address | SanitizerKind::KernelAddress))
145639d628a0SDimitry Andric     return false;
145739d628a0SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
145839d628a0SDimitry Andric   if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
145939d628a0SDimitry Andric     return true;
146039d628a0SDimitry Andric   if (SanitizerBL.isBlacklistedLocation(Loc, Category))
146139d628a0SDimitry Andric     return true;
146239d628a0SDimitry Andric   // Check global type.
146339d628a0SDimitry Andric   if (!Ty.isNull()) {
146439d628a0SDimitry Andric     // Drill down the array types: if global variable of a fixed type is
146539d628a0SDimitry Andric     // blacklisted, we also don't instrument arrays of them.
146639d628a0SDimitry Andric     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
146739d628a0SDimitry Andric       Ty = AT->getElementType();
146839d628a0SDimitry Andric     Ty = Ty.getCanonicalType().getUnqualifiedType();
146939d628a0SDimitry Andric     // We allow to blacklist only record types (classes, structs etc.)
147039d628a0SDimitry Andric     if (Ty->isRecordType()) {
147139d628a0SDimitry Andric       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
147239d628a0SDimitry Andric       if (SanitizerBL.isBlacklistedType(TypeStr, Category))
147339d628a0SDimitry Andric         return true;
147439d628a0SDimitry Andric     }
147539d628a0SDimitry Andric   }
147639d628a0SDimitry Andric   return false;
147739d628a0SDimitry Andric }
147839d628a0SDimitry Andric 
147939d628a0SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
1480e580952dSDimitry Andric   // Never defer when EmitAllDecls is specified.
1481dff0c46cSDimitry Andric   if (LangOpts.EmitAllDecls)
148239d628a0SDimitry Andric     return true;
148339d628a0SDimitry Andric 
148439d628a0SDimitry Andric   return getContext().DeclMustBeEmitted(Global);
148539d628a0SDimitry Andric }
148639d628a0SDimitry Andric 
148739d628a0SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
148839d628a0SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global))
148939d628a0SDimitry Andric     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
149039d628a0SDimitry Andric       // Implicit template instantiations may change linkage if they are later
149139d628a0SDimitry Andric       // explicitly instantiated, so they should not be emitted eagerly.
1492f22ef01cSRoman Divacky       return false;
1493e7145dcbSDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(Global))
1494e7145dcbSDimitry Andric     if (Context.getInlineVariableDefinitionKind(VD) ==
1495e7145dcbSDimitry Andric         ASTContext::InlineVariableDefinitionKind::WeakUnknown)
1496e7145dcbSDimitry Andric       // A definition of an inline constexpr static data member may change
1497e7145dcbSDimitry Andric       // linkage later if it's redeclared outside the class.
1498e7145dcbSDimitry Andric       return false;
1499875ed548SDimitry Andric   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
1500875ed548SDimitry Andric   // codegen for global variables, because they may be marked as threadprivate.
1501875ed548SDimitry Andric   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1502875ed548SDimitry Andric       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
1503875ed548SDimitry Andric     return false;
1504f22ef01cSRoman Divacky 
150539d628a0SDimitry Andric   return true;
1506f22ef01cSRoman Divacky }
1507f22ef01cSRoman Divacky 
15080623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
15093861d79fSDimitry Andric     const CXXUuidofExpr* E) {
15103861d79fSDimitry Andric   // Sema has verified that IIDSource has a __declspec(uuid()), and that its
15113861d79fSDimitry Andric   // well-formed.
1512e7145dcbSDimitry Andric   StringRef Uuid = E->getUuidStr();
1513f785676fSDimitry Andric   std::string Name = "_GUID_" + Uuid.lower();
1514f785676fSDimitry Andric   std::replace(Name.begin(), Name.end(), '-', '_');
15153861d79fSDimitry Andric 
1516e7145dcbSDimitry Andric   // The UUID descriptor should be pointer aligned.
1517e7145dcbSDimitry Andric   CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
15180623d748SDimitry Andric 
15193861d79fSDimitry Andric   // Look for an existing global.
15203861d79fSDimitry Andric   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
15210623d748SDimitry Andric     return ConstantAddress(GV, Alignment);
15223861d79fSDimitry Andric 
152339d628a0SDimitry Andric   llvm::Constant *Init = EmitUuidofInitializer(Uuid);
15243861d79fSDimitry Andric   assert(Init && "failed to initialize as constant");
15253861d79fSDimitry Andric 
152659d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
1527f785676fSDimitry Andric       getModule(), Init->getType(),
1528f785676fSDimitry Andric       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
152933956c43SDimitry Andric   if (supportsCOMDAT())
153033956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
15310623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
15323861d79fSDimitry Andric }
15333861d79fSDimitry Andric 
15340623d748SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1535f22ef01cSRoman Divacky   const AliasAttr *AA = VD->getAttr<AliasAttr>();
1536f22ef01cSRoman Divacky   assert(AA && "No alias?");
1537f22ef01cSRoman Divacky 
15380623d748SDimitry Andric   CharUnits Alignment = getContext().getDeclAlign(VD);
15396122f3e6SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1540f22ef01cSRoman Divacky 
1541f22ef01cSRoman Divacky   // See if there is already something with the target's name in the module.
1542f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
15433861d79fSDimitry Andric   if (Entry) {
15443861d79fSDimitry Andric     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
15450623d748SDimitry Andric     auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
15460623d748SDimitry Andric     return ConstantAddress(Ptr, Alignment);
15473861d79fSDimitry Andric   }
1548f22ef01cSRoman Divacky 
1549f22ef01cSRoman Divacky   llvm::Constant *Aliasee;
1550f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(DeclTy))
15513861d79fSDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
15523861d79fSDimitry Andric                                       GlobalDecl(cast<FunctionDecl>(VD)),
15532754fe60SDimitry Andric                                       /*ForVTable=*/false);
1554f22ef01cSRoman Divacky   else
1555f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
155659d1ed5bSDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
155759d1ed5bSDimitry Andric                                     nullptr);
15583861d79fSDimitry Andric 
155959d1ed5bSDimitry Andric   auto *F = cast<llvm::GlobalValue>(Aliasee);
1560f22ef01cSRoman Divacky   F->setLinkage(llvm::Function::ExternalWeakLinkage);
1561f22ef01cSRoman Divacky   WeakRefReferences.insert(F);
1562f22ef01cSRoman Divacky 
15630623d748SDimitry Andric   return ConstantAddress(Aliasee, Alignment);
1564f22ef01cSRoman Divacky }
1565f22ef01cSRoman Divacky 
1566f22ef01cSRoman Divacky void CodeGenModule::EmitGlobal(GlobalDecl GD) {
156759d1ed5bSDimitry Andric   const auto *Global = cast<ValueDecl>(GD.getDecl());
1568f22ef01cSRoman Divacky 
1569f22ef01cSRoman Divacky   // Weak references don't produce any output by themselves.
1570f22ef01cSRoman Divacky   if (Global->hasAttr<WeakRefAttr>())
1571f22ef01cSRoman Divacky     return;
1572f22ef01cSRoman Divacky 
1573f22ef01cSRoman Divacky   // If this is an alias definition (which otherwise looks like a declaration)
1574f22ef01cSRoman Divacky   // emit it now.
1575f22ef01cSRoman Divacky   if (Global->hasAttr<AliasAttr>())
1576f22ef01cSRoman Divacky     return EmitAliasDefinition(GD);
1577f22ef01cSRoman Divacky 
1578e7145dcbSDimitry Andric   // IFunc like an alias whose value is resolved at runtime by calling resolver.
1579e7145dcbSDimitry Andric   if (Global->hasAttr<IFuncAttr>())
1580e7145dcbSDimitry Andric     return emitIFuncDefinition(GD);
1581e7145dcbSDimitry Andric 
15826122f3e6SDimitry Andric   // If this is CUDA, be selective about which declarations we emit.
1583dff0c46cSDimitry Andric   if (LangOpts.CUDA) {
158433956c43SDimitry Andric     if (LangOpts.CUDAIsDevice) {
15856122f3e6SDimitry Andric       if (!Global->hasAttr<CUDADeviceAttr>() &&
15866122f3e6SDimitry Andric           !Global->hasAttr<CUDAGlobalAttr>() &&
15876122f3e6SDimitry Andric           !Global->hasAttr<CUDAConstantAttr>() &&
15886122f3e6SDimitry Andric           !Global->hasAttr<CUDASharedAttr>())
15896122f3e6SDimitry Andric         return;
15906122f3e6SDimitry Andric     } else {
1591e7145dcbSDimitry Andric       // We need to emit host-side 'shadows' for all global
1592e7145dcbSDimitry Andric       // device-side variables because the CUDA runtime needs their
1593e7145dcbSDimitry Andric       // size and host-side address in order to provide access to
1594e7145dcbSDimitry Andric       // their device-side incarnations.
1595e7145dcbSDimitry Andric 
1596e7145dcbSDimitry Andric       // So device-only functions are the only things we skip.
1597e7145dcbSDimitry Andric       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
1598e7145dcbSDimitry Andric           Global->hasAttr<CUDADeviceAttr>())
15996122f3e6SDimitry Andric         return;
1600e7145dcbSDimitry Andric 
1601e7145dcbSDimitry Andric       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
1602e7145dcbSDimitry Andric              "Expected Variable or Function");
1603e580952dSDimitry Andric     }
1604e580952dSDimitry Andric   }
1605e580952dSDimitry Andric 
1606e7145dcbSDimitry Andric   if (LangOpts.OpenMP) {
1607ea942507SDimitry Andric     // If this is OpenMP device, check if it is legal to emit this global
1608ea942507SDimitry Andric     // normally.
1609ea942507SDimitry Andric     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
1610ea942507SDimitry Andric       return;
1611e7145dcbSDimitry Andric     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
1612e7145dcbSDimitry Andric       if (MustBeEmitted(Global))
1613e7145dcbSDimitry Andric         EmitOMPDeclareReduction(DRD);
1614e7145dcbSDimitry Andric       return;
1615e7145dcbSDimitry Andric     }
1616e7145dcbSDimitry Andric   }
1617ea942507SDimitry Andric 
16186122f3e6SDimitry Andric   // Ignore declarations, they will be emitted on their first use.
161959d1ed5bSDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1620f22ef01cSRoman Divacky     // Forward declarations are emitted lazily on first use.
16216122f3e6SDimitry Andric     if (!FD->doesThisDeclarationHaveABody()) {
16226122f3e6SDimitry Andric       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1623f22ef01cSRoman Divacky         return;
16246122f3e6SDimitry Andric 
16256122f3e6SDimitry Andric       StringRef MangledName = getMangledName(GD);
162659d1ed5bSDimitry Andric 
162759d1ed5bSDimitry Andric       // Compute the function info and LLVM type.
162859d1ed5bSDimitry Andric       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
162959d1ed5bSDimitry Andric       llvm::Type *Ty = getTypes().GetFunctionType(FI);
163059d1ed5bSDimitry Andric 
163159d1ed5bSDimitry Andric       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
163259d1ed5bSDimitry Andric                               /*DontDefer=*/false);
16336122f3e6SDimitry Andric       return;
16346122f3e6SDimitry Andric     }
1635f22ef01cSRoman Divacky   } else {
163659d1ed5bSDimitry Andric     const auto *VD = cast<VarDecl>(Global);
1637f22ef01cSRoman Divacky     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1638e7145dcbSDimitry Andric     // We need to emit device-side global CUDA variables even if a
1639e7145dcbSDimitry Andric     // variable does not have a definition -- we still need to define
1640e7145dcbSDimitry Andric     // host-side shadow for it.
1641e7145dcbSDimitry Andric     bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
1642e7145dcbSDimitry Andric                            !VD->hasDefinition() &&
1643e7145dcbSDimitry Andric                            (VD->hasAttr<CUDAConstantAttr>() ||
1644e7145dcbSDimitry Andric                             VD->hasAttr<CUDADeviceAttr>());
1645e7145dcbSDimitry Andric     if (!MustEmitForCuda &&
1646e7145dcbSDimitry Andric         VD->isThisDeclarationADefinition() != VarDecl::Definition &&
1647e7145dcbSDimitry Andric         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
1648e7145dcbSDimitry Andric       // If this declaration may have caused an inline variable definition to
1649e7145dcbSDimitry Andric       // change linkage, make sure that it's emitted.
1650e7145dcbSDimitry Andric       if (Context.getInlineVariableDefinitionKind(VD) ==
1651e7145dcbSDimitry Andric           ASTContext::InlineVariableDefinitionKind::Strong)
1652e7145dcbSDimitry Andric         GetAddrOfGlobalVar(VD);
1653f22ef01cSRoman Divacky       return;
1654f22ef01cSRoman Divacky     }
1655e7145dcbSDimitry Andric   }
1656f22ef01cSRoman Divacky 
165739d628a0SDimitry Andric   // Defer code generation to first use when possible, e.g. if this is an inline
165839d628a0SDimitry Andric   // function. If the global must always be emitted, do it eagerly if possible
165939d628a0SDimitry Andric   // to benefit from cache locality.
166039d628a0SDimitry Andric   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
1661f22ef01cSRoman Divacky     // Emit the definition if it can't be deferred.
1662f22ef01cSRoman Divacky     EmitGlobalDefinition(GD);
1663f22ef01cSRoman Divacky     return;
1664f22ef01cSRoman Divacky   }
1665f22ef01cSRoman Divacky 
1666e580952dSDimitry Andric   // If we're deferring emission of a C++ variable with an
1667e580952dSDimitry Andric   // initializer, remember the order in which it appeared in the file.
1668dff0c46cSDimitry Andric   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1669e580952dSDimitry Andric       cast<VarDecl>(Global)->hasInit()) {
1670e580952dSDimitry Andric     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
167159d1ed5bSDimitry Andric     CXXGlobalInits.push_back(nullptr);
1672e580952dSDimitry Andric   }
1673e580952dSDimitry Andric 
16746122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
167539d628a0SDimitry Andric   if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) {
167639d628a0SDimitry Andric     // The value has already been used and should therefore be emitted.
167759d1ed5bSDimitry Andric     addDeferredDeclToEmit(GV, GD);
167839d628a0SDimitry Andric   } else if (MustBeEmitted(Global)) {
167939d628a0SDimitry Andric     // The value must be emitted, but cannot be emitted eagerly.
168039d628a0SDimitry Andric     assert(!MayBeEmittedEagerly(Global));
168139d628a0SDimitry Andric     addDeferredDeclToEmit(/*GV=*/nullptr, GD);
168239d628a0SDimitry Andric   } else {
1683f22ef01cSRoman Divacky     // Otherwise, remember that we saw a deferred decl with this name.  The
1684f22ef01cSRoman Divacky     // first use of the mangled name will cause it to move into
1685f22ef01cSRoman Divacky     // DeferredDeclsToEmit.
1686f22ef01cSRoman Divacky     DeferredDecls[MangledName] = GD;
1687f22ef01cSRoman Divacky   }
1688f22ef01cSRoman Divacky }
1689f22ef01cSRoman Divacky 
1690f8254f43SDimitry Andric namespace {
1691f8254f43SDimitry Andric   struct FunctionIsDirectlyRecursive :
1692f8254f43SDimitry Andric     public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1693f8254f43SDimitry Andric     const StringRef Name;
1694dff0c46cSDimitry Andric     const Builtin::Context &BI;
1695f8254f43SDimitry Andric     bool Result;
1696dff0c46cSDimitry Andric     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1697dff0c46cSDimitry Andric       Name(N), BI(C), Result(false) {
1698f8254f43SDimitry Andric     }
1699f8254f43SDimitry Andric     typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1700f8254f43SDimitry Andric 
1701f8254f43SDimitry Andric     bool TraverseCallExpr(CallExpr *E) {
1702dff0c46cSDimitry Andric       const FunctionDecl *FD = E->getDirectCallee();
1703dff0c46cSDimitry Andric       if (!FD)
1704f8254f43SDimitry Andric         return true;
1705dff0c46cSDimitry Andric       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1706dff0c46cSDimitry Andric       if (Attr && Name == Attr->getLabel()) {
1707dff0c46cSDimitry Andric         Result = true;
1708dff0c46cSDimitry Andric         return false;
1709dff0c46cSDimitry Andric       }
1710dff0c46cSDimitry Andric       unsigned BuiltinID = FD->getBuiltinID();
17113dac3a9bSDimitry Andric       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
1712f8254f43SDimitry Andric         return true;
17130623d748SDimitry Andric       StringRef BuiltinName = BI.getName(BuiltinID);
1714dff0c46cSDimitry Andric       if (BuiltinName.startswith("__builtin_") &&
1715dff0c46cSDimitry Andric           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1716f8254f43SDimitry Andric         Result = true;
1717f8254f43SDimitry Andric         return false;
1718f8254f43SDimitry Andric       }
1719f8254f43SDimitry Andric       return true;
1720f8254f43SDimitry Andric     }
1721f8254f43SDimitry Andric   };
17220623d748SDimitry Andric 
17230623d748SDimitry Andric   struct DLLImportFunctionVisitor
17240623d748SDimitry Andric       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
17250623d748SDimitry Andric     bool SafeToInline = true;
17260623d748SDimitry Andric 
172744290647SDimitry Andric     bool shouldVisitImplicitCode() const { return true; }
172844290647SDimitry Andric 
17290623d748SDimitry Andric     bool VisitVarDecl(VarDecl *VD) {
17300623d748SDimitry Andric       // A thread-local variable cannot be imported.
17310623d748SDimitry Andric       SafeToInline = !VD->getTLSKind();
17320623d748SDimitry Andric       return SafeToInline;
17330623d748SDimitry Andric     }
17340623d748SDimitry Andric 
17350623d748SDimitry Andric     // Make sure we're not referencing non-imported vars or functions.
17360623d748SDimitry Andric     bool VisitDeclRefExpr(DeclRefExpr *E) {
17370623d748SDimitry Andric       ValueDecl *VD = E->getDecl();
17380623d748SDimitry Andric       if (isa<FunctionDecl>(VD))
17390623d748SDimitry Andric         SafeToInline = VD->hasAttr<DLLImportAttr>();
17400623d748SDimitry Andric       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
17410623d748SDimitry Andric         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
17420623d748SDimitry Andric       return SafeToInline;
17430623d748SDimitry Andric     }
174444290647SDimitry Andric     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
174544290647SDimitry Andric       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
174644290647SDimitry Andric       return SafeToInline;
174744290647SDimitry Andric     }
17480623d748SDimitry Andric     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
17490623d748SDimitry Andric       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
17500623d748SDimitry Andric       return SafeToInline;
17510623d748SDimitry Andric     }
17520623d748SDimitry Andric     bool VisitCXXNewExpr(CXXNewExpr *E) {
17530623d748SDimitry Andric       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
17540623d748SDimitry Andric       return SafeToInline;
17550623d748SDimitry Andric     }
17560623d748SDimitry Andric   };
1757f8254f43SDimitry Andric }
1758f8254f43SDimitry Andric 
1759dff0c46cSDimitry Andric // isTriviallyRecursive - Check if this function calls another
1760dff0c46cSDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin,
1761dff0c46cSDimitry Andric // ends up pointing to itself.
1762f8254f43SDimitry Andric bool
1763dff0c46cSDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1764dff0c46cSDimitry Andric   StringRef Name;
1765dff0c46cSDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1766dff0c46cSDimitry Andric     // asm labels are a special kind of mangling we have to support.
1767dff0c46cSDimitry Andric     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1768dff0c46cSDimitry Andric     if (!Attr)
1769f8254f43SDimitry Andric       return false;
1770dff0c46cSDimitry Andric     Name = Attr->getLabel();
1771dff0c46cSDimitry Andric   } else {
1772dff0c46cSDimitry Andric     Name = FD->getName();
1773dff0c46cSDimitry Andric   }
1774f8254f43SDimitry Andric 
1775dff0c46cSDimitry Andric   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1776dff0c46cSDimitry Andric   Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1777f8254f43SDimitry Andric   return Walker.Result;
1778f8254f43SDimitry Andric }
1779f8254f43SDimitry Andric 
178044290647SDimitry Andric // Check if T is a class type with a destructor that's not dllimport.
178144290647SDimitry Andric static bool HasNonDllImportDtor(QualType T) {
178244290647SDimitry Andric   if (const RecordType *RT = dyn_cast<RecordType>(T))
178344290647SDimitry Andric     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
178444290647SDimitry Andric       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
178544290647SDimitry Andric         return true;
178644290647SDimitry Andric 
178744290647SDimitry Andric   return false;
178844290647SDimitry Andric }
178944290647SDimitry Andric 
179044290647SDimitry Andric bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1791f785676fSDimitry Andric   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1792f8254f43SDimitry Andric     return true;
179359d1ed5bSDimitry Andric   const auto *F = cast<FunctionDecl>(GD.getDecl());
179459d1ed5bSDimitry Andric   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1795f8254f43SDimitry Andric     return false;
17960623d748SDimitry Andric 
17970623d748SDimitry Andric   if (F->hasAttr<DLLImportAttr>()) {
17980623d748SDimitry Andric     // Check whether it would be safe to inline this dllimport function.
17990623d748SDimitry Andric     DLLImportFunctionVisitor Visitor;
18000623d748SDimitry Andric     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
18010623d748SDimitry Andric     if (!Visitor.SafeToInline)
18020623d748SDimitry Andric       return false;
180344290647SDimitry Andric 
180444290647SDimitry Andric     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
180544290647SDimitry Andric       // Implicit destructor invocations aren't captured in the AST, so the
180644290647SDimitry Andric       // check above can't see them. Check for them manually here.
180744290647SDimitry Andric       for (const Decl *Member : Dtor->getParent()->decls())
180844290647SDimitry Andric         if (isa<FieldDecl>(Member))
180944290647SDimitry Andric           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
181044290647SDimitry Andric             return false;
181144290647SDimitry Andric       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
181244290647SDimitry Andric         if (HasNonDllImportDtor(B.getType()))
181344290647SDimitry Andric           return false;
181444290647SDimitry Andric     }
18150623d748SDimitry Andric   }
18160623d748SDimitry Andric 
1817f8254f43SDimitry Andric   // PR9614. Avoid cases where the source code is lying to us. An available
1818f8254f43SDimitry Andric   // externally function should have an equivalent function somewhere else,
1819f8254f43SDimitry Andric   // but a function that calls itself is clearly not equivalent to the real
1820f8254f43SDimitry Andric   // implementation.
1821f8254f43SDimitry Andric   // This happens in glibc's btowc and in some configure checks.
1822dff0c46cSDimitry Andric   return !isTriviallyRecursive(F);
1823f8254f43SDimitry Andric }
1824f8254f43SDimitry Andric 
1825f785676fSDimitry Andric /// If the type for the method's class was generated by
1826f785676fSDimitry Andric /// CGDebugInfo::createContextChain(), the cache contains only a
1827f785676fSDimitry Andric /// limited DIType without any declarations. Since EmitFunctionStart()
1828f785676fSDimitry Andric /// needs to find the canonical declaration for each method, we need
1829f785676fSDimitry Andric /// to construct the complete type prior to emitting the method.
1830f785676fSDimitry Andric void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
1831f785676fSDimitry Andric   if (!D->isInstance())
1832f785676fSDimitry Andric     return;
1833f785676fSDimitry Andric 
1834f785676fSDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
1835e7145dcbSDimitry Andric     if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
183659d1ed5bSDimitry Andric       const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext()));
1837f785676fSDimitry Andric       DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
1838f785676fSDimitry Andric     }
1839f785676fSDimitry Andric }
1840f785676fSDimitry Andric 
184159d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
184259d1ed5bSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
1843f22ef01cSRoman Divacky 
1844f22ef01cSRoman Divacky   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1845f22ef01cSRoman Divacky                                  Context.getSourceManager(),
1846f22ef01cSRoman Divacky                                  "Generating code for declaration");
1847f22ef01cSRoman Divacky 
1848f785676fSDimitry Andric   if (isa<FunctionDecl>(D)) {
1849ffd1746dSEd Schouten     // At -O0, don't generate IR for functions with available_externally
1850ffd1746dSEd Schouten     // linkage.
1851f785676fSDimitry Andric     if (!shouldEmitFunction(GD))
1852ffd1746dSEd Schouten       return;
1853ffd1746dSEd Schouten 
185459d1ed5bSDimitry Andric     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
1855f785676fSDimitry Andric       CompleteDIClassType(Method);
1856bd5abe19SDimitry Andric       // Make sure to emit the definition(s) before we emit the thunks.
1857bd5abe19SDimitry Andric       // This is necessary for the generation of certain thunks.
185859d1ed5bSDimitry Andric       if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
185939d628a0SDimitry Andric         ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
186059d1ed5bSDimitry Andric       else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
186139d628a0SDimitry Andric         ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
1862bd5abe19SDimitry Andric       else
186359d1ed5bSDimitry Andric         EmitGlobalFunctionDefinition(GD, GV);
1864bd5abe19SDimitry Andric 
1865f22ef01cSRoman Divacky       if (Method->isVirtual())
1866f22ef01cSRoman Divacky         getVTables().EmitThunks(GD);
1867f22ef01cSRoman Divacky 
1868bd5abe19SDimitry Andric       return;
1869ffd1746dSEd Schouten     }
1870f22ef01cSRoman Divacky 
187159d1ed5bSDimitry Andric     return EmitGlobalFunctionDefinition(GD, GV);
1872ffd1746dSEd Schouten   }
1873f22ef01cSRoman Divacky 
187459d1ed5bSDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
1875e7145dcbSDimitry Andric     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
1876f22ef01cSRoman Divacky 
18776122f3e6SDimitry Andric   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1878f22ef01cSRoman Divacky }
1879f22ef01cSRoman Divacky 
18800623d748SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
18810623d748SDimitry Andric                                                       llvm::Function *NewFn);
18820623d748SDimitry Andric 
1883f22ef01cSRoman Divacky /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1884f22ef01cSRoman Divacky /// module, create and return an llvm Function with the specified type. If there
1885f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially
1886f22ef01cSRoman Divacky /// bitcasted to the right type.
1887f22ef01cSRoman Divacky ///
1888f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this.  This is used
1889f22ef01cSRoman Divacky /// to set the attributes on the function when it is first created.
1890f22ef01cSRoman Divacky llvm::Constant *
18916122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
18926122f3e6SDimitry Andric                                        llvm::Type *Ty,
1893f785676fSDimitry Andric                                        GlobalDecl GD, bool ForVTable,
189439d628a0SDimitry Andric                                        bool DontDefer, bool IsThunk,
18950623d748SDimitry Andric                                        llvm::AttributeSet ExtraAttrs,
189644290647SDimitry Andric                                        ForDefinition_t IsForDefinition) {
1897f785676fSDimitry Andric   const Decl *D = GD.getDecl();
1898f785676fSDimitry Andric 
1899f22ef01cSRoman Divacky   // Lookup the entry, lazily creating it if necessary.
1900f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1901f22ef01cSRoman Divacky   if (Entry) {
19023861d79fSDimitry Andric     if (WeakRefReferences.erase(Entry)) {
1903f785676fSDimitry Andric       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
1904f22ef01cSRoman Divacky       if (FD && !FD->hasAttr<WeakAttr>())
1905f22ef01cSRoman Divacky         Entry->setLinkage(llvm::Function::ExternalLinkage);
1906f22ef01cSRoman Divacky     }
1907f22ef01cSRoman Divacky 
190839d628a0SDimitry Andric     // Handle dropped DLL attributes.
190939d628a0SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
191039d628a0SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
191139d628a0SDimitry Andric 
19120623d748SDimitry Andric     // If there are two attempts to define the same mangled name, issue an
19130623d748SDimitry Andric     // error.
19140623d748SDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
19150623d748SDimitry Andric       GlobalDecl OtherGD;
1916e7145dcbSDimitry Andric       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
1917e7145dcbSDimitry Andric       // to make sure that we issue an error only once.
19180623d748SDimitry Andric       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
19190623d748SDimitry Andric           (GD.getCanonicalDecl().getDecl() !=
19200623d748SDimitry Andric            OtherGD.getCanonicalDecl().getDecl()) &&
19210623d748SDimitry Andric           DiagnosedConflictingDefinitions.insert(GD).second) {
19220623d748SDimitry Andric         getDiags().Report(D->getLocation(),
19230623d748SDimitry Andric                           diag::err_duplicate_mangled_name);
19240623d748SDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
19250623d748SDimitry Andric                           diag::note_previous_definition);
19260623d748SDimitry Andric       }
19270623d748SDimitry Andric     }
19280623d748SDimitry Andric 
19290623d748SDimitry Andric     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
19300623d748SDimitry Andric         (Entry->getType()->getElementType() == Ty)) {
1931f22ef01cSRoman Divacky       return Entry;
19320623d748SDimitry Andric     }
1933f22ef01cSRoman Divacky 
1934f22ef01cSRoman Divacky     // Make sure the result is of the correct type.
19350623d748SDimitry Andric     // (If function is requested for a definition, we always need to create a new
19360623d748SDimitry Andric     // function, not just return a bitcast.)
19370623d748SDimitry Andric     if (!IsForDefinition)
193817a519f9SDimitry Andric       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1939f22ef01cSRoman Divacky   }
1940f22ef01cSRoman Divacky 
1941f22ef01cSRoman Divacky   // This function doesn't have a complete type (for example, the return
1942f22ef01cSRoman Divacky   // type is an incomplete struct). Use a fake type instead, and make
1943f22ef01cSRoman Divacky   // sure not to try to set attributes.
1944f22ef01cSRoman Divacky   bool IsIncompleteFunction = false;
1945f22ef01cSRoman Divacky 
19466122f3e6SDimitry Andric   llvm::FunctionType *FTy;
1947f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(Ty)) {
1948f22ef01cSRoman Divacky     FTy = cast<llvm::FunctionType>(Ty);
1949f22ef01cSRoman Divacky   } else {
1950bd5abe19SDimitry Andric     FTy = llvm::FunctionType::get(VoidTy, false);
1951f22ef01cSRoman Divacky     IsIncompleteFunction = true;
1952f22ef01cSRoman Divacky   }
1953ffd1746dSEd Schouten 
19540623d748SDimitry Andric   llvm::Function *F =
19550623d748SDimitry Andric       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
19560623d748SDimitry Andric                              Entry ? StringRef() : MangledName, &getModule());
19570623d748SDimitry Andric 
19580623d748SDimitry Andric   // If we already created a function with the same mangled name (but different
19590623d748SDimitry Andric   // type) before, take its name and add it to the list of functions to be
19600623d748SDimitry Andric   // replaced with F at the end of CodeGen.
19610623d748SDimitry Andric   //
19620623d748SDimitry Andric   // This happens if there is a prototype for a function (e.g. "int f()") and
19630623d748SDimitry Andric   // then a definition of a different type (e.g. "int f(int x)").
19640623d748SDimitry Andric   if (Entry) {
19650623d748SDimitry Andric     F->takeName(Entry);
19660623d748SDimitry Andric 
19670623d748SDimitry Andric     // This might be an implementation of a function without a prototype, in
19680623d748SDimitry Andric     // which case, try to do special replacement of calls which match the new
19690623d748SDimitry Andric     // prototype.  The really key thing here is that we also potentially drop
19700623d748SDimitry Andric     // arguments from the call site so as to make a direct call, which makes the
19710623d748SDimitry Andric     // inliner happier and suppresses a number of optimizer warnings (!) about
19720623d748SDimitry Andric     // dropping arguments.
19730623d748SDimitry Andric     if (!Entry->use_empty()) {
19740623d748SDimitry Andric       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
19750623d748SDimitry Andric       Entry->removeDeadConstantUsers();
19760623d748SDimitry Andric     }
19770623d748SDimitry Andric 
19780623d748SDimitry Andric     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
19790623d748SDimitry Andric         F, Entry->getType()->getElementType()->getPointerTo());
19800623d748SDimitry Andric     addGlobalValReplacement(Entry, BC);
19810623d748SDimitry Andric   }
19820623d748SDimitry Andric 
1983f22ef01cSRoman Divacky   assert(F->getName() == MangledName && "name was uniqued!");
1984f785676fSDimitry Andric   if (D)
198539d628a0SDimitry Andric     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
1986139f7f9bSDimitry Andric   if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1987139f7f9bSDimitry Andric     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
1988139f7f9bSDimitry Andric     F->addAttributes(llvm::AttributeSet::FunctionIndex,
1989139f7f9bSDimitry Andric                      llvm::AttributeSet::get(VMContext,
1990139f7f9bSDimitry Andric                                              llvm::AttributeSet::FunctionIndex,
1991139f7f9bSDimitry Andric                                              B));
1992139f7f9bSDimitry Andric   }
1993f22ef01cSRoman Divacky 
199459d1ed5bSDimitry Andric   if (!DontDefer) {
199559d1ed5bSDimitry Andric     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
199659d1ed5bSDimitry Andric     // each other bottoming out with the base dtor.  Therefore we emit non-base
199759d1ed5bSDimitry Andric     // dtors on usage, even if there is no dtor definition in the TU.
199859d1ed5bSDimitry Andric     if (D && isa<CXXDestructorDecl>(D) &&
199959d1ed5bSDimitry Andric         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
200059d1ed5bSDimitry Andric                                            GD.getDtorType()))
200159d1ed5bSDimitry Andric       addDeferredDeclToEmit(F, GD);
200259d1ed5bSDimitry Andric 
2003f22ef01cSRoman Divacky     // This is the first use or definition of a mangled name.  If there is a
2004f22ef01cSRoman Divacky     // deferred decl with this name, remember that we need to emit it at the end
2005f22ef01cSRoman Divacky     // of the file.
200659d1ed5bSDimitry Andric     auto DDI = DeferredDecls.find(MangledName);
2007f22ef01cSRoman Divacky     if (DDI != DeferredDecls.end()) {
200859d1ed5bSDimitry Andric       // Move the potentially referenced deferred decl to the
200959d1ed5bSDimitry Andric       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
201059d1ed5bSDimitry Andric       // don't need it anymore).
201159d1ed5bSDimitry Andric       addDeferredDeclToEmit(F, DDI->second);
2012f22ef01cSRoman Divacky       DeferredDecls.erase(DDI);
20132754fe60SDimitry Andric 
20142754fe60SDimitry Andric       // Otherwise, there are cases we have to worry about where we're
20152754fe60SDimitry Andric       // using a declaration for which we must emit a definition but where
20162754fe60SDimitry Andric       // we might not find a top-level definition:
20172754fe60SDimitry Andric       //   - member functions defined inline in their classes
20182754fe60SDimitry Andric       //   - friend functions defined inline in some class
20192754fe60SDimitry Andric       //   - special member functions with implicit definitions
20202754fe60SDimitry Andric       // If we ever change our AST traversal to walk into class methods,
20212754fe60SDimitry Andric       // this will be unnecessary.
20222754fe60SDimitry Andric       //
202359d1ed5bSDimitry Andric       // We also don't emit a definition for a function if it's going to be an
202439d628a0SDimitry Andric       // entry in a vtable, unless it's already marked as used.
2025f785676fSDimitry Andric     } else if (getLangOpts().CPlusPlus && D) {
20262754fe60SDimitry Andric       // Look for a declaration that's lexically in a record.
202739d628a0SDimitry Andric       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
202839d628a0SDimitry Andric            FD = FD->getPreviousDecl()) {
20292754fe60SDimitry Andric         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
203039d628a0SDimitry Andric           if (FD->doesThisDeclarationHaveABody()) {
203159d1ed5bSDimitry Andric             addDeferredDeclToEmit(F, GD.getWithDecl(FD));
20322754fe60SDimitry Andric             break;
2033f22ef01cSRoman Divacky           }
2034f22ef01cSRoman Divacky         }
203539d628a0SDimitry Andric       }
2036f22ef01cSRoman Divacky     }
203759d1ed5bSDimitry Andric   }
2038f22ef01cSRoman Divacky 
2039f22ef01cSRoman Divacky   // Make sure the result is of the requested type.
2040f22ef01cSRoman Divacky   if (!IsIncompleteFunction) {
2041f22ef01cSRoman Divacky     assert(F->getType()->getElementType() == Ty);
2042f22ef01cSRoman Divacky     return F;
2043f22ef01cSRoman Divacky   }
2044f22ef01cSRoman Divacky 
204517a519f9SDimitry Andric   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2046f22ef01cSRoman Divacky   return llvm::ConstantExpr::getBitCast(F, PTy);
2047f22ef01cSRoman Divacky }
2048f22ef01cSRoman Divacky 
2049f22ef01cSRoman Divacky /// GetAddrOfFunction - Return the address of the given function.  If Ty is
2050f22ef01cSRoman Divacky /// non-null, then this function will use the specified type if it has to
2051f22ef01cSRoman Divacky /// create it (this occurs when we see a definition of the function).
2052f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
20536122f3e6SDimitry Andric                                                  llvm::Type *Ty,
205459d1ed5bSDimitry Andric                                                  bool ForVTable,
20550623d748SDimitry Andric                                                  bool DontDefer,
205644290647SDimitry Andric                                               ForDefinition_t IsForDefinition) {
2057f22ef01cSRoman Divacky   // If there was no specific requested type, just convert it now.
20580623d748SDimitry Andric   if (!Ty) {
20590623d748SDimitry Andric     const auto *FD = cast<FunctionDecl>(GD.getDecl());
20600623d748SDimitry Andric     auto CanonTy = Context.getCanonicalType(FD->getType());
20610623d748SDimitry Andric     Ty = getTypes().ConvertFunctionType(CanonTy, FD);
20620623d748SDimitry Andric   }
2063ffd1746dSEd Schouten 
20646122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
20650623d748SDimitry Andric   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
20660623d748SDimitry Andric                                  /*IsThunk=*/false, llvm::AttributeSet(),
20670623d748SDimitry Andric                                  IsForDefinition);
2068f22ef01cSRoman Divacky }
2069f22ef01cSRoman Divacky 
207044290647SDimitry Andric static const FunctionDecl *
207144290647SDimitry Andric GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
207244290647SDimitry Andric   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
207344290647SDimitry Andric   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
207444290647SDimitry Andric 
207544290647SDimitry Andric   IdentifierInfo &CII = C.Idents.get(Name);
207644290647SDimitry Andric   for (const auto &Result : DC->lookup(&CII))
207744290647SDimitry Andric     if (const auto FD = dyn_cast<FunctionDecl>(Result))
207844290647SDimitry Andric       return FD;
207944290647SDimitry Andric 
208044290647SDimitry Andric   if (!C.getLangOpts().CPlusPlus)
208144290647SDimitry Andric     return nullptr;
208244290647SDimitry Andric 
208344290647SDimitry Andric   // Demangle the premangled name from getTerminateFn()
208444290647SDimitry Andric   IdentifierInfo &CXXII =
208544290647SDimitry Andric       (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ")
208644290647SDimitry Andric           ? C.Idents.get("terminate")
208744290647SDimitry Andric           : C.Idents.get(Name);
208844290647SDimitry Andric 
208944290647SDimitry Andric   for (const auto &N : {"__cxxabiv1", "std"}) {
209044290647SDimitry Andric     IdentifierInfo &NS = C.Idents.get(N);
209144290647SDimitry Andric     for (const auto &Result : DC->lookup(&NS)) {
209244290647SDimitry Andric       NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
209344290647SDimitry Andric       if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
209444290647SDimitry Andric         for (const auto &Result : LSD->lookup(&NS))
209544290647SDimitry Andric           if ((ND = dyn_cast<NamespaceDecl>(Result)))
209644290647SDimitry Andric             break;
209744290647SDimitry Andric 
209844290647SDimitry Andric       if (ND)
209944290647SDimitry Andric         for (const auto &Result : ND->lookup(&CXXII))
210044290647SDimitry Andric           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
210144290647SDimitry Andric             return FD;
210244290647SDimitry Andric     }
210344290647SDimitry Andric   }
210444290647SDimitry Andric 
210544290647SDimitry Andric   return nullptr;
210644290647SDimitry Andric }
210744290647SDimitry Andric 
2108f22ef01cSRoman Divacky /// CreateRuntimeFunction - Create a new runtime function with the specified
2109f22ef01cSRoman Divacky /// type and name.
2110f22ef01cSRoman Divacky llvm::Constant *
211144290647SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
211244290647SDimitry Andric                                      llvm::AttributeSet ExtraAttrs,
211344290647SDimitry Andric                                      bool Local) {
211459d1ed5bSDimitry Andric   llvm::Constant *C =
211559d1ed5bSDimitry Andric       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
211644290647SDimitry Andric                               /*DontDefer=*/false, /*IsThunk=*/false,
211744290647SDimitry Andric                               ExtraAttrs);
211844290647SDimitry Andric 
211944290647SDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(C)) {
212044290647SDimitry Andric     if (F->empty()) {
2121139f7f9bSDimitry Andric       F->setCallingConv(getRuntimeCC());
212244290647SDimitry Andric 
212344290647SDimitry Andric       if (!Local && getTriple().isOSBinFormatCOFF() &&
212444290647SDimitry Andric           !getCodeGenOpts().LTOVisibilityPublicStd) {
212544290647SDimitry Andric         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
212644290647SDimitry Andric         if (!FD || FD->hasAttr<DLLImportAttr>()) {
212744290647SDimitry Andric           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
212844290647SDimitry Andric           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
212944290647SDimitry Andric         }
213044290647SDimitry Andric       }
213144290647SDimitry Andric     }
213244290647SDimitry Andric   }
213344290647SDimitry Andric 
2134139f7f9bSDimitry Andric   return C;
2135f22ef01cSRoman Divacky }
2136f22ef01cSRoman Divacky 
213739d628a0SDimitry Andric /// CreateBuiltinFunction - Create a new builtin function with the specified
213839d628a0SDimitry Andric /// type and name.
213939d628a0SDimitry Andric llvm::Constant *
214039d628a0SDimitry Andric CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy,
214139d628a0SDimitry Andric                                      StringRef Name,
214239d628a0SDimitry Andric                                      llvm::AttributeSet ExtraAttrs) {
214339d628a0SDimitry Andric   llvm::Constant *C =
214439d628a0SDimitry Andric       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
214539d628a0SDimitry Andric                               /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
214639d628a0SDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(C))
214739d628a0SDimitry Andric     if (F->empty())
214839d628a0SDimitry Andric       F->setCallingConv(getBuiltinCC());
214939d628a0SDimitry Andric   return C;
215039d628a0SDimitry Andric }
215139d628a0SDimitry Andric 
2152dff0c46cSDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted
2153dff0c46cSDimitry Andric /// as a constant.
2154dff0c46cSDimitry Andric ///
2155dff0c46cSDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs
2156dff0c46cSDimitry Andric /// will not be considered. The caller will need to verify that the object is
2157dff0c46cSDimitry Andric /// not written to during its construction.
2158dff0c46cSDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2159dff0c46cSDimitry Andric   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
2160f22ef01cSRoman Divacky     return false;
2161bd5abe19SDimitry Andric 
2162dff0c46cSDimitry Andric   if (Context.getLangOpts().CPlusPlus) {
2163dff0c46cSDimitry Andric     if (const CXXRecordDecl *Record
2164dff0c46cSDimitry Andric           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2165dff0c46cSDimitry Andric       return ExcludeCtor && !Record->hasMutableFields() &&
2166dff0c46cSDimitry Andric              Record->hasTrivialDestructor();
2167f22ef01cSRoman Divacky   }
2168bd5abe19SDimitry Andric 
2169f22ef01cSRoman Divacky   return true;
2170f22ef01cSRoman Divacky }
2171f22ef01cSRoman Divacky 
2172f22ef01cSRoman Divacky /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2173f22ef01cSRoman Divacky /// create and return an llvm GlobalVariable with the specified type.  If there
2174f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially
2175f22ef01cSRoman Divacky /// bitcasted to the right type.
2176f22ef01cSRoman Divacky ///
2177f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this.  This is used
2178f22ef01cSRoman Divacky /// to set the attributes on the global when it is first created.
2179e7145dcbSDimitry Andric ///
2180e7145dcbSDimitry Andric /// If IsForDefinition is true, it is guranteed that an actual global with
2181e7145dcbSDimitry Andric /// type Ty will be returned, not conversion of a variable with the same
2182e7145dcbSDimitry Andric /// mangled name but some other type.
2183f22ef01cSRoman Divacky llvm::Constant *
21846122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
21856122f3e6SDimitry Andric                                      llvm::PointerType *Ty,
2186e7145dcbSDimitry Andric                                      const VarDecl *D,
218744290647SDimitry Andric                                      ForDefinition_t IsForDefinition) {
2188f22ef01cSRoman Divacky   // Lookup the entry, lazily creating it if necessary.
2189f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2190f22ef01cSRoman Divacky   if (Entry) {
21913861d79fSDimitry Andric     if (WeakRefReferences.erase(Entry)) {
2192f22ef01cSRoman Divacky       if (D && !D->hasAttr<WeakAttr>())
2193f22ef01cSRoman Divacky         Entry->setLinkage(llvm::Function::ExternalLinkage);
2194f22ef01cSRoman Divacky     }
2195f22ef01cSRoman Divacky 
219639d628a0SDimitry Andric     // Handle dropped DLL attributes.
219739d628a0SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
219839d628a0SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
219939d628a0SDimitry Andric 
2200f22ef01cSRoman Divacky     if (Entry->getType() == Ty)
2201f22ef01cSRoman Divacky       return Entry;
2202f22ef01cSRoman Divacky 
2203e7145dcbSDimitry Andric     // If there are two attempts to define the same mangled name, issue an
2204e7145dcbSDimitry Andric     // error.
2205e7145dcbSDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
2206e7145dcbSDimitry Andric       GlobalDecl OtherGD;
2207e7145dcbSDimitry Andric       const VarDecl *OtherD;
2208e7145dcbSDimitry Andric 
2209e7145dcbSDimitry Andric       // Check that D is not yet in DiagnosedConflictingDefinitions is required
2210e7145dcbSDimitry Andric       // to make sure that we issue an error only once.
2211e7145dcbSDimitry Andric       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
2212e7145dcbSDimitry Andric           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2213e7145dcbSDimitry Andric           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2214e7145dcbSDimitry Andric           OtherD->hasInit() &&
2215e7145dcbSDimitry Andric           DiagnosedConflictingDefinitions.insert(D).second) {
2216e7145dcbSDimitry Andric         getDiags().Report(D->getLocation(),
2217e7145dcbSDimitry Andric                           diag::err_duplicate_mangled_name);
2218e7145dcbSDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
2219e7145dcbSDimitry Andric                           diag::note_previous_definition);
2220e7145dcbSDimitry Andric       }
2221e7145dcbSDimitry Andric     }
2222e7145dcbSDimitry Andric 
2223f22ef01cSRoman Divacky     // Make sure the result is of the correct type.
2224f785676fSDimitry Andric     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2225f785676fSDimitry Andric       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2226f785676fSDimitry Andric 
2227e7145dcbSDimitry Andric     // (If global is requested for a definition, we always need to create a new
2228e7145dcbSDimitry Andric     // global, not just return a bitcast.)
2229e7145dcbSDimitry Andric     if (!IsForDefinition)
2230f22ef01cSRoman Divacky       return llvm::ConstantExpr::getBitCast(Entry, Ty);
2231f22ef01cSRoman Divacky   }
2232f22ef01cSRoman Divacky 
223359d1ed5bSDimitry Andric   unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
223459d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
223559d1ed5bSDimitry Andric       getModule(), Ty->getElementType(), false,
223659d1ed5bSDimitry Andric       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
223759d1ed5bSDimitry Andric       llvm::GlobalVariable::NotThreadLocal, AddrSpace);
223859d1ed5bSDimitry Andric 
2239e7145dcbSDimitry Andric   // If we already created a global with the same mangled name (but different
2240e7145dcbSDimitry Andric   // type) before, take its name and remove it from its parent.
2241e7145dcbSDimitry Andric   if (Entry) {
2242e7145dcbSDimitry Andric     GV->takeName(Entry);
2243e7145dcbSDimitry Andric 
2244e7145dcbSDimitry Andric     if (!Entry->use_empty()) {
2245e7145dcbSDimitry Andric       llvm::Constant *NewPtrForOldDecl =
2246e7145dcbSDimitry Andric           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2247e7145dcbSDimitry Andric       Entry->replaceAllUsesWith(NewPtrForOldDecl);
2248e7145dcbSDimitry Andric     }
2249e7145dcbSDimitry Andric 
2250e7145dcbSDimitry Andric     Entry->eraseFromParent();
2251e7145dcbSDimitry Andric   }
2252e7145dcbSDimitry Andric 
2253f22ef01cSRoman Divacky   // This is the first use or definition of a mangled name.  If there is a
2254f22ef01cSRoman Divacky   // deferred decl with this name, remember that we need to emit it at the end
2255f22ef01cSRoman Divacky   // of the file.
225659d1ed5bSDimitry Andric   auto DDI = DeferredDecls.find(MangledName);
2257f22ef01cSRoman Divacky   if (DDI != DeferredDecls.end()) {
2258f22ef01cSRoman Divacky     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2259f22ef01cSRoman Divacky     // list, and remove it from DeferredDecls (since we don't need it anymore).
226059d1ed5bSDimitry Andric     addDeferredDeclToEmit(GV, DDI->second);
2261f22ef01cSRoman Divacky     DeferredDecls.erase(DDI);
2262f22ef01cSRoman Divacky   }
2263f22ef01cSRoman Divacky 
2264f22ef01cSRoman Divacky   // Handle things which are present even on external declarations.
2265f22ef01cSRoman Divacky   if (D) {
2266f22ef01cSRoman Divacky     // FIXME: This code is overly simple and should be merged with other global
2267f22ef01cSRoman Divacky     // handling.
2268dff0c46cSDimitry Andric     GV->setConstant(isTypeConstant(D->getType(), false));
2269f22ef01cSRoman Divacky 
227033956c43SDimitry Andric     GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
227133956c43SDimitry Andric 
227259d1ed5bSDimitry Andric     setLinkageAndVisibilityForGV(GV, D);
22732754fe60SDimitry Andric 
2274284c1978SDimitry Andric     if (D->getTLSKind()) {
2275284c1978SDimitry Andric       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
22760623d748SDimitry Andric         CXXThreadLocals.push_back(D);
22777ae0e2c9SDimitry Andric       setTLSMode(GV, *D);
2278f22ef01cSRoman Divacky     }
2279f785676fSDimitry Andric 
2280f785676fSDimitry Andric     // If required by the ABI, treat declarations of static data members with
2281f785676fSDimitry Andric     // inline initializers as definitions.
228259d1ed5bSDimitry Andric     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
2283f785676fSDimitry Andric       EmitGlobalVarDefinition(D);
2284284c1978SDimitry Andric     }
2285f22ef01cSRoman Divacky 
228659d1ed5bSDimitry Andric     // Handle XCore specific ABI requirements.
228744290647SDimitry Andric     if (getTriple().getArch() == llvm::Triple::xcore &&
228859d1ed5bSDimitry Andric         D->getLanguageLinkage() == CLanguageLinkage &&
228959d1ed5bSDimitry Andric         D->getType().isConstant(Context) &&
229059d1ed5bSDimitry Andric         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
229159d1ed5bSDimitry Andric       GV->setSection(".cp.rodata");
229259d1ed5bSDimitry Andric   }
229359d1ed5bSDimitry Andric 
22947ae0e2c9SDimitry Andric   if (AddrSpace != Ty->getAddressSpace())
2295f785676fSDimitry Andric     return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
2296f785676fSDimitry Andric 
2297f22ef01cSRoman Divacky   return GV;
2298f22ef01cSRoman Divacky }
2299f22ef01cSRoman Divacky 
23000623d748SDimitry Andric llvm::Constant *
23010623d748SDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
230244290647SDimitry Andric                                ForDefinition_t IsForDefinition) {
230344290647SDimitry Andric   const Decl *D = GD.getDecl();
230444290647SDimitry Andric   if (isa<CXXConstructorDecl>(D))
230544290647SDimitry Andric     return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
23060623d748SDimitry Andric                                 getFromCtorType(GD.getCtorType()),
23070623d748SDimitry Andric                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
23080623d748SDimitry Andric                                 /*DontDefer=*/false, IsForDefinition);
230944290647SDimitry Andric   else if (isa<CXXDestructorDecl>(D))
231044290647SDimitry Andric     return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
23110623d748SDimitry Andric                                 getFromDtorType(GD.getDtorType()),
23120623d748SDimitry Andric                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
23130623d748SDimitry Andric                                 /*DontDefer=*/false, IsForDefinition);
231444290647SDimitry Andric   else if (isa<CXXMethodDecl>(D)) {
23150623d748SDimitry Andric     auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
231644290647SDimitry Andric         cast<CXXMethodDecl>(D));
23170623d748SDimitry Andric     auto Ty = getTypes().GetFunctionType(*FInfo);
23180623d748SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
23190623d748SDimitry Andric                              IsForDefinition);
232044290647SDimitry Andric   } else if (isa<FunctionDecl>(D)) {
23210623d748SDimitry Andric     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
23220623d748SDimitry Andric     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
23230623d748SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
23240623d748SDimitry Andric                              IsForDefinition);
23250623d748SDimitry Andric   } else
232644290647SDimitry Andric     return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
2327e7145dcbSDimitry Andric                               IsForDefinition);
23280623d748SDimitry Andric }
2329f22ef01cSRoman Divacky 
23302754fe60SDimitry Andric llvm::GlobalVariable *
23316122f3e6SDimitry Andric CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
23326122f3e6SDimitry Andric                                       llvm::Type *Ty,
23332754fe60SDimitry Andric                                       llvm::GlobalValue::LinkageTypes Linkage) {
23342754fe60SDimitry Andric   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
233559d1ed5bSDimitry Andric   llvm::GlobalVariable *OldGV = nullptr;
23362754fe60SDimitry Andric 
23372754fe60SDimitry Andric   if (GV) {
23382754fe60SDimitry Andric     // Check if the variable has the right type.
23392754fe60SDimitry Andric     if (GV->getType()->getElementType() == Ty)
23402754fe60SDimitry Andric       return GV;
23412754fe60SDimitry Andric 
23422754fe60SDimitry Andric     // Because C++ name mangling, the only way we can end up with an already
23432754fe60SDimitry Andric     // existing global with the same name is if it has been declared extern "C".
23442754fe60SDimitry Andric     assert(GV->isDeclaration() && "Declaration has wrong type!");
23452754fe60SDimitry Andric     OldGV = GV;
23462754fe60SDimitry Andric   }
23472754fe60SDimitry Andric 
23482754fe60SDimitry Andric   // Create a new variable.
23492754fe60SDimitry Andric   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
235059d1ed5bSDimitry Andric                                 Linkage, nullptr, Name);
23512754fe60SDimitry Andric 
23522754fe60SDimitry Andric   if (OldGV) {
23532754fe60SDimitry Andric     // Replace occurrences of the old variable if needed.
23542754fe60SDimitry Andric     GV->takeName(OldGV);
23552754fe60SDimitry Andric 
23562754fe60SDimitry Andric     if (!OldGV->use_empty()) {
23572754fe60SDimitry Andric       llvm::Constant *NewPtrForOldDecl =
23582754fe60SDimitry Andric       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
23592754fe60SDimitry Andric       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
23602754fe60SDimitry Andric     }
23612754fe60SDimitry Andric 
23622754fe60SDimitry Andric     OldGV->eraseFromParent();
23632754fe60SDimitry Andric   }
23642754fe60SDimitry Andric 
236533956c43SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker() &&
236633956c43SDimitry Andric       !GV->hasAvailableExternallyLinkage())
236733956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
236833956c43SDimitry Andric 
23692754fe60SDimitry Andric   return GV;
23702754fe60SDimitry Andric }
23712754fe60SDimitry Andric 
2372f22ef01cSRoman Divacky /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
2373f22ef01cSRoman Divacky /// given global variable.  If Ty is non-null and if the global doesn't exist,
2374cb4dff85SDimitry Andric /// then it will be created with the specified type instead of whatever the
2375e7145dcbSDimitry Andric /// normal requested type would be. If IsForDefinition is true, it is guranteed
2376e7145dcbSDimitry Andric /// that an actual global with type Ty will be returned, not conversion of a
2377e7145dcbSDimitry Andric /// variable with the same mangled name but some other type.
2378f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
2379e7145dcbSDimitry Andric                                                   llvm::Type *Ty,
238044290647SDimitry Andric                                            ForDefinition_t IsForDefinition) {
2381f22ef01cSRoman Divacky   assert(D->hasGlobalStorage() && "Not a global variable");
2382f22ef01cSRoman Divacky   QualType ASTTy = D->getType();
238359d1ed5bSDimitry Andric   if (!Ty)
2384f22ef01cSRoman Divacky     Ty = getTypes().ConvertTypeForMem(ASTTy);
2385f22ef01cSRoman Divacky 
23866122f3e6SDimitry Andric   llvm::PointerType *PTy =
23873b0f4066SDimitry Andric     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
2388f22ef01cSRoman Divacky 
23896122f3e6SDimitry Andric   StringRef MangledName = getMangledName(D);
2390e7145dcbSDimitry Andric   return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
2391f22ef01cSRoman Divacky }
2392f22ef01cSRoman Divacky 
2393f22ef01cSRoman Divacky /// CreateRuntimeVariable - Create a new runtime global variable with the
2394f22ef01cSRoman Divacky /// specified type and name.
2395f22ef01cSRoman Divacky llvm::Constant *
23966122f3e6SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
23976122f3e6SDimitry Andric                                      StringRef Name) {
239859d1ed5bSDimitry Andric   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
2399f22ef01cSRoman Divacky }
2400f22ef01cSRoman Divacky 
2401f22ef01cSRoman Divacky void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
2402f22ef01cSRoman Divacky   assert(!D->getInit() && "Cannot emit definite definitions here!");
2403f22ef01cSRoman Divacky 
24046122f3e6SDimitry Andric   StringRef MangledName = getMangledName(D);
2405e7145dcbSDimitry Andric   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
2406e7145dcbSDimitry Andric 
2407e7145dcbSDimitry Andric   // We already have a definition, not declaration, with the same mangled name.
2408e7145dcbSDimitry Andric   // Emitting of declaration is not required (and actually overwrites emitted
2409e7145dcbSDimitry Andric   // definition).
2410e7145dcbSDimitry Andric   if (GV && !GV->isDeclaration())
2411e7145dcbSDimitry Andric     return;
2412e7145dcbSDimitry Andric 
2413e7145dcbSDimitry Andric   // If we have not seen a reference to this variable yet, place it into the
2414e7145dcbSDimitry Andric   // deferred declarations table to be emitted if needed later.
2415e7145dcbSDimitry Andric   if (!MustBeEmitted(D) && !GV) {
2416f22ef01cSRoman Divacky       DeferredDecls[MangledName] = D;
2417f22ef01cSRoman Divacky       return;
2418f22ef01cSRoman Divacky   }
2419f22ef01cSRoman Divacky 
2420f22ef01cSRoman Divacky   // The tentative definition is the only definition.
2421f22ef01cSRoman Divacky   EmitGlobalVarDefinition(D);
2422f22ef01cSRoman Divacky }
2423f22ef01cSRoman Divacky 
24246122f3e6SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
24252754fe60SDimitry Andric   return Context.toCharUnitsFromBits(
24260623d748SDimitry Andric       getDataLayout().getTypeStoreSizeInBits(Ty));
2427f22ef01cSRoman Divacky }
2428f22ef01cSRoman Divacky 
24297ae0e2c9SDimitry Andric unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
24307ae0e2c9SDimitry Andric                                                  unsigned AddrSpace) {
2431e7145dcbSDimitry Andric   if (D && LangOpts.CUDA && LangOpts.CUDAIsDevice) {
24327ae0e2c9SDimitry Andric     if (D->hasAttr<CUDAConstantAttr>())
24337ae0e2c9SDimitry Andric       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
24347ae0e2c9SDimitry Andric     else if (D->hasAttr<CUDASharedAttr>())
24357ae0e2c9SDimitry Andric       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
24367ae0e2c9SDimitry Andric     else
24377ae0e2c9SDimitry Andric       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
24387ae0e2c9SDimitry Andric   }
24397ae0e2c9SDimitry Andric 
24407ae0e2c9SDimitry Andric   return AddrSpace;
24417ae0e2c9SDimitry Andric }
24427ae0e2c9SDimitry Andric 
2443284c1978SDimitry Andric template<typename SomeDecl>
2444284c1978SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
2445284c1978SDimitry Andric                                                llvm::GlobalValue *GV) {
2446284c1978SDimitry Andric   if (!getLangOpts().CPlusPlus)
2447284c1978SDimitry Andric     return;
2448284c1978SDimitry Andric 
2449284c1978SDimitry Andric   // Must have 'used' attribute, or else inline assembly can't rely on
2450284c1978SDimitry Andric   // the name existing.
2451284c1978SDimitry Andric   if (!D->template hasAttr<UsedAttr>())
2452284c1978SDimitry Andric     return;
2453284c1978SDimitry Andric 
2454284c1978SDimitry Andric   // Must have internal linkage and an ordinary name.
2455f785676fSDimitry Andric   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
2456284c1978SDimitry Andric     return;
2457284c1978SDimitry Andric 
2458284c1978SDimitry Andric   // Must be in an extern "C" context. Entities declared directly within
2459284c1978SDimitry Andric   // a record are not extern "C" even if the record is in such a context.
2460f785676fSDimitry Andric   const SomeDecl *First = D->getFirstDecl();
2461284c1978SDimitry Andric   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
2462284c1978SDimitry Andric     return;
2463284c1978SDimitry Andric 
2464284c1978SDimitry Andric   // OK, this is an internal linkage entity inside an extern "C" linkage
2465284c1978SDimitry Andric   // specification. Make a note of that so we can give it the "expected"
2466284c1978SDimitry Andric   // mangled name if nothing else is using that name.
2467284c1978SDimitry Andric   std::pair<StaticExternCMap::iterator, bool> R =
2468284c1978SDimitry Andric       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
2469284c1978SDimitry Andric 
2470284c1978SDimitry Andric   // If we have multiple internal linkage entities with the same name
2471284c1978SDimitry Andric   // in extern "C" regions, none of them gets that name.
2472284c1978SDimitry Andric   if (!R.second)
247359d1ed5bSDimitry Andric     R.first->second = nullptr;
2474284c1978SDimitry Andric }
2475284c1978SDimitry Andric 
247633956c43SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
247733956c43SDimitry Andric   if (!CGM.supportsCOMDAT())
247833956c43SDimitry Andric     return false;
247933956c43SDimitry Andric 
248033956c43SDimitry Andric   if (D.hasAttr<SelectAnyAttr>())
248133956c43SDimitry Andric     return true;
248233956c43SDimitry Andric 
248333956c43SDimitry Andric   GVALinkage Linkage;
248433956c43SDimitry Andric   if (auto *VD = dyn_cast<VarDecl>(&D))
248533956c43SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
248633956c43SDimitry Andric   else
248733956c43SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
248833956c43SDimitry Andric 
248933956c43SDimitry Andric   switch (Linkage) {
249033956c43SDimitry Andric   case GVA_Internal:
249133956c43SDimitry Andric   case GVA_AvailableExternally:
249233956c43SDimitry Andric   case GVA_StrongExternal:
249333956c43SDimitry Andric     return false;
249433956c43SDimitry Andric   case GVA_DiscardableODR:
249533956c43SDimitry Andric   case GVA_StrongODR:
249633956c43SDimitry Andric     return true;
249733956c43SDimitry Andric   }
249833956c43SDimitry Andric   llvm_unreachable("No such linkage");
249933956c43SDimitry Andric }
250033956c43SDimitry Andric 
250133956c43SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
250233956c43SDimitry Andric                                           llvm::GlobalObject &GO) {
250333956c43SDimitry Andric   if (!shouldBeInCOMDAT(*this, D))
250433956c43SDimitry Andric     return;
250533956c43SDimitry Andric   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
250633956c43SDimitry Andric }
250733956c43SDimitry Andric 
2508e7145dcbSDimitry Andric /// Pass IsTentative as true if you want to create a tentative definition.
2509e7145dcbSDimitry Andric void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
2510e7145dcbSDimitry Andric                                             bool IsTentative) {
251144290647SDimitry Andric   // OpenCL global variables of sampler type are translated to function calls,
251244290647SDimitry Andric   // therefore no need to be translated.
2513f22ef01cSRoman Divacky   QualType ASTTy = D->getType();
251444290647SDimitry Andric   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
251544290647SDimitry Andric     return;
251644290647SDimitry Andric 
251744290647SDimitry Andric   llvm::Constant *Init = nullptr;
2518dff0c46cSDimitry Andric   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2519dff0c46cSDimitry Andric   bool NeedsGlobalCtor = false;
2520dff0c46cSDimitry Andric   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
2521f22ef01cSRoman Divacky 
2522dff0c46cSDimitry Andric   const VarDecl *InitDecl;
2523dff0c46cSDimitry Andric   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2524f22ef01cSRoman Divacky 
2525e7145dcbSDimitry Andric   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
2526e7145dcbSDimitry Andric   // as part of their declaration."  Sema has already checked for
2527e7145dcbSDimitry Andric   // error cases, so we just need to set Init to UndefValue.
2528e7145dcbSDimitry Andric   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
2529e7145dcbSDimitry Andric       D->hasAttr<CUDASharedAttr>())
25300623d748SDimitry Andric     Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
2531e7145dcbSDimitry Andric   else if (!InitExpr) {
2532f22ef01cSRoman Divacky     // This is a tentative definition; tentative definitions are
2533f22ef01cSRoman Divacky     // implicitly initialized with { 0 }.
2534f22ef01cSRoman Divacky     //
2535f22ef01cSRoman Divacky     // Note that tentative definitions are only emitted at the end of
2536f22ef01cSRoman Divacky     // a translation unit, so they should never have incomplete
2537f22ef01cSRoman Divacky     // type. In addition, EmitTentativeDefinition makes sure that we
2538f22ef01cSRoman Divacky     // never attempt to emit a tentative definition if a real one
2539f22ef01cSRoman Divacky     // exists. A use may still exists, however, so we still may need
2540f22ef01cSRoman Divacky     // to do a RAUW.
2541f22ef01cSRoman Divacky     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
2542f22ef01cSRoman Divacky     Init = EmitNullConstant(D->getType());
2543f22ef01cSRoman Divacky   } else {
25447ae0e2c9SDimitry Andric     initializedGlobalDecl = GlobalDecl(D);
2545dff0c46cSDimitry Andric     Init = EmitConstantInit(*InitDecl);
2546f785676fSDimitry Andric 
2547f22ef01cSRoman Divacky     if (!Init) {
2548f22ef01cSRoman Divacky       QualType T = InitExpr->getType();
2549f22ef01cSRoman Divacky       if (D->getType()->isReferenceType())
2550f22ef01cSRoman Divacky         T = D->getType();
2551f22ef01cSRoman Divacky 
2552dff0c46cSDimitry Andric       if (getLangOpts().CPlusPlus) {
2553f22ef01cSRoman Divacky         Init = EmitNullConstant(T);
2554dff0c46cSDimitry Andric         NeedsGlobalCtor = true;
2555f22ef01cSRoman Divacky       } else {
2556f22ef01cSRoman Divacky         ErrorUnsupported(D, "static initializer");
2557f22ef01cSRoman Divacky         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2558f22ef01cSRoman Divacky       }
2559e580952dSDimitry Andric     } else {
2560e580952dSDimitry Andric       // We don't need an initializer, so remove the entry for the delayed
2561dff0c46cSDimitry Andric       // initializer position (just in case this entry was delayed) if we
2562dff0c46cSDimitry Andric       // also don't need to register a destructor.
2563dff0c46cSDimitry Andric       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
2564e580952dSDimitry Andric         DelayedCXXInitPosition.erase(D);
2565f22ef01cSRoman Divacky     }
2566f22ef01cSRoman Divacky   }
2567f22ef01cSRoman Divacky 
25686122f3e6SDimitry Andric   llvm::Type* InitType = Init->getType();
2569e7145dcbSDimitry Andric   llvm::Constant *Entry =
257044290647SDimitry Andric       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
2571f22ef01cSRoman Divacky 
2572f22ef01cSRoman Divacky   // Strip off a bitcast if we got one back.
257359d1ed5bSDimitry Andric   if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2574f22ef01cSRoman Divacky     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2575f785676fSDimitry Andric            CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2576f785676fSDimitry Andric            // All zero index gep.
2577f22ef01cSRoman Divacky            CE->getOpcode() == llvm::Instruction::GetElementPtr);
2578f22ef01cSRoman Divacky     Entry = CE->getOperand(0);
2579f22ef01cSRoman Divacky   }
2580f22ef01cSRoman Divacky 
2581f22ef01cSRoman Divacky   // Entry is now either a Function or GlobalVariable.
258259d1ed5bSDimitry Andric   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2583f22ef01cSRoman Divacky 
2584f22ef01cSRoman Divacky   // We have a definition after a declaration with the wrong type.
2585f22ef01cSRoman Divacky   // We must make a new GlobalVariable* and update everything that used OldGV
2586f22ef01cSRoman Divacky   // (a declaration or tentative definition) with the new GlobalVariable*
2587f22ef01cSRoman Divacky   // (which will be a definition).
2588f22ef01cSRoman Divacky   //
2589f22ef01cSRoman Divacky   // This happens if there is a prototype for a global (e.g.
2590f22ef01cSRoman Divacky   // "extern int x[];") and then a definition of a different type (e.g.
2591f22ef01cSRoman Divacky   // "int x[10];"). This also happens when an initializer has a different type
2592f22ef01cSRoman Divacky   // from the type of the global (this happens with unions).
259359d1ed5bSDimitry Andric   if (!GV ||
2594f22ef01cSRoman Divacky       GV->getType()->getElementType() != InitType ||
25953b0f4066SDimitry Andric       GV->getType()->getAddressSpace() !=
25967ae0e2c9SDimitry Andric        GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
2597f22ef01cSRoman Divacky 
2598f22ef01cSRoman Divacky     // Move the old entry aside so that we'll create a new one.
25996122f3e6SDimitry Andric     Entry->setName(StringRef());
2600f22ef01cSRoman Divacky 
2601f22ef01cSRoman Divacky     // Make a new global with the correct type, this is now guaranteed to work.
2602e7145dcbSDimitry Andric     GV = cast<llvm::GlobalVariable>(
260344290647SDimitry Andric         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
2604f22ef01cSRoman Divacky 
2605f22ef01cSRoman Divacky     // Replace all uses of the old global with the new global
2606f22ef01cSRoman Divacky     llvm::Constant *NewPtrForOldDecl =
2607f22ef01cSRoman Divacky         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2608f22ef01cSRoman Divacky     Entry->replaceAllUsesWith(NewPtrForOldDecl);
2609f22ef01cSRoman Divacky 
2610f22ef01cSRoman Divacky     // Erase the old global, since it is no longer used.
2611f22ef01cSRoman Divacky     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2612f22ef01cSRoman Divacky   }
2613f22ef01cSRoman Divacky 
2614284c1978SDimitry Andric   MaybeHandleStaticInExternC(D, GV);
2615284c1978SDimitry Andric 
26166122f3e6SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
26176122f3e6SDimitry Andric     AddGlobalAnnotations(D, GV);
2618f22ef01cSRoman Divacky 
2619e7145dcbSDimitry Andric   // Set the llvm linkage type as appropriate.
2620e7145dcbSDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
2621e7145dcbSDimitry Andric       getLLVMLinkageVarDefinition(D, GV->isConstant());
2622e7145dcbSDimitry Andric 
26230623d748SDimitry Andric   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
26240623d748SDimitry Andric   // the device. [...]"
26250623d748SDimitry Andric   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
26260623d748SDimitry Andric   // __device__, declares a variable that: [...]
26270623d748SDimitry Andric   // Is accessible from all the threads within the grid and from the host
26280623d748SDimitry Andric   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
26290623d748SDimitry Andric   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
2630e7145dcbSDimitry Andric   if (GV && LangOpts.CUDA) {
2631e7145dcbSDimitry Andric     if (LangOpts.CUDAIsDevice) {
2632e7145dcbSDimitry Andric       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
26330623d748SDimitry Andric         GV->setExternallyInitialized(true);
2634e7145dcbSDimitry Andric     } else {
2635e7145dcbSDimitry Andric       // Host-side shadows of external declarations of device-side
2636e7145dcbSDimitry Andric       // global variables become internal definitions. These have to
2637e7145dcbSDimitry Andric       // be internal in order to prevent name conflicts with global
2638e7145dcbSDimitry Andric       // host variables with the same name in a different TUs.
2639e7145dcbSDimitry Andric       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
2640e7145dcbSDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
2641e7145dcbSDimitry Andric 
2642e7145dcbSDimitry Andric         // Shadow variables and their properties must be registered
2643e7145dcbSDimitry Andric         // with CUDA runtime.
2644e7145dcbSDimitry Andric         unsigned Flags = 0;
2645e7145dcbSDimitry Andric         if (!D->hasDefinition())
2646e7145dcbSDimitry Andric           Flags |= CGCUDARuntime::ExternDeviceVar;
2647e7145dcbSDimitry Andric         if (D->hasAttr<CUDAConstantAttr>())
2648e7145dcbSDimitry Andric           Flags |= CGCUDARuntime::ConstantDeviceVar;
2649e7145dcbSDimitry Andric         getCUDARuntime().registerDeviceVar(*GV, Flags);
2650e7145dcbSDimitry Andric       } else if (D->hasAttr<CUDASharedAttr>())
2651e7145dcbSDimitry Andric         // __shared__ variables are odd. Shadows do get created, but
2652e7145dcbSDimitry Andric         // they are not registered with the CUDA runtime, so they
2653e7145dcbSDimitry Andric         // can't really be used to access their device-side
2654e7145dcbSDimitry Andric         // counterparts. It's not clear yet whether it's nvcc's bug or
2655e7145dcbSDimitry Andric         // a feature, but we've got to do the same for compatibility.
2656e7145dcbSDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
2657e7145dcbSDimitry Andric     }
26580623d748SDimitry Andric   }
2659f22ef01cSRoman Divacky   GV->setInitializer(Init);
2660f22ef01cSRoman Divacky 
2661f22ef01cSRoman Divacky   // If it is safe to mark the global 'constant', do so now.
2662dff0c46cSDimitry Andric   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2663dff0c46cSDimitry Andric                   isTypeConstant(D->getType(), true));
2664f22ef01cSRoman Divacky 
266539d628a0SDimitry Andric   // If it is in a read-only section, mark it 'constant'.
266639d628a0SDimitry Andric   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
266739d628a0SDimitry Andric     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
266839d628a0SDimitry Andric     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
266939d628a0SDimitry Andric       GV->setConstant(true);
267039d628a0SDimitry Andric   }
267139d628a0SDimitry Andric 
2672f22ef01cSRoman Divacky   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2673f22ef01cSRoman Divacky 
2674f785676fSDimitry Andric 
26750623d748SDimitry Andric   // On Darwin, if the normal linkage of a C++ thread_local variable is
26760623d748SDimitry Andric   // LinkOnce or Weak, we keep the normal linkage to prevent multiple
26770623d748SDimitry Andric   // copies within a linkage unit; otherwise, the backing variable has
26780623d748SDimitry Andric   // internal linkage and all accesses should just be calls to the
267959d1ed5bSDimitry Andric   // Itanium-specified entry point, which has the normal linkage of the
26800623d748SDimitry Andric   // variable. This is to preserve the ability to change the implementation
26810623d748SDimitry Andric   // behind the scenes.
268239d628a0SDimitry Andric   if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
26830623d748SDimitry Andric       Context.getTargetInfo().getTriple().isOSDarwin() &&
26840623d748SDimitry Andric       !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
26850623d748SDimitry Andric       !llvm::GlobalVariable::isWeakLinkage(Linkage))
268659d1ed5bSDimitry Andric     Linkage = llvm::GlobalValue::InternalLinkage;
268759d1ed5bSDimitry Andric 
268859d1ed5bSDimitry Andric   GV->setLinkage(Linkage);
268959d1ed5bSDimitry Andric   if (D->hasAttr<DLLImportAttr>())
269059d1ed5bSDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
269159d1ed5bSDimitry Andric   else if (D->hasAttr<DLLExportAttr>())
269259d1ed5bSDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
269339d628a0SDimitry Andric   else
269439d628a0SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2695f785676fSDimitry Andric 
269644290647SDimitry Andric   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
2697f22ef01cSRoman Divacky     // common vars aren't constant even if declared const.
2698f22ef01cSRoman Divacky     GV->setConstant(false);
269944290647SDimitry Andric     // Tentative definition of global variables may be initialized with
270044290647SDimitry Andric     // non-zero null pointers. In this case they should have weak linkage
270144290647SDimitry Andric     // since common linkage must have zero initializer and must not have
270244290647SDimitry Andric     // explicit section therefore cannot have non-zero initial value.
270344290647SDimitry Andric     if (!GV->getInitializer()->isNullValue())
270444290647SDimitry Andric       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
270544290647SDimitry Andric   }
2706f22ef01cSRoman Divacky 
270759d1ed5bSDimitry Andric   setNonAliasAttributes(D, GV);
2708f22ef01cSRoman Divacky 
270939d628a0SDimitry Andric   if (D->getTLSKind() && !GV->isThreadLocal()) {
271039d628a0SDimitry Andric     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
27110623d748SDimitry Andric       CXXThreadLocals.push_back(D);
271239d628a0SDimitry Andric     setTLSMode(GV, *D);
271339d628a0SDimitry Andric   }
271439d628a0SDimitry Andric 
271533956c43SDimitry Andric   maybeSetTrivialComdat(*D, *GV);
271633956c43SDimitry Andric 
27172754fe60SDimitry Andric   // Emit the initializer function if necessary.
2718dff0c46cSDimitry Andric   if (NeedsGlobalCtor || NeedsGlobalDtor)
2719dff0c46cSDimitry Andric     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
27202754fe60SDimitry Andric 
272139d628a0SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
27223861d79fSDimitry Andric 
2723f22ef01cSRoman Divacky   // Emit global variable debug information.
27246122f3e6SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
2725e7145dcbSDimitry Andric     if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
2726f22ef01cSRoman Divacky       DI->EmitGlobalVariable(GV, D);
2727f22ef01cSRoman Divacky }
2728f22ef01cSRoman Divacky 
272939d628a0SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context,
273033956c43SDimitry Andric                                       CodeGenModule &CGM, const VarDecl *D,
273133956c43SDimitry Andric                                       bool NoCommon) {
273259d1ed5bSDimitry Andric   // Don't give variables common linkage if -fno-common was specified unless it
273359d1ed5bSDimitry Andric   // was overridden by a NoCommon attribute.
273459d1ed5bSDimitry Andric   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
273559d1ed5bSDimitry Andric     return true;
273659d1ed5bSDimitry Andric 
273759d1ed5bSDimitry Andric   // C11 6.9.2/2:
273859d1ed5bSDimitry Andric   //   A declaration of an identifier for an object that has file scope without
273959d1ed5bSDimitry Andric   //   an initializer, and without a storage-class specifier or with the
274059d1ed5bSDimitry Andric   //   storage-class specifier static, constitutes a tentative definition.
274159d1ed5bSDimitry Andric   if (D->getInit() || D->hasExternalStorage())
274259d1ed5bSDimitry Andric     return true;
274359d1ed5bSDimitry Andric 
274459d1ed5bSDimitry Andric   // A variable cannot be both common and exist in a section.
274559d1ed5bSDimitry Andric   if (D->hasAttr<SectionAttr>())
274659d1ed5bSDimitry Andric     return true;
274759d1ed5bSDimitry Andric 
274859d1ed5bSDimitry Andric   // Thread local vars aren't considered common linkage.
274959d1ed5bSDimitry Andric   if (D->getTLSKind())
275059d1ed5bSDimitry Andric     return true;
275159d1ed5bSDimitry Andric 
275259d1ed5bSDimitry Andric   // Tentative definitions marked with WeakImportAttr are true definitions.
275359d1ed5bSDimitry Andric   if (D->hasAttr<WeakImportAttr>())
275459d1ed5bSDimitry Andric     return true;
275559d1ed5bSDimitry Andric 
275633956c43SDimitry Andric   // A variable cannot be both common and exist in a comdat.
275733956c43SDimitry Andric   if (shouldBeInCOMDAT(CGM, *D))
275833956c43SDimitry Andric     return true;
275933956c43SDimitry Andric 
2760e7145dcbSDimitry Andric   // Declarations with a required alignment do not have common linkage in MSVC
276139d628a0SDimitry Andric   // mode.
27620623d748SDimitry Andric   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
276333956c43SDimitry Andric     if (D->hasAttr<AlignedAttr>())
276439d628a0SDimitry Andric       return true;
276533956c43SDimitry Andric     QualType VarType = D->getType();
276633956c43SDimitry Andric     if (Context.isAlignmentRequired(VarType))
276733956c43SDimitry Andric       return true;
276833956c43SDimitry Andric 
276933956c43SDimitry Andric     if (const auto *RT = VarType->getAs<RecordType>()) {
277033956c43SDimitry Andric       const RecordDecl *RD = RT->getDecl();
277133956c43SDimitry Andric       for (const FieldDecl *FD : RD->fields()) {
277233956c43SDimitry Andric         if (FD->isBitField())
277333956c43SDimitry Andric           continue;
277433956c43SDimitry Andric         if (FD->hasAttr<AlignedAttr>())
277533956c43SDimitry Andric           return true;
277633956c43SDimitry Andric         if (Context.isAlignmentRequired(FD->getType()))
277733956c43SDimitry Andric           return true;
277833956c43SDimitry Andric       }
277933956c43SDimitry Andric     }
278033956c43SDimitry Andric   }
278139d628a0SDimitry Andric 
278259d1ed5bSDimitry Andric   return false;
278359d1ed5bSDimitry Andric }
278459d1ed5bSDimitry Andric 
278559d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
278659d1ed5bSDimitry Andric     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
27872754fe60SDimitry Andric   if (Linkage == GVA_Internal)
27882754fe60SDimitry Andric     return llvm::Function::InternalLinkage;
278959d1ed5bSDimitry Andric 
279059d1ed5bSDimitry Andric   if (D->hasAttr<WeakAttr>()) {
279159d1ed5bSDimitry Andric     if (IsConstantVariable)
279259d1ed5bSDimitry Andric       return llvm::GlobalVariable::WeakODRLinkage;
279359d1ed5bSDimitry Andric     else
279459d1ed5bSDimitry Andric       return llvm::GlobalVariable::WeakAnyLinkage;
279559d1ed5bSDimitry Andric   }
279659d1ed5bSDimitry Andric 
279759d1ed5bSDimitry Andric   // We are guaranteed to have a strong definition somewhere else,
279859d1ed5bSDimitry Andric   // so we can use available_externally linkage.
279959d1ed5bSDimitry Andric   if (Linkage == GVA_AvailableExternally)
280059d1ed5bSDimitry Andric     return llvm::Function::AvailableExternallyLinkage;
280159d1ed5bSDimitry Andric 
280259d1ed5bSDimitry Andric   // Note that Apple's kernel linker doesn't support symbol
280359d1ed5bSDimitry Andric   // coalescing, so we need to avoid linkonce and weak linkages there.
280459d1ed5bSDimitry Andric   // Normally, this means we just map to internal, but for explicit
280559d1ed5bSDimitry Andric   // instantiations we'll map to external.
280659d1ed5bSDimitry Andric 
280759d1ed5bSDimitry Andric   // In C++, the compiler has to emit a definition in every translation unit
280859d1ed5bSDimitry Andric   // that references the function.  We should use linkonce_odr because
280959d1ed5bSDimitry Andric   // a) if all references in this translation unit are optimized away, we
281059d1ed5bSDimitry Andric   // don't need to codegen it.  b) if the function persists, it needs to be
281159d1ed5bSDimitry Andric   // merged with other definitions. c) C++ has the ODR, so we know the
281259d1ed5bSDimitry Andric   // definition is dependable.
281359d1ed5bSDimitry Andric   if (Linkage == GVA_DiscardableODR)
281459d1ed5bSDimitry Andric     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
281559d1ed5bSDimitry Andric                                             : llvm::Function::InternalLinkage;
281659d1ed5bSDimitry Andric 
281759d1ed5bSDimitry Andric   // An explicit instantiation of a template has weak linkage, since
281859d1ed5bSDimitry Andric   // explicit instantiations can occur in multiple translation units
281959d1ed5bSDimitry Andric   // and must all be equivalent. However, we are not allowed to
282059d1ed5bSDimitry Andric   // throw away these explicit instantiations.
2821e7145dcbSDimitry Andric   //
2822e7145dcbSDimitry Andric   // We don't currently support CUDA device code spread out across multiple TUs,
2823e7145dcbSDimitry Andric   // so say that CUDA templates are either external (for kernels) or internal.
2824e7145dcbSDimitry Andric   // This lets llvm perform aggressive inter-procedural optimizations.
2825e7145dcbSDimitry Andric   if (Linkage == GVA_StrongODR) {
2826e7145dcbSDimitry Andric     if (Context.getLangOpts().AppleKext)
2827e7145dcbSDimitry Andric       return llvm::Function::ExternalLinkage;
2828e7145dcbSDimitry Andric     if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
2829e7145dcbSDimitry Andric       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
2830e7145dcbSDimitry Andric                                           : llvm::Function::InternalLinkage;
2831e7145dcbSDimitry Andric     return llvm::Function::WeakODRLinkage;
2832e7145dcbSDimitry Andric   }
283359d1ed5bSDimitry Andric 
283459d1ed5bSDimitry Andric   // C++ doesn't have tentative definitions and thus cannot have common
283559d1ed5bSDimitry Andric   // linkage.
283659d1ed5bSDimitry Andric   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
283733956c43SDimitry Andric       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
283839d628a0SDimitry Andric                                  CodeGenOpts.NoCommon))
283959d1ed5bSDimitry Andric     return llvm::GlobalVariable::CommonLinkage;
284059d1ed5bSDimitry Andric 
2841f785676fSDimitry Andric   // selectany symbols are externally visible, so use weak instead of
2842f785676fSDimitry Andric   // linkonce.  MSVC optimizes away references to const selectany globals, so
2843f785676fSDimitry Andric   // all definitions should be the same and ODR linkage should be used.
2844f785676fSDimitry Andric   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
284559d1ed5bSDimitry Andric   if (D->hasAttr<SelectAnyAttr>())
2846f785676fSDimitry Andric     return llvm::GlobalVariable::WeakODRLinkage;
284759d1ed5bSDimitry Andric 
284859d1ed5bSDimitry Andric   // Otherwise, we have strong external linkage.
284959d1ed5bSDimitry Andric   assert(Linkage == GVA_StrongExternal);
28502754fe60SDimitry Andric   return llvm::GlobalVariable::ExternalLinkage;
28512754fe60SDimitry Andric }
28522754fe60SDimitry Andric 
285359d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
285459d1ed5bSDimitry Andric     const VarDecl *VD, bool IsConstant) {
285559d1ed5bSDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
285659d1ed5bSDimitry Andric   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
285759d1ed5bSDimitry Andric }
285859d1ed5bSDimitry Andric 
2859139f7f9bSDimitry Andric /// Replace the uses of a function that was declared with a non-proto type.
2860139f7f9bSDimitry Andric /// We want to silently drop extra arguments from call sites
2861139f7f9bSDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2862139f7f9bSDimitry Andric                                           llvm::Function *newFn) {
2863139f7f9bSDimitry Andric   // Fast path.
2864139f7f9bSDimitry Andric   if (old->use_empty()) return;
2865139f7f9bSDimitry Andric 
2866139f7f9bSDimitry Andric   llvm::Type *newRetTy = newFn->getReturnType();
2867139f7f9bSDimitry Andric   SmallVector<llvm::Value*, 4> newArgs;
28680623d748SDimitry Andric   SmallVector<llvm::OperandBundleDef, 1> newBundles;
2869139f7f9bSDimitry Andric 
2870139f7f9bSDimitry Andric   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2871139f7f9bSDimitry Andric          ui != ue; ) {
2872139f7f9bSDimitry Andric     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
287359d1ed5bSDimitry Andric     llvm::User *user = use->getUser();
2874139f7f9bSDimitry Andric 
2875139f7f9bSDimitry Andric     // Recognize and replace uses of bitcasts.  Most calls to
2876139f7f9bSDimitry Andric     // unprototyped functions will use bitcasts.
287759d1ed5bSDimitry Andric     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
2878139f7f9bSDimitry Andric       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2879139f7f9bSDimitry Andric         replaceUsesOfNonProtoConstant(bitcast, newFn);
2880139f7f9bSDimitry Andric       continue;
2881139f7f9bSDimitry Andric     }
2882139f7f9bSDimitry Andric 
2883139f7f9bSDimitry Andric     // Recognize calls to the function.
2884139f7f9bSDimitry Andric     llvm::CallSite callSite(user);
2885139f7f9bSDimitry Andric     if (!callSite) continue;
288659d1ed5bSDimitry Andric     if (!callSite.isCallee(&*use)) continue;
2887139f7f9bSDimitry Andric 
2888139f7f9bSDimitry Andric     // If the return types don't match exactly, then we can't
2889139f7f9bSDimitry Andric     // transform this call unless it's dead.
2890139f7f9bSDimitry Andric     if (callSite->getType() != newRetTy && !callSite->use_empty())
2891139f7f9bSDimitry Andric       continue;
2892139f7f9bSDimitry Andric 
2893139f7f9bSDimitry Andric     // Get the call site's attribute list.
2894139f7f9bSDimitry Andric     SmallVector<llvm::AttributeSet, 8> newAttrs;
2895139f7f9bSDimitry Andric     llvm::AttributeSet oldAttrs = callSite.getAttributes();
2896139f7f9bSDimitry Andric 
2897139f7f9bSDimitry Andric     // Collect any return attributes from the call.
2898139f7f9bSDimitry Andric     if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
2899139f7f9bSDimitry Andric       newAttrs.push_back(
2900139f7f9bSDimitry Andric         llvm::AttributeSet::get(newFn->getContext(),
2901139f7f9bSDimitry Andric                                 oldAttrs.getRetAttributes()));
2902139f7f9bSDimitry Andric 
2903139f7f9bSDimitry Andric     // If the function was passed too few arguments, don't transform.
2904139f7f9bSDimitry Andric     unsigned newNumArgs = newFn->arg_size();
2905139f7f9bSDimitry Andric     if (callSite.arg_size() < newNumArgs) continue;
2906139f7f9bSDimitry Andric 
2907139f7f9bSDimitry Andric     // If extra arguments were passed, we silently drop them.
2908139f7f9bSDimitry Andric     // If any of the types mismatch, we don't transform.
2909139f7f9bSDimitry Andric     unsigned argNo = 0;
2910139f7f9bSDimitry Andric     bool dontTransform = false;
2911139f7f9bSDimitry Andric     for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
2912139f7f9bSDimitry Andric            ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
2913139f7f9bSDimitry Andric       if (callSite.getArgument(argNo)->getType() != ai->getType()) {
2914139f7f9bSDimitry Andric         dontTransform = true;
2915139f7f9bSDimitry Andric         break;
2916139f7f9bSDimitry Andric       }
2917139f7f9bSDimitry Andric 
2918139f7f9bSDimitry Andric       // Add any parameter attributes.
2919139f7f9bSDimitry Andric       if (oldAttrs.hasAttributes(argNo + 1))
2920139f7f9bSDimitry Andric         newAttrs.
2921139f7f9bSDimitry Andric           push_back(llvm::
2922139f7f9bSDimitry Andric                     AttributeSet::get(newFn->getContext(),
2923139f7f9bSDimitry Andric                                       oldAttrs.getParamAttributes(argNo + 1)));
2924139f7f9bSDimitry Andric     }
2925139f7f9bSDimitry Andric     if (dontTransform)
2926139f7f9bSDimitry Andric       continue;
2927139f7f9bSDimitry Andric 
2928139f7f9bSDimitry Andric     if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
2929139f7f9bSDimitry Andric       newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
2930139f7f9bSDimitry Andric                                                  oldAttrs.getFnAttributes()));
2931139f7f9bSDimitry Andric 
2932139f7f9bSDimitry Andric     // Okay, we can transform this.  Create the new call instruction and copy
2933139f7f9bSDimitry Andric     // over the required information.
2934139f7f9bSDimitry Andric     newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2935139f7f9bSDimitry Andric 
29360623d748SDimitry Andric     // Copy over any operand bundles.
29370623d748SDimitry Andric     callSite.getOperandBundlesAsDefs(newBundles);
29380623d748SDimitry Andric 
2939139f7f9bSDimitry Andric     llvm::CallSite newCall;
2940139f7f9bSDimitry Andric     if (callSite.isCall()) {
29410623d748SDimitry Andric       newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
2942139f7f9bSDimitry Andric                                        callSite.getInstruction());
2943139f7f9bSDimitry Andric     } else {
294459d1ed5bSDimitry Andric       auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
2945139f7f9bSDimitry Andric       newCall = llvm::InvokeInst::Create(newFn,
2946139f7f9bSDimitry Andric                                          oldInvoke->getNormalDest(),
2947139f7f9bSDimitry Andric                                          oldInvoke->getUnwindDest(),
29480623d748SDimitry Andric                                          newArgs, newBundles, "",
2949139f7f9bSDimitry Andric                                          callSite.getInstruction());
2950139f7f9bSDimitry Andric     }
2951139f7f9bSDimitry Andric     newArgs.clear(); // for the next iteration
2952139f7f9bSDimitry Andric 
2953139f7f9bSDimitry Andric     if (!newCall->getType()->isVoidTy())
2954139f7f9bSDimitry Andric       newCall->takeName(callSite.getInstruction());
2955139f7f9bSDimitry Andric     newCall.setAttributes(
2956139f7f9bSDimitry Andric                      llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2957139f7f9bSDimitry Andric     newCall.setCallingConv(callSite.getCallingConv());
2958139f7f9bSDimitry Andric 
2959139f7f9bSDimitry Andric     // Finally, remove the old call, replacing any uses with the new one.
2960139f7f9bSDimitry Andric     if (!callSite->use_empty())
2961139f7f9bSDimitry Andric       callSite->replaceAllUsesWith(newCall.getInstruction());
2962139f7f9bSDimitry Andric 
2963139f7f9bSDimitry Andric     // Copy debug location attached to CI.
296433956c43SDimitry Andric     if (callSite->getDebugLoc())
2965139f7f9bSDimitry Andric       newCall->setDebugLoc(callSite->getDebugLoc());
29660623d748SDimitry Andric 
2967139f7f9bSDimitry Andric     callSite->eraseFromParent();
2968139f7f9bSDimitry Andric   }
2969139f7f9bSDimitry Andric }
2970139f7f9bSDimitry Andric 
2971f22ef01cSRoman Divacky /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2972f22ef01cSRoman Divacky /// implement a function with no prototype, e.g. "int foo() {}".  If there are
2973f22ef01cSRoman Divacky /// existing call uses of the old function in the module, this adjusts them to
2974f22ef01cSRoman Divacky /// call the new function directly.
2975f22ef01cSRoman Divacky ///
2976f22ef01cSRoman Divacky /// This is not just a cleanup: the always_inline pass requires direct calls to
2977f22ef01cSRoman Divacky /// functions to be able to inline them.  If there is a bitcast in the way, it
2978f22ef01cSRoman Divacky /// won't inline them.  Instcombine normally deletes these calls, but it isn't
2979f22ef01cSRoman Divacky /// run at -O0.
2980f22ef01cSRoman Divacky static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2981f22ef01cSRoman Divacky                                                       llvm::Function *NewFn) {
2982f22ef01cSRoman Divacky   // If we're redefining a global as a function, don't transform it.
2983139f7f9bSDimitry Andric   if (!isa<llvm::Function>(Old)) return;
2984f22ef01cSRoman Divacky 
2985139f7f9bSDimitry Andric   replaceUsesOfNonProtoConstant(Old, NewFn);
2986f22ef01cSRoman Divacky }
2987f22ef01cSRoman Divacky 
2988dff0c46cSDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2989e7145dcbSDimitry Andric   auto DK = VD->isThisDeclarationADefinition();
2990e7145dcbSDimitry Andric   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
2991e7145dcbSDimitry Andric     return;
2992e7145dcbSDimitry Andric 
2993dff0c46cSDimitry Andric   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2994dff0c46cSDimitry Andric   // If we have a definition, this might be a deferred decl. If the
2995dff0c46cSDimitry Andric   // instantiation is explicit, make sure we emit it at the end.
2996dff0c46cSDimitry Andric   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2997dff0c46cSDimitry Andric     GetAddrOfGlobalVar(VD);
2998139f7f9bSDimitry Andric 
2999139f7f9bSDimitry Andric   EmitTopLevelDecl(VD);
3000dff0c46cSDimitry Andric }
3001f22ef01cSRoman Divacky 
300259d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
300359d1ed5bSDimitry Andric                                                  llvm::GlobalValue *GV) {
300459d1ed5bSDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
30053b0f4066SDimitry Andric 
30063b0f4066SDimitry Andric   // Compute the function info and LLVM type.
3007dff0c46cSDimitry Andric   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3008dff0c46cSDimitry Andric   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
30093b0f4066SDimitry Andric 
3010f22ef01cSRoman Divacky   // Get or create the prototype for the function.
30110623d748SDimitry Andric   if (!GV || (GV->getType()->getElementType() != Ty))
30120623d748SDimitry Andric     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
30130623d748SDimitry Andric                                                    /*DontDefer=*/true,
301444290647SDimitry Andric                                                    ForDefinition));
3015f22ef01cSRoman Divacky 
30160623d748SDimitry Andric   // Already emitted.
30170623d748SDimitry Andric   if (!GV->isDeclaration())
3018f785676fSDimitry Andric     return;
3019f22ef01cSRoman Divacky 
30202754fe60SDimitry Andric   // We need to set linkage and visibility on the function before
30212754fe60SDimitry Andric   // generating code for it because various parts of IR generation
30222754fe60SDimitry Andric   // want to propagate this information down (e.g. to local static
30232754fe60SDimitry Andric   // declarations).
302459d1ed5bSDimitry Andric   auto *Fn = cast<llvm::Function>(GV);
3025f785676fSDimitry Andric   setFunctionLinkage(GD, Fn);
302697bc6c73SDimitry Andric   setFunctionDLLStorageClass(GD, Fn);
3027f22ef01cSRoman Divacky 
302859d1ed5bSDimitry Andric   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
30292754fe60SDimitry Andric   setGlobalVisibility(Fn, D);
30302754fe60SDimitry Andric 
3031284c1978SDimitry Andric   MaybeHandleStaticInExternC(D, Fn);
3032284c1978SDimitry Andric 
303333956c43SDimitry Andric   maybeSetTrivialComdat(*D, *Fn);
303433956c43SDimitry Andric 
30353b0f4066SDimitry Andric   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
3036f22ef01cSRoman Divacky 
303759d1ed5bSDimitry Andric   setFunctionDefinitionAttributes(D, Fn);
3038f22ef01cSRoman Divacky   SetLLVMFunctionAttributesForDefinition(D, Fn);
3039f22ef01cSRoman Divacky 
3040f22ef01cSRoman Divacky   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
3041f22ef01cSRoman Divacky     AddGlobalCtor(Fn, CA->getPriority());
3042f22ef01cSRoman Divacky   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
3043f22ef01cSRoman Divacky     AddGlobalDtor(Fn, DA->getPriority());
30446122f3e6SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
30456122f3e6SDimitry Andric     AddGlobalAnnotations(D, Fn);
3046f22ef01cSRoman Divacky }
3047f22ef01cSRoman Divacky 
3048f22ef01cSRoman Divacky void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
304959d1ed5bSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
3050f22ef01cSRoman Divacky   const AliasAttr *AA = D->getAttr<AliasAttr>();
3051f22ef01cSRoman Divacky   assert(AA && "Not an alias?");
3052f22ef01cSRoman Divacky 
30536122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
3054f22ef01cSRoman Divacky 
30559a4b3118SDimitry Andric   if (AA->getAliasee() == MangledName) {
3056e7145dcbSDimitry Andric     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
30579a4b3118SDimitry Andric     return;
30589a4b3118SDimitry Andric   }
30599a4b3118SDimitry Andric 
3060f22ef01cSRoman Divacky   // If there is a definition in the module, then it wins over the alias.
3061f22ef01cSRoman Divacky   // This is dubious, but allow it to be safe.  Just ignore the alias.
3062f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3063f22ef01cSRoman Divacky   if (Entry && !Entry->isDeclaration())
3064f22ef01cSRoman Divacky     return;
3065f22ef01cSRoman Divacky 
3066f785676fSDimitry Andric   Aliases.push_back(GD);
3067f785676fSDimitry Andric 
30686122f3e6SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3069f22ef01cSRoman Divacky 
3070f22ef01cSRoman Divacky   // Create a reference to the named value.  This ensures that it is emitted
3071f22ef01cSRoman Divacky   // if a deferred decl.
3072f22ef01cSRoman Divacky   llvm::Constant *Aliasee;
3073f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(DeclTy))
30743861d79fSDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
30752754fe60SDimitry Andric                                       /*ForVTable=*/false);
3076f22ef01cSRoman Divacky   else
3077f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
307859d1ed5bSDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
307939d628a0SDimitry Andric                                     /*D=*/nullptr);
3080f22ef01cSRoman Divacky 
3081f22ef01cSRoman Divacky   // Create the new alias itself, but don't set a name yet.
308259d1ed5bSDimitry Andric   auto *GA = llvm::GlobalAlias::create(
30830623d748SDimitry Andric       DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
3084f22ef01cSRoman Divacky 
3085f22ef01cSRoman Divacky   if (Entry) {
308659d1ed5bSDimitry Andric     if (GA->getAliasee() == Entry) {
3087e7145dcbSDimitry Andric       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
308859d1ed5bSDimitry Andric       return;
308959d1ed5bSDimitry Andric     }
309059d1ed5bSDimitry Andric 
3091f22ef01cSRoman Divacky     assert(Entry->isDeclaration());
3092f22ef01cSRoman Divacky 
3093f22ef01cSRoman Divacky     // If there is a declaration in the module, then we had an extern followed
3094f22ef01cSRoman Divacky     // by the alias, as in:
3095f22ef01cSRoman Divacky     //   extern int test6();
3096f22ef01cSRoman Divacky     //   ...
3097f22ef01cSRoman Divacky     //   int test6() __attribute__((alias("test7")));
3098f22ef01cSRoman Divacky     //
3099f22ef01cSRoman Divacky     // Remove it and replace uses of it with the alias.
3100f22ef01cSRoman Divacky     GA->takeName(Entry);
3101f22ef01cSRoman Divacky 
3102f22ef01cSRoman Divacky     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
3103f22ef01cSRoman Divacky                                                           Entry->getType()));
3104f22ef01cSRoman Divacky     Entry->eraseFromParent();
3105f22ef01cSRoman Divacky   } else {
3106ffd1746dSEd Schouten     GA->setName(MangledName);
3107f22ef01cSRoman Divacky   }
3108f22ef01cSRoman Divacky 
3109f22ef01cSRoman Divacky   // Set attributes which are particular to an alias; this is a
3110f22ef01cSRoman Divacky   // specialization of the attributes which may be set on a global
3111f22ef01cSRoman Divacky   // variable/function.
311239d628a0SDimitry Andric   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
31133b0f4066SDimitry Andric       D->isWeakImported()) {
3114f22ef01cSRoman Divacky     GA->setLinkage(llvm::Function::WeakAnyLinkage);
3115f22ef01cSRoman Divacky   }
3116f22ef01cSRoman Divacky 
311739d628a0SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
311839d628a0SDimitry Andric     if (VD->getTLSKind())
311939d628a0SDimitry Andric       setTLSMode(GA, *VD);
312039d628a0SDimitry Andric 
312139d628a0SDimitry Andric   setAliasAttributes(D, GA);
3122f22ef01cSRoman Divacky }
3123f22ef01cSRoman Divacky 
3124e7145dcbSDimitry Andric void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
3125e7145dcbSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
3126e7145dcbSDimitry Andric   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
3127e7145dcbSDimitry Andric   assert(IFA && "Not an ifunc?");
3128e7145dcbSDimitry Andric 
3129e7145dcbSDimitry Andric   StringRef MangledName = getMangledName(GD);
3130e7145dcbSDimitry Andric 
3131e7145dcbSDimitry Andric   if (IFA->getResolver() == MangledName) {
3132e7145dcbSDimitry Andric     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3133e7145dcbSDimitry Andric     return;
3134e7145dcbSDimitry Andric   }
3135e7145dcbSDimitry Andric 
3136e7145dcbSDimitry Andric   // Report an error if some definition overrides ifunc.
3137e7145dcbSDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3138e7145dcbSDimitry Andric   if (Entry && !Entry->isDeclaration()) {
3139e7145dcbSDimitry Andric     GlobalDecl OtherGD;
3140e7145dcbSDimitry Andric     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3141e7145dcbSDimitry Andric         DiagnosedConflictingDefinitions.insert(GD).second) {
3142e7145dcbSDimitry Andric       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
3143e7145dcbSDimitry Andric       Diags.Report(OtherGD.getDecl()->getLocation(),
3144e7145dcbSDimitry Andric                    diag::note_previous_definition);
3145e7145dcbSDimitry Andric     }
3146e7145dcbSDimitry Andric     return;
3147e7145dcbSDimitry Andric   }
3148e7145dcbSDimitry Andric 
3149e7145dcbSDimitry Andric   Aliases.push_back(GD);
3150e7145dcbSDimitry Andric 
3151e7145dcbSDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3152e7145dcbSDimitry Andric   llvm::Constant *Resolver =
3153e7145dcbSDimitry Andric       GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3154e7145dcbSDimitry Andric                               /*ForVTable=*/false);
3155e7145dcbSDimitry Andric   llvm::GlobalIFunc *GIF =
3156e7145dcbSDimitry Andric       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
3157e7145dcbSDimitry Andric                                 "", Resolver, &getModule());
3158e7145dcbSDimitry Andric   if (Entry) {
3159e7145dcbSDimitry Andric     if (GIF->getResolver() == Entry) {
3160e7145dcbSDimitry Andric       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3161e7145dcbSDimitry Andric       return;
3162e7145dcbSDimitry Andric     }
3163e7145dcbSDimitry Andric     assert(Entry->isDeclaration());
3164e7145dcbSDimitry Andric 
3165e7145dcbSDimitry Andric     // If there is a declaration in the module, then we had an extern followed
3166e7145dcbSDimitry Andric     // by the ifunc, as in:
3167e7145dcbSDimitry Andric     //   extern int test();
3168e7145dcbSDimitry Andric     //   ...
3169e7145dcbSDimitry Andric     //   int test() __attribute__((ifunc("resolver")));
3170e7145dcbSDimitry Andric     //
3171e7145dcbSDimitry Andric     // Remove it and replace uses of it with the ifunc.
3172e7145dcbSDimitry Andric     GIF->takeName(Entry);
3173e7145dcbSDimitry Andric 
3174e7145dcbSDimitry Andric     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3175e7145dcbSDimitry Andric                                                           Entry->getType()));
3176e7145dcbSDimitry Andric     Entry->eraseFromParent();
3177e7145dcbSDimitry Andric   } else
3178e7145dcbSDimitry Andric     GIF->setName(MangledName);
3179e7145dcbSDimitry Andric 
3180e7145dcbSDimitry Andric   SetCommonAttributes(D, GIF);
3181e7145dcbSDimitry Andric }
3182e7145dcbSDimitry Andric 
318317a519f9SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
31846122f3e6SDimitry Andric                                             ArrayRef<llvm::Type*> Tys) {
318517a519f9SDimitry Andric   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
318617a519f9SDimitry Andric                                          Tys);
3187f22ef01cSRoman Divacky }
3188f22ef01cSRoman Divacky 
318933956c43SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> &
319033956c43SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
319133956c43SDimitry Andric                          const StringLiteral *Literal, bool TargetIsLSB,
319233956c43SDimitry Andric                          bool &IsUTF16, unsigned &StringLength) {
31936122f3e6SDimitry Andric   StringRef String = Literal->getString();
3194e580952dSDimitry Andric   unsigned NumBytes = String.size();
3195f22ef01cSRoman Divacky 
3196f22ef01cSRoman Divacky   // Check for simple case.
3197f22ef01cSRoman Divacky   if (!Literal->containsNonAsciiOrNull()) {
3198f22ef01cSRoman Divacky     StringLength = NumBytes;
319939d628a0SDimitry Andric     return *Map.insert(std::make_pair(String, nullptr)).first;
3200f22ef01cSRoman Divacky   }
3201f22ef01cSRoman Divacky 
3202dff0c46cSDimitry Andric   // Otherwise, convert the UTF8 literals into a string of shorts.
3203dff0c46cSDimitry Andric   IsUTF16 = true;
3204dff0c46cSDimitry Andric 
320544290647SDimitry Andric   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
320644290647SDimitry Andric   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
320744290647SDimitry Andric   llvm::UTF16 *ToPtr = &ToBuf[0];
3208f22ef01cSRoman Divacky 
320944290647SDimitry Andric   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
321044290647SDimitry Andric                                  ToPtr + NumBytes, llvm::strictConversion);
3211f22ef01cSRoman Divacky 
3212f22ef01cSRoman Divacky   // ConvertUTF8toUTF16 returns the length in ToPtr.
3213f22ef01cSRoman Divacky   StringLength = ToPtr - &ToBuf[0];
3214f22ef01cSRoman Divacky 
3215dff0c46cSDimitry Andric   // Add an explicit null.
3216dff0c46cSDimitry Andric   *ToPtr = 0;
321739d628a0SDimitry Andric   return *Map.insert(std::make_pair(
321839d628a0SDimitry Andric                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
321939d628a0SDimitry Andric                                    (StringLength + 1) * 2),
322039d628a0SDimitry Andric                          nullptr)).first;
3221f22ef01cSRoman Divacky }
3222f22ef01cSRoman Divacky 
32230623d748SDimitry Andric ConstantAddress
3224f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
3225f22ef01cSRoman Divacky   unsigned StringLength = 0;
3226f22ef01cSRoman Divacky   bool isUTF16 = false;
322733956c43SDimitry Andric   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3228f22ef01cSRoman Divacky       GetConstantCFStringEntry(CFConstantStringMap, Literal,
322933956c43SDimitry Andric                                getDataLayout().isLittleEndian(), isUTF16,
323033956c43SDimitry Andric                                StringLength);
3231f22ef01cSRoman Divacky 
323239d628a0SDimitry Andric   if (auto *C = Entry.second)
32330623d748SDimitry Andric     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
3234f22ef01cSRoman Divacky 
3235dff0c46cSDimitry Andric   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
3236f22ef01cSRoman Divacky   llvm::Constant *Zeros[] = { Zero, Zero };
3237f22ef01cSRoman Divacky 
3238f22ef01cSRoman Divacky   // If we don't already have it, get __CFConstantStringClassReference.
3239f22ef01cSRoman Divacky   if (!CFConstantStringClassRef) {
32406122f3e6SDimitry Andric     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
3241f22ef01cSRoman Divacky     Ty = llvm::ArrayType::get(Ty, 0);
3242e7145dcbSDimitry Andric     llvm::Constant *GV =
3243e7145dcbSDimitry Andric         CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
3244e7145dcbSDimitry Andric 
324544290647SDimitry Andric     if (getTriple().isOSBinFormatCOFF()) {
3246e7145dcbSDimitry Andric       IdentifierInfo &II = getContext().Idents.get(GV->getName());
3247e7145dcbSDimitry Andric       TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
3248e7145dcbSDimitry Andric       DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3249e7145dcbSDimitry Andric       llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
3250e7145dcbSDimitry Andric 
3251e7145dcbSDimitry Andric       const VarDecl *VD = nullptr;
3252e7145dcbSDimitry Andric       for (const auto &Result : DC->lookup(&II))
3253e7145dcbSDimitry Andric         if ((VD = dyn_cast<VarDecl>(Result)))
3254e7145dcbSDimitry Andric           break;
3255e7145dcbSDimitry Andric 
3256e7145dcbSDimitry Andric       if (!VD || !VD->hasAttr<DLLExportAttr>()) {
3257e7145dcbSDimitry Andric         CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3258e7145dcbSDimitry Andric         CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3259e7145dcbSDimitry Andric       } else {
3260e7145dcbSDimitry Andric         CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3261e7145dcbSDimitry Andric         CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3262e7145dcbSDimitry Andric       }
3263e7145dcbSDimitry Andric     }
3264e7145dcbSDimitry Andric 
3265f22ef01cSRoman Divacky     // Decay array -> ptr
326644290647SDimitry Andric     CFConstantStringClassRef =
326744290647SDimitry Andric         llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
3268e7145dcbSDimitry Andric   }
3269f22ef01cSRoman Divacky 
3270f22ef01cSRoman Divacky   QualType CFTy = getContext().getCFConstantStringType();
3271f22ef01cSRoman Divacky 
327259d1ed5bSDimitry Andric   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
3273f22ef01cSRoman Divacky 
327444290647SDimitry Andric   ConstantInitBuilder Builder(*this);
327544290647SDimitry Andric   auto Fields = Builder.beginStruct(STy);
3276f22ef01cSRoman Divacky 
3277f22ef01cSRoman Divacky   // Class pointer.
327844290647SDimitry Andric   Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
3279f22ef01cSRoman Divacky 
3280f22ef01cSRoman Divacky   // Flags.
328144290647SDimitry Andric   Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
3282f22ef01cSRoman Divacky 
3283f22ef01cSRoman Divacky   // String pointer.
328459d1ed5bSDimitry Andric   llvm::Constant *C = nullptr;
3285dff0c46cSDimitry Andric   if (isUTF16) {
32860623d748SDimitry Andric     auto Arr = llvm::makeArrayRef(
328739d628a0SDimitry Andric         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
328839d628a0SDimitry Andric         Entry.first().size() / 2);
3289dff0c46cSDimitry Andric     C = llvm::ConstantDataArray::get(VMContext, Arr);
3290dff0c46cSDimitry Andric   } else {
329139d628a0SDimitry Andric     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
3292dff0c46cSDimitry Andric   }
3293f22ef01cSRoman Divacky 
3294dff0c46cSDimitry Andric   // Note: -fwritable-strings doesn't make the backing store strings of
3295dff0c46cSDimitry Andric   // CFStrings writable. (See <rdar://problem/10657500>)
329659d1ed5bSDimitry Andric   auto *GV =
3297dff0c46cSDimitry Andric       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
329859d1ed5bSDimitry Andric                                llvm::GlobalValue::PrivateLinkage, C, ".str");
3299e7145dcbSDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3300284c1978SDimitry Andric   // Don't enforce the target's minimum global alignment, since the only use
3301284c1978SDimitry Andric   // of the string is via this class initializer.
3302e7145dcbSDimitry Andric   CharUnits Align = isUTF16
3303e7145dcbSDimitry Andric                         ? getContext().getTypeAlignInChars(getContext().ShortTy)
3304e7145dcbSDimitry Andric                         : getContext().getTypeAlignInChars(getContext().CharTy);
3305f22ef01cSRoman Divacky   GV->setAlignment(Align.getQuantity());
3306e7145dcbSDimitry Andric 
3307e7145dcbSDimitry Andric   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
3308e7145dcbSDimitry Andric   // Without it LLVM can merge the string with a non unnamed_addr one during
3309e7145dcbSDimitry Andric   // LTO.  Doing that changes the section it ends in, which surprises ld64.
331044290647SDimitry Andric   if (getTriple().isOSBinFormatMachO())
3311e7145dcbSDimitry Andric     GV->setSection(isUTF16 ? "__TEXT,__ustring"
3312e7145dcbSDimitry Andric                            : "__TEXT,__cstring,cstring_literals");
3313dff0c46cSDimitry Andric 
3314dff0c46cSDimitry Andric   // String.
331544290647SDimitry Andric   llvm::Constant *Str =
331633956c43SDimitry Andric       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3317f22ef01cSRoman Divacky 
3318dff0c46cSDimitry Andric   if (isUTF16)
3319dff0c46cSDimitry Andric     // Cast the UTF16 string to the correct type.
332044290647SDimitry Andric     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
332144290647SDimitry Andric   Fields.add(Str);
3322dff0c46cSDimitry Andric 
3323f22ef01cSRoman Divacky   // String length.
332444290647SDimitry Andric   auto Ty = getTypes().ConvertType(getContext().LongTy);
332544290647SDimitry Andric   Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
3326f22ef01cSRoman Divacky 
33270623d748SDimitry Andric   CharUnits Alignment = getPointerAlign();
33280623d748SDimitry Andric 
3329f22ef01cSRoman Divacky   // The struct.
333044290647SDimitry Andric   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
333144290647SDimitry Andric                                     /*isConstant=*/false,
333244290647SDimitry Andric                                     llvm::GlobalVariable::PrivateLinkage);
333344290647SDimitry Andric   switch (getTriple().getObjectFormat()) {
3334e7145dcbSDimitry Andric   case llvm::Triple::UnknownObjectFormat:
3335e7145dcbSDimitry Andric     llvm_unreachable("unknown file format");
3336e7145dcbSDimitry Andric   case llvm::Triple::COFF:
3337e7145dcbSDimitry Andric   case llvm::Triple::ELF:
3338e7145dcbSDimitry Andric     GV->setSection("cfstring");
3339e7145dcbSDimitry Andric     break;
3340e7145dcbSDimitry Andric   case llvm::Triple::MachO:
3341e7145dcbSDimitry Andric     GV->setSection("__DATA,__cfstring");
3342e7145dcbSDimitry Andric     break;
3343e7145dcbSDimitry Andric   }
334439d628a0SDimitry Andric   Entry.second = GV;
3345f22ef01cSRoman Divacky 
33460623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
3347f22ef01cSRoman Divacky }
3348f22ef01cSRoman Divacky 
33496122f3e6SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() {
33506122f3e6SDimitry Andric   if (ObjCFastEnumerationStateType.isNull()) {
335159d1ed5bSDimitry Andric     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
33526122f3e6SDimitry Andric     D->startDefinition();
33536122f3e6SDimitry Andric 
33546122f3e6SDimitry Andric     QualType FieldTypes[] = {
33556122f3e6SDimitry Andric       Context.UnsignedLongTy,
33566122f3e6SDimitry Andric       Context.getPointerType(Context.getObjCIdType()),
33576122f3e6SDimitry Andric       Context.getPointerType(Context.UnsignedLongTy),
33586122f3e6SDimitry Andric       Context.getConstantArrayType(Context.UnsignedLongTy,
33596122f3e6SDimitry Andric                            llvm::APInt(32, 5), ArrayType::Normal, 0)
33606122f3e6SDimitry Andric     };
33616122f3e6SDimitry Andric 
33626122f3e6SDimitry Andric     for (size_t i = 0; i < 4; ++i) {
33636122f3e6SDimitry Andric       FieldDecl *Field = FieldDecl::Create(Context,
33646122f3e6SDimitry Andric                                            D,
33656122f3e6SDimitry Andric                                            SourceLocation(),
336659d1ed5bSDimitry Andric                                            SourceLocation(), nullptr,
336759d1ed5bSDimitry Andric                                            FieldTypes[i], /*TInfo=*/nullptr,
336859d1ed5bSDimitry Andric                                            /*BitWidth=*/nullptr,
33696122f3e6SDimitry Andric                                            /*Mutable=*/false,
33707ae0e2c9SDimitry Andric                                            ICIS_NoInit);
33716122f3e6SDimitry Andric       Field->setAccess(AS_public);
33726122f3e6SDimitry Andric       D->addDecl(Field);
33736122f3e6SDimitry Andric     }
33746122f3e6SDimitry Andric 
33756122f3e6SDimitry Andric     D->completeDefinition();
33766122f3e6SDimitry Andric     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
33776122f3e6SDimitry Andric   }
33786122f3e6SDimitry Andric 
33796122f3e6SDimitry Andric   return ObjCFastEnumerationStateType;
33806122f3e6SDimitry Andric }
33816122f3e6SDimitry Andric 
3382dff0c46cSDimitry Andric llvm::Constant *
3383dff0c46cSDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
3384dff0c46cSDimitry Andric   assert(!E->getType()->isPointerType() && "Strings are always arrays");
3385f22ef01cSRoman Divacky 
3386dff0c46cSDimitry Andric   // Don't emit it as the address of the string, emit the string data itself
3387dff0c46cSDimitry Andric   // as an inline array.
3388dff0c46cSDimitry Andric   if (E->getCharByteWidth() == 1) {
3389dff0c46cSDimitry Andric     SmallString<64> Str(E->getString());
3390f22ef01cSRoman Divacky 
3391dff0c46cSDimitry Andric     // Resize the string to the right size, which is indicated by its type.
3392dff0c46cSDimitry Andric     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
3393dff0c46cSDimitry Andric     Str.resize(CAT->getSize().getZExtValue());
3394dff0c46cSDimitry Andric     return llvm::ConstantDataArray::getString(VMContext, Str, false);
33956122f3e6SDimitry Andric   }
3396f22ef01cSRoman Divacky 
339759d1ed5bSDimitry Andric   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
3398dff0c46cSDimitry Andric   llvm::Type *ElemTy = AType->getElementType();
3399dff0c46cSDimitry Andric   unsigned NumElements = AType->getNumElements();
3400f22ef01cSRoman Divacky 
3401dff0c46cSDimitry Andric   // Wide strings have either 2-byte or 4-byte elements.
3402dff0c46cSDimitry Andric   if (ElemTy->getPrimitiveSizeInBits() == 16) {
3403dff0c46cSDimitry Andric     SmallVector<uint16_t, 32> Elements;
3404dff0c46cSDimitry Andric     Elements.reserve(NumElements);
3405dff0c46cSDimitry Andric 
3406dff0c46cSDimitry Andric     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3407dff0c46cSDimitry Andric       Elements.push_back(E->getCodeUnit(i));
3408dff0c46cSDimitry Andric     Elements.resize(NumElements);
3409dff0c46cSDimitry Andric     return llvm::ConstantDataArray::get(VMContext, Elements);
3410dff0c46cSDimitry Andric   }
3411dff0c46cSDimitry Andric 
3412dff0c46cSDimitry Andric   assert(ElemTy->getPrimitiveSizeInBits() == 32);
3413dff0c46cSDimitry Andric   SmallVector<uint32_t, 32> Elements;
3414dff0c46cSDimitry Andric   Elements.reserve(NumElements);
3415dff0c46cSDimitry Andric 
3416dff0c46cSDimitry Andric   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3417dff0c46cSDimitry Andric     Elements.push_back(E->getCodeUnit(i));
3418dff0c46cSDimitry Andric   Elements.resize(NumElements);
3419dff0c46cSDimitry Andric   return llvm::ConstantDataArray::get(VMContext, Elements);
3420f22ef01cSRoman Divacky }
3421f22ef01cSRoman Divacky 
342259d1ed5bSDimitry Andric static llvm::GlobalVariable *
342359d1ed5bSDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
342459d1ed5bSDimitry Andric                       CodeGenModule &CGM, StringRef GlobalName,
34250623d748SDimitry Andric                       CharUnits Alignment) {
342659d1ed5bSDimitry Andric   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
342759d1ed5bSDimitry Andric   unsigned AddrSpace = 0;
342859d1ed5bSDimitry Andric   if (CGM.getLangOpts().OpenCL)
342959d1ed5bSDimitry Andric     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
3430dff0c46cSDimitry Andric 
343133956c43SDimitry Andric   llvm::Module &M = CGM.getModule();
343259d1ed5bSDimitry Andric   // Create a global variable for this string
343359d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
343433956c43SDimitry Andric       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
343533956c43SDimitry Andric       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
34360623d748SDimitry Andric   GV->setAlignment(Alignment.getQuantity());
3437e7145dcbSDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
343833956c43SDimitry Andric   if (GV->isWeakForLinker()) {
343933956c43SDimitry Andric     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
344033956c43SDimitry Andric     GV->setComdat(M.getOrInsertComdat(GV->getName()));
344133956c43SDimitry Andric   }
344233956c43SDimitry Andric 
344359d1ed5bSDimitry Andric   return GV;
3444f22ef01cSRoman Divacky }
3445dff0c46cSDimitry Andric 
344659d1ed5bSDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
344759d1ed5bSDimitry Andric /// constant array for the given string literal.
34480623d748SDimitry Andric ConstantAddress
344939d628a0SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
345039d628a0SDimitry Andric                                                   StringRef Name) {
34510623d748SDimitry Andric   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
3452dff0c46cSDimitry Andric 
345359d1ed5bSDimitry Andric   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
345459d1ed5bSDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
345559d1ed5bSDimitry Andric   if (!LangOpts.WritableStrings) {
345659d1ed5bSDimitry Andric     Entry = &ConstantStringMap[C];
345759d1ed5bSDimitry Andric     if (auto GV = *Entry) {
34580623d748SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
34590623d748SDimitry Andric         GV->setAlignment(Alignment.getQuantity());
34600623d748SDimitry Andric       return ConstantAddress(GV, Alignment);
346159d1ed5bSDimitry Andric     }
346259d1ed5bSDimitry Andric   }
346359d1ed5bSDimitry Andric 
346459d1ed5bSDimitry Andric   SmallString<256> MangledNameBuffer;
346559d1ed5bSDimitry Andric   StringRef GlobalVariableName;
346659d1ed5bSDimitry Andric   llvm::GlobalValue::LinkageTypes LT;
346759d1ed5bSDimitry Andric 
346859d1ed5bSDimitry Andric   // Mangle the string literal if the ABI allows for it.  However, we cannot
346959d1ed5bSDimitry Andric   // do this if  we are compiling with ASan or -fwritable-strings because they
347059d1ed5bSDimitry Andric   // rely on strings having normal linkage.
347139d628a0SDimitry Andric   if (!LangOpts.WritableStrings &&
347239d628a0SDimitry Andric       !LangOpts.Sanitize.has(SanitizerKind::Address) &&
347359d1ed5bSDimitry Andric       getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
347459d1ed5bSDimitry Andric     llvm::raw_svector_ostream Out(MangledNameBuffer);
347559d1ed5bSDimitry Andric     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
347659d1ed5bSDimitry Andric 
347759d1ed5bSDimitry Andric     LT = llvm::GlobalValue::LinkOnceODRLinkage;
347859d1ed5bSDimitry Andric     GlobalVariableName = MangledNameBuffer;
347959d1ed5bSDimitry Andric   } else {
348059d1ed5bSDimitry Andric     LT = llvm::GlobalValue::PrivateLinkage;
348139d628a0SDimitry Andric     GlobalVariableName = Name;
348259d1ed5bSDimitry Andric   }
348359d1ed5bSDimitry Andric 
348459d1ed5bSDimitry Andric   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
348559d1ed5bSDimitry Andric   if (Entry)
348659d1ed5bSDimitry Andric     *Entry = GV;
348759d1ed5bSDimitry Andric 
348839d628a0SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
348939d628a0SDimitry Andric                                   QualType());
34900623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
3491f22ef01cSRoman Divacky }
3492f22ef01cSRoman Divacky 
3493f22ef01cSRoman Divacky /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
3494f22ef01cSRoman Divacky /// array for the given ObjCEncodeExpr node.
34950623d748SDimitry Andric ConstantAddress
3496f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
3497f22ef01cSRoman Divacky   std::string Str;
3498f22ef01cSRoman Divacky   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
3499f22ef01cSRoman Divacky 
3500f22ef01cSRoman Divacky   return GetAddrOfConstantCString(Str);
3501f22ef01cSRoman Divacky }
3502f22ef01cSRoman Divacky 
350359d1ed5bSDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing
350459d1ed5bSDimitry Andric /// the literal and a terminating '\0' character.
350559d1ed5bSDimitry Andric /// The result has pointer to array type.
35060623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString(
35070623d748SDimitry Andric     const std::string &Str, const char *GlobalName) {
350859d1ed5bSDimitry Andric   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
35090623d748SDimitry Andric   CharUnits Alignment =
35100623d748SDimitry Andric     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
3511f22ef01cSRoman Divacky 
351259d1ed5bSDimitry Andric   llvm::Constant *C =
351359d1ed5bSDimitry Andric       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
351459d1ed5bSDimitry Andric 
351559d1ed5bSDimitry Andric   // Don't share any string literals if strings aren't constant.
351659d1ed5bSDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
351759d1ed5bSDimitry Andric   if (!LangOpts.WritableStrings) {
351859d1ed5bSDimitry Andric     Entry = &ConstantStringMap[C];
351959d1ed5bSDimitry Andric     if (auto GV = *Entry) {
35200623d748SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
35210623d748SDimitry Andric         GV->setAlignment(Alignment.getQuantity());
35220623d748SDimitry Andric       return ConstantAddress(GV, Alignment);
352359d1ed5bSDimitry Andric     }
352459d1ed5bSDimitry Andric   }
352559d1ed5bSDimitry Andric 
3526f22ef01cSRoman Divacky   // Get the default prefix if a name wasn't specified.
3527f22ef01cSRoman Divacky   if (!GlobalName)
3528f22ef01cSRoman Divacky     GlobalName = ".str";
3529f22ef01cSRoman Divacky   // Create a global variable for this.
353059d1ed5bSDimitry Andric   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
353159d1ed5bSDimitry Andric                                   GlobalName, Alignment);
353259d1ed5bSDimitry Andric   if (Entry)
353359d1ed5bSDimitry Andric     *Entry = GV;
35340623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
3535f22ef01cSRoman Divacky }
3536f22ef01cSRoman Divacky 
35370623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
3538f785676fSDimitry Andric     const MaterializeTemporaryExpr *E, const Expr *Init) {
3539f785676fSDimitry Andric   assert((E->getStorageDuration() == SD_Static ||
3540f785676fSDimitry Andric           E->getStorageDuration() == SD_Thread) && "not a global temporary");
354159d1ed5bSDimitry Andric   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
3542f785676fSDimitry Andric 
3543f785676fSDimitry Andric   // If we're not materializing a subobject of the temporary, keep the
3544f785676fSDimitry Andric   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
3545f785676fSDimitry Andric   QualType MaterializedType = Init->getType();
3546f785676fSDimitry Andric   if (Init == E->GetTemporaryExpr())
3547f785676fSDimitry Andric     MaterializedType = E->getType();
3548f785676fSDimitry Andric 
35490623d748SDimitry Andric   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
35500623d748SDimitry Andric 
35510623d748SDimitry Andric   if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
35520623d748SDimitry Andric     return ConstantAddress(Slot, Align);
3553f785676fSDimitry Andric 
3554f785676fSDimitry Andric   // FIXME: If an externally-visible declaration extends multiple temporaries,
3555f785676fSDimitry Andric   // we need to give each temporary the same name in every translation unit (and
3556f785676fSDimitry Andric   // we also need to make the temporaries externally-visible).
3557f785676fSDimitry Andric   SmallString<256> Name;
3558f785676fSDimitry Andric   llvm::raw_svector_ostream Out(Name);
355959d1ed5bSDimitry Andric   getCXXABI().getMangleContext().mangleReferenceTemporary(
356059d1ed5bSDimitry Andric       VD, E->getManglingNumber(), Out);
3561f785676fSDimitry Andric 
356259d1ed5bSDimitry Andric   APValue *Value = nullptr;
3563f785676fSDimitry Andric   if (E->getStorageDuration() == SD_Static) {
3564f785676fSDimitry Andric     // We might have a cached constant initializer for this temporary. Note
3565f785676fSDimitry Andric     // that this might have a different value from the value computed by
3566f785676fSDimitry Andric     // evaluating the initializer if the surrounding constant expression
3567f785676fSDimitry Andric     // modifies the temporary.
3568f785676fSDimitry Andric     Value = getContext().getMaterializedTemporaryValue(E, false);
3569f785676fSDimitry Andric     if (Value && Value->isUninit())
357059d1ed5bSDimitry Andric       Value = nullptr;
3571f785676fSDimitry Andric   }
3572f785676fSDimitry Andric 
3573f785676fSDimitry Andric   // Try evaluating it now, it might have a constant initializer.
3574f785676fSDimitry Andric   Expr::EvalResult EvalResult;
3575f785676fSDimitry Andric   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3576f785676fSDimitry Andric       !EvalResult.hasSideEffects())
3577f785676fSDimitry Andric     Value = &EvalResult.Val;
3578f785676fSDimitry Andric 
357959d1ed5bSDimitry Andric   llvm::Constant *InitialValue = nullptr;
3580f785676fSDimitry Andric   bool Constant = false;
3581f785676fSDimitry Andric   llvm::Type *Type;
3582f785676fSDimitry Andric   if (Value) {
3583f785676fSDimitry Andric     // The temporary has a constant initializer, use it.
358459d1ed5bSDimitry Andric     InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
3585f785676fSDimitry Andric     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3586f785676fSDimitry Andric     Type = InitialValue->getType();
3587f785676fSDimitry Andric   } else {
3588f785676fSDimitry Andric     // No initializer, the initialization will be provided when we
3589f785676fSDimitry Andric     // initialize the declaration which performed lifetime extension.
3590f785676fSDimitry Andric     Type = getTypes().ConvertTypeForMem(MaterializedType);
3591f785676fSDimitry Andric   }
3592f785676fSDimitry Andric 
3593f785676fSDimitry Andric   // Create a global variable for this lifetime-extended temporary.
359459d1ed5bSDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
359559d1ed5bSDimitry Andric       getLLVMLinkageVarDefinition(VD, Constant);
359633956c43SDimitry Andric   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
359733956c43SDimitry Andric     const VarDecl *InitVD;
359833956c43SDimitry Andric     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
359933956c43SDimitry Andric         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
360033956c43SDimitry Andric       // Temporaries defined inside a class get linkonce_odr linkage because the
360133956c43SDimitry Andric       // class can be defined in multipe translation units.
360233956c43SDimitry Andric       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
360333956c43SDimitry Andric     } else {
360433956c43SDimitry Andric       // There is no need for this temporary to have external linkage if the
360533956c43SDimitry Andric       // VarDecl has external linkage.
360633956c43SDimitry Andric       Linkage = llvm::GlobalVariable::InternalLinkage;
360733956c43SDimitry Andric     }
360833956c43SDimitry Andric   }
360959d1ed5bSDimitry Andric   unsigned AddrSpace = GetGlobalVarAddressSpace(
361059d1ed5bSDimitry Andric       VD, getContext().getTargetAddressSpace(MaterializedType));
361159d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
361259d1ed5bSDimitry Andric       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
361359d1ed5bSDimitry Andric       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
361459d1ed5bSDimitry Andric       AddrSpace);
361559d1ed5bSDimitry Andric   setGlobalVisibility(GV, VD);
36160623d748SDimitry Andric   GV->setAlignment(Align.getQuantity());
361733956c43SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker())
361833956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3619f785676fSDimitry Andric   if (VD->getTLSKind())
3620f785676fSDimitry Andric     setTLSMode(GV, *VD);
36210623d748SDimitry Andric   MaterializedGlobalTemporaryMap[E] = GV;
36220623d748SDimitry Andric   return ConstantAddress(GV, Align);
3623f785676fSDimitry Andric }
3624f785676fSDimitry Andric 
3625f22ef01cSRoman Divacky /// EmitObjCPropertyImplementations - Emit information for synthesized
3626f22ef01cSRoman Divacky /// properties for an implementation.
3627f22ef01cSRoman Divacky void CodeGenModule::EmitObjCPropertyImplementations(const
3628f22ef01cSRoman Divacky                                                     ObjCImplementationDecl *D) {
362959d1ed5bSDimitry Andric   for (const auto *PID : D->property_impls()) {
3630f22ef01cSRoman Divacky     // Dynamic is just for type-checking.
3631f22ef01cSRoman Divacky     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3632f22ef01cSRoman Divacky       ObjCPropertyDecl *PD = PID->getPropertyDecl();
3633f22ef01cSRoman Divacky 
3634f22ef01cSRoman Divacky       // Determine which methods need to be implemented, some may have
36353861d79fSDimitry Andric       // been overridden. Note that ::isPropertyAccessor is not the method
3636f22ef01cSRoman Divacky       // we want, that just indicates if the decl came from a
3637f22ef01cSRoman Divacky       // property. What we want to know is if the method is defined in
3638f22ef01cSRoman Divacky       // this implementation.
3639f22ef01cSRoman Divacky       if (!D->getInstanceMethod(PD->getGetterName()))
3640f22ef01cSRoman Divacky         CodeGenFunction(*this).GenerateObjCGetter(
3641f22ef01cSRoman Divacky                                  const_cast<ObjCImplementationDecl *>(D), PID);
3642f22ef01cSRoman Divacky       if (!PD->isReadOnly() &&
3643f22ef01cSRoman Divacky           !D->getInstanceMethod(PD->getSetterName()))
3644f22ef01cSRoman Divacky         CodeGenFunction(*this).GenerateObjCSetter(
3645f22ef01cSRoman Divacky                                  const_cast<ObjCImplementationDecl *>(D), PID);
3646f22ef01cSRoman Divacky     }
3647f22ef01cSRoman Divacky   }
3648f22ef01cSRoman Divacky }
3649f22ef01cSRoman Divacky 
36503b0f4066SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) {
36516122f3e6SDimitry Andric   const ObjCInterfaceDecl *iface = impl->getClassInterface();
36526122f3e6SDimitry Andric   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
36533b0f4066SDimitry Andric        ivar; ivar = ivar->getNextIvar())
36543b0f4066SDimitry Andric     if (ivar->getType().isDestructedType())
36553b0f4066SDimitry Andric       return true;
36563b0f4066SDimitry Andric 
36573b0f4066SDimitry Andric   return false;
36583b0f4066SDimitry Andric }
36593b0f4066SDimitry Andric 
366039d628a0SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM,
366139d628a0SDimitry Andric                                    ObjCImplementationDecl *D) {
366239d628a0SDimitry Andric   CodeGenFunction CGF(CGM);
366339d628a0SDimitry Andric   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
366439d628a0SDimitry Andric        E = D->init_end(); B != E; ++B) {
366539d628a0SDimitry Andric     CXXCtorInitializer *CtorInitExp = *B;
366639d628a0SDimitry Andric     Expr *Init = CtorInitExp->getInit();
366739d628a0SDimitry Andric     if (!CGF.isTrivialInitializer(Init))
366839d628a0SDimitry Andric       return false;
366939d628a0SDimitry Andric   }
367039d628a0SDimitry Andric   return true;
367139d628a0SDimitry Andric }
367239d628a0SDimitry Andric 
3673f22ef01cSRoman Divacky /// EmitObjCIvarInitializations - Emit information for ivar initialization
3674f22ef01cSRoman Divacky /// for an implementation.
3675f22ef01cSRoman Divacky void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
36763b0f4066SDimitry Andric   // We might need a .cxx_destruct even if we don't have any ivar initializers.
36773b0f4066SDimitry Andric   if (needsDestructMethod(D)) {
3678f22ef01cSRoman Divacky     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3679f22ef01cSRoman Divacky     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
36803b0f4066SDimitry Andric     ObjCMethodDecl *DTORMethod =
36813b0f4066SDimitry Andric       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
368259d1ed5bSDimitry Andric                              cxxSelector, getContext().VoidTy, nullptr, D,
36836122f3e6SDimitry Andric                              /*isInstance=*/true, /*isVariadic=*/false,
36843861d79fSDimitry Andric                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
36856122f3e6SDimitry Andric                              /*isDefined=*/false, ObjCMethodDecl::Required);
3686f22ef01cSRoman Divacky     D->addInstanceMethod(DTORMethod);
3687f22ef01cSRoman Divacky     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
36883861d79fSDimitry Andric     D->setHasDestructors(true);
36893b0f4066SDimitry Andric   }
3690f22ef01cSRoman Divacky 
36913b0f4066SDimitry Andric   // If the implementation doesn't have any ivar initializers, we don't need
36923b0f4066SDimitry Andric   // a .cxx_construct.
369339d628a0SDimitry Andric   if (D->getNumIvarInitializers() == 0 ||
369439d628a0SDimitry Andric       AllTrivialInitializers(*this, D))
36953b0f4066SDimitry Andric     return;
36963b0f4066SDimitry Andric 
36973b0f4066SDimitry Andric   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
36983b0f4066SDimitry Andric   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3699f22ef01cSRoman Divacky   // The constructor returns 'self'.
3700f22ef01cSRoman Divacky   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3701f22ef01cSRoman Divacky                                                 D->getLocation(),
37026122f3e6SDimitry Andric                                                 D->getLocation(),
37036122f3e6SDimitry Andric                                                 cxxSelector,
370459d1ed5bSDimitry Andric                                                 getContext().getObjCIdType(),
370559d1ed5bSDimitry Andric                                                 nullptr, D, /*isInstance=*/true,
37066122f3e6SDimitry Andric                                                 /*isVariadic=*/false,
37073861d79fSDimitry Andric                                                 /*isPropertyAccessor=*/true,
37086122f3e6SDimitry Andric                                                 /*isImplicitlyDeclared=*/true,
37096122f3e6SDimitry Andric                                                 /*isDefined=*/false,
3710f22ef01cSRoman Divacky                                                 ObjCMethodDecl::Required);
3711f22ef01cSRoman Divacky   D->addInstanceMethod(CTORMethod);
3712f22ef01cSRoman Divacky   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
37133861d79fSDimitry Andric   D->setHasNonZeroConstructors(true);
3714f22ef01cSRoman Divacky }
3715f22ef01cSRoman Divacky 
3716f22ef01cSRoman Divacky // EmitLinkageSpec - Emit all declarations in a linkage spec.
3717f22ef01cSRoman Divacky void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
3718f22ef01cSRoman Divacky   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3719f22ef01cSRoman Divacky       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
3720f22ef01cSRoman Divacky     ErrorUnsupported(LSD, "linkage spec");
3721f22ef01cSRoman Divacky     return;
3722f22ef01cSRoman Divacky   }
3723f22ef01cSRoman Divacky 
372444290647SDimitry Andric   EmitDeclContext(LSD);
372544290647SDimitry Andric }
372644290647SDimitry Andric 
372744290647SDimitry Andric void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
372844290647SDimitry Andric   for (auto *I : DC->decls()) {
372944290647SDimitry Andric     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
373044290647SDimitry Andric     // are themselves considered "top-level", so EmitTopLevelDecl on an
373144290647SDimitry Andric     // ObjCImplDecl does not recursively visit them. We need to do that in
373244290647SDimitry Andric     // case they're nested inside another construct (LinkageSpecDecl /
373344290647SDimitry Andric     // ExportDecl) that does stop them from being considered "top-level".
373459d1ed5bSDimitry Andric     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
373559d1ed5bSDimitry Andric       for (auto *M : OID->methods())
373659d1ed5bSDimitry Andric         EmitTopLevelDecl(M);
37373861d79fSDimitry Andric     }
373844290647SDimitry Andric 
373959d1ed5bSDimitry Andric     EmitTopLevelDecl(I);
3740f22ef01cSRoman Divacky   }
37413861d79fSDimitry Andric }
3742f22ef01cSRoman Divacky 
3743f22ef01cSRoman Divacky /// EmitTopLevelDecl - Emit code for a single top level declaration.
3744f22ef01cSRoman Divacky void CodeGenModule::EmitTopLevelDecl(Decl *D) {
3745f22ef01cSRoman Divacky   // Ignore dependent declarations.
3746f22ef01cSRoman Divacky   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3747f22ef01cSRoman Divacky     return;
3748f22ef01cSRoman Divacky 
3749f22ef01cSRoman Divacky   switch (D->getKind()) {
3750f22ef01cSRoman Divacky   case Decl::CXXConversion:
3751f22ef01cSRoman Divacky   case Decl::CXXMethod:
3752f22ef01cSRoman Divacky   case Decl::Function:
3753f22ef01cSRoman Divacky     // Skip function templates
37543b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
37553b0f4066SDimitry Andric         cast<FunctionDecl>(D)->isLateTemplateParsed())
3756f22ef01cSRoman Divacky       return;
3757f22ef01cSRoman Divacky 
3758f22ef01cSRoman Divacky     EmitGlobal(cast<FunctionDecl>(D));
375939d628a0SDimitry Andric     // Always provide some coverage mapping
376039d628a0SDimitry Andric     // even for the functions that aren't emitted.
376139d628a0SDimitry Andric     AddDeferredUnusedCoverageMapping(D);
3762f22ef01cSRoman Divacky     break;
3763f22ef01cSRoman Divacky 
3764f22ef01cSRoman Divacky   case Decl::Var:
376544290647SDimitry Andric   case Decl::Decomposition:
3766f785676fSDimitry Andric     // Skip variable templates
3767f785676fSDimitry Andric     if (cast<VarDecl>(D)->getDescribedVarTemplate())
3768f785676fSDimitry Andric       return;
3769f785676fSDimitry Andric   case Decl::VarTemplateSpecialization:
3770f22ef01cSRoman Divacky     EmitGlobal(cast<VarDecl>(D));
377144290647SDimitry Andric     if (auto *DD = dyn_cast<DecompositionDecl>(D))
377244290647SDimitry Andric       for (auto *B : DD->bindings())
377344290647SDimitry Andric         if (auto *HD = B->getHoldingVar())
377444290647SDimitry Andric           EmitGlobal(HD);
3775f22ef01cSRoman Divacky     break;
3776f22ef01cSRoman Divacky 
37773b0f4066SDimitry Andric   // Indirect fields from global anonymous structs and unions can be
37783b0f4066SDimitry Andric   // ignored; only the actual variable requires IR gen support.
37793b0f4066SDimitry Andric   case Decl::IndirectField:
37803b0f4066SDimitry Andric     break;
37813b0f4066SDimitry Andric 
3782f22ef01cSRoman Divacky   // C++ Decls
3783f22ef01cSRoman Divacky   case Decl::Namespace:
378444290647SDimitry Andric     EmitDeclContext(cast<NamespaceDecl>(D));
3785f22ef01cSRoman Divacky     break;
3786e7145dcbSDimitry Andric   case Decl::CXXRecord:
3787e7145dcbSDimitry Andric     // Emit any static data members, they may be definitions.
3788e7145dcbSDimitry Andric     for (auto *I : cast<CXXRecordDecl>(D)->decls())
3789e7145dcbSDimitry Andric       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
3790e7145dcbSDimitry Andric         EmitTopLevelDecl(I);
3791e7145dcbSDimitry Andric     break;
3792f22ef01cSRoman Divacky     // No code generation needed.
3793f22ef01cSRoman Divacky   case Decl::UsingShadow:
3794f22ef01cSRoman Divacky   case Decl::ClassTemplate:
3795f785676fSDimitry Andric   case Decl::VarTemplate:
3796f785676fSDimitry Andric   case Decl::VarTemplatePartialSpecialization:
3797f22ef01cSRoman Divacky   case Decl::FunctionTemplate:
3798bd5abe19SDimitry Andric   case Decl::TypeAliasTemplate:
3799bd5abe19SDimitry Andric   case Decl::Block:
3800139f7f9bSDimitry Andric   case Decl::Empty:
3801f22ef01cSRoman Divacky     break;
380259d1ed5bSDimitry Andric   case Decl::Using:          // using X; [C++]
380359d1ed5bSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
380459d1ed5bSDimitry Andric         DI->EmitUsingDecl(cast<UsingDecl>(*D));
380559d1ed5bSDimitry Andric     return;
3806f785676fSDimitry Andric   case Decl::NamespaceAlias:
3807f785676fSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
3808f785676fSDimitry Andric         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3809f785676fSDimitry Andric     return;
3810284c1978SDimitry Andric   case Decl::UsingDirective: // using namespace X; [C++]
3811284c1978SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
3812284c1978SDimitry Andric       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3813284c1978SDimitry Andric     return;
3814f22ef01cSRoman Divacky   case Decl::CXXConstructor:
3815f22ef01cSRoman Divacky     // Skip function templates
38163b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
38173b0f4066SDimitry Andric         cast<FunctionDecl>(D)->isLateTemplateParsed())
3818f22ef01cSRoman Divacky       return;
3819f22ef01cSRoman Divacky 
3820f785676fSDimitry Andric     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
3821f22ef01cSRoman Divacky     break;
3822f22ef01cSRoman Divacky   case Decl::CXXDestructor:
38233b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
38243b0f4066SDimitry Andric       return;
3825f785676fSDimitry Andric     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
3826f22ef01cSRoman Divacky     break;
3827f22ef01cSRoman Divacky 
3828f22ef01cSRoman Divacky   case Decl::StaticAssert:
3829f22ef01cSRoman Divacky     // Nothing to do.
3830f22ef01cSRoman Divacky     break;
3831f22ef01cSRoman Divacky 
3832f22ef01cSRoman Divacky   // Objective-C Decls
3833f22ef01cSRoman Divacky 
3834f22ef01cSRoman Divacky   // Forward declarations, no (immediate) code generation.
3835f22ef01cSRoman Divacky   case Decl::ObjCInterface:
38367ae0e2c9SDimitry Andric   case Decl::ObjCCategory:
3837f22ef01cSRoman Divacky     break;
3838f22ef01cSRoman Divacky 
3839dff0c46cSDimitry Andric   case Decl::ObjCProtocol: {
384059d1ed5bSDimitry Andric     auto *Proto = cast<ObjCProtocolDecl>(D);
3841dff0c46cSDimitry Andric     if (Proto->isThisDeclarationADefinition())
3842dff0c46cSDimitry Andric       ObjCRuntime->GenerateProtocol(Proto);
3843f22ef01cSRoman Divacky     break;
3844dff0c46cSDimitry Andric   }
3845f22ef01cSRoman Divacky 
3846f22ef01cSRoman Divacky   case Decl::ObjCCategoryImpl:
3847f22ef01cSRoman Divacky     // Categories have properties but don't support synthesize so we
3848f22ef01cSRoman Divacky     // can ignore them here.
38496122f3e6SDimitry Andric     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
3850f22ef01cSRoman Divacky     break;
3851f22ef01cSRoman Divacky 
3852f22ef01cSRoman Divacky   case Decl::ObjCImplementation: {
385359d1ed5bSDimitry Andric     auto *OMD = cast<ObjCImplementationDecl>(D);
3854f22ef01cSRoman Divacky     EmitObjCPropertyImplementations(OMD);
3855f22ef01cSRoman Divacky     EmitObjCIvarInitializations(OMD);
38566122f3e6SDimitry Andric     ObjCRuntime->GenerateClass(OMD);
3857dff0c46cSDimitry Andric     // Emit global variable debug information.
3858dff0c46cSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
3859e7145dcbSDimitry Andric       if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
3860139f7f9bSDimitry Andric         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3861139f7f9bSDimitry Andric             OMD->getClassInterface()), OMD->getLocation());
3862f22ef01cSRoman Divacky     break;
3863f22ef01cSRoman Divacky   }
3864f22ef01cSRoman Divacky   case Decl::ObjCMethod: {
386559d1ed5bSDimitry Andric     auto *OMD = cast<ObjCMethodDecl>(D);
3866f22ef01cSRoman Divacky     // If this is not a prototype, emit the body.
3867f22ef01cSRoman Divacky     if (OMD->getBody())
3868f22ef01cSRoman Divacky       CodeGenFunction(*this).GenerateObjCMethod(OMD);
3869f22ef01cSRoman Divacky     break;
3870f22ef01cSRoman Divacky   }
3871f22ef01cSRoman Divacky   case Decl::ObjCCompatibleAlias:
3872dff0c46cSDimitry Andric     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3873f22ef01cSRoman Divacky     break;
3874f22ef01cSRoman Divacky 
3875e7145dcbSDimitry Andric   case Decl::PragmaComment: {
3876e7145dcbSDimitry Andric     const auto *PCD = cast<PragmaCommentDecl>(D);
3877e7145dcbSDimitry Andric     switch (PCD->getCommentKind()) {
3878e7145dcbSDimitry Andric     case PCK_Unknown:
3879e7145dcbSDimitry Andric       llvm_unreachable("unexpected pragma comment kind");
3880e7145dcbSDimitry Andric     case PCK_Linker:
3881e7145dcbSDimitry Andric       AppendLinkerOptions(PCD->getArg());
3882e7145dcbSDimitry Andric       break;
3883e7145dcbSDimitry Andric     case PCK_Lib:
3884e7145dcbSDimitry Andric       AddDependentLib(PCD->getArg());
3885e7145dcbSDimitry Andric       break;
3886e7145dcbSDimitry Andric     case PCK_Compiler:
3887e7145dcbSDimitry Andric     case PCK_ExeStr:
3888e7145dcbSDimitry Andric     case PCK_User:
3889e7145dcbSDimitry Andric       break; // We ignore all of these.
3890e7145dcbSDimitry Andric     }
3891e7145dcbSDimitry Andric     break;
3892e7145dcbSDimitry Andric   }
3893e7145dcbSDimitry Andric 
3894e7145dcbSDimitry Andric   case Decl::PragmaDetectMismatch: {
3895e7145dcbSDimitry Andric     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
3896e7145dcbSDimitry Andric     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
3897e7145dcbSDimitry Andric     break;
3898e7145dcbSDimitry Andric   }
3899e7145dcbSDimitry Andric 
3900f22ef01cSRoman Divacky   case Decl::LinkageSpec:
3901f22ef01cSRoman Divacky     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
3902f22ef01cSRoman Divacky     break;
3903f22ef01cSRoman Divacky 
3904f22ef01cSRoman Divacky   case Decl::FileScopeAsm: {
390533956c43SDimitry Andric     // File-scope asm is ignored during device-side CUDA compilation.
390633956c43SDimitry Andric     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
390733956c43SDimitry Andric       break;
3908ea942507SDimitry Andric     // File-scope asm is ignored during device-side OpenMP compilation.
3909ea942507SDimitry Andric     if (LangOpts.OpenMPIsDevice)
3910ea942507SDimitry Andric       break;
391159d1ed5bSDimitry Andric     auto *AD = cast<FileScopeAsmDecl>(D);
391233956c43SDimitry Andric     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
3913f22ef01cSRoman Divacky     break;
3914f22ef01cSRoman Divacky   }
3915f22ef01cSRoman Divacky 
3916139f7f9bSDimitry Andric   case Decl::Import: {
391759d1ed5bSDimitry Andric     auto *Import = cast<ImportDecl>(D);
3918139f7f9bSDimitry Andric 
391944290647SDimitry Andric     // If we've already imported this module, we're done.
392044290647SDimitry Andric     if (!ImportedModules.insert(Import->getImportedModule()))
3921139f7f9bSDimitry Andric       break;
392244290647SDimitry Andric 
392344290647SDimitry Andric     // Emit debug information for direct imports.
392444290647SDimitry Andric     if (!Import->getImportedOwningModule()) {
39253dac3a9bSDimitry Andric       if (CGDebugInfo *DI = getModuleDebugInfo())
39263dac3a9bSDimitry Andric         DI->EmitImportDecl(*Import);
392744290647SDimitry Andric     }
3928139f7f9bSDimitry Andric 
392944290647SDimitry Andric     // Find all of the submodules and emit the module initializers.
393044290647SDimitry Andric     llvm::SmallPtrSet<clang::Module *, 16> Visited;
393144290647SDimitry Andric     SmallVector<clang::Module *, 16> Stack;
393244290647SDimitry Andric     Visited.insert(Import->getImportedModule());
393344290647SDimitry Andric     Stack.push_back(Import->getImportedModule());
393444290647SDimitry Andric 
393544290647SDimitry Andric     while (!Stack.empty()) {
393644290647SDimitry Andric       clang::Module *Mod = Stack.pop_back_val();
393744290647SDimitry Andric       if (!EmittedModuleInitializers.insert(Mod).second)
393844290647SDimitry Andric         continue;
393944290647SDimitry Andric 
394044290647SDimitry Andric       for (auto *D : Context.getModuleInitializers(Mod))
394144290647SDimitry Andric         EmitTopLevelDecl(D);
394244290647SDimitry Andric 
394344290647SDimitry Andric       // Visit the submodules of this module.
394444290647SDimitry Andric       for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
394544290647SDimitry Andric                                              SubEnd = Mod->submodule_end();
394644290647SDimitry Andric            Sub != SubEnd; ++Sub) {
394744290647SDimitry Andric         // Skip explicit children; they need to be explicitly imported to emit
394844290647SDimitry Andric         // the initializers.
394944290647SDimitry Andric         if ((*Sub)->IsExplicit)
395044290647SDimitry Andric           continue;
395144290647SDimitry Andric 
395244290647SDimitry Andric         if (Visited.insert(*Sub).second)
395344290647SDimitry Andric           Stack.push_back(*Sub);
395444290647SDimitry Andric       }
395544290647SDimitry Andric     }
3956139f7f9bSDimitry Andric     break;
3957139f7f9bSDimitry Andric   }
3958139f7f9bSDimitry Andric 
395944290647SDimitry Andric   case Decl::Export:
396044290647SDimitry Andric     EmitDeclContext(cast<ExportDecl>(D));
396144290647SDimitry Andric     break;
396244290647SDimitry Andric 
396339d628a0SDimitry Andric   case Decl::OMPThreadPrivate:
396439d628a0SDimitry Andric     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
396539d628a0SDimitry Andric     break;
396639d628a0SDimitry Andric 
396759d1ed5bSDimitry Andric   case Decl::ClassTemplateSpecialization: {
396859d1ed5bSDimitry Andric     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
396959d1ed5bSDimitry Andric     if (DebugInfo &&
397039d628a0SDimitry Andric         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
397139d628a0SDimitry Andric         Spec->hasDefinition())
397259d1ed5bSDimitry Andric       DebugInfo->completeTemplateDefinition(*Spec);
397339d628a0SDimitry Andric     break;
397459d1ed5bSDimitry Andric   }
397559d1ed5bSDimitry Andric 
3976e7145dcbSDimitry Andric   case Decl::OMPDeclareReduction:
3977e7145dcbSDimitry Andric     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
3978e7145dcbSDimitry Andric     break;
3979e7145dcbSDimitry Andric 
3980f22ef01cSRoman Divacky   default:
3981f22ef01cSRoman Divacky     // Make sure we handled everything we should, every other kind is a
3982f22ef01cSRoman Divacky     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
3983f22ef01cSRoman Divacky     // function. Need to recode Decl::Kind to do that easily.
3984f22ef01cSRoman Divacky     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
398539d628a0SDimitry Andric     break;
398639d628a0SDimitry Andric   }
398739d628a0SDimitry Andric }
398839d628a0SDimitry Andric 
398939d628a0SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
399039d628a0SDimitry Andric   // Do we need to generate coverage mapping?
399139d628a0SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
399239d628a0SDimitry Andric     return;
399339d628a0SDimitry Andric   switch (D->getKind()) {
399439d628a0SDimitry Andric   case Decl::CXXConversion:
399539d628a0SDimitry Andric   case Decl::CXXMethod:
399639d628a0SDimitry Andric   case Decl::Function:
399739d628a0SDimitry Andric   case Decl::ObjCMethod:
399839d628a0SDimitry Andric   case Decl::CXXConstructor:
399939d628a0SDimitry Andric   case Decl::CXXDestructor: {
40000623d748SDimitry Andric     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
400139d628a0SDimitry Andric       return;
400239d628a0SDimitry Andric     auto I = DeferredEmptyCoverageMappingDecls.find(D);
400339d628a0SDimitry Andric     if (I == DeferredEmptyCoverageMappingDecls.end())
400439d628a0SDimitry Andric       DeferredEmptyCoverageMappingDecls[D] = true;
400539d628a0SDimitry Andric     break;
400639d628a0SDimitry Andric   }
400739d628a0SDimitry Andric   default:
400839d628a0SDimitry Andric     break;
400939d628a0SDimitry Andric   };
401039d628a0SDimitry Andric }
401139d628a0SDimitry Andric 
401239d628a0SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
401339d628a0SDimitry Andric   // Do we need to generate coverage mapping?
401439d628a0SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
401539d628a0SDimitry Andric     return;
401639d628a0SDimitry Andric   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
401739d628a0SDimitry Andric     if (Fn->isTemplateInstantiation())
401839d628a0SDimitry Andric       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
401939d628a0SDimitry Andric   }
402039d628a0SDimitry Andric   auto I = DeferredEmptyCoverageMappingDecls.find(D);
402139d628a0SDimitry Andric   if (I == DeferredEmptyCoverageMappingDecls.end())
402239d628a0SDimitry Andric     DeferredEmptyCoverageMappingDecls[D] = false;
402339d628a0SDimitry Andric   else
402439d628a0SDimitry Andric     I->second = false;
402539d628a0SDimitry Andric }
402639d628a0SDimitry Andric 
402739d628a0SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
402839d628a0SDimitry Andric   std::vector<const Decl *> DeferredDecls;
402933956c43SDimitry Andric   for (const auto &I : DeferredEmptyCoverageMappingDecls) {
403039d628a0SDimitry Andric     if (!I.second)
403139d628a0SDimitry Andric       continue;
403239d628a0SDimitry Andric     DeferredDecls.push_back(I.first);
403339d628a0SDimitry Andric   }
403439d628a0SDimitry Andric   // Sort the declarations by their location to make sure that the tests get a
403539d628a0SDimitry Andric   // predictable order for the coverage mapping for the unused declarations.
403639d628a0SDimitry Andric   if (CodeGenOpts.DumpCoverageMapping)
403739d628a0SDimitry Andric     std::sort(DeferredDecls.begin(), DeferredDecls.end(),
403839d628a0SDimitry Andric               [] (const Decl *LHS, const Decl *RHS) {
403939d628a0SDimitry Andric       return LHS->getLocStart() < RHS->getLocStart();
404039d628a0SDimitry Andric     });
404139d628a0SDimitry Andric   for (const auto *D : DeferredDecls) {
404239d628a0SDimitry Andric     switch (D->getKind()) {
404339d628a0SDimitry Andric     case Decl::CXXConversion:
404439d628a0SDimitry Andric     case Decl::CXXMethod:
404539d628a0SDimitry Andric     case Decl::Function:
404639d628a0SDimitry Andric     case Decl::ObjCMethod: {
404739d628a0SDimitry Andric       CodeGenPGO PGO(*this);
404839d628a0SDimitry Andric       GlobalDecl GD(cast<FunctionDecl>(D));
404939d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
405039d628a0SDimitry Andric                                   getFunctionLinkage(GD));
405139d628a0SDimitry Andric       break;
405239d628a0SDimitry Andric     }
405339d628a0SDimitry Andric     case Decl::CXXConstructor: {
405439d628a0SDimitry Andric       CodeGenPGO PGO(*this);
405539d628a0SDimitry Andric       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
405639d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
405739d628a0SDimitry Andric                                   getFunctionLinkage(GD));
405839d628a0SDimitry Andric       break;
405939d628a0SDimitry Andric     }
406039d628a0SDimitry Andric     case Decl::CXXDestructor: {
406139d628a0SDimitry Andric       CodeGenPGO PGO(*this);
406239d628a0SDimitry Andric       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
406339d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
406439d628a0SDimitry Andric                                   getFunctionLinkage(GD));
406539d628a0SDimitry Andric       break;
406639d628a0SDimitry Andric     }
406739d628a0SDimitry Andric     default:
406839d628a0SDimitry Andric       break;
406939d628a0SDimitry Andric     };
4070f22ef01cSRoman Divacky   }
4071f22ef01cSRoman Divacky }
4072ffd1746dSEd Schouten 
4073ffd1746dSEd Schouten /// Turns the given pointer into a constant.
4074ffd1746dSEd Schouten static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4075ffd1746dSEd Schouten                                           const void *Ptr) {
4076ffd1746dSEd Schouten   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
40776122f3e6SDimitry Andric   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
4078ffd1746dSEd Schouten   return llvm::ConstantInt::get(i64, PtrInt);
4079ffd1746dSEd Schouten }
4080ffd1746dSEd Schouten 
4081ffd1746dSEd Schouten static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
4082ffd1746dSEd Schouten                                    llvm::NamedMDNode *&GlobalMetadata,
4083ffd1746dSEd Schouten                                    GlobalDecl D,
4084ffd1746dSEd Schouten                                    llvm::GlobalValue *Addr) {
4085ffd1746dSEd Schouten   if (!GlobalMetadata)
4086ffd1746dSEd Schouten     GlobalMetadata =
4087ffd1746dSEd Schouten       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4088ffd1746dSEd Schouten 
4089ffd1746dSEd Schouten   // TODO: should we report variant information for ctors/dtors?
409039d628a0SDimitry Andric   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
409139d628a0SDimitry Andric                            llvm::ConstantAsMetadata::get(GetPointerConstant(
409239d628a0SDimitry Andric                                CGM.getLLVMContext(), D.getDecl()))};
40933b0f4066SDimitry Andric   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
4094ffd1746dSEd Schouten }
4095ffd1746dSEd Schouten 
4096284c1978SDimitry Andric /// For each function which is declared within an extern "C" region and marked
4097284c1978SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled
4098284c1978SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer
4099284c1978SDimitry Andric /// to such functions with an unmangled name from inline assembly within the
4100284c1978SDimitry Andric /// same translation unit.
4101284c1978SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() {
4102e7145dcbSDimitry Andric   // Don't do anything if we're generating CUDA device code -- the NVPTX
4103e7145dcbSDimitry Andric   // assembly target doesn't support aliases.
4104e7145dcbSDimitry Andric   if (Context.getTargetInfo().getTriple().isNVPTX())
4105e7145dcbSDimitry Andric     return;
41068f0fd8f6SDimitry Andric   for (auto &I : StaticExternCValues) {
41078f0fd8f6SDimitry Andric     IdentifierInfo *Name = I.first;
41088f0fd8f6SDimitry Andric     llvm::GlobalValue *Val = I.second;
4109284c1978SDimitry Andric     if (Val && !getModule().getNamedValue(Name->getName()))
411059d1ed5bSDimitry Andric       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
4111284c1978SDimitry Andric   }
4112284c1978SDimitry Andric }
4113284c1978SDimitry Andric 
411459d1ed5bSDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
411559d1ed5bSDimitry Andric                                              GlobalDecl &Result) const {
411659d1ed5bSDimitry Andric   auto Res = Manglings.find(MangledName);
411759d1ed5bSDimitry Andric   if (Res == Manglings.end())
411859d1ed5bSDimitry Andric     return false;
411959d1ed5bSDimitry Andric   Result = Res->getValue();
412059d1ed5bSDimitry Andric   return true;
412159d1ed5bSDimitry Andric }
412259d1ed5bSDimitry Andric 
4123ffd1746dSEd Schouten /// Emits metadata nodes associating all the global values in the
4124ffd1746dSEd Schouten /// current module with the Decls they came from.  This is useful for
4125ffd1746dSEd Schouten /// projects using IR gen as a subroutine.
4126ffd1746dSEd Schouten ///
4127ffd1746dSEd Schouten /// Since there's currently no way to associate an MDNode directly
4128ffd1746dSEd Schouten /// with an llvm::GlobalValue, we create a global named metadata
4129ffd1746dSEd Schouten /// with the name 'clang.global.decl.ptrs'.
4130ffd1746dSEd Schouten void CodeGenModule::EmitDeclMetadata() {
413159d1ed5bSDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
4132ffd1746dSEd Schouten 
413359d1ed5bSDimitry Andric   for (auto &I : MangledDeclNames) {
413459d1ed5bSDimitry Andric     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
41350623d748SDimitry Andric     // Some mangled names don't necessarily have an associated GlobalValue
41360623d748SDimitry Andric     // in this module, e.g. if we mangled it for DebugInfo.
41370623d748SDimitry Andric     if (Addr)
413859d1ed5bSDimitry Andric       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
4139ffd1746dSEd Schouten   }
4140ffd1746dSEd Schouten }
4141ffd1746dSEd Schouten 
4142ffd1746dSEd Schouten /// Emits metadata nodes for all the local variables in the current
4143ffd1746dSEd Schouten /// function.
4144ffd1746dSEd Schouten void CodeGenFunction::EmitDeclMetadata() {
4145ffd1746dSEd Schouten   if (LocalDeclMap.empty()) return;
4146ffd1746dSEd Schouten 
4147ffd1746dSEd Schouten   llvm::LLVMContext &Context = getLLVMContext();
4148ffd1746dSEd Schouten 
4149ffd1746dSEd Schouten   // Find the unique metadata ID for this name.
4150ffd1746dSEd Schouten   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
4151ffd1746dSEd Schouten 
415259d1ed5bSDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
4153ffd1746dSEd Schouten 
415459d1ed5bSDimitry Andric   for (auto &I : LocalDeclMap) {
415559d1ed5bSDimitry Andric     const Decl *D = I.first;
41560623d748SDimitry Andric     llvm::Value *Addr = I.second.getPointer();
415759d1ed5bSDimitry Andric     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
4158ffd1746dSEd Schouten       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
415939d628a0SDimitry Andric       Alloca->setMetadata(
416039d628a0SDimitry Andric           DeclPtrKind, llvm::MDNode::get(
416139d628a0SDimitry Andric                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
416259d1ed5bSDimitry Andric     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
4163ffd1746dSEd Schouten       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
4164ffd1746dSEd Schouten       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
4165ffd1746dSEd Schouten     }
4166ffd1746dSEd Schouten   }
4167ffd1746dSEd Schouten }
4168e580952dSDimitry Andric 
4169f785676fSDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() {
4170f785676fSDimitry Andric   llvm::NamedMDNode *IdentMetadata =
4171f785676fSDimitry Andric     TheModule.getOrInsertNamedMetadata("llvm.ident");
4172f785676fSDimitry Andric   std::string Version = getClangFullVersion();
4173f785676fSDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
4174f785676fSDimitry Andric 
417539d628a0SDimitry Andric   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
4176f785676fSDimitry Andric   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4177f785676fSDimitry Andric }
4178f785676fSDimitry Andric 
417959d1ed5bSDimitry Andric void CodeGenModule::EmitTargetMetadata() {
418039d628a0SDimitry Andric   // Warning, new MangledDeclNames may be appended within this loop.
418139d628a0SDimitry Andric   // We rely on MapVector insertions adding new elements to the end
418239d628a0SDimitry Andric   // of the container.
418339d628a0SDimitry Andric   // FIXME: Move this loop into the one target that needs it, and only
418439d628a0SDimitry Andric   // loop over those declarations for which we couldn't emit the target
418539d628a0SDimitry Andric   // metadata when we emitted the declaration.
418639d628a0SDimitry Andric   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
418739d628a0SDimitry Andric     auto Val = *(MangledDeclNames.begin() + I);
418839d628a0SDimitry Andric     const Decl *D = Val.first.getDecl()->getMostRecentDecl();
418939d628a0SDimitry Andric     llvm::GlobalValue *GV = GetGlobalValue(Val.second);
419059d1ed5bSDimitry Andric     getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
419159d1ed5bSDimitry Andric   }
419259d1ed5bSDimitry Andric }
419359d1ed5bSDimitry Andric 
4194bd5abe19SDimitry Andric void CodeGenModule::EmitCoverageFile() {
419544290647SDimitry Andric   if (getCodeGenOpts().CoverageDataFile.empty() &&
419644290647SDimitry Andric       getCodeGenOpts().CoverageNotesFile.empty())
419744290647SDimitry Andric     return;
419844290647SDimitry Andric 
419944290647SDimitry Andric   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
420044290647SDimitry Andric   if (!CUNode)
420144290647SDimitry Andric     return;
420244290647SDimitry Andric 
4203bd5abe19SDimitry Andric   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
4204bd5abe19SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
420544290647SDimitry Andric   auto *CoverageDataFile =
420644290647SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
420744290647SDimitry Andric   auto *CoverageNotesFile =
420844290647SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
4209bd5abe19SDimitry Andric   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
4210bd5abe19SDimitry Andric     llvm::MDNode *CU = CUNode->getOperand(i);
421144290647SDimitry Andric     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
421239d628a0SDimitry Andric     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
4213bd5abe19SDimitry Andric   }
4214bd5abe19SDimitry Andric }
42153861d79fSDimitry Andric 
421639d628a0SDimitry Andric llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
42173861d79fSDimitry Andric   // Sema has checked that all uuid strings are of the form
42183861d79fSDimitry Andric   // "12345678-1234-1234-1234-1234567890ab".
42193861d79fSDimitry Andric   assert(Uuid.size() == 36);
4220f785676fSDimitry Andric   for (unsigned i = 0; i < 36; ++i) {
4221f785676fSDimitry Andric     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
4222f785676fSDimitry Andric     else                                         assert(isHexDigit(Uuid[i]));
42233861d79fSDimitry Andric   }
42243861d79fSDimitry Andric 
422539d628a0SDimitry Andric   // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
4226f785676fSDimitry Andric   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
42273861d79fSDimitry Andric 
4228f785676fSDimitry Andric   llvm::Constant *Field3[8];
4229f785676fSDimitry Andric   for (unsigned Idx = 0; Idx < 8; ++Idx)
4230f785676fSDimitry Andric     Field3[Idx] = llvm::ConstantInt::get(
4231f785676fSDimitry Andric         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
42323861d79fSDimitry Andric 
4233f785676fSDimitry Andric   llvm::Constant *Fields[4] = {
4234f785676fSDimitry Andric     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
4235f785676fSDimitry Andric     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
4236f785676fSDimitry Andric     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
4237f785676fSDimitry Andric     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
4238f785676fSDimitry Andric   };
4239f785676fSDimitry Andric 
4240f785676fSDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
42413861d79fSDimitry Andric }
424259d1ed5bSDimitry Andric 
424359d1ed5bSDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
424459d1ed5bSDimitry Andric                                                        bool ForEH) {
424559d1ed5bSDimitry Andric   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
424659d1ed5bSDimitry Andric   // FIXME: should we even be calling this method if RTTI is disabled
424759d1ed5bSDimitry Andric   // and it's not for EH?
424859d1ed5bSDimitry Andric   if (!ForEH && !getLangOpts().RTTI)
424959d1ed5bSDimitry Andric     return llvm::Constant::getNullValue(Int8PtrTy);
425059d1ed5bSDimitry Andric 
425159d1ed5bSDimitry Andric   if (ForEH && Ty->isObjCObjectPointerType() &&
425259d1ed5bSDimitry Andric       LangOpts.ObjCRuntime.isGNUFamily())
425359d1ed5bSDimitry Andric     return ObjCRuntime->GetEHType(Ty);
425459d1ed5bSDimitry Andric 
425559d1ed5bSDimitry Andric   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
425659d1ed5bSDimitry Andric }
425759d1ed5bSDimitry Andric 
425839d628a0SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
425939d628a0SDimitry Andric   for (auto RefExpr : D->varlists()) {
426039d628a0SDimitry Andric     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
426139d628a0SDimitry Andric     bool PerformInit =
426239d628a0SDimitry Andric         VD->getAnyInitializer() &&
426339d628a0SDimitry Andric         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
426439d628a0SDimitry Andric                                                         /*ForRef=*/false);
42650623d748SDimitry Andric 
42660623d748SDimitry Andric     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
426733956c43SDimitry Andric     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
42680623d748SDimitry Andric             VD, Addr, RefExpr->getLocStart(), PerformInit))
426939d628a0SDimitry Andric       CXXGlobalInits.push_back(InitFunction);
427039d628a0SDimitry Andric   }
427139d628a0SDimitry Andric }
42728f0fd8f6SDimitry Andric 
42730623d748SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
42740623d748SDimitry Andric   llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
42750623d748SDimitry Andric   if (InternalId)
42760623d748SDimitry Andric     return InternalId;
42770623d748SDimitry Andric 
42780623d748SDimitry Andric   if (isExternallyVisible(T->getLinkage())) {
42798f0fd8f6SDimitry Andric     std::string OutName;
42808f0fd8f6SDimitry Andric     llvm::raw_string_ostream Out(OutName);
42810623d748SDimitry Andric     getCXXABI().getMangleContext().mangleTypeName(T, Out);
42828f0fd8f6SDimitry Andric 
42830623d748SDimitry Andric     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
42840623d748SDimitry Andric   } else {
42850623d748SDimitry Andric     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
42860623d748SDimitry Andric                                            llvm::ArrayRef<llvm::Metadata *>());
42870623d748SDimitry Andric   }
42880623d748SDimitry Andric 
42890623d748SDimitry Andric   return InternalId;
42900623d748SDimitry Andric }
42910623d748SDimitry Andric 
4292e7145dcbSDimitry Andric /// Returns whether this module needs the "all-vtables" type identifier.
4293e7145dcbSDimitry Andric bool CodeGenModule::NeedAllVtablesTypeId() const {
4294e7145dcbSDimitry Andric   // Returns true if at least one of vtable-based CFI checkers is enabled and
4295e7145dcbSDimitry Andric   // is not in the trapping mode.
4296e7145dcbSDimitry Andric   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
4297e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
4298e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
4299e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
4300e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
4301e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
4302e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
4303e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
4304e7145dcbSDimitry Andric }
4305e7145dcbSDimitry Andric 
4306e7145dcbSDimitry Andric void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
43070623d748SDimitry Andric                                           CharUnits Offset,
43080623d748SDimitry Andric                                           const CXXRecordDecl *RD) {
43090623d748SDimitry Andric   llvm::Metadata *MD =
43100623d748SDimitry Andric       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
4311e7145dcbSDimitry Andric   VTable->addTypeMetadata(Offset.getQuantity(), MD);
43120623d748SDimitry Andric 
4313e7145dcbSDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
4314e7145dcbSDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
4315e7145dcbSDimitry Andric       VTable->addTypeMetadata(Offset.getQuantity(),
4316e7145dcbSDimitry Andric                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
4317e7145dcbSDimitry Andric 
4318e7145dcbSDimitry Andric   if (NeedAllVtablesTypeId()) {
4319e7145dcbSDimitry Andric     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
4320e7145dcbSDimitry Andric     VTable->addTypeMetadata(Offset.getQuantity(), MD);
43210623d748SDimitry Andric   }
43220623d748SDimitry Andric }
43230623d748SDimitry Andric 
43240623d748SDimitry Andric // Fills in the supplied string map with the set of target features for the
43250623d748SDimitry Andric // passed in function.
43260623d748SDimitry Andric void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
43270623d748SDimitry Andric                                           const FunctionDecl *FD) {
43280623d748SDimitry Andric   StringRef TargetCPU = Target.getTargetOpts().CPU;
43290623d748SDimitry Andric   if (const auto *TD = FD->getAttr<TargetAttr>()) {
43300623d748SDimitry Andric     // If we have a TargetAttr build up the feature map based on that.
43310623d748SDimitry Andric     TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
43320623d748SDimitry Andric 
43330623d748SDimitry Andric     // Make a copy of the features as passed on the command line into the
43340623d748SDimitry Andric     // beginning of the additional features from the function to override.
43350623d748SDimitry Andric     ParsedAttr.first.insert(ParsedAttr.first.begin(),
43360623d748SDimitry Andric                             Target.getTargetOpts().FeaturesAsWritten.begin(),
43370623d748SDimitry Andric                             Target.getTargetOpts().FeaturesAsWritten.end());
43380623d748SDimitry Andric 
43390623d748SDimitry Andric     if (ParsedAttr.second != "")
43400623d748SDimitry Andric       TargetCPU = ParsedAttr.second;
43410623d748SDimitry Andric 
43420623d748SDimitry Andric     // Now populate the feature map, first with the TargetCPU which is either
43430623d748SDimitry Andric     // the default or a new one from the target attribute string. Then we'll use
43440623d748SDimitry Andric     // the passed in features (FeaturesAsWritten) along with the new ones from
43450623d748SDimitry Andric     // the attribute.
43460623d748SDimitry Andric     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first);
43470623d748SDimitry Andric   } else {
43480623d748SDimitry Andric     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
43490623d748SDimitry Andric                           Target.getTargetOpts().Features);
43500623d748SDimitry Andric   }
43518f0fd8f6SDimitry Andric }
4352e7145dcbSDimitry Andric 
4353e7145dcbSDimitry Andric llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
4354e7145dcbSDimitry Andric   if (!SanStats)
4355e7145dcbSDimitry Andric     SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
4356e7145dcbSDimitry Andric 
4357e7145dcbSDimitry Andric   return *SanStats;
4358e7145dcbSDimitry Andric }
435944290647SDimitry Andric llvm::Value *
436044290647SDimitry Andric CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
436144290647SDimitry Andric                                                   CodeGenFunction &CGF) {
436244290647SDimitry Andric   llvm::Constant *C = EmitConstantExpr(E, E->getType(), &CGF);
436344290647SDimitry Andric   auto SamplerT = getOpenCLRuntime().getSamplerType();
436444290647SDimitry Andric   auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
436544290647SDimitry Andric   return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
436644290647SDimitry Andric                                 "__translate_sampler_initializer"),
436744290647SDimitry Andric                                 {C});
436844290647SDimitry Andric }
4369