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"
2739d628a0SDimitry Andric #include "CoverageMappingGen.h"
28f22ef01cSRoman Divacky #include "TargetInfo.h"
29f22ef01cSRoman Divacky #include "clang/AST/ASTContext.h"
30f22ef01cSRoman Divacky #include "clang/AST/CharUnits.h"
31f22ef01cSRoman Divacky #include "clang/AST/DeclCXX.h"
32139f7f9bSDimitry Andric #include "clang/AST/DeclObjC.h"
33ffd1746dSEd Schouten #include "clang/AST/DeclTemplate.h"
342754fe60SDimitry Andric #include "clang/AST/Mangle.h"
35f22ef01cSRoman Divacky #include "clang/AST/RecordLayout.h"
36f8254f43SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h"
37dff0c46cSDimitry Andric #include "clang/Basic/Builtins.h"
38139f7f9bSDimitry Andric #include "clang/Basic/CharInfo.h"
39f22ef01cSRoman Divacky #include "clang/Basic/Diagnostic.h"
40139f7f9bSDimitry Andric #include "clang/Basic/Module.h"
41f22ef01cSRoman Divacky #include "clang/Basic/SourceManager.h"
42f22ef01cSRoman Divacky #include "clang/Basic/TargetInfo.h"
43f785676fSDimitry Andric #include "clang/Basic/Version.h"
4420e90f04SDimitry Andric #include "clang/CodeGen/ConstantInitBuilder.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();
40920e90f04SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
410e7145dcbSDimitry Andric     CodeGenFunction(*this).EmitCfiCheckFail();
41120e90f04SDimitry Andric     CodeGenFunction(*this).EmitCfiCheckStub();
41220e90f04SDimitry Andric   }
41320e90f04SDimitry Andric   emitAtAvailableLinkGuard();
41459d1ed5bSDimitry Andric   emitLLVMUsed();
415e7145dcbSDimitry Andric   if (SanStats)
416e7145dcbSDimitry Andric     SanStats->finish();
417ffd1746dSEd Schouten 
418f785676fSDimitry Andric   if (CodeGenOpts.Autolink &&
419f785676fSDimitry Andric       (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
420139f7f9bSDimitry Andric     EmitModuleLinkOptions();
421139f7f9bSDimitry Andric   }
42220e90f04SDimitry Andric 
42320e90f04SDimitry Andric   // Record mregparm value now so it is visible through rest of codegen.
42420e90f04SDimitry Andric   if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
42520e90f04SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
42620e90f04SDimitry Andric                               CodeGenOpts.NumRegisterParameters);
42720e90f04SDimitry Andric 
4280623d748SDimitry Andric   if (CodeGenOpts.DwarfVersion) {
429f785676fSDimitry Andric     // We actually want the latest version when there are conflicts.
430f785676fSDimitry Andric     // We can change from Warning to Latest if such mode is supported.
431f785676fSDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
432f785676fSDimitry Andric                               CodeGenOpts.DwarfVersion);
4330623d748SDimitry Andric   }
4340623d748SDimitry Andric   if (CodeGenOpts.EmitCodeView) {
4350623d748SDimitry Andric     // Indicate that we want CodeView in the metadata.
4360623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
4370623d748SDimitry Andric   }
4380623d748SDimitry Andric   if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
4390623d748SDimitry Andric     // We don't support LTO with 2 with different StrictVTablePointers
4400623d748SDimitry Andric     // FIXME: we could support it by stripping all the information introduced
4410623d748SDimitry Andric     // by StrictVTablePointers.
4420623d748SDimitry Andric 
4430623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
4440623d748SDimitry Andric 
4450623d748SDimitry Andric     llvm::Metadata *Ops[2] = {
4460623d748SDimitry Andric               llvm::MDString::get(VMContext, "StrictVTablePointers"),
4470623d748SDimitry Andric               llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
4480623d748SDimitry Andric                   llvm::Type::getInt32Ty(VMContext), 1))};
4490623d748SDimitry Andric 
4500623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Require,
4510623d748SDimitry Andric                               "StrictVTablePointersRequirement",
4520623d748SDimitry Andric                               llvm::MDNode::get(VMContext, Ops));
4530623d748SDimitry Andric   }
454f785676fSDimitry Andric   if (DebugInfo)
45559d1ed5bSDimitry Andric     // We support a single version in the linked module. The LLVM
45659d1ed5bSDimitry Andric     // parser will drop debug info with a different version number
45759d1ed5bSDimitry Andric     // (and warn about it, too).
45859d1ed5bSDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
459f785676fSDimitry Andric                               llvm::DEBUG_METADATA_VERSION);
460139f7f9bSDimitry Andric 
46159d1ed5bSDimitry Andric   // We need to record the widths of enums and wchar_t, so that we can generate
46259d1ed5bSDimitry Andric   // the correct build attributes in the ARM backend.
46359d1ed5bSDimitry Andric   llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
46459d1ed5bSDimitry Andric   if (   Arch == llvm::Triple::arm
46559d1ed5bSDimitry Andric       || Arch == llvm::Triple::armeb
46659d1ed5bSDimitry Andric       || Arch == llvm::Triple::thumb
46759d1ed5bSDimitry Andric       || Arch == llvm::Triple::thumbeb) {
46859d1ed5bSDimitry Andric     // Width of wchar_t in bytes
46959d1ed5bSDimitry Andric     uint64_t WCharWidth =
47059d1ed5bSDimitry Andric         Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
47159d1ed5bSDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
47259d1ed5bSDimitry Andric 
47359d1ed5bSDimitry Andric     // The minimum width of an enum in bytes
47459d1ed5bSDimitry Andric     uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
47559d1ed5bSDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
47659d1ed5bSDimitry Andric   }
47759d1ed5bSDimitry Andric 
4780623d748SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
4790623d748SDimitry Andric     // Indicate that we want cross-DSO control flow integrity checks.
4800623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
4810623d748SDimitry Andric   }
4820623d748SDimitry Andric 
48344290647SDimitry Andric   if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
484e7145dcbSDimitry Andric     // Indicate whether __nvvm_reflect should be configured to flush denormal
485e7145dcbSDimitry Andric     // floating point values to 0.  (This corresponds to its "__CUDA_FTZ"
486e7145dcbSDimitry Andric     // property.)
487e7145dcbSDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
488e7145dcbSDimitry Andric                               LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
48939d628a0SDimitry Andric   }
49039d628a0SDimitry Andric 
491e7145dcbSDimitry Andric   if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
492e7145dcbSDimitry Andric     assert(PLevel < 3 && "Invalid PIC Level");
493e7145dcbSDimitry Andric     getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
494e7145dcbSDimitry Andric     if (Context.getLangOpts().PIE)
495e7145dcbSDimitry Andric       getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
49639d628a0SDimitry Andric   }
49739d628a0SDimitry Andric 
4982754fe60SDimitry Andric   SimplifyPersonality();
4992754fe60SDimitry Andric 
500ffd1746dSEd Schouten   if (getCodeGenOpts().EmitDeclMetadata)
501ffd1746dSEd Schouten     EmitDeclMetadata();
502bd5abe19SDimitry Andric 
503bd5abe19SDimitry Andric   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
504bd5abe19SDimitry Andric     EmitCoverageFile();
5056122f3e6SDimitry Andric 
5066122f3e6SDimitry Andric   if (DebugInfo)
5076122f3e6SDimitry Andric     DebugInfo->finalize();
508f785676fSDimitry Andric 
509f785676fSDimitry Andric   EmitVersionIdentMetadata();
51059d1ed5bSDimitry Andric 
51159d1ed5bSDimitry Andric   EmitTargetMetadata();
512f22ef01cSRoman Divacky }
513f22ef01cSRoman Divacky 
5143b0f4066SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
5153b0f4066SDimitry Andric   // Make sure that this type is translated.
5163b0f4066SDimitry Andric   Types.UpdateCompletedType(TD);
5173b0f4066SDimitry Andric }
5183b0f4066SDimitry Andric 
519e7145dcbSDimitry Andric void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
520e7145dcbSDimitry Andric   // Make sure that this type is translated.
521e7145dcbSDimitry Andric   Types.RefreshTypeCacheForClass(RD);
522e7145dcbSDimitry Andric }
523e7145dcbSDimitry Andric 
5242754fe60SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
5252754fe60SDimitry Andric   if (!TBAA)
52659d1ed5bSDimitry Andric     return nullptr;
5272754fe60SDimitry Andric   return TBAA->getTBAAInfo(QTy);
5282754fe60SDimitry Andric }
5292754fe60SDimitry Andric 
530dff0c46cSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
531dff0c46cSDimitry Andric   if (!TBAA)
53259d1ed5bSDimitry Andric     return nullptr;
533dff0c46cSDimitry Andric   return TBAA->getTBAAInfoForVTablePtr();
534dff0c46cSDimitry Andric }
535dff0c46cSDimitry Andric 
5363861d79fSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
5373861d79fSDimitry Andric   if (!TBAA)
53859d1ed5bSDimitry Andric     return nullptr;
5393861d79fSDimitry Andric   return TBAA->getTBAAStructInfo(QTy);
5403861d79fSDimitry Andric }
5413861d79fSDimitry Andric 
542139f7f9bSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
543139f7f9bSDimitry Andric                                                   llvm::MDNode *AccessN,
544139f7f9bSDimitry Andric                                                   uint64_t O) {
545139f7f9bSDimitry Andric   if (!TBAA)
54659d1ed5bSDimitry Andric     return nullptr;
547139f7f9bSDimitry Andric   return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
548139f7f9bSDimitry Andric }
549139f7f9bSDimitry Andric 
550f785676fSDimitry Andric /// Decorate the instruction with a TBAA tag. For both scalar TBAA
551f785676fSDimitry Andric /// and struct-path aware TBAA, the tag has the same format:
552f785676fSDimitry Andric /// base type, access type and offset.
553284c1978SDimitry Andric /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
5540623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
555284c1978SDimitry Andric                                                 llvm::MDNode *TBAAInfo,
556284c1978SDimitry Andric                                                 bool ConvertTypeToTag) {
557f785676fSDimitry Andric   if (ConvertTypeToTag && TBAA)
558284c1978SDimitry Andric     Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
559284c1978SDimitry Andric                       TBAA->getTBAAScalarTagInfo(TBAAInfo));
560284c1978SDimitry Andric   else
5612754fe60SDimitry Andric     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
5622754fe60SDimitry Andric }
5632754fe60SDimitry Andric 
5640623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup(
5650623d748SDimitry Andric     llvm::Instruction *I, const CXXRecordDecl *RD) {
5660623d748SDimitry Andric   llvm::Metadata *MD = CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
5670623d748SDimitry Andric   auto *MetaDataNode = dyn_cast<llvm::MDNode>(MD);
5680623d748SDimitry Andric   // Check if we have to wrap MDString in MDNode.
5690623d748SDimitry Andric   if (!MetaDataNode)
5700623d748SDimitry Andric     MetaDataNode = llvm::MDNode::get(getLLVMContext(), MD);
5710623d748SDimitry Andric   I->setMetadata(llvm::LLVMContext::MD_invariant_group, MetaDataNode);
5720623d748SDimitry Andric }
5730623d748SDimitry Andric 
57459d1ed5bSDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) {
57559d1ed5bSDimitry Andric   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
57659d1ed5bSDimitry Andric   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
577f22ef01cSRoman Divacky }
578f22ef01cSRoman Divacky 
579f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
580f22ef01cSRoman Divacky /// specified stmt yet.
581f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
5826122f3e6SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
583f22ef01cSRoman Divacky                                                "cannot compile this %0 yet");
584f22ef01cSRoman Divacky   std::string Msg = Type;
585f22ef01cSRoman Divacky   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
586f22ef01cSRoman Divacky     << Msg << S->getSourceRange();
587f22ef01cSRoman Divacky }
588f22ef01cSRoman Divacky 
589f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
590f22ef01cSRoman Divacky /// specified decl yet.
591f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
5926122f3e6SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
593f22ef01cSRoman Divacky                                                "cannot compile this %0 yet");
594f22ef01cSRoman Divacky   std::string Msg = Type;
595f22ef01cSRoman Divacky   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
596f22ef01cSRoman Divacky }
597f22ef01cSRoman Divacky 
59817a519f9SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
59917a519f9SDimitry Andric   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
60017a519f9SDimitry Andric }
60117a519f9SDimitry Andric 
602f22ef01cSRoman Divacky void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
6032754fe60SDimitry Andric                                         const NamedDecl *D) const {
604f22ef01cSRoman Divacky   // Internal definitions always have default visibility.
605f22ef01cSRoman Divacky   if (GV->hasLocalLinkage()) {
606f22ef01cSRoman Divacky     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
607f22ef01cSRoman Divacky     return;
608f22ef01cSRoman Divacky   }
609f22ef01cSRoman Divacky 
6102754fe60SDimitry Andric   // Set visibility for definitions.
611139f7f9bSDimitry Andric   LinkageInfo LV = D->getLinkageAndVisibility();
612139f7f9bSDimitry Andric   if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
613139f7f9bSDimitry Andric     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
614f22ef01cSRoman Divacky }
615f22ef01cSRoman Divacky 
6167ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
6177ae0e2c9SDimitry Andric   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
6187ae0e2c9SDimitry Andric       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
6197ae0e2c9SDimitry Andric       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
6207ae0e2c9SDimitry Andric       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
6217ae0e2c9SDimitry Andric       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
6227ae0e2c9SDimitry Andric }
6237ae0e2c9SDimitry Andric 
6247ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
6257ae0e2c9SDimitry Andric     CodeGenOptions::TLSModel M) {
6267ae0e2c9SDimitry Andric   switch (M) {
6277ae0e2c9SDimitry Andric   case CodeGenOptions::GeneralDynamicTLSModel:
6287ae0e2c9SDimitry Andric     return llvm::GlobalVariable::GeneralDynamicTLSModel;
6297ae0e2c9SDimitry Andric   case CodeGenOptions::LocalDynamicTLSModel:
6307ae0e2c9SDimitry Andric     return llvm::GlobalVariable::LocalDynamicTLSModel;
6317ae0e2c9SDimitry Andric   case CodeGenOptions::InitialExecTLSModel:
6327ae0e2c9SDimitry Andric     return llvm::GlobalVariable::InitialExecTLSModel;
6337ae0e2c9SDimitry Andric   case CodeGenOptions::LocalExecTLSModel:
6347ae0e2c9SDimitry Andric     return llvm::GlobalVariable::LocalExecTLSModel;
6357ae0e2c9SDimitry Andric   }
6367ae0e2c9SDimitry Andric   llvm_unreachable("Invalid TLS model!");
6377ae0e2c9SDimitry Andric }
6387ae0e2c9SDimitry Andric 
63939d628a0SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
640284c1978SDimitry Andric   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
6417ae0e2c9SDimitry Andric 
64239d628a0SDimitry Andric   llvm::GlobalValue::ThreadLocalMode TLM;
6433861d79fSDimitry Andric   TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
6447ae0e2c9SDimitry Andric 
6457ae0e2c9SDimitry Andric   // Override the TLS model if it is explicitly specified.
64659d1ed5bSDimitry Andric   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
6477ae0e2c9SDimitry Andric     TLM = GetLLVMTLSModel(Attr->getModel());
6487ae0e2c9SDimitry Andric   }
6497ae0e2c9SDimitry Andric 
6507ae0e2c9SDimitry Andric   GV->setThreadLocalMode(TLM);
6517ae0e2c9SDimitry Andric }
6527ae0e2c9SDimitry Andric 
6536122f3e6SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
654444ed5c5SDimitry Andric   GlobalDecl CanonicalGD = GD.getCanonicalDecl();
655444ed5c5SDimitry Andric 
656444ed5c5SDimitry Andric   // Some ABIs don't have constructor variants.  Make sure that base and
657444ed5c5SDimitry Andric   // complete constructors get mangled the same.
658444ed5c5SDimitry Andric   if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
659444ed5c5SDimitry Andric     if (!getTarget().getCXXABI().hasConstructorVariants()) {
660444ed5c5SDimitry Andric       CXXCtorType OrigCtorType = GD.getCtorType();
661444ed5c5SDimitry Andric       assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
662444ed5c5SDimitry Andric       if (OrigCtorType == Ctor_Base)
663444ed5c5SDimitry Andric         CanonicalGD = GlobalDecl(CD, Ctor_Complete);
664444ed5c5SDimitry Andric     }
665444ed5c5SDimitry Andric   }
666444ed5c5SDimitry Andric 
667444ed5c5SDimitry Andric   StringRef &FoundStr = MangledDeclNames[CanonicalGD];
66859d1ed5bSDimitry Andric   if (!FoundStr.empty())
66959d1ed5bSDimitry Andric     return FoundStr;
670f22ef01cSRoman Divacky 
67159d1ed5bSDimitry Andric   const auto *ND = cast<NamedDecl>(GD.getDecl());
672dff0c46cSDimitry Andric   SmallString<256> Buffer;
67359d1ed5bSDimitry Andric   StringRef Str;
67459d1ed5bSDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
6752754fe60SDimitry Andric     llvm::raw_svector_ostream Out(Buffer);
67659d1ed5bSDimitry Andric     if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
6772754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
67859d1ed5bSDimitry Andric     else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
6792754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
680ffd1746dSEd Schouten     else
6812754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleName(ND, Out);
68259d1ed5bSDimitry Andric     Str = Out.str();
68359d1ed5bSDimitry Andric   } else {
68459d1ed5bSDimitry Andric     IdentifierInfo *II = ND->getIdentifier();
68559d1ed5bSDimitry Andric     assert(II && "Attempt to mangle unnamed decl.");
68644290647SDimitry Andric     const auto *FD = dyn_cast<FunctionDecl>(ND);
68744290647SDimitry Andric 
68844290647SDimitry Andric     if (FD &&
68944290647SDimitry Andric         FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
69044290647SDimitry Andric       llvm::raw_svector_ostream Out(Buffer);
69144290647SDimitry Andric       Out << "__regcall3__" << II->getName();
69244290647SDimitry Andric       Str = Out.str();
69344290647SDimitry Andric     } else {
69459d1ed5bSDimitry Andric       Str = II->getName();
695ffd1746dSEd Schouten     }
69644290647SDimitry Andric   }
697ffd1746dSEd Schouten 
69839d628a0SDimitry Andric   // Keep the first result in the case of a mangling collision.
69939d628a0SDimitry Andric   auto Result = Manglings.insert(std::make_pair(Str, GD));
70039d628a0SDimitry Andric   return FoundStr = Result.first->first();
70159d1ed5bSDimitry Andric }
70259d1ed5bSDimitry Andric 
70359d1ed5bSDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
704ffd1746dSEd Schouten                                              const BlockDecl *BD) {
7052754fe60SDimitry Andric   MangleContext &MangleCtx = getCXXABI().getMangleContext();
7062754fe60SDimitry Andric   const Decl *D = GD.getDecl();
70759d1ed5bSDimitry Andric 
70859d1ed5bSDimitry Andric   SmallString<256> Buffer;
70959d1ed5bSDimitry Andric   llvm::raw_svector_ostream Out(Buffer);
71059d1ed5bSDimitry Andric   if (!D)
7117ae0e2c9SDimitry Andric     MangleCtx.mangleGlobalBlock(BD,
7127ae0e2c9SDimitry Andric       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
71359d1ed5bSDimitry Andric   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
7142754fe60SDimitry Andric     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
71559d1ed5bSDimitry Andric   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
7162754fe60SDimitry Andric     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
7172754fe60SDimitry Andric   else
7182754fe60SDimitry Andric     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
71959d1ed5bSDimitry Andric 
72039d628a0SDimitry Andric   auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
72139d628a0SDimitry Andric   return Result.first->first();
722f22ef01cSRoman Divacky }
723f22ef01cSRoman Divacky 
7246122f3e6SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
725f22ef01cSRoman Divacky   return getModule().getNamedValue(Name);
726f22ef01cSRoman Divacky }
727f22ef01cSRoman Divacky 
728f22ef01cSRoman Divacky /// AddGlobalCtor - Add a function to the list that will be called before
729f22ef01cSRoman Divacky /// main() runs.
73059d1ed5bSDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
73159d1ed5bSDimitry Andric                                   llvm::Constant *AssociatedData) {
732f22ef01cSRoman Divacky   // FIXME: Type coercion of void()* types.
73359d1ed5bSDimitry Andric   GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
734f22ef01cSRoman Divacky }
735f22ef01cSRoman Divacky 
736f22ef01cSRoman Divacky /// AddGlobalDtor - Add a function to the list that will be called
737f22ef01cSRoman Divacky /// when the module is unloaded.
738f22ef01cSRoman Divacky void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
739f22ef01cSRoman Divacky   // FIXME: Type coercion of void()* types.
74059d1ed5bSDimitry Andric   GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
741f22ef01cSRoman Divacky }
742f22ef01cSRoman Divacky 
74344290647SDimitry Andric void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
74444290647SDimitry Andric   if (Fns.empty()) return;
74544290647SDimitry Andric 
746f22ef01cSRoman Divacky   // Ctor function type is void()*.
747bd5abe19SDimitry Andric   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
748f22ef01cSRoman Divacky   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
749f22ef01cSRoman Divacky 
75059d1ed5bSDimitry Andric   // Get the type of a ctor entry, { i32, void ()*, i8* }.
75159d1ed5bSDimitry Andric   llvm::StructType *CtorStructTy = llvm::StructType::get(
75239d628a0SDimitry Andric       Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr);
753f22ef01cSRoman Divacky 
754f22ef01cSRoman Divacky   // Construct the constructor and destructor arrays.
75544290647SDimitry Andric   ConstantInitBuilder builder(*this);
75644290647SDimitry Andric   auto ctors = builder.beginArray(CtorStructTy);
7578f0fd8f6SDimitry Andric   for (const auto &I : Fns) {
75844290647SDimitry Andric     auto ctor = ctors.beginStruct(CtorStructTy);
75944290647SDimitry Andric     ctor.addInt(Int32Ty, I.Priority);
76044290647SDimitry Andric     ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
76144290647SDimitry Andric     if (I.AssociatedData)
76244290647SDimitry Andric       ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
76344290647SDimitry Andric     else
76444290647SDimitry Andric       ctor.addNullPointer(VoidPtrTy);
76544290647SDimitry Andric     ctor.finishAndAddTo(ctors);
766f22ef01cSRoman Divacky   }
767f22ef01cSRoman Divacky 
76844290647SDimitry Andric   auto list =
76944290647SDimitry Andric     ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
77044290647SDimitry Andric                                 /*constant*/ false,
77144290647SDimitry Andric                                 llvm::GlobalValue::AppendingLinkage);
77244290647SDimitry Andric 
77344290647SDimitry Andric   // The LTO linker doesn't seem to like it when we set an alignment
77444290647SDimitry Andric   // on appending variables.  Take it off as a workaround.
77544290647SDimitry Andric   list->setAlignment(0);
77644290647SDimitry Andric 
77744290647SDimitry Andric   Fns.clear();
778f22ef01cSRoman Divacky }
779f22ef01cSRoman Divacky 
780f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes
781f785676fSDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
78259d1ed5bSDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
783f785676fSDimitry Andric 
784e580952dSDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
785f22ef01cSRoman Divacky 
78659d1ed5bSDimitry Andric   if (isa<CXXDestructorDecl>(D) &&
78759d1ed5bSDimitry Andric       getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
78859d1ed5bSDimitry Andric                                          GD.getDtorType())) {
78959d1ed5bSDimitry Andric     // Destructor variants in the Microsoft C++ ABI are always internal or
79059d1ed5bSDimitry Andric     // linkonce_odr thunks emitted on an as-needed basis.
79159d1ed5bSDimitry Andric     return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
79259d1ed5bSDimitry Andric                                    : llvm::GlobalValue::LinkOnceODRLinkage;
793f22ef01cSRoman Divacky   }
794f22ef01cSRoman Divacky 
795e7145dcbSDimitry Andric   if (isa<CXXConstructorDecl>(D) &&
796e7145dcbSDimitry Andric       cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
797e7145dcbSDimitry Andric       Context.getTargetInfo().getCXXABI().isMicrosoft()) {
798e7145dcbSDimitry Andric     // Our approach to inheriting constructors is fundamentally different from
799e7145dcbSDimitry Andric     // that used by the MS ABI, so keep our inheriting constructor thunks
800e7145dcbSDimitry Andric     // internal rather than trying to pick an unambiguous mangling for them.
801e7145dcbSDimitry Andric     return llvm::GlobalValue::InternalLinkage;
802e7145dcbSDimitry Andric   }
803e7145dcbSDimitry Andric 
80459d1ed5bSDimitry Andric   return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
80559d1ed5bSDimitry Andric }
806f22ef01cSRoman Divacky 
80797bc6c73SDimitry Andric void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
80897bc6c73SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
80997bc6c73SDimitry Andric 
81097bc6c73SDimitry Andric   if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
81197bc6c73SDimitry Andric     if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
81297bc6c73SDimitry Andric       // Don't dllexport/import destructor thunks.
81397bc6c73SDimitry Andric       F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
81497bc6c73SDimitry Andric       return;
81597bc6c73SDimitry Andric     }
81697bc6c73SDimitry Andric   }
81797bc6c73SDimitry Andric 
81897bc6c73SDimitry Andric   if (FD->hasAttr<DLLImportAttr>())
81997bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
82097bc6c73SDimitry Andric   else if (FD->hasAttr<DLLExportAttr>())
82197bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
82297bc6c73SDimitry Andric   else
82397bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
82497bc6c73SDimitry Andric }
82597bc6c73SDimitry Andric 
826e7145dcbSDimitry Andric llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
8270623d748SDimitry Andric   llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
8280623d748SDimitry Andric   if (!MDS) return nullptr;
8290623d748SDimitry Andric 
83044290647SDimitry Andric   return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
8310623d748SDimitry Andric }
8320623d748SDimitry Andric 
83359d1ed5bSDimitry Andric void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
83459d1ed5bSDimitry Andric                                                     llvm::Function *F) {
83559d1ed5bSDimitry Andric   setNonAliasAttributes(D, F);
836f22ef01cSRoman Divacky }
837f22ef01cSRoman Divacky 
838f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
839f22ef01cSRoman Divacky                                               const CGFunctionInfo &Info,
840f22ef01cSRoman Divacky                                               llvm::Function *F) {
841f22ef01cSRoman Divacky   unsigned CallingConv;
842f22ef01cSRoman Divacky   AttributeListType AttributeList;
843ea942507SDimitry Andric   ConstructAttributeList(F->getName(), Info, D, AttributeList, CallingConv,
844ea942507SDimitry Andric                          false);
84520e90f04SDimitry Andric   F->setAttributes(llvm::AttributeList::get(getLLVMContext(), AttributeList));
846f22ef01cSRoman Divacky   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
847f22ef01cSRoman Divacky }
848f22ef01cSRoman Divacky 
8496122f3e6SDimitry Andric /// Determines whether the language options require us to model
8506122f3e6SDimitry Andric /// unwind exceptions.  We treat -fexceptions as mandating this
8516122f3e6SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions
8526122f3e6SDimitry Andric /// enabled.  This means, for example, that C with -fexceptions
8536122f3e6SDimitry Andric /// enables this.
854dff0c46cSDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) {
8556122f3e6SDimitry Andric   // If exceptions are completely disabled, obviously this is false.
856dff0c46cSDimitry Andric   if (!LangOpts.Exceptions) return false;
8576122f3e6SDimitry Andric 
8586122f3e6SDimitry Andric   // If C++ exceptions are enabled, this is true.
859dff0c46cSDimitry Andric   if (LangOpts.CXXExceptions) return true;
8606122f3e6SDimitry Andric 
8616122f3e6SDimitry Andric   // If ObjC exceptions are enabled, this depends on the ABI.
862dff0c46cSDimitry Andric   if (LangOpts.ObjCExceptions) {
8637ae0e2c9SDimitry Andric     return LangOpts.ObjCRuntime.hasUnwindExceptions();
8646122f3e6SDimitry Andric   }
8656122f3e6SDimitry Andric 
8666122f3e6SDimitry Andric   return true;
8676122f3e6SDimitry Andric }
8686122f3e6SDimitry Andric 
869f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
870f22ef01cSRoman Divacky                                                            llvm::Function *F) {
871f785676fSDimitry Andric   llvm::AttrBuilder B;
872f785676fSDimitry Andric 
873bd5abe19SDimitry Andric   if (CodeGenOpts.UnwindTables)
874f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::UWTable);
875bd5abe19SDimitry Andric 
876dff0c46cSDimitry Andric   if (!hasUnwindExceptions(LangOpts))
877f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoUnwind);
878f22ef01cSRoman Divacky 
8790623d748SDimitry Andric   if (LangOpts.getStackProtector() == LangOptions::SSPOn)
8800623d748SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtect);
8810623d748SDimitry Andric   else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
8820623d748SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtectStrong);
8830623d748SDimitry Andric   else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
8840623d748SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtectReq);
8850623d748SDimitry Andric 
8860623d748SDimitry Andric   if (!D) {
88744290647SDimitry Andric     // If we don't have a declaration to control inlining, the function isn't
88844290647SDimitry Andric     // explicitly marked as alwaysinline for semantic reasons, and inlining is
88944290647SDimitry Andric     // disabled, mark the function as noinline.
89044290647SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
89144290647SDimitry Andric         CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
89244290647SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
89344290647SDimitry Andric 
89420e90f04SDimitry Andric     F->addAttributes(
89520e90f04SDimitry Andric         llvm::AttributeList::FunctionIndex,
89620e90f04SDimitry Andric         llvm::AttributeList::get(F->getContext(),
89720e90f04SDimitry Andric                                  llvm::AttributeList::FunctionIndex, B));
8980623d748SDimitry Andric     return;
8990623d748SDimitry Andric   }
9000623d748SDimitry Andric 
90144290647SDimitry Andric   if (D->hasAttr<OptimizeNoneAttr>()) {
90244290647SDimitry Andric     B.addAttribute(llvm::Attribute::OptimizeNone);
90344290647SDimitry Andric 
90444290647SDimitry Andric     // OptimizeNone implies noinline; we should not be inlining such functions.
90544290647SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
90644290647SDimitry Andric     assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
90744290647SDimitry Andric            "OptimizeNone and AlwaysInline on same function!");
90844290647SDimitry Andric 
90944290647SDimitry Andric     // We still need to handle naked functions even though optnone subsumes
91044290647SDimitry Andric     // much of their semantics.
91144290647SDimitry Andric     if (D->hasAttr<NakedAttr>())
91244290647SDimitry Andric       B.addAttribute(llvm::Attribute::Naked);
91344290647SDimitry Andric 
91444290647SDimitry Andric     // OptimizeNone wins over OptimizeForSize and MinSize.
91544290647SDimitry Andric     F->removeFnAttr(llvm::Attribute::OptimizeForSize);
91644290647SDimitry Andric     F->removeFnAttr(llvm::Attribute::MinSize);
91744290647SDimitry Andric   } else if (D->hasAttr<NakedAttr>()) {
9186122f3e6SDimitry Andric     // Naked implies noinline: we should not be inlining such functions.
919f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::Naked);
920f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
92159d1ed5bSDimitry Andric   } else if (D->hasAttr<NoDuplicateAttr>()) {
92259d1ed5bSDimitry Andric     B.addAttribute(llvm::Attribute::NoDuplicate);
923f785676fSDimitry Andric   } else if (D->hasAttr<NoInlineAttr>()) {
924f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
92559d1ed5bSDimitry Andric   } else if (D->hasAttr<AlwaysInlineAttr>() &&
92644290647SDimitry Andric              !F->hasFnAttribute(llvm::Attribute::NoInline)) {
927f785676fSDimitry Andric     // (noinline wins over always_inline, and we can't specify both in IR)
928f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::AlwaysInline);
92944290647SDimitry Andric   } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
93044290647SDimitry Andric     // If we're not inlining, then force everything that isn't always_inline to
93144290647SDimitry Andric     // carry an explicit noinline attribute.
93244290647SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
93344290647SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
93444290647SDimitry Andric   } else {
93544290647SDimitry Andric     // Otherwise, propagate the inline hint attribute and potentially use its
93644290647SDimitry Andric     // absence to mark things as noinline.
93744290647SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
93844290647SDimitry Andric       if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
93944290647SDimitry Andric             return Redecl->isInlineSpecified();
94044290647SDimitry Andric           })) {
94144290647SDimitry Andric         B.addAttribute(llvm::Attribute::InlineHint);
94244290647SDimitry Andric       } else if (CodeGenOpts.getInlining() ==
94344290647SDimitry Andric                      CodeGenOptions::OnlyHintInlining &&
94444290647SDimitry Andric                  !FD->isInlined() &&
94544290647SDimitry Andric                  !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
94644290647SDimitry Andric         B.addAttribute(llvm::Attribute::NoInline);
94744290647SDimitry Andric       }
94844290647SDimitry Andric     }
9496122f3e6SDimitry Andric   }
9502754fe60SDimitry Andric 
95144290647SDimitry Andric   // Add other optimization related attributes if we are optimizing this
95244290647SDimitry Andric   // function.
95344290647SDimitry Andric   if (!D->hasAttr<OptimizeNoneAttr>()) {
954f785676fSDimitry Andric     if (D->hasAttr<ColdAttr>()) {
955f785676fSDimitry Andric       B.addAttribute(llvm::Attribute::OptimizeForSize);
956f785676fSDimitry Andric       B.addAttribute(llvm::Attribute::Cold);
957f785676fSDimitry Andric     }
9583861d79fSDimitry Andric 
9593861d79fSDimitry Andric     if (D->hasAttr<MinSizeAttr>())
960f785676fSDimitry Andric       B.addAttribute(llvm::Attribute::MinSize);
96144290647SDimitry Andric   }
962f22ef01cSRoman Divacky 
96320e90f04SDimitry Andric   F->addAttributes(llvm::AttributeList::FunctionIndex,
96420e90f04SDimitry Andric                    llvm::AttributeList::get(
96520e90f04SDimitry Andric                        F->getContext(), llvm::AttributeList::FunctionIndex, B));
966f785676fSDimitry Andric 
967e580952dSDimitry Andric   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
968e580952dSDimitry Andric   if (alignment)
969e580952dSDimitry Andric     F->setAlignment(alignment);
970e580952dSDimitry Andric 
9710623d748SDimitry Andric   // Some C++ ABIs require 2-byte alignment for member functions, in order to
9720623d748SDimitry Andric   // reserve a bit for differentiating between virtual and non-virtual member
9730623d748SDimitry Andric   // functions. If the current target's C++ ABI requires this and this is a
9740623d748SDimitry Andric   // member function, set its alignment accordingly.
9750623d748SDimitry Andric   if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
976f22ef01cSRoman Divacky     if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
977f22ef01cSRoman Divacky       F->setAlignment(2);
978f22ef01cSRoman Divacky   }
97944290647SDimitry Andric 
98044290647SDimitry Andric   // In the cross-dso CFI mode, we want !type attributes on definitions only.
98144290647SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
98244290647SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D))
98344290647SDimitry Andric       CreateFunctionTypeMetadata(FD, F);
9840623d748SDimitry Andric }
985f22ef01cSRoman Divacky 
986f22ef01cSRoman Divacky void CodeGenModule::SetCommonAttributes(const Decl *D,
987f22ef01cSRoman Divacky                                         llvm::GlobalValue *GV) {
9880623d748SDimitry Andric   if (const auto *ND = dyn_cast_or_null<NamedDecl>(D))
9892754fe60SDimitry Andric     setGlobalVisibility(GV, ND);
9902754fe60SDimitry Andric   else
9912754fe60SDimitry Andric     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
992f22ef01cSRoman Divacky 
9930623d748SDimitry Andric   if (D && D->hasAttr<UsedAttr>())
99459d1ed5bSDimitry Andric     addUsedGlobal(GV);
99559d1ed5bSDimitry Andric }
99659d1ed5bSDimitry Andric 
99739d628a0SDimitry Andric void CodeGenModule::setAliasAttributes(const Decl *D,
99839d628a0SDimitry Andric                                        llvm::GlobalValue *GV) {
99939d628a0SDimitry Andric   SetCommonAttributes(D, GV);
100039d628a0SDimitry Andric 
100139d628a0SDimitry Andric   // Process the dllexport attribute based on whether the original definition
100239d628a0SDimitry Andric   // (not necessarily the aliasee) was exported.
100339d628a0SDimitry Andric   if (D->hasAttr<DLLExportAttr>())
100439d628a0SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
100539d628a0SDimitry Andric }
100639d628a0SDimitry Andric 
100759d1ed5bSDimitry Andric void CodeGenModule::setNonAliasAttributes(const Decl *D,
100859d1ed5bSDimitry Andric                                           llvm::GlobalObject *GO) {
100959d1ed5bSDimitry Andric   SetCommonAttributes(D, GO);
1010f22ef01cSRoman Divacky 
10110623d748SDimitry Andric   if (D)
1012f22ef01cSRoman Divacky     if (const SectionAttr *SA = D->getAttr<SectionAttr>())
101359d1ed5bSDimitry Andric       GO->setSection(SA->getName());
1014f22ef01cSRoman Divacky 
101597bc6c73SDimitry Andric   getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
1016f22ef01cSRoman Divacky }
1017f22ef01cSRoman Divacky 
1018f22ef01cSRoman Divacky void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
1019f22ef01cSRoman Divacky                                                   llvm::Function *F,
1020f22ef01cSRoman Divacky                                                   const CGFunctionInfo &FI) {
1021f22ef01cSRoman Divacky   SetLLVMFunctionAttributes(D, FI, F);
1022f22ef01cSRoman Divacky   SetLLVMFunctionAttributesForDefinition(D, F);
1023f22ef01cSRoman Divacky 
1024f22ef01cSRoman Divacky   F->setLinkage(llvm::Function::InternalLinkage);
1025f22ef01cSRoman Divacky 
102659d1ed5bSDimitry Andric   setNonAliasAttributes(D, F);
102759d1ed5bSDimitry Andric }
102859d1ed5bSDimitry Andric 
102959d1ed5bSDimitry Andric static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
103059d1ed5bSDimitry Andric                                          const NamedDecl *ND) {
103159d1ed5bSDimitry Andric   // Set linkage and visibility in case we never see a definition.
103259d1ed5bSDimitry Andric   LinkageInfo LV = ND->getLinkageAndVisibility();
103359d1ed5bSDimitry Andric   if (LV.getLinkage() != ExternalLinkage) {
103459d1ed5bSDimitry Andric     // Don't set internal linkage on declarations.
103559d1ed5bSDimitry Andric   } else {
103659d1ed5bSDimitry Andric     if (ND->hasAttr<DLLImportAttr>()) {
103759d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
103859d1ed5bSDimitry Andric       GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
103959d1ed5bSDimitry Andric     } else if (ND->hasAttr<DLLExportAttr>()) {
104059d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
104159d1ed5bSDimitry Andric     } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
104259d1ed5bSDimitry Andric       // "extern_weak" is overloaded in LLVM; we probably should have
104359d1ed5bSDimitry Andric       // separate linkage types for this.
104459d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
104559d1ed5bSDimitry Andric     }
104659d1ed5bSDimitry Andric 
104759d1ed5bSDimitry Andric     // Set visibility on a declaration only if it's explicit.
104859d1ed5bSDimitry Andric     if (LV.isVisibilityExplicit())
104959d1ed5bSDimitry Andric       GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
105059d1ed5bSDimitry Andric   }
1051f22ef01cSRoman Divacky }
1052f22ef01cSRoman Divacky 
1053e7145dcbSDimitry Andric void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD,
10540623d748SDimitry Andric                                                llvm::Function *F) {
10550623d748SDimitry Andric   // Only if we are checking indirect calls.
10560623d748SDimitry Andric   if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
10570623d748SDimitry Andric     return;
10580623d748SDimitry Andric 
10590623d748SDimitry Andric   // Non-static class methods are handled via vtable pointer checks elsewhere.
10600623d748SDimitry Andric   if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
10610623d748SDimitry Andric     return;
10620623d748SDimitry Andric 
10630623d748SDimitry Andric   // Additionally, if building with cross-DSO support...
10640623d748SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
10650623d748SDimitry Andric     // Skip available_externally functions. They won't be codegen'ed in the
10660623d748SDimitry Andric     // current module anyway.
10670623d748SDimitry Andric     if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
10680623d748SDimitry Andric       return;
10690623d748SDimitry Andric   }
10700623d748SDimitry Andric 
10710623d748SDimitry Andric   llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
1072e7145dcbSDimitry Andric   F->addTypeMetadata(0, MD);
10730623d748SDimitry Andric 
10740623d748SDimitry Andric   // Emit a hash-based bit set entry for cross-DSO calls.
1075e7145dcbSDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
1076e7145dcbSDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1077e7145dcbSDimitry Andric       F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
10780623d748SDimitry Andric }
10790623d748SDimitry Andric 
108039d628a0SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
108139d628a0SDimitry Andric                                           bool IsIncompleteFunction,
108239d628a0SDimitry Andric                                           bool IsThunk) {
108333956c43SDimitry Andric   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
10843b0f4066SDimitry Andric     // If this is an intrinsic function, set the function's attributes
10853b0f4066SDimitry Andric     // to the intrinsic's attributes.
108633956c43SDimitry Andric     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
10873b0f4066SDimitry Andric     return;
10883b0f4066SDimitry Andric   }
10893b0f4066SDimitry Andric 
109059d1ed5bSDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
1091f22ef01cSRoman Divacky 
1092f22ef01cSRoman Divacky   if (!IsIncompleteFunction)
1093dff0c46cSDimitry Andric     SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
1094f22ef01cSRoman Divacky 
109559d1ed5bSDimitry Andric   // Add the Returned attribute for "this", except for iOS 5 and earlier
109659d1ed5bSDimitry Andric   // where substantial code, including the libstdc++ dylib, was compiled with
109759d1ed5bSDimitry Andric   // GCC and does not actually return "this".
109839d628a0SDimitry Andric   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
109944290647SDimitry Andric       !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
1100f785676fSDimitry Andric     assert(!F->arg_empty() &&
1101f785676fSDimitry Andric            F->arg_begin()->getType()
1102f785676fSDimitry Andric              ->canLosslesslyBitCastTo(F->getReturnType()) &&
1103f785676fSDimitry Andric            "unexpected this return");
1104f785676fSDimitry Andric     F->addAttribute(1, llvm::Attribute::Returned);
1105f785676fSDimitry Andric   }
1106f785676fSDimitry Andric 
1107f22ef01cSRoman Divacky   // Only a few attributes are set on declarations; these may later be
1108f22ef01cSRoman Divacky   // overridden by a definition.
1109f22ef01cSRoman Divacky 
111059d1ed5bSDimitry Andric   setLinkageAndVisibilityForGV(F, FD);
11112754fe60SDimitry Andric 
1112f22ef01cSRoman Divacky   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
1113f22ef01cSRoman Divacky     F->setSection(SA->getName());
1114f785676fSDimitry Andric 
1115e7145dcbSDimitry Andric   if (FD->isReplaceableGlobalAllocationFunction()) {
1116f785676fSDimitry Andric     // A replaceable global allocation function does not act like a builtin by
1117f785676fSDimitry Andric     // default, only if it is invoked by a new-expression or delete-expression.
111820e90f04SDimitry Andric     F->addAttribute(llvm::AttributeList::FunctionIndex,
1119f785676fSDimitry Andric                     llvm::Attribute::NoBuiltin);
11200623d748SDimitry Andric 
1121e7145dcbSDimitry Andric     // A sane operator new returns a non-aliasing pointer.
1122e7145dcbSDimitry Andric     // FIXME: Also add NonNull attribute to the return value
1123e7145dcbSDimitry Andric     // for the non-nothrow forms?
1124e7145dcbSDimitry Andric     auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1125e7145dcbSDimitry Andric     if (getCodeGenOpts().AssumeSaneOperatorNew &&
1126e7145dcbSDimitry Andric         (Kind == OO_New || Kind == OO_Array_New))
112720e90f04SDimitry Andric       F->addAttribute(llvm::AttributeList::ReturnIndex,
1128e7145dcbSDimitry Andric                       llvm::Attribute::NoAlias);
1129e7145dcbSDimitry Andric   }
1130e7145dcbSDimitry Andric 
1131e7145dcbSDimitry Andric   if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1132e7145dcbSDimitry Andric     F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1133e7145dcbSDimitry Andric   else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1134e7145dcbSDimitry Andric     if (MD->isVirtual())
1135e7145dcbSDimitry Andric       F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1136e7145dcbSDimitry Andric 
113744290647SDimitry Andric   // Don't emit entries for function declarations in the cross-DSO mode. This
113844290647SDimitry Andric   // is handled with better precision by the receiving DSO.
113944290647SDimitry Andric   if (!CodeGenOpts.SanitizeCfiCrossDso)
1140e7145dcbSDimitry Andric     CreateFunctionTypeMetadata(FD, F);
1141f22ef01cSRoman Divacky }
1142f22ef01cSRoman Divacky 
114359d1ed5bSDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
1144f22ef01cSRoman Divacky   assert(!GV->isDeclaration() &&
1145f22ef01cSRoman Divacky          "Only globals with definition can force usage.");
114697bc6c73SDimitry Andric   LLVMUsed.emplace_back(GV);
1147f22ef01cSRoman Divacky }
1148f22ef01cSRoman Divacky 
114959d1ed5bSDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
115059d1ed5bSDimitry Andric   assert(!GV->isDeclaration() &&
115159d1ed5bSDimitry Andric          "Only globals with definition can force usage.");
115297bc6c73SDimitry Andric   LLVMCompilerUsed.emplace_back(GV);
115359d1ed5bSDimitry Andric }
115459d1ed5bSDimitry Andric 
115559d1ed5bSDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name,
115659d1ed5bSDimitry Andric                      std::vector<llvm::WeakVH> &List) {
1157f22ef01cSRoman Divacky   // Don't create llvm.used if there is no need.
115859d1ed5bSDimitry Andric   if (List.empty())
1159f22ef01cSRoman Divacky     return;
1160f22ef01cSRoman Divacky 
116159d1ed5bSDimitry Andric   // Convert List to what ConstantArray needs.
1162dff0c46cSDimitry Andric   SmallVector<llvm::Constant*, 8> UsedArray;
116359d1ed5bSDimitry Andric   UsedArray.resize(List.size());
116459d1ed5bSDimitry Andric   for (unsigned i = 0, e = List.size(); i != e; ++i) {
1165f22ef01cSRoman Divacky     UsedArray[i] =
116644f7b0dcSDimitry Andric         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
116744f7b0dcSDimitry Andric             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
1168f22ef01cSRoman Divacky   }
1169f22ef01cSRoman Divacky 
1170f22ef01cSRoman Divacky   if (UsedArray.empty())
1171f22ef01cSRoman Divacky     return;
117259d1ed5bSDimitry Andric   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
1173f22ef01cSRoman Divacky 
117459d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
117559d1ed5bSDimitry Andric       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
117659d1ed5bSDimitry Andric       llvm::ConstantArray::get(ATy, UsedArray), Name);
1177f22ef01cSRoman Divacky 
1178f22ef01cSRoman Divacky   GV->setSection("llvm.metadata");
1179f22ef01cSRoman Divacky }
1180f22ef01cSRoman Divacky 
118159d1ed5bSDimitry Andric void CodeGenModule::emitLLVMUsed() {
118259d1ed5bSDimitry Andric   emitUsed(*this, "llvm.used", LLVMUsed);
118359d1ed5bSDimitry Andric   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
118459d1ed5bSDimitry Andric }
118559d1ed5bSDimitry Andric 
1186f785676fSDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
118739d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
1188f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1189f785676fSDimitry Andric }
1190f785676fSDimitry Andric 
1191f785676fSDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1192f785676fSDimitry Andric   llvm::SmallString<32> Opt;
1193f785676fSDimitry Andric   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
119439d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1195f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1196f785676fSDimitry Andric }
1197f785676fSDimitry Andric 
1198f785676fSDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) {
1199f785676fSDimitry Andric   llvm::SmallString<24> Opt;
1200f785676fSDimitry Andric   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
120139d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1202f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1203f785676fSDimitry Andric }
1204f785676fSDimitry Andric 
1205139f7f9bSDimitry Andric /// \brief Add link options implied by the given module, including modules
1206139f7f9bSDimitry Andric /// it depends on, using a postorder walk.
120739d628a0SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
120839d628a0SDimitry Andric                                     SmallVectorImpl<llvm::Metadata *> &Metadata,
1209139f7f9bSDimitry Andric                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
1210139f7f9bSDimitry Andric   // Import this module's parent.
121139d628a0SDimitry Andric   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
1212f785676fSDimitry Andric     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
1213139f7f9bSDimitry Andric   }
1214139f7f9bSDimitry Andric 
1215139f7f9bSDimitry Andric   // Import this module's dependencies.
1216139f7f9bSDimitry Andric   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
121739d628a0SDimitry Andric     if (Visited.insert(Mod->Imports[I - 1]).second)
1218f785676fSDimitry Andric       addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
1219139f7f9bSDimitry Andric   }
1220139f7f9bSDimitry Andric 
1221139f7f9bSDimitry Andric   // Add linker options to link against the libraries/frameworks
1222139f7f9bSDimitry Andric   // described by this module.
1223f785676fSDimitry Andric   llvm::LLVMContext &Context = CGM.getLLVMContext();
1224139f7f9bSDimitry Andric   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
1225f785676fSDimitry Andric     // Link against a framework.  Frameworks are currently Darwin only, so we
1226f785676fSDimitry Andric     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
1227139f7f9bSDimitry Andric     if (Mod->LinkLibraries[I-1].IsFramework) {
122839d628a0SDimitry Andric       llvm::Metadata *Args[2] = {
1229139f7f9bSDimitry Andric           llvm::MDString::get(Context, "-framework"),
123039d628a0SDimitry Andric           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1231139f7f9bSDimitry Andric 
1232139f7f9bSDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, Args));
1233139f7f9bSDimitry Andric       continue;
1234139f7f9bSDimitry Andric     }
1235139f7f9bSDimitry Andric 
1236139f7f9bSDimitry Andric     // Link against a library.
1237f785676fSDimitry Andric     llvm::SmallString<24> Opt;
1238f785676fSDimitry Andric     CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1239f785676fSDimitry Andric       Mod->LinkLibraries[I-1].Library, Opt);
124039d628a0SDimitry Andric     auto *OptString = llvm::MDString::get(Context, Opt);
1241139f7f9bSDimitry Andric     Metadata.push_back(llvm::MDNode::get(Context, OptString));
1242139f7f9bSDimitry Andric   }
1243139f7f9bSDimitry Andric }
1244139f7f9bSDimitry Andric 
1245139f7f9bSDimitry Andric void CodeGenModule::EmitModuleLinkOptions() {
1246139f7f9bSDimitry Andric   // Collect the set of all of the modules we want to visit to emit link
1247139f7f9bSDimitry Andric   // options, which is essentially the imported modules and all of their
1248139f7f9bSDimitry Andric   // non-explicit child modules.
1249139f7f9bSDimitry Andric   llvm::SetVector<clang::Module *> LinkModules;
1250139f7f9bSDimitry Andric   llvm::SmallPtrSet<clang::Module *, 16> Visited;
1251139f7f9bSDimitry Andric   SmallVector<clang::Module *, 16> Stack;
1252139f7f9bSDimitry Andric 
1253139f7f9bSDimitry Andric   // Seed the stack with imported modules.
1254f1a29dd3SDimitry Andric   for (Module *M : ImportedModules) {
1255f1a29dd3SDimitry Andric     // Do not add any link flags when an implementation TU of a module imports
1256f1a29dd3SDimitry Andric     // a header of that same module.
1257f1a29dd3SDimitry Andric     if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
1258f1a29dd3SDimitry Andric         !getLangOpts().isCompilingModule())
1259f1a29dd3SDimitry Andric       continue;
12608f0fd8f6SDimitry Andric     if (Visited.insert(M).second)
12618f0fd8f6SDimitry Andric       Stack.push_back(M);
1262f1a29dd3SDimitry Andric   }
1263139f7f9bSDimitry Andric 
1264139f7f9bSDimitry Andric   // Find all of the modules to import, making a little effort to prune
1265139f7f9bSDimitry Andric   // non-leaf modules.
1266139f7f9bSDimitry Andric   while (!Stack.empty()) {
1267f785676fSDimitry Andric     clang::Module *Mod = Stack.pop_back_val();
1268139f7f9bSDimitry Andric 
1269139f7f9bSDimitry Andric     bool AnyChildren = false;
1270139f7f9bSDimitry Andric 
1271139f7f9bSDimitry Andric     // Visit the submodules of this module.
1272139f7f9bSDimitry Andric     for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1273139f7f9bSDimitry Andric                                         SubEnd = Mod->submodule_end();
1274139f7f9bSDimitry Andric          Sub != SubEnd; ++Sub) {
1275139f7f9bSDimitry Andric       // Skip explicit children; they need to be explicitly imported to be
1276139f7f9bSDimitry Andric       // linked against.
1277139f7f9bSDimitry Andric       if ((*Sub)->IsExplicit)
1278139f7f9bSDimitry Andric         continue;
1279139f7f9bSDimitry Andric 
128039d628a0SDimitry Andric       if (Visited.insert(*Sub).second) {
1281139f7f9bSDimitry Andric         Stack.push_back(*Sub);
1282139f7f9bSDimitry Andric         AnyChildren = true;
1283139f7f9bSDimitry Andric       }
1284139f7f9bSDimitry Andric     }
1285139f7f9bSDimitry Andric 
1286139f7f9bSDimitry Andric     // We didn't find any children, so add this module to the list of
1287139f7f9bSDimitry Andric     // modules to link against.
1288139f7f9bSDimitry Andric     if (!AnyChildren) {
1289139f7f9bSDimitry Andric       LinkModules.insert(Mod);
1290139f7f9bSDimitry Andric     }
1291139f7f9bSDimitry Andric   }
1292139f7f9bSDimitry Andric 
1293139f7f9bSDimitry Andric   // Add link options for all of the imported modules in reverse topological
1294f785676fSDimitry Andric   // order.  We don't do anything to try to order import link flags with respect
1295f785676fSDimitry Andric   // to linker options inserted by things like #pragma comment().
129639d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 16> MetadataArgs;
1297139f7f9bSDimitry Andric   Visited.clear();
12988f0fd8f6SDimitry Andric   for (Module *M : LinkModules)
12998f0fd8f6SDimitry Andric     if (Visited.insert(M).second)
13008f0fd8f6SDimitry Andric       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
1301139f7f9bSDimitry Andric   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1302f785676fSDimitry Andric   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1303139f7f9bSDimitry Andric 
1304139f7f9bSDimitry Andric   // Add the linker options metadata flag.
1305139f7f9bSDimitry Andric   getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
1306f785676fSDimitry Andric                             llvm::MDNode::get(getLLVMContext(),
1307f785676fSDimitry Andric                                               LinkerOptionsMetadata));
1308139f7f9bSDimitry Andric }
1309139f7f9bSDimitry Andric 
1310f22ef01cSRoman Divacky void CodeGenModule::EmitDeferred() {
1311f22ef01cSRoman Divacky   // Emit code for any potentially referenced deferred decls.  Since a
1312f22ef01cSRoman Divacky   // previously unused static decl may become used during the generation of code
1313f22ef01cSRoman Divacky   // for a static function, iterate until no changes are made.
1314f22ef01cSRoman Divacky 
1315f22ef01cSRoman Divacky   if (!DeferredVTables.empty()) {
1316139f7f9bSDimitry Andric     EmitDeferredVTables();
1317139f7f9bSDimitry Andric 
1318e7145dcbSDimitry Andric     // Emitting a vtable doesn't directly cause more vtables to
1319139f7f9bSDimitry Andric     // become deferred, although it can cause functions to be
1320e7145dcbSDimitry Andric     // emitted that then need those vtables.
1321139f7f9bSDimitry Andric     assert(DeferredVTables.empty());
1322f22ef01cSRoman Divacky   }
1323f22ef01cSRoman Divacky 
1324e7145dcbSDimitry Andric   // Stop if we're out of both deferred vtables and deferred declarations.
132533956c43SDimitry Andric   if (DeferredDeclsToEmit.empty())
132633956c43SDimitry Andric     return;
1327139f7f9bSDimitry Andric 
132833956c43SDimitry Andric   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
132933956c43SDimitry Andric   // work, it will not interfere with this.
133033956c43SDimitry Andric   std::vector<DeferredGlobal> CurDeclsToEmit;
133133956c43SDimitry Andric   CurDeclsToEmit.swap(DeferredDeclsToEmit);
133233956c43SDimitry Andric 
133333956c43SDimitry Andric   for (DeferredGlobal &G : CurDeclsToEmit) {
133459d1ed5bSDimitry Andric     GlobalDecl D = G.GD;
133533956c43SDimitry Andric     G.GV = nullptr;
1336f22ef01cSRoman Divacky 
13370623d748SDimitry Andric     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
13380623d748SDimitry Andric     // to get GlobalValue with exactly the type we need, not something that
13390623d748SDimitry Andric     // might had been created for another decl with the same mangled name but
13400623d748SDimitry Andric     // different type.
1341e7145dcbSDimitry Andric     llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
134244290647SDimitry Andric         GetAddrOfGlobal(D, ForDefinition));
1343e7145dcbSDimitry Andric 
1344e7145dcbSDimitry Andric     // In case of different address spaces, we may still get a cast, even with
1345e7145dcbSDimitry Andric     // IsForDefinition equal to true. Query mangled names table to get
1346e7145dcbSDimitry Andric     // GlobalValue.
134739d628a0SDimitry Andric     if (!GV)
134839d628a0SDimitry Andric       GV = GetGlobalValue(getMangledName(D));
134939d628a0SDimitry Andric 
1350e7145dcbSDimitry Andric     // Make sure GetGlobalValue returned non-null.
1351e7145dcbSDimitry Andric     assert(GV);
1352e7145dcbSDimitry Andric 
1353f22ef01cSRoman Divacky     // Check to see if we've already emitted this.  This is necessary
1354f22ef01cSRoman Divacky     // for a couple of reasons: first, decls can end up in the
1355f22ef01cSRoman Divacky     // deferred-decls queue multiple times, and second, decls can end
1356f22ef01cSRoman Divacky     // up with definitions in unusual ways (e.g. by an extern inline
1357f22ef01cSRoman Divacky     // function acquiring a strong function redefinition).  Just
1358f22ef01cSRoman Divacky     // ignore these cases.
1359e7145dcbSDimitry Andric     if (!GV->isDeclaration())
1360f22ef01cSRoman Divacky       continue;
1361f22ef01cSRoman Divacky 
1362f22ef01cSRoman Divacky     // Otherwise, emit the definition and move on to the next one.
136359d1ed5bSDimitry Andric     EmitGlobalDefinition(D, GV);
136433956c43SDimitry Andric 
136533956c43SDimitry Andric     // If we found out that we need to emit more decls, do that recursively.
136633956c43SDimitry Andric     // This has the advantage that the decls are emitted in a DFS and related
136733956c43SDimitry Andric     // ones are close together, which is convenient for testing.
136833956c43SDimitry Andric     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
136933956c43SDimitry Andric       EmitDeferred();
137033956c43SDimitry Andric       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
137133956c43SDimitry Andric     }
1372f22ef01cSRoman Divacky   }
1373f22ef01cSRoman Divacky }
1374f22ef01cSRoman Divacky 
13756122f3e6SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() {
13766122f3e6SDimitry Andric   if (Annotations.empty())
13776122f3e6SDimitry Andric     return;
13786122f3e6SDimitry Andric 
13796122f3e6SDimitry Andric   // Create a new global variable for the ConstantStruct in the Module.
13806122f3e6SDimitry Andric   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
13816122f3e6SDimitry Andric     Annotations[0]->getType(), Annotations.size()), Annotations);
138259d1ed5bSDimitry Andric   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
138359d1ed5bSDimitry Andric                                       llvm::GlobalValue::AppendingLinkage,
138459d1ed5bSDimitry Andric                                       Array, "llvm.global.annotations");
13856122f3e6SDimitry Andric   gv->setSection(AnnotationSection);
13866122f3e6SDimitry Andric }
13876122f3e6SDimitry Andric 
1388139f7f9bSDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1389f785676fSDimitry Andric   llvm::Constant *&AStr = AnnotationStrings[Str];
1390f785676fSDimitry Andric   if (AStr)
1391f785676fSDimitry Andric     return AStr;
13926122f3e6SDimitry Andric 
13936122f3e6SDimitry Andric   // Not found yet, create a new global.
1394dff0c46cSDimitry Andric   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
139559d1ed5bSDimitry Andric   auto *gv =
139659d1ed5bSDimitry Andric       new llvm::GlobalVariable(getModule(), s->getType(), true,
139759d1ed5bSDimitry Andric                                llvm::GlobalValue::PrivateLinkage, s, ".str");
13986122f3e6SDimitry Andric   gv->setSection(AnnotationSection);
1399e7145dcbSDimitry Andric   gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1400f785676fSDimitry Andric   AStr = gv;
14016122f3e6SDimitry Andric   return gv;
14026122f3e6SDimitry Andric }
14036122f3e6SDimitry Andric 
14046122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
14056122f3e6SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
14066122f3e6SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
14076122f3e6SDimitry Andric   if (PLoc.isValid())
14086122f3e6SDimitry Andric     return EmitAnnotationString(PLoc.getFilename());
14096122f3e6SDimitry Andric   return EmitAnnotationString(SM.getBufferName(Loc));
14106122f3e6SDimitry Andric }
14116122f3e6SDimitry Andric 
14126122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
14136122f3e6SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
14146122f3e6SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(L);
14156122f3e6SDimitry Andric   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
14166122f3e6SDimitry Andric     SM.getExpansionLineNumber(L);
14176122f3e6SDimitry Andric   return llvm::ConstantInt::get(Int32Ty, LineNo);
14186122f3e6SDimitry Andric }
14196122f3e6SDimitry Andric 
1420f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1421f22ef01cSRoman Divacky                                                 const AnnotateAttr *AA,
14226122f3e6SDimitry Andric                                                 SourceLocation L) {
14236122f3e6SDimitry Andric   // Get the globals for file name, annotation, and the line number.
14246122f3e6SDimitry Andric   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
14256122f3e6SDimitry Andric                  *UnitGV = EmitAnnotationUnit(L),
14266122f3e6SDimitry Andric                  *LineNoCst = EmitAnnotationLineNo(L);
1427f22ef01cSRoman Divacky 
1428f22ef01cSRoman Divacky   // Create the ConstantStruct for the global annotation.
1429f22ef01cSRoman Divacky   llvm::Constant *Fields[4] = {
14306122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
14316122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
14326122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
14336122f3e6SDimitry Andric     LineNoCst
1434f22ef01cSRoman Divacky   };
143517a519f9SDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
1436f22ef01cSRoman Divacky }
1437f22ef01cSRoman Divacky 
14386122f3e6SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
14396122f3e6SDimitry Andric                                          llvm::GlobalValue *GV) {
14406122f3e6SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
14416122f3e6SDimitry Andric   // Get the struct elements for these annotations.
144259d1ed5bSDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>())
144359d1ed5bSDimitry Andric     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
14446122f3e6SDimitry Andric }
14456122f3e6SDimitry Andric 
144639d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
144739d628a0SDimitry Andric                                            SourceLocation Loc) const {
144839d628a0SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
144939d628a0SDimitry Andric   // Blacklist by function name.
145039d628a0SDimitry Andric   if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
145139d628a0SDimitry Andric     return true;
145239d628a0SDimitry Andric   // Blacklist by location.
14530623d748SDimitry Andric   if (Loc.isValid())
145439d628a0SDimitry Andric     return SanitizerBL.isBlacklistedLocation(Loc);
145539d628a0SDimitry Andric   // If location is unknown, this may be a compiler-generated function. Assume
145639d628a0SDimitry Andric   // it's located in the main file.
145739d628a0SDimitry Andric   auto &SM = Context.getSourceManager();
145839d628a0SDimitry Andric   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
145939d628a0SDimitry Andric     return SanitizerBL.isBlacklistedFile(MainFile->getName());
146039d628a0SDimitry Andric   }
146139d628a0SDimitry Andric   return false;
146239d628a0SDimitry Andric }
146339d628a0SDimitry Andric 
146439d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
146539d628a0SDimitry Andric                                            SourceLocation Loc, QualType Ty,
146639d628a0SDimitry Andric                                            StringRef Category) const {
14678f0fd8f6SDimitry Andric   // For now globals can be blacklisted only in ASan and KASan.
14688f0fd8f6SDimitry Andric   if (!LangOpts.Sanitize.hasOneOf(
14698f0fd8f6SDimitry Andric           SanitizerKind::Address | SanitizerKind::KernelAddress))
147039d628a0SDimitry Andric     return false;
147139d628a0SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
147239d628a0SDimitry Andric   if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
147339d628a0SDimitry Andric     return true;
147439d628a0SDimitry Andric   if (SanitizerBL.isBlacklistedLocation(Loc, Category))
147539d628a0SDimitry Andric     return true;
147639d628a0SDimitry Andric   // Check global type.
147739d628a0SDimitry Andric   if (!Ty.isNull()) {
147839d628a0SDimitry Andric     // Drill down the array types: if global variable of a fixed type is
147939d628a0SDimitry Andric     // blacklisted, we also don't instrument arrays of them.
148039d628a0SDimitry Andric     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
148139d628a0SDimitry Andric       Ty = AT->getElementType();
148239d628a0SDimitry Andric     Ty = Ty.getCanonicalType().getUnqualifiedType();
148339d628a0SDimitry Andric     // We allow to blacklist only record types (classes, structs etc.)
148439d628a0SDimitry Andric     if (Ty->isRecordType()) {
148539d628a0SDimitry Andric       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
148639d628a0SDimitry Andric       if (SanitizerBL.isBlacklistedType(TypeStr, Category))
148739d628a0SDimitry Andric         return true;
148839d628a0SDimitry Andric     }
148939d628a0SDimitry Andric   }
149039d628a0SDimitry Andric   return false;
149139d628a0SDimitry Andric }
149239d628a0SDimitry Andric 
149320e90f04SDimitry Andric bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
149420e90f04SDimitry Andric                                    StringRef Category) const {
149520e90f04SDimitry Andric   if (!LangOpts.XRayInstrument)
149620e90f04SDimitry Andric     return false;
149720e90f04SDimitry Andric   const auto &XRayFilter = getContext().getXRayFilter();
149820e90f04SDimitry Andric   using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
149920e90f04SDimitry Andric   auto Attr = XRayFunctionFilter::ImbueAttribute::NONE;
150020e90f04SDimitry Andric   if (Loc.isValid())
150120e90f04SDimitry Andric     Attr = XRayFilter.shouldImbueLocation(Loc, Category);
150220e90f04SDimitry Andric   if (Attr == ImbueAttr::NONE)
150320e90f04SDimitry Andric     Attr = XRayFilter.shouldImbueFunction(Fn->getName());
150420e90f04SDimitry Andric   switch (Attr) {
150520e90f04SDimitry Andric   case ImbueAttr::NONE:
150620e90f04SDimitry Andric     return false;
150720e90f04SDimitry Andric   case ImbueAttr::ALWAYS:
150820e90f04SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-always");
150920e90f04SDimitry Andric     break;
151020e90f04SDimitry Andric   case ImbueAttr::NEVER:
151120e90f04SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-never");
151220e90f04SDimitry Andric     break;
151320e90f04SDimitry Andric   }
151420e90f04SDimitry Andric   return true;
151520e90f04SDimitry Andric }
151620e90f04SDimitry Andric 
151739d628a0SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
1518e580952dSDimitry Andric   // Never defer when EmitAllDecls is specified.
1519dff0c46cSDimitry Andric   if (LangOpts.EmitAllDecls)
152039d628a0SDimitry Andric     return true;
152139d628a0SDimitry Andric 
152239d628a0SDimitry Andric   return getContext().DeclMustBeEmitted(Global);
152339d628a0SDimitry Andric }
152439d628a0SDimitry Andric 
152539d628a0SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
152639d628a0SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global))
152739d628a0SDimitry Andric     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
152839d628a0SDimitry Andric       // Implicit template instantiations may change linkage if they are later
152939d628a0SDimitry Andric       // explicitly instantiated, so they should not be emitted eagerly.
1530f22ef01cSRoman Divacky       return false;
1531e7145dcbSDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(Global))
1532e7145dcbSDimitry Andric     if (Context.getInlineVariableDefinitionKind(VD) ==
1533e7145dcbSDimitry Andric         ASTContext::InlineVariableDefinitionKind::WeakUnknown)
1534e7145dcbSDimitry Andric       // A definition of an inline constexpr static data member may change
1535e7145dcbSDimitry Andric       // linkage later if it's redeclared outside the class.
1536e7145dcbSDimitry Andric       return false;
1537875ed548SDimitry Andric   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
1538875ed548SDimitry Andric   // codegen for global variables, because they may be marked as threadprivate.
1539875ed548SDimitry Andric   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1540875ed548SDimitry Andric       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
1541875ed548SDimitry Andric     return false;
1542f22ef01cSRoman Divacky 
154339d628a0SDimitry Andric   return true;
1544f22ef01cSRoman Divacky }
1545f22ef01cSRoman Divacky 
15460623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
15473861d79fSDimitry Andric     const CXXUuidofExpr* E) {
15483861d79fSDimitry Andric   // Sema has verified that IIDSource has a __declspec(uuid()), and that its
15493861d79fSDimitry Andric   // well-formed.
1550e7145dcbSDimitry Andric   StringRef Uuid = E->getUuidStr();
1551f785676fSDimitry Andric   std::string Name = "_GUID_" + Uuid.lower();
1552f785676fSDimitry Andric   std::replace(Name.begin(), Name.end(), '-', '_');
15533861d79fSDimitry Andric 
1554e7145dcbSDimitry Andric   // The UUID descriptor should be pointer aligned.
1555e7145dcbSDimitry Andric   CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
15560623d748SDimitry Andric 
15573861d79fSDimitry Andric   // Look for an existing global.
15583861d79fSDimitry Andric   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
15590623d748SDimitry Andric     return ConstantAddress(GV, Alignment);
15603861d79fSDimitry Andric 
156139d628a0SDimitry Andric   llvm::Constant *Init = EmitUuidofInitializer(Uuid);
15623861d79fSDimitry Andric   assert(Init && "failed to initialize as constant");
15633861d79fSDimitry Andric 
156459d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
1565f785676fSDimitry Andric       getModule(), Init->getType(),
1566f785676fSDimitry Andric       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
156733956c43SDimitry Andric   if (supportsCOMDAT())
156833956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
15690623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
15703861d79fSDimitry Andric }
15713861d79fSDimitry Andric 
15720623d748SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1573f22ef01cSRoman Divacky   const AliasAttr *AA = VD->getAttr<AliasAttr>();
1574f22ef01cSRoman Divacky   assert(AA && "No alias?");
1575f22ef01cSRoman Divacky 
15760623d748SDimitry Andric   CharUnits Alignment = getContext().getDeclAlign(VD);
15776122f3e6SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1578f22ef01cSRoman Divacky 
1579f22ef01cSRoman Divacky   // See if there is already something with the target's name in the module.
1580f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
15813861d79fSDimitry Andric   if (Entry) {
15823861d79fSDimitry Andric     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
15830623d748SDimitry Andric     auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
15840623d748SDimitry Andric     return ConstantAddress(Ptr, Alignment);
15853861d79fSDimitry Andric   }
1586f22ef01cSRoman Divacky 
1587f22ef01cSRoman Divacky   llvm::Constant *Aliasee;
1588f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(DeclTy))
15893861d79fSDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
15903861d79fSDimitry Andric                                       GlobalDecl(cast<FunctionDecl>(VD)),
15912754fe60SDimitry Andric                                       /*ForVTable=*/false);
1592f22ef01cSRoman Divacky   else
1593f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
159459d1ed5bSDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
159559d1ed5bSDimitry Andric                                     nullptr);
15963861d79fSDimitry Andric 
159759d1ed5bSDimitry Andric   auto *F = cast<llvm::GlobalValue>(Aliasee);
1598f22ef01cSRoman Divacky   F->setLinkage(llvm::Function::ExternalWeakLinkage);
1599f22ef01cSRoman Divacky   WeakRefReferences.insert(F);
1600f22ef01cSRoman Divacky 
16010623d748SDimitry Andric   return ConstantAddress(Aliasee, Alignment);
1602f22ef01cSRoman Divacky }
1603f22ef01cSRoman Divacky 
1604f22ef01cSRoman Divacky void CodeGenModule::EmitGlobal(GlobalDecl GD) {
160559d1ed5bSDimitry Andric   const auto *Global = cast<ValueDecl>(GD.getDecl());
1606f22ef01cSRoman Divacky 
1607f22ef01cSRoman Divacky   // Weak references don't produce any output by themselves.
1608f22ef01cSRoman Divacky   if (Global->hasAttr<WeakRefAttr>())
1609f22ef01cSRoman Divacky     return;
1610f22ef01cSRoman Divacky 
1611f22ef01cSRoman Divacky   // If this is an alias definition (which otherwise looks like a declaration)
1612f22ef01cSRoman Divacky   // emit it now.
1613f22ef01cSRoman Divacky   if (Global->hasAttr<AliasAttr>())
1614f22ef01cSRoman Divacky     return EmitAliasDefinition(GD);
1615f22ef01cSRoman Divacky 
1616e7145dcbSDimitry Andric   // IFunc like an alias whose value is resolved at runtime by calling resolver.
1617e7145dcbSDimitry Andric   if (Global->hasAttr<IFuncAttr>())
1618e7145dcbSDimitry Andric     return emitIFuncDefinition(GD);
1619e7145dcbSDimitry Andric 
16206122f3e6SDimitry Andric   // If this is CUDA, be selective about which declarations we emit.
1621dff0c46cSDimitry Andric   if (LangOpts.CUDA) {
162233956c43SDimitry Andric     if (LangOpts.CUDAIsDevice) {
16236122f3e6SDimitry Andric       if (!Global->hasAttr<CUDADeviceAttr>() &&
16246122f3e6SDimitry Andric           !Global->hasAttr<CUDAGlobalAttr>() &&
16256122f3e6SDimitry Andric           !Global->hasAttr<CUDAConstantAttr>() &&
16266122f3e6SDimitry Andric           !Global->hasAttr<CUDASharedAttr>())
16276122f3e6SDimitry Andric         return;
16286122f3e6SDimitry Andric     } else {
1629e7145dcbSDimitry Andric       // We need to emit host-side 'shadows' for all global
1630e7145dcbSDimitry Andric       // device-side variables because the CUDA runtime needs their
1631e7145dcbSDimitry Andric       // size and host-side address in order to provide access to
1632e7145dcbSDimitry Andric       // their device-side incarnations.
1633e7145dcbSDimitry Andric 
1634e7145dcbSDimitry Andric       // So device-only functions are the only things we skip.
1635e7145dcbSDimitry Andric       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
1636e7145dcbSDimitry Andric           Global->hasAttr<CUDADeviceAttr>())
16376122f3e6SDimitry Andric         return;
1638e7145dcbSDimitry Andric 
1639e7145dcbSDimitry Andric       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
1640e7145dcbSDimitry Andric              "Expected Variable or Function");
1641e580952dSDimitry Andric     }
1642e580952dSDimitry Andric   }
1643e580952dSDimitry Andric 
1644e7145dcbSDimitry Andric   if (LangOpts.OpenMP) {
1645ea942507SDimitry Andric     // If this is OpenMP device, check if it is legal to emit this global
1646ea942507SDimitry Andric     // normally.
1647ea942507SDimitry Andric     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
1648ea942507SDimitry Andric       return;
1649e7145dcbSDimitry Andric     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
1650e7145dcbSDimitry Andric       if (MustBeEmitted(Global))
1651e7145dcbSDimitry Andric         EmitOMPDeclareReduction(DRD);
1652e7145dcbSDimitry Andric       return;
1653e7145dcbSDimitry Andric     }
1654e7145dcbSDimitry Andric   }
1655ea942507SDimitry Andric 
16566122f3e6SDimitry Andric   // Ignore declarations, they will be emitted on their first use.
165759d1ed5bSDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1658f22ef01cSRoman Divacky     // Forward declarations are emitted lazily on first use.
16596122f3e6SDimitry Andric     if (!FD->doesThisDeclarationHaveABody()) {
16606122f3e6SDimitry Andric       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1661f22ef01cSRoman Divacky         return;
16626122f3e6SDimitry Andric 
16636122f3e6SDimitry Andric       StringRef MangledName = getMangledName(GD);
166459d1ed5bSDimitry Andric 
166559d1ed5bSDimitry Andric       // Compute the function info and LLVM type.
166659d1ed5bSDimitry Andric       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
166759d1ed5bSDimitry Andric       llvm::Type *Ty = getTypes().GetFunctionType(FI);
166859d1ed5bSDimitry Andric 
166959d1ed5bSDimitry Andric       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
167059d1ed5bSDimitry Andric                               /*DontDefer=*/false);
16716122f3e6SDimitry Andric       return;
16726122f3e6SDimitry Andric     }
1673f22ef01cSRoman Divacky   } else {
167459d1ed5bSDimitry Andric     const auto *VD = cast<VarDecl>(Global);
1675f22ef01cSRoman Divacky     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1676e7145dcbSDimitry Andric     // We need to emit device-side global CUDA variables even if a
1677e7145dcbSDimitry Andric     // variable does not have a definition -- we still need to define
1678e7145dcbSDimitry Andric     // host-side shadow for it.
1679e7145dcbSDimitry Andric     bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
1680e7145dcbSDimitry Andric                            !VD->hasDefinition() &&
1681e7145dcbSDimitry Andric                            (VD->hasAttr<CUDAConstantAttr>() ||
1682e7145dcbSDimitry Andric                             VD->hasAttr<CUDADeviceAttr>());
1683e7145dcbSDimitry Andric     if (!MustEmitForCuda &&
1684e7145dcbSDimitry Andric         VD->isThisDeclarationADefinition() != VarDecl::Definition &&
1685e7145dcbSDimitry Andric         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
1686e7145dcbSDimitry Andric       // If this declaration may have caused an inline variable definition to
1687e7145dcbSDimitry Andric       // change linkage, make sure that it's emitted.
1688e7145dcbSDimitry Andric       if (Context.getInlineVariableDefinitionKind(VD) ==
1689e7145dcbSDimitry Andric           ASTContext::InlineVariableDefinitionKind::Strong)
1690e7145dcbSDimitry Andric         GetAddrOfGlobalVar(VD);
1691f22ef01cSRoman Divacky       return;
1692f22ef01cSRoman Divacky     }
1693e7145dcbSDimitry Andric   }
1694f22ef01cSRoman Divacky 
169539d628a0SDimitry Andric   // Defer code generation to first use when possible, e.g. if this is an inline
169639d628a0SDimitry Andric   // function. If the global must always be emitted, do it eagerly if possible
169739d628a0SDimitry Andric   // to benefit from cache locality.
169839d628a0SDimitry Andric   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
1699f22ef01cSRoman Divacky     // Emit the definition if it can't be deferred.
1700f22ef01cSRoman Divacky     EmitGlobalDefinition(GD);
1701f22ef01cSRoman Divacky     return;
1702f22ef01cSRoman Divacky   }
1703f22ef01cSRoman Divacky 
1704e580952dSDimitry Andric   // If we're deferring emission of a C++ variable with an
1705e580952dSDimitry Andric   // initializer, remember the order in which it appeared in the file.
1706dff0c46cSDimitry Andric   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1707e580952dSDimitry Andric       cast<VarDecl>(Global)->hasInit()) {
1708e580952dSDimitry Andric     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
170959d1ed5bSDimitry Andric     CXXGlobalInits.push_back(nullptr);
1710e580952dSDimitry Andric   }
1711e580952dSDimitry Andric 
17126122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
171339d628a0SDimitry Andric   if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) {
171439d628a0SDimitry Andric     // The value has already been used and should therefore be emitted.
171559d1ed5bSDimitry Andric     addDeferredDeclToEmit(GV, GD);
171639d628a0SDimitry Andric   } else if (MustBeEmitted(Global)) {
171739d628a0SDimitry Andric     // The value must be emitted, but cannot be emitted eagerly.
171839d628a0SDimitry Andric     assert(!MayBeEmittedEagerly(Global));
171939d628a0SDimitry Andric     addDeferredDeclToEmit(/*GV=*/nullptr, GD);
172039d628a0SDimitry Andric   } else {
1721f22ef01cSRoman Divacky     // Otherwise, remember that we saw a deferred decl with this name.  The
1722f22ef01cSRoman Divacky     // first use of the mangled name will cause it to move into
1723f22ef01cSRoman Divacky     // DeferredDeclsToEmit.
1724f22ef01cSRoman Divacky     DeferredDecls[MangledName] = GD;
1725f22ef01cSRoman Divacky   }
1726f22ef01cSRoman Divacky }
1727f22ef01cSRoman Divacky 
172820e90f04SDimitry Andric // Check if T is a class type with a destructor that's not dllimport.
172920e90f04SDimitry Andric static bool HasNonDllImportDtor(QualType T) {
173020e90f04SDimitry Andric   if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
173120e90f04SDimitry Andric     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
173220e90f04SDimitry Andric       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
173320e90f04SDimitry Andric         return true;
173420e90f04SDimitry Andric 
173520e90f04SDimitry Andric   return false;
173620e90f04SDimitry Andric }
173720e90f04SDimitry Andric 
1738f8254f43SDimitry Andric namespace {
1739f8254f43SDimitry Andric   struct FunctionIsDirectlyRecursive :
1740f8254f43SDimitry Andric     public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1741f8254f43SDimitry Andric     const StringRef Name;
1742dff0c46cSDimitry Andric     const Builtin::Context &BI;
1743f8254f43SDimitry Andric     bool Result;
1744dff0c46cSDimitry Andric     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1745dff0c46cSDimitry Andric       Name(N), BI(C), Result(false) {
1746f8254f43SDimitry Andric     }
1747f8254f43SDimitry Andric     typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1748f8254f43SDimitry Andric 
1749f8254f43SDimitry Andric     bool TraverseCallExpr(CallExpr *E) {
1750dff0c46cSDimitry Andric       const FunctionDecl *FD = E->getDirectCallee();
1751dff0c46cSDimitry Andric       if (!FD)
1752f8254f43SDimitry Andric         return true;
1753dff0c46cSDimitry Andric       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1754dff0c46cSDimitry Andric       if (Attr && Name == Attr->getLabel()) {
1755dff0c46cSDimitry Andric         Result = true;
1756dff0c46cSDimitry Andric         return false;
1757dff0c46cSDimitry Andric       }
1758dff0c46cSDimitry Andric       unsigned BuiltinID = FD->getBuiltinID();
17593dac3a9bSDimitry Andric       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
1760f8254f43SDimitry Andric         return true;
17610623d748SDimitry Andric       StringRef BuiltinName = BI.getName(BuiltinID);
1762dff0c46cSDimitry Andric       if (BuiltinName.startswith("__builtin_") &&
1763dff0c46cSDimitry Andric           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1764f8254f43SDimitry Andric         Result = true;
1765f8254f43SDimitry Andric         return false;
1766f8254f43SDimitry Andric       }
1767f8254f43SDimitry Andric       return true;
1768f8254f43SDimitry Andric     }
1769f8254f43SDimitry Andric   };
17700623d748SDimitry Andric 
177120e90f04SDimitry Andric   // Make sure we're not referencing non-imported vars or functions.
17720623d748SDimitry Andric   struct DLLImportFunctionVisitor
17730623d748SDimitry Andric       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
17740623d748SDimitry Andric     bool SafeToInline = true;
17750623d748SDimitry Andric 
177644290647SDimitry Andric     bool shouldVisitImplicitCode() const { return true; }
177744290647SDimitry Andric 
17780623d748SDimitry Andric     bool VisitVarDecl(VarDecl *VD) {
177920e90f04SDimitry Andric       if (VD->getTLSKind()) {
17800623d748SDimitry Andric         // A thread-local variable cannot be imported.
178120e90f04SDimitry Andric         SafeToInline = false;
17820623d748SDimitry Andric         return SafeToInline;
17830623d748SDimitry Andric       }
17840623d748SDimitry Andric 
178520e90f04SDimitry Andric       // A variable definition might imply a destructor call.
178620e90f04SDimitry Andric       if (VD->isThisDeclarationADefinition())
178720e90f04SDimitry Andric         SafeToInline = !HasNonDllImportDtor(VD->getType());
178820e90f04SDimitry Andric 
178920e90f04SDimitry Andric       return SafeToInline;
179020e90f04SDimitry Andric     }
179120e90f04SDimitry Andric 
179220e90f04SDimitry Andric     bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
179320e90f04SDimitry Andric       if (const auto *D = E->getTemporary()->getDestructor())
179420e90f04SDimitry Andric         SafeToInline = D->hasAttr<DLLImportAttr>();
179520e90f04SDimitry Andric       return SafeToInline;
179620e90f04SDimitry Andric     }
179720e90f04SDimitry Andric 
17980623d748SDimitry Andric     bool VisitDeclRefExpr(DeclRefExpr *E) {
17990623d748SDimitry Andric       ValueDecl *VD = E->getDecl();
18000623d748SDimitry Andric       if (isa<FunctionDecl>(VD))
18010623d748SDimitry Andric         SafeToInline = VD->hasAttr<DLLImportAttr>();
18020623d748SDimitry Andric       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
18030623d748SDimitry Andric         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
18040623d748SDimitry Andric       return SafeToInline;
18050623d748SDimitry Andric     }
180620e90f04SDimitry Andric 
180744290647SDimitry Andric     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
180844290647SDimitry Andric       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
180944290647SDimitry Andric       return SafeToInline;
181044290647SDimitry Andric     }
181120e90f04SDimitry Andric 
181220e90f04SDimitry Andric     bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
181320e90f04SDimitry Andric       CXXMethodDecl *M = E->getMethodDecl();
181420e90f04SDimitry Andric       if (!M) {
181520e90f04SDimitry Andric         // Call through a pointer to member function. This is safe to inline.
181620e90f04SDimitry Andric         SafeToInline = true;
181720e90f04SDimitry Andric       } else {
181820e90f04SDimitry Andric         SafeToInline = M->hasAttr<DLLImportAttr>();
181920e90f04SDimitry Andric       }
182020e90f04SDimitry Andric       return SafeToInline;
182120e90f04SDimitry Andric     }
182220e90f04SDimitry Andric 
18230623d748SDimitry Andric     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
18240623d748SDimitry Andric       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
18250623d748SDimitry Andric       return SafeToInline;
18260623d748SDimitry Andric     }
182720e90f04SDimitry Andric 
18280623d748SDimitry Andric     bool VisitCXXNewExpr(CXXNewExpr *E) {
18290623d748SDimitry Andric       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
18300623d748SDimitry Andric       return SafeToInline;
18310623d748SDimitry Andric     }
18320623d748SDimitry Andric   };
1833f8254f43SDimitry Andric }
1834f8254f43SDimitry Andric 
1835dff0c46cSDimitry Andric // isTriviallyRecursive - Check if this function calls another
1836dff0c46cSDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin,
1837dff0c46cSDimitry Andric // ends up pointing to itself.
1838f8254f43SDimitry Andric bool
1839dff0c46cSDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1840dff0c46cSDimitry Andric   StringRef Name;
1841dff0c46cSDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1842dff0c46cSDimitry Andric     // asm labels are a special kind of mangling we have to support.
1843dff0c46cSDimitry Andric     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1844dff0c46cSDimitry Andric     if (!Attr)
1845f8254f43SDimitry Andric       return false;
1846dff0c46cSDimitry Andric     Name = Attr->getLabel();
1847dff0c46cSDimitry Andric   } else {
1848dff0c46cSDimitry Andric     Name = FD->getName();
1849dff0c46cSDimitry Andric   }
1850f8254f43SDimitry Andric 
1851dff0c46cSDimitry Andric   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1852dff0c46cSDimitry Andric   Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1853f8254f43SDimitry Andric   return Walker.Result;
1854f8254f43SDimitry Andric }
1855f8254f43SDimitry Andric 
185644290647SDimitry Andric bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1857f785676fSDimitry Andric   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1858f8254f43SDimitry Andric     return true;
185959d1ed5bSDimitry Andric   const auto *F = cast<FunctionDecl>(GD.getDecl());
186059d1ed5bSDimitry Andric   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1861f8254f43SDimitry Andric     return false;
18620623d748SDimitry Andric 
18630623d748SDimitry Andric   if (F->hasAttr<DLLImportAttr>()) {
18640623d748SDimitry Andric     // Check whether it would be safe to inline this dllimport function.
18650623d748SDimitry Andric     DLLImportFunctionVisitor Visitor;
18660623d748SDimitry Andric     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
18670623d748SDimitry Andric     if (!Visitor.SafeToInline)
18680623d748SDimitry Andric       return false;
186944290647SDimitry Andric 
187044290647SDimitry Andric     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
187144290647SDimitry Andric       // Implicit destructor invocations aren't captured in the AST, so the
187244290647SDimitry Andric       // check above can't see them. Check for them manually here.
187344290647SDimitry Andric       for (const Decl *Member : Dtor->getParent()->decls())
187444290647SDimitry Andric         if (isa<FieldDecl>(Member))
187544290647SDimitry Andric           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
187644290647SDimitry Andric             return false;
187744290647SDimitry Andric       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
187844290647SDimitry Andric         if (HasNonDllImportDtor(B.getType()))
187944290647SDimitry Andric           return false;
188044290647SDimitry Andric     }
18810623d748SDimitry Andric   }
18820623d748SDimitry Andric 
1883f8254f43SDimitry Andric   // PR9614. Avoid cases where the source code is lying to us. An available
1884f8254f43SDimitry Andric   // externally function should have an equivalent function somewhere else,
1885f8254f43SDimitry Andric   // but a function that calls itself is clearly not equivalent to the real
1886f8254f43SDimitry Andric   // implementation.
1887f8254f43SDimitry Andric   // This happens in glibc's btowc and in some configure checks.
1888dff0c46cSDimitry Andric   return !isTriviallyRecursive(F);
1889f8254f43SDimitry Andric }
1890f8254f43SDimitry Andric 
189159d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
189259d1ed5bSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
1893f22ef01cSRoman Divacky 
1894f22ef01cSRoman Divacky   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1895f22ef01cSRoman Divacky                                  Context.getSourceManager(),
1896f22ef01cSRoman Divacky                                  "Generating code for declaration");
1897f22ef01cSRoman Divacky 
1898f785676fSDimitry Andric   if (isa<FunctionDecl>(D)) {
1899ffd1746dSEd Schouten     // At -O0, don't generate IR for functions with available_externally
1900ffd1746dSEd Schouten     // linkage.
1901f785676fSDimitry Andric     if (!shouldEmitFunction(GD))
1902ffd1746dSEd Schouten       return;
1903ffd1746dSEd Schouten 
190459d1ed5bSDimitry Andric     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
1905bd5abe19SDimitry Andric       // Make sure to emit the definition(s) before we emit the thunks.
1906bd5abe19SDimitry Andric       // This is necessary for the generation of certain thunks.
190759d1ed5bSDimitry Andric       if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
190839d628a0SDimitry Andric         ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
190959d1ed5bSDimitry Andric       else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
191039d628a0SDimitry Andric         ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
1911bd5abe19SDimitry Andric       else
191259d1ed5bSDimitry Andric         EmitGlobalFunctionDefinition(GD, GV);
1913bd5abe19SDimitry Andric 
1914f22ef01cSRoman Divacky       if (Method->isVirtual())
1915f22ef01cSRoman Divacky         getVTables().EmitThunks(GD);
1916f22ef01cSRoman Divacky 
1917bd5abe19SDimitry Andric       return;
1918ffd1746dSEd Schouten     }
1919f22ef01cSRoman Divacky 
192059d1ed5bSDimitry Andric     return EmitGlobalFunctionDefinition(GD, GV);
1921ffd1746dSEd Schouten   }
1922f22ef01cSRoman Divacky 
192359d1ed5bSDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
1924e7145dcbSDimitry Andric     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
1925f22ef01cSRoman Divacky 
19266122f3e6SDimitry Andric   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1927f22ef01cSRoman Divacky }
1928f22ef01cSRoman Divacky 
19290623d748SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
19300623d748SDimitry Andric                                                       llvm::Function *NewFn);
19310623d748SDimitry Andric 
1932f22ef01cSRoman Divacky /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1933f22ef01cSRoman Divacky /// module, create and return an llvm Function with the specified type. If there
1934f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially
1935f22ef01cSRoman Divacky /// bitcasted to the right type.
1936f22ef01cSRoman Divacky ///
1937f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this.  This is used
1938f22ef01cSRoman Divacky /// to set the attributes on the function when it is first created.
193920e90f04SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
194020e90f04SDimitry Andric     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
194120e90f04SDimitry Andric     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
194244290647SDimitry Andric     ForDefinition_t IsForDefinition) {
1943f785676fSDimitry Andric   const Decl *D = GD.getDecl();
1944f785676fSDimitry Andric 
1945f22ef01cSRoman Divacky   // Lookup the entry, lazily creating it if necessary.
1946f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1947f22ef01cSRoman Divacky   if (Entry) {
19483861d79fSDimitry Andric     if (WeakRefReferences.erase(Entry)) {
1949f785676fSDimitry Andric       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
1950f22ef01cSRoman Divacky       if (FD && !FD->hasAttr<WeakAttr>())
1951f22ef01cSRoman Divacky         Entry->setLinkage(llvm::Function::ExternalLinkage);
1952f22ef01cSRoman Divacky     }
1953f22ef01cSRoman Divacky 
195439d628a0SDimitry Andric     // Handle dropped DLL attributes.
195539d628a0SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
195639d628a0SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
195739d628a0SDimitry Andric 
19580623d748SDimitry Andric     // If there are two attempts to define the same mangled name, issue an
19590623d748SDimitry Andric     // error.
19600623d748SDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
19610623d748SDimitry Andric       GlobalDecl OtherGD;
1962e7145dcbSDimitry Andric       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
1963e7145dcbSDimitry Andric       // to make sure that we issue an error only once.
19640623d748SDimitry Andric       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
19650623d748SDimitry Andric           (GD.getCanonicalDecl().getDecl() !=
19660623d748SDimitry Andric            OtherGD.getCanonicalDecl().getDecl()) &&
19670623d748SDimitry Andric           DiagnosedConflictingDefinitions.insert(GD).second) {
19680623d748SDimitry Andric         getDiags().Report(D->getLocation(),
19690623d748SDimitry Andric                           diag::err_duplicate_mangled_name);
19700623d748SDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
19710623d748SDimitry Andric                           diag::note_previous_definition);
19720623d748SDimitry Andric       }
19730623d748SDimitry Andric     }
19740623d748SDimitry Andric 
19750623d748SDimitry Andric     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
19760623d748SDimitry Andric         (Entry->getType()->getElementType() == Ty)) {
1977f22ef01cSRoman Divacky       return Entry;
19780623d748SDimitry Andric     }
1979f22ef01cSRoman Divacky 
1980f22ef01cSRoman Divacky     // Make sure the result is of the correct type.
19810623d748SDimitry Andric     // (If function is requested for a definition, we always need to create a new
19820623d748SDimitry Andric     // function, not just return a bitcast.)
19830623d748SDimitry Andric     if (!IsForDefinition)
198417a519f9SDimitry Andric       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1985f22ef01cSRoman Divacky   }
1986f22ef01cSRoman Divacky 
1987f22ef01cSRoman Divacky   // This function doesn't have a complete type (for example, the return
1988f22ef01cSRoman Divacky   // type is an incomplete struct). Use a fake type instead, and make
1989f22ef01cSRoman Divacky   // sure not to try to set attributes.
1990f22ef01cSRoman Divacky   bool IsIncompleteFunction = false;
1991f22ef01cSRoman Divacky 
19926122f3e6SDimitry Andric   llvm::FunctionType *FTy;
1993f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(Ty)) {
1994f22ef01cSRoman Divacky     FTy = cast<llvm::FunctionType>(Ty);
1995f22ef01cSRoman Divacky   } else {
1996bd5abe19SDimitry Andric     FTy = llvm::FunctionType::get(VoidTy, false);
1997f22ef01cSRoman Divacky     IsIncompleteFunction = true;
1998f22ef01cSRoman Divacky   }
1999ffd1746dSEd Schouten 
20000623d748SDimitry Andric   llvm::Function *F =
20010623d748SDimitry Andric       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
20020623d748SDimitry Andric                              Entry ? StringRef() : MangledName, &getModule());
20030623d748SDimitry Andric 
20040623d748SDimitry Andric   // If we already created a function with the same mangled name (but different
20050623d748SDimitry Andric   // type) before, take its name and add it to the list of functions to be
20060623d748SDimitry Andric   // replaced with F at the end of CodeGen.
20070623d748SDimitry Andric   //
20080623d748SDimitry Andric   // This happens if there is a prototype for a function (e.g. "int f()") and
20090623d748SDimitry Andric   // then a definition of a different type (e.g. "int f(int x)").
20100623d748SDimitry Andric   if (Entry) {
20110623d748SDimitry Andric     F->takeName(Entry);
20120623d748SDimitry Andric 
20130623d748SDimitry Andric     // This might be an implementation of a function without a prototype, in
20140623d748SDimitry Andric     // which case, try to do special replacement of calls which match the new
20150623d748SDimitry Andric     // prototype.  The really key thing here is that we also potentially drop
20160623d748SDimitry Andric     // arguments from the call site so as to make a direct call, which makes the
20170623d748SDimitry Andric     // inliner happier and suppresses a number of optimizer warnings (!) about
20180623d748SDimitry Andric     // dropping arguments.
20190623d748SDimitry Andric     if (!Entry->use_empty()) {
20200623d748SDimitry Andric       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
20210623d748SDimitry Andric       Entry->removeDeadConstantUsers();
20220623d748SDimitry Andric     }
20230623d748SDimitry Andric 
20240623d748SDimitry Andric     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
20250623d748SDimitry Andric         F, Entry->getType()->getElementType()->getPointerTo());
20260623d748SDimitry Andric     addGlobalValReplacement(Entry, BC);
20270623d748SDimitry Andric   }
20280623d748SDimitry Andric 
2029f22ef01cSRoman Divacky   assert(F->getName() == MangledName && "name was uniqued!");
2030f785676fSDimitry Andric   if (D)
203139d628a0SDimitry Andric     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
203220e90f04SDimitry Andric   if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
203320e90f04SDimitry Andric     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
203420e90f04SDimitry Andric     F->addAttributes(llvm::AttributeList::FunctionIndex,
203520e90f04SDimitry Andric                      llvm::AttributeList::get(
203620e90f04SDimitry Andric                          VMContext, llvm::AttributeList::FunctionIndex, B));
2037139f7f9bSDimitry Andric   }
2038f22ef01cSRoman Divacky 
203959d1ed5bSDimitry Andric   if (!DontDefer) {
204059d1ed5bSDimitry Andric     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
204159d1ed5bSDimitry Andric     // each other bottoming out with the base dtor.  Therefore we emit non-base
204259d1ed5bSDimitry Andric     // dtors on usage, even if there is no dtor definition in the TU.
204359d1ed5bSDimitry Andric     if (D && isa<CXXDestructorDecl>(D) &&
204459d1ed5bSDimitry Andric         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
204559d1ed5bSDimitry Andric                                            GD.getDtorType()))
204659d1ed5bSDimitry Andric       addDeferredDeclToEmit(F, GD);
204759d1ed5bSDimitry Andric 
2048f22ef01cSRoman Divacky     // This is the first use or definition of a mangled name.  If there is a
2049f22ef01cSRoman Divacky     // deferred decl with this name, remember that we need to emit it at the end
2050f22ef01cSRoman Divacky     // of the file.
205159d1ed5bSDimitry Andric     auto DDI = DeferredDecls.find(MangledName);
2052f22ef01cSRoman Divacky     if (DDI != DeferredDecls.end()) {
205359d1ed5bSDimitry Andric       // Move the potentially referenced deferred decl to the
205459d1ed5bSDimitry Andric       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
205559d1ed5bSDimitry Andric       // don't need it anymore).
205659d1ed5bSDimitry Andric       addDeferredDeclToEmit(F, DDI->second);
2057f22ef01cSRoman Divacky       DeferredDecls.erase(DDI);
20582754fe60SDimitry Andric 
20592754fe60SDimitry Andric       // Otherwise, there are cases we have to worry about where we're
20602754fe60SDimitry Andric       // using a declaration for which we must emit a definition but where
20612754fe60SDimitry Andric       // we might not find a top-level definition:
20622754fe60SDimitry Andric       //   - member functions defined inline in their classes
20632754fe60SDimitry Andric       //   - friend functions defined inline in some class
20642754fe60SDimitry Andric       //   - special member functions with implicit definitions
20652754fe60SDimitry Andric       // If we ever change our AST traversal to walk into class methods,
20662754fe60SDimitry Andric       // this will be unnecessary.
20672754fe60SDimitry Andric       //
206859d1ed5bSDimitry Andric       // We also don't emit a definition for a function if it's going to be an
206939d628a0SDimitry Andric       // entry in a vtable, unless it's already marked as used.
2070f785676fSDimitry Andric     } else if (getLangOpts().CPlusPlus && D) {
20712754fe60SDimitry Andric       // Look for a declaration that's lexically in a record.
207239d628a0SDimitry Andric       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
207339d628a0SDimitry Andric            FD = FD->getPreviousDecl()) {
20742754fe60SDimitry Andric         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
207539d628a0SDimitry Andric           if (FD->doesThisDeclarationHaveABody()) {
207659d1ed5bSDimitry Andric             addDeferredDeclToEmit(F, GD.getWithDecl(FD));
20772754fe60SDimitry Andric             break;
2078f22ef01cSRoman Divacky           }
2079f22ef01cSRoman Divacky         }
208039d628a0SDimitry Andric       }
2081f22ef01cSRoman Divacky     }
208259d1ed5bSDimitry Andric   }
2083f22ef01cSRoman Divacky 
2084f22ef01cSRoman Divacky   // Make sure the result is of the requested type.
2085f22ef01cSRoman Divacky   if (!IsIncompleteFunction) {
2086f22ef01cSRoman Divacky     assert(F->getType()->getElementType() == Ty);
2087f22ef01cSRoman Divacky     return F;
2088f22ef01cSRoman Divacky   }
2089f22ef01cSRoman Divacky 
209017a519f9SDimitry Andric   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2091f22ef01cSRoman Divacky   return llvm::ConstantExpr::getBitCast(F, PTy);
2092f22ef01cSRoman Divacky }
2093f22ef01cSRoman Divacky 
2094f22ef01cSRoman Divacky /// GetAddrOfFunction - Return the address of the given function.  If Ty is
2095f22ef01cSRoman Divacky /// non-null, then this function will use the specified type if it has to
2096f22ef01cSRoman Divacky /// create it (this occurs when we see a definition of the function).
2097f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
20986122f3e6SDimitry Andric                                                  llvm::Type *Ty,
209959d1ed5bSDimitry Andric                                                  bool ForVTable,
21000623d748SDimitry Andric                                                  bool DontDefer,
210144290647SDimitry Andric                                               ForDefinition_t IsForDefinition) {
2102f22ef01cSRoman Divacky   // If there was no specific requested type, just convert it now.
21030623d748SDimitry Andric   if (!Ty) {
21040623d748SDimitry Andric     const auto *FD = cast<FunctionDecl>(GD.getDecl());
21050623d748SDimitry Andric     auto CanonTy = Context.getCanonicalType(FD->getType());
21060623d748SDimitry Andric     Ty = getTypes().ConvertFunctionType(CanonTy, FD);
21070623d748SDimitry Andric   }
2108ffd1746dSEd Schouten 
21096122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
21100623d748SDimitry Andric   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
211120e90f04SDimitry Andric                                  /*IsThunk=*/false, llvm::AttributeList(),
21120623d748SDimitry Andric                                  IsForDefinition);
2113f22ef01cSRoman Divacky }
2114f22ef01cSRoman Divacky 
211544290647SDimitry Andric static const FunctionDecl *
211644290647SDimitry Andric GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
211744290647SDimitry Andric   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
211844290647SDimitry Andric   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
211944290647SDimitry Andric 
212044290647SDimitry Andric   IdentifierInfo &CII = C.Idents.get(Name);
212144290647SDimitry Andric   for (const auto &Result : DC->lookup(&CII))
212244290647SDimitry Andric     if (const auto FD = dyn_cast<FunctionDecl>(Result))
212344290647SDimitry Andric       return FD;
212444290647SDimitry Andric 
212544290647SDimitry Andric   if (!C.getLangOpts().CPlusPlus)
212644290647SDimitry Andric     return nullptr;
212744290647SDimitry Andric 
212844290647SDimitry Andric   // Demangle the premangled name from getTerminateFn()
212944290647SDimitry Andric   IdentifierInfo &CXXII =
213044290647SDimitry Andric       (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ")
213144290647SDimitry Andric           ? C.Idents.get("terminate")
213244290647SDimitry Andric           : C.Idents.get(Name);
213344290647SDimitry Andric 
213444290647SDimitry Andric   for (const auto &N : {"__cxxabiv1", "std"}) {
213544290647SDimitry Andric     IdentifierInfo &NS = C.Idents.get(N);
213644290647SDimitry Andric     for (const auto &Result : DC->lookup(&NS)) {
213744290647SDimitry Andric       NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
213844290647SDimitry Andric       if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
213944290647SDimitry Andric         for (const auto &Result : LSD->lookup(&NS))
214044290647SDimitry Andric           if ((ND = dyn_cast<NamespaceDecl>(Result)))
214144290647SDimitry Andric             break;
214244290647SDimitry Andric 
214344290647SDimitry Andric       if (ND)
214444290647SDimitry Andric         for (const auto &Result : ND->lookup(&CXXII))
214544290647SDimitry Andric           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
214644290647SDimitry Andric             return FD;
214744290647SDimitry Andric     }
214844290647SDimitry Andric   }
214944290647SDimitry Andric 
215044290647SDimitry Andric   return nullptr;
215144290647SDimitry Andric }
215244290647SDimitry Andric 
2153f22ef01cSRoman Divacky /// CreateRuntimeFunction - Create a new runtime function with the specified
2154f22ef01cSRoman Divacky /// type and name.
2155f22ef01cSRoman Divacky llvm::Constant *
215644290647SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
215720e90f04SDimitry Andric                                      llvm::AttributeList ExtraAttrs,
215844290647SDimitry Andric                                      bool Local) {
215959d1ed5bSDimitry Andric   llvm::Constant *C =
216059d1ed5bSDimitry Andric       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
216144290647SDimitry Andric                               /*DontDefer=*/false, /*IsThunk=*/false,
216244290647SDimitry Andric                               ExtraAttrs);
216344290647SDimitry Andric 
216444290647SDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(C)) {
216544290647SDimitry Andric     if (F->empty()) {
2166139f7f9bSDimitry Andric       F->setCallingConv(getRuntimeCC());
216744290647SDimitry Andric 
216844290647SDimitry Andric       if (!Local && getTriple().isOSBinFormatCOFF() &&
216944290647SDimitry Andric           !getCodeGenOpts().LTOVisibilityPublicStd) {
217044290647SDimitry Andric         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
217144290647SDimitry Andric         if (!FD || FD->hasAttr<DLLImportAttr>()) {
217244290647SDimitry Andric           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
217344290647SDimitry Andric           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
217444290647SDimitry Andric         }
217544290647SDimitry Andric       }
217644290647SDimitry Andric     }
217744290647SDimitry Andric   }
217844290647SDimitry Andric 
2179139f7f9bSDimitry Andric   return C;
2180f22ef01cSRoman Divacky }
2181f22ef01cSRoman Divacky 
218239d628a0SDimitry Andric /// CreateBuiltinFunction - Create a new builtin function with the specified
218339d628a0SDimitry Andric /// type and name.
218439d628a0SDimitry Andric llvm::Constant *
218520e90f04SDimitry Andric CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
218620e90f04SDimitry Andric                                      llvm::AttributeList ExtraAttrs) {
218739d628a0SDimitry Andric   llvm::Constant *C =
218839d628a0SDimitry Andric       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
218939d628a0SDimitry Andric                               /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
219039d628a0SDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(C))
219139d628a0SDimitry Andric     if (F->empty())
219239d628a0SDimitry Andric       F->setCallingConv(getBuiltinCC());
219339d628a0SDimitry Andric   return C;
219439d628a0SDimitry Andric }
219539d628a0SDimitry Andric 
2196dff0c46cSDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted
2197dff0c46cSDimitry Andric /// as a constant.
2198dff0c46cSDimitry Andric ///
2199dff0c46cSDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs
2200dff0c46cSDimitry Andric /// will not be considered. The caller will need to verify that the object is
2201dff0c46cSDimitry Andric /// not written to during its construction.
2202dff0c46cSDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2203dff0c46cSDimitry Andric   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
2204f22ef01cSRoman Divacky     return false;
2205bd5abe19SDimitry Andric 
2206dff0c46cSDimitry Andric   if (Context.getLangOpts().CPlusPlus) {
2207dff0c46cSDimitry Andric     if (const CXXRecordDecl *Record
2208dff0c46cSDimitry Andric           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2209dff0c46cSDimitry Andric       return ExcludeCtor && !Record->hasMutableFields() &&
2210dff0c46cSDimitry Andric              Record->hasTrivialDestructor();
2211f22ef01cSRoman Divacky   }
2212bd5abe19SDimitry Andric 
2213f22ef01cSRoman Divacky   return true;
2214f22ef01cSRoman Divacky }
2215f22ef01cSRoman Divacky 
2216f22ef01cSRoman Divacky /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2217f22ef01cSRoman Divacky /// create and return an llvm GlobalVariable with the specified type.  If there
2218f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially
2219f22ef01cSRoman Divacky /// bitcasted to the right type.
2220f22ef01cSRoman Divacky ///
2221f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this.  This is used
2222f22ef01cSRoman Divacky /// to set the attributes on the global when it is first created.
2223e7145dcbSDimitry Andric ///
2224e7145dcbSDimitry Andric /// If IsForDefinition is true, it is guranteed that an actual global with
2225e7145dcbSDimitry Andric /// type Ty will be returned, not conversion of a variable with the same
2226e7145dcbSDimitry Andric /// mangled name but some other type.
2227f22ef01cSRoman Divacky llvm::Constant *
22286122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
22296122f3e6SDimitry Andric                                      llvm::PointerType *Ty,
2230e7145dcbSDimitry Andric                                      const VarDecl *D,
223144290647SDimitry Andric                                      ForDefinition_t IsForDefinition) {
2232f22ef01cSRoman Divacky   // Lookup the entry, lazily creating it if necessary.
2233f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2234f22ef01cSRoman Divacky   if (Entry) {
22353861d79fSDimitry Andric     if (WeakRefReferences.erase(Entry)) {
2236f22ef01cSRoman Divacky       if (D && !D->hasAttr<WeakAttr>())
2237f22ef01cSRoman Divacky         Entry->setLinkage(llvm::Function::ExternalLinkage);
2238f22ef01cSRoman Divacky     }
2239f22ef01cSRoman Divacky 
224039d628a0SDimitry Andric     // Handle dropped DLL attributes.
224139d628a0SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
224239d628a0SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
224339d628a0SDimitry Andric 
2244f22ef01cSRoman Divacky     if (Entry->getType() == Ty)
2245f22ef01cSRoman Divacky       return Entry;
2246f22ef01cSRoman Divacky 
2247e7145dcbSDimitry Andric     // If there are two attempts to define the same mangled name, issue an
2248e7145dcbSDimitry Andric     // error.
2249e7145dcbSDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
2250e7145dcbSDimitry Andric       GlobalDecl OtherGD;
2251e7145dcbSDimitry Andric       const VarDecl *OtherD;
2252e7145dcbSDimitry Andric 
2253e7145dcbSDimitry Andric       // Check that D is not yet in DiagnosedConflictingDefinitions is required
2254e7145dcbSDimitry Andric       // to make sure that we issue an error only once.
2255e7145dcbSDimitry Andric       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
2256e7145dcbSDimitry Andric           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2257e7145dcbSDimitry Andric           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2258e7145dcbSDimitry Andric           OtherD->hasInit() &&
2259e7145dcbSDimitry Andric           DiagnosedConflictingDefinitions.insert(D).second) {
2260e7145dcbSDimitry Andric         getDiags().Report(D->getLocation(),
2261e7145dcbSDimitry Andric                           diag::err_duplicate_mangled_name);
2262e7145dcbSDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
2263e7145dcbSDimitry Andric                           diag::note_previous_definition);
2264e7145dcbSDimitry Andric       }
2265e7145dcbSDimitry Andric     }
2266e7145dcbSDimitry Andric 
2267f22ef01cSRoman Divacky     // Make sure the result is of the correct type.
2268f785676fSDimitry Andric     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2269f785676fSDimitry Andric       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2270f785676fSDimitry Andric 
2271e7145dcbSDimitry Andric     // (If global is requested for a definition, we always need to create a new
2272e7145dcbSDimitry Andric     // global, not just return a bitcast.)
2273e7145dcbSDimitry Andric     if (!IsForDefinition)
2274f22ef01cSRoman Divacky       return llvm::ConstantExpr::getBitCast(Entry, Ty);
2275f22ef01cSRoman Divacky   }
2276f22ef01cSRoman Divacky 
227759d1ed5bSDimitry Andric   unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
227859d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
227959d1ed5bSDimitry Andric       getModule(), Ty->getElementType(), false,
228059d1ed5bSDimitry Andric       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
228159d1ed5bSDimitry Andric       llvm::GlobalVariable::NotThreadLocal, AddrSpace);
228259d1ed5bSDimitry Andric 
2283e7145dcbSDimitry Andric   // If we already created a global with the same mangled name (but different
2284e7145dcbSDimitry Andric   // type) before, take its name and remove it from its parent.
2285e7145dcbSDimitry Andric   if (Entry) {
2286e7145dcbSDimitry Andric     GV->takeName(Entry);
2287e7145dcbSDimitry Andric 
2288e7145dcbSDimitry Andric     if (!Entry->use_empty()) {
2289e7145dcbSDimitry Andric       llvm::Constant *NewPtrForOldDecl =
2290e7145dcbSDimitry Andric           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2291e7145dcbSDimitry Andric       Entry->replaceAllUsesWith(NewPtrForOldDecl);
2292e7145dcbSDimitry Andric     }
2293e7145dcbSDimitry Andric 
2294e7145dcbSDimitry Andric     Entry->eraseFromParent();
2295e7145dcbSDimitry Andric   }
2296e7145dcbSDimitry Andric 
2297f22ef01cSRoman Divacky   // This is the first use or definition of a mangled name.  If there is a
2298f22ef01cSRoman Divacky   // deferred decl with this name, remember that we need to emit it at the end
2299f22ef01cSRoman Divacky   // of the file.
230059d1ed5bSDimitry Andric   auto DDI = DeferredDecls.find(MangledName);
2301f22ef01cSRoman Divacky   if (DDI != DeferredDecls.end()) {
2302f22ef01cSRoman Divacky     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2303f22ef01cSRoman Divacky     // list, and remove it from DeferredDecls (since we don't need it anymore).
230459d1ed5bSDimitry Andric     addDeferredDeclToEmit(GV, DDI->second);
2305f22ef01cSRoman Divacky     DeferredDecls.erase(DDI);
2306f22ef01cSRoman Divacky   }
2307f22ef01cSRoman Divacky 
2308f22ef01cSRoman Divacky   // Handle things which are present even on external declarations.
2309f22ef01cSRoman Divacky   if (D) {
2310f22ef01cSRoman Divacky     // FIXME: This code is overly simple and should be merged with other global
2311f22ef01cSRoman Divacky     // handling.
2312dff0c46cSDimitry Andric     GV->setConstant(isTypeConstant(D->getType(), false));
2313f22ef01cSRoman Divacky 
231433956c43SDimitry Andric     GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
231533956c43SDimitry Andric 
231659d1ed5bSDimitry Andric     setLinkageAndVisibilityForGV(GV, D);
23172754fe60SDimitry Andric 
2318284c1978SDimitry Andric     if (D->getTLSKind()) {
2319284c1978SDimitry Andric       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
23200623d748SDimitry Andric         CXXThreadLocals.push_back(D);
23217ae0e2c9SDimitry Andric       setTLSMode(GV, *D);
2322f22ef01cSRoman Divacky     }
2323f785676fSDimitry Andric 
2324f785676fSDimitry Andric     // If required by the ABI, treat declarations of static data members with
2325f785676fSDimitry Andric     // inline initializers as definitions.
232659d1ed5bSDimitry Andric     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
2327f785676fSDimitry Andric       EmitGlobalVarDefinition(D);
2328284c1978SDimitry Andric     }
2329f22ef01cSRoman Divacky 
233059d1ed5bSDimitry Andric     // Handle XCore specific ABI requirements.
233144290647SDimitry Andric     if (getTriple().getArch() == llvm::Triple::xcore &&
233259d1ed5bSDimitry Andric         D->getLanguageLinkage() == CLanguageLinkage &&
233359d1ed5bSDimitry Andric         D->getType().isConstant(Context) &&
233459d1ed5bSDimitry Andric         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
233559d1ed5bSDimitry Andric       GV->setSection(".cp.rodata");
233659d1ed5bSDimitry Andric   }
233759d1ed5bSDimitry Andric 
23387ae0e2c9SDimitry Andric   if (AddrSpace != Ty->getAddressSpace())
2339f785676fSDimitry Andric     return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
2340f785676fSDimitry Andric 
2341f22ef01cSRoman Divacky   return GV;
2342f22ef01cSRoman Divacky }
2343f22ef01cSRoman Divacky 
23440623d748SDimitry Andric llvm::Constant *
23450623d748SDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
234644290647SDimitry Andric                                ForDefinition_t IsForDefinition) {
234744290647SDimitry Andric   const Decl *D = GD.getDecl();
234844290647SDimitry Andric   if (isa<CXXConstructorDecl>(D))
234944290647SDimitry Andric     return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
23500623d748SDimitry Andric                                 getFromCtorType(GD.getCtorType()),
23510623d748SDimitry Andric                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
23520623d748SDimitry Andric                                 /*DontDefer=*/false, IsForDefinition);
235344290647SDimitry Andric   else if (isa<CXXDestructorDecl>(D))
235444290647SDimitry Andric     return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
23550623d748SDimitry Andric                                 getFromDtorType(GD.getDtorType()),
23560623d748SDimitry Andric                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
23570623d748SDimitry Andric                                 /*DontDefer=*/false, IsForDefinition);
235844290647SDimitry Andric   else if (isa<CXXMethodDecl>(D)) {
23590623d748SDimitry Andric     auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
236044290647SDimitry Andric         cast<CXXMethodDecl>(D));
23610623d748SDimitry Andric     auto Ty = getTypes().GetFunctionType(*FInfo);
23620623d748SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
23630623d748SDimitry Andric                              IsForDefinition);
236444290647SDimitry Andric   } else if (isa<FunctionDecl>(D)) {
23650623d748SDimitry Andric     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
23660623d748SDimitry Andric     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
23670623d748SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
23680623d748SDimitry Andric                              IsForDefinition);
23690623d748SDimitry Andric   } else
237044290647SDimitry Andric     return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
2371e7145dcbSDimitry Andric                               IsForDefinition);
23720623d748SDimitry Andric }
2373f22ef01cSRoman Divacky 
23742754fe60SDimitry Andric llvm::GlobalVariable *
23756122f3e6SDimitry Andric CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
23766122f3e6SDimitry Andric                                       llvm::Type *Ty,
23772754fe60SDimitry Andric                                       llvm::GlobalValue::LinkageTypes Linkage) {
23782754fe60SDimitry Andric   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
237959d1ed5bSDimitry Andric   llvm::GlobalVariable *OldGV = nullptr;
23802754fe60SDimitry Andric 
23812754fe60SDimitry Andric   if (GV) {
23822754fe60SDimitry Andric     // Check if the variable has the right type.
23832754fe60SDimitry Andric     if (GV->getType()->getElementType() == Ty)
23842754fe60SDimitry Andric       return GV;
23852754fe60SDimitry Andric 
23862754fe60SDimitry Andric     // Because C++ name mangling, the only way we can end up with an already
23872754fe60SDimitry Andric     // existing global with the same name is if it has been declared extern "C".
23882754fe60SDimitry Andric     assert(GV->isDeclaration() && "Declaration has wrong type!");
23892754fe60SDimitry Andric     OldGV = GV;
23902754fe60SDimitry Andric   }
23912754fe60SDimitry Andric 
23922754fe60SDimitry Andric   // Create a new variable.
23932754fe60SDimitry Andric   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
239459d1ed5bSDimitry Andric                                 Linkage, nullptr, Name);
23952754fe60SDimitry Andric 
23962754fe60SDimitry Andric   if (OldGV) {
23972754fe60SDimitry Andric     // Replace occurrences of the old variable if needed.
23982754fe60SDimitry Andric     GV->takeName(OldGV);
23992754fe60SDimitry Andric 
24002754fe60SDimitry Andric     if (!OldGV->use_empty()) {
24012754fe60SDimitry Andric       llvm::Constant *NewPtrForOldDecl =
24022754fe60SDimitry Andric       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
24032754fe60SDimitry Andric       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
24042754fe60SDimitry Andric     }
24052754fe60SDimitry Andric 
24062754fe60SDimitry Andric     OldGV->eraseFromParent();
24072754fe60SDimitry Andric   }
24082754fe60SDimitry Andric 
240933956c43SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker() &&
241033956c43SDimitry Andric       !GV->hasAvailableExternallyLinkage())
241133956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
241233956c43SDimitry Andric 
24132754fe60SDimitry Andric   return GV;
24142754fe60SDimitry Andric }
24152754fe60SDimitry Andric 
2416f22ef01cSRoman Divacky /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
2417f22ef01cSRoman Divacky /// given global variable.  If Ty is non-null and if the global doesn't exist,
2418cb4dff85SDimitry Andric /// then it will be created with the specified type instead of whatever the
2419e7145dcbSDimitry Andric /// normal requested type would be. If IsForDefinition is true, it is guranteed
2420e7145dcbSDimitry Andric /// that an actual global with type Ty will be returned, not conversion of a
2421e7145dcbSDimitry Andric /// variable with the same mangled name but some other type.
2422f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
2423e7145dcbSDimitry Andric                                                   llvm::Type *Ty,
242444290647SDimitry Andric                                            ForDefinition_t IsForDefinition) {
2425f22ef01cSRoman Divacky   assert(D->hasGlobalStorage() && "Not a global variable");
2426f22ef01cSRoman Divacky   QualType ASTTy = D->getType();
242759d1ed5bSDimitry Andric   if (!Ty)
2428f22ef01cSRoman Divacky     Ty = getTypes().ConvertTypeForMem(ASTTy);
2429f22ef01cSRoman Divacky 
24306122f3e6SDimitry Andric   llvm::PointerType *PTy =
24313b0f4066SDimitry Andric     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
2432f22ef01cSRoman Divacky 
24336122f3e6SDimitry Andric   StringRef MangledName = getMangledName(D);
2434e7145dcbSDimitry Andric   return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
2435f22ef01cSRoman Divacky }
2436f22ef01cSRoman Divacky 
2437f22ef01cSRoman Divacky /// CreateRuntimeVariable - Create a new runtime global variable with the
2438f22ef01cSRoman Divacky /// specified type and name.
2439f22ef01cSRoman Divacky llvm::Constant *
24406122f3e6SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
24416122f3e6SDimitry Andric                                      StringRef Name) {
244259d1ed5bSDimitry Andric   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
2443f22ef01cSRoman Divacky }
2444f22ef01cSRoman Divacky 
2445f22ef01cSRoman Divacky void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
2446f22ef01cSRoman Divacky   assert(!D->getInit() && "Cannot emit definite definitions here!");
2447f22ef01cSRoman Divacky 
24486122f3e6SDimitry Andric   StringRef MangledName = getMangledName(D);
2449e7145dcbSDimitry Andric   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
2450e7145dcbSDimitry Andric 
2451e7145dcbSDimitry Andric   // We already have a definition, not declaration, with the same mangled name.
2452e7145dcbSDimitry Andric   // Emitting of declaration is not required (and actually overwrites emitted
2453e7145dcbSDimitry Andric   // definition).
2454e7145dcbSDimitry Andric   if (GV && !GV->isDeclaration())
2455e7145dcbSDimitry Andric     return;
2456e7145dcbSDimitry Andric 
2457e7145dcbSDimitry Andric   // If we have not seen a reference to this variable yet, place it into the
2458e7145dcbSDimitry Andric   // deferred declarations table to be emitted if needed later.
2459e7145dcbSDimitry Andric   if (!MustBeEmitted(D) && !GV) {
2460f22ef01cSRoman Divacky       DeferredDecls[MangledName] = D;
2461f22ef01cSRoman Divacky       return;
2462f22ef01cSRoman Divacky   }
2463f22ef01cSRoman Divacky 
2464f22ef01cSRoman Divacky   // The tentative definition is the only definition.
2465f22ef01cSRoman Divacky   EmitGlobalVarDefinition(D);
2466f22ef01cSRoman Divacky }
2467f22ef01cSRoman Divacky 
24686122f3e6SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
24692754fe60SDimitry Andric   return Context.toCharUnitsFromBits(
24700623d748SDimitry Andric       getDataLayout().getTypeStoreSizeInBits(Ty));
2471f22ef01cSRoman Divacky }
2472f22ef01cSRoman Divacky 
24737ae0e2c9SDimitry Andric unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
24747ae0e2c9SDimitry Andric                                                  unsigned AddrSpace) {
2475e7145dcbSDimitry Andric   if (D && LangOpts.CUDA && LangOpts.CUDAIsDevice) {
24767ae0e2c9SDimitry Andric     if (D->hasAttr<CUDAConstantAttr>())
24777ae0e2c9SDimitry Andric       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
24787ae0e2c9SDimitry Andric     else if (D->hasAttr<CUDASharedAttr>())
24797ae0e2c9SDimitry Andric       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
24807ae0e2c9SDimitry Andric     else
24817ae0e2c9SDimitry Andric       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
24827ae0e2c9SDimitry Andric   }
24837ae0e2c9SDimitry Andric 
24847ae0e2c9SDimitry Andric   return AddrSpace;
24857ae0e2c9SDimitry Andric }
24867ae0e2c9SDimitry Andric 
2487284c1978SDimitry Andric template<typename SomeDecl>
2488284c1978SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
2489284c1978SDimitry Andric                                                llvm::GlobalValue *GV) {
2490284c1978SDimitry Andric   if (!getLangOpts().CPlusPlus)
2491284c1978SDimitry Andric     return;
2492284c1978SDimitry Andric 
2493284c1978SDimitry Andric   // Must have 'used' attribute, or else inline assembly can't rely on
2494284c1978SDimitry Andric   // the name existing.
2495284c1978SDimitry Andric   if (!D->template hasAttr<UsedAttr>())
2496284c1978SDimitry Andric     return;
2497284c1978SDimitry Andric 
2498284c1978SDimitry Andric   // Must have internal linkage and an ordinary name.
2499f785676fSDimitry Andric   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
2500284c1978SDimitry Andric     return;
2501284c1978SDimitry Andric 
2502284c1978SDimitry Andric   // Must be in an extern "C" context. Entities declared directly within
2503284c1978SDimitry Andric   // a record are not extern "C" even if the record is in such a context.
2504f785676fSDimitry Andric   const SomeDecl *First = D->getFirstDecl();
2505284c1978SDimitry Andric   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
2506284c1978SDimitry Andric     return;
2507284c1978SDimitry Andric 
2508284c1978SDimitry Andric   // OK, this is an internal linkage entity inside an extern "C" linkage
2509284c1978SDimitry Andric   // specification. Make a note of that so we can give it the "expected"
2510284c1978SDimitry Andric   // mangled name if nothing else is using that name.
2511284c1978SDimitry Andric   std::pair<StaticExternCMap::iterator, bool> R =
2512284c1978SDimitry Andric       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
2513284c1978SDimitry Andric 
2514284c1978SDimitry Andric   // If we have multiple internal linkage entities with the same name
2515284c1978SDimitry Andric   // in extern "C" regions, none of them gets that name.
2516284c1978SDimitry Andric   if (!R.second)
251759d1ed5bSDimitry Andric     R.first->second = nullptr;
2518284c1978SDimitry Andric }
2519284c1978SDimitry Andric 
252033956c43SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
252133956c43SDimitry Andric   if (!CGM.supportsCOMDAT())
252233956c43SDimitry Andric     return false;
252333956c43SDimitry Andric 
252433956c43SDimitry Andric   if (D.hasAttr<SelectAnyAttr>())
252533956c43SDimitry Andric     return true;
252633956c43SDimitry Andric 
252733956c43SDimitry Andric   GVALinkage Linkage;
252833956c43SDimitry Andric   if (auto *VD = dyn_cast<VarDecl>(&D))
252933956c43SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
253033956c43SDimitry Andric   else
253133956c43SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
253233956c43SDimitry Andric 
253333956c43SDimitry Andric   switch (Linkage) {
253433956c43SDimitry Andric   case GVA_Internal:
253533956c43SDimitry Andric   case GVA_AvailableExternally:
253633956c43SDimitry Andric   case GVA_StrongExternal:
253733956c43SDimitry Andric     return false;
253833956c43SDimitry Andric   case GVA_DiscardableODR:
253933956c43SDimitry Andric   case GVA_StrongODR:
254033956c43SDimitry Andric     return true;
254133956c43SDimitry Andric   }
254233956c43SDimitry Andric   llvm_unreachable("No such linkage");
254333956c43SDimitry Andric }
254433956c43SDimitry Andric 
254533956c43SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
254633956c43SDimitry Andric                                           llvm::GlobalObject &GO) {
254733956c43SDimitry Andric   if (!shouldBeInCOMDAT(*this, D))
254833956c43SDimitry Andric     return;
254933956c43SDimitry Andric   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
255033956c43SDimitry Andric }
255133956c43SDimitry Andric 
2552e7145dcbSDimitry Andric /// Pass IsTentative as true if you want to create a tentative definition.
2553e7145dcbSDimitry Andric void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
2554e7145dcbSDimitry Andric                                             bool IsTentative) {
255544290647SDimitry Andric   // OpenCL global variables of sampler type are translated to function calls,
255644290647SDimitry Andric   // therefore no need to be translated.
2557f22ef01cSRoman Divacky   QualType ASTTy = D->getType();
255844290647SDimitry Andric   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
255944290647SDimitry Andric     return;
256044290647SDimitry Andric 
256144290647SDimitry Andric   llvm::Constant *Init = nullptr;
2562dff0c46cSDimitry Andric   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2563dff0c46cSDimitry Andric   bool NeedsGlobalCtor = false;
2564dff0c46cSDimitry Andric   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
2565f22ef01cSRoman Divacky 
2566dff0c46cSDimitry Andric   const VarDecl *InitDecl;
2567dff0c46cSDimitry Andric   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2568f22ef01cSRoman Divacky 
2569e7145dcbSDimitry Andric   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
2570e7145dcbSDimitry Andric   // as part of their declaration."  Sema has already checked for
2571e7145dcbSDimitry Andric   // error cases, so we just need to set Init to UndefValue.
2572e7145dcbSDimitry Andric   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
2573e7145dcbSDimitry Andric       D->hasAttr<CUDASharedAttr>())
25740623d748SDimitry Andric     Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
2575e7145dcbSDimitry Andric   else if (!InitExpr) {
2576f22ef01cSRoman Divacky     // This is a tentative definition; tentative definitions are
2577f22ef01cSRoman Divacky     // implicitly initialized with { 0 }.
2578f22ef01cSRoman Divacky     //
2579f22ef01cSRoman Divacky     // Note that tentative definitions are only emitted at the end of
2580f22ef01cSRoman Divacky     // a translation unit, so they should never have incomplete
2581f22ef01cSRoman Divacky     // type. In addition, EmitTentativeDefinition makes sure that we
2582f22ef01cSRoman Divacky     // never attempt to emit a tentative definition if a real one
2583f22ef01cSRoman Divacky     // exists. A use may still exists, however, so we still may need
2584f22ef01cSRoman Divacky     // to do a RAUW.
2585f22ef01cSRoman Divacky     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
2586f22ef01cSRoman Divacky     Init = EmitNullConstant(D->getType());
2587f22ef01cSRoman Divacky   } else {
25887ae0e2c9SDimitry Andric     initializedGlobalDecl = GlobalDecl(D);
2589dff0c46cSDimitry Andric     Init = EmitConstantInit(*InitDecl);
2590f785676fSDimitry Andric 
2591f22ef01cSRoman Divacky     if (!Init) {
2592f22ef01cSRoman Divacky       QualType T = InitExpr->getType();
2593f22ef01cSRoman Divacky       if (D->getType()->isReferenceType())
2594f22ef01cSRoman Divacky         T = D->getType();
2595f22ef01cSRoman Divacky 
2596dff0c46cSDimitry Andric       if (getLangOpts().CPlusPlus) {
2597f22ef01cSRoman Divacky         Init = EmitNullConstant(T);
2598dff0c46cSDimitry Andric         NeedsGlobalCtor = true;
2599f22ef01cSRoman Divacky       } else {
2600f22ef01cSRoman Divacky         ErrorUnsupported(D, "static initializer");
2601f22ef01cSRoman Divacky         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2602f22ef01cSRoman Divacky       }
2603e580952dSDimitry Andric     } else {
2604e580952dSDimitry Andric       // We don't need an initializer, so remove the entry for the delayed
2605dff0c46cSDimitry Andric       // initializer position (just in case this entry was delayed) if we
2606dff0c46cSDimitry Andric       // also don't need to register a destructor.
2607dff0c46cSDimitry Andric       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
2608e580952dSDimitry Andric         DelayedCXXInitPosition.erase(D);
2609f22ef01cSRoman Divacky     }
2610f22ef01cSRoman Divacky   }
2611f22ef01cSRoman Divacky 
26126122f3e6SDimitry Andric   llvm::Type* InitType = Init->getType();
2613e7145dcbSDimitry Andric   llvm::Constant *Entry =
261444290647SDimitry Andric       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
2615f22ef01cSRoman Divacky 
2616f22ef01cSRoman Divacky   // Strip off a bitcast if we got one back.
261759d1ed5bSDimitry Andric   if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2618f22ef01cSRoman Divacky     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2619f785676fSDimitry Andric            CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2620f785676fSDimitry Andric            // All zero index gep.
2621f22ef01cSRoman Divacky            CE->getOpcode() == llvm::Instruction::GetElementPtr);
2622f22ef01cSRoman Divacky     Entry = CE->getOperand(0);
2623f22ef01cSRoman Divacky   }
2624f22ef01cSRoman Divacky 
2625f22ef01cSRoman Divacky   // Entry is now either a Function or GlobalVariable.
262659d1ed5bSDimitry Andric   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2627f22ef01cSRoman Divacky 
2628f22ef01cSRoman Divacky   // We have a definition after a declaration with the wrong type.
2629f22ef01cSRoman Divacky   // We must make a new GlobalVariable* and update everything that used OldGV
2630f22ef01cSRoman Divacky   // (a declaration or tentative definition) with the new GlobalVariable*
2631f22ef01cSRoman Divacky   // (which will be a definition).
2632f22ef01cSRoman Divacky   //
2633f22ef01cSRoman Divacky   // This happens if there is a prototype for a global (e.g.
2634f22ef01cSRoman Divacky   // "extern int x[];") and then a definition of a different type (e.g.
2635f22ef01cSRoman Divacky   // "int x[10];"). This also happens when an initializer has a different type
2636f22ef01cSRoman Divacky   // from the type of the global (this happens with unions).
263759d1ed5bSDimitry Andric   if (!GV ||
2638f22ef01cSRoman Divacky       GV->getType()->getElementType() != InitType ||
26393b0f4066SDimitry Andric       GV->getType()->getAddressSpace() !=
26407ae0e2c9SDimitry Andric        GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
2641f22ef01cSRoman Divacky 
2642f22ef01cSRoman Divacky     // Move the old entry aside so that we'll create a new one.
26436122f3e6SDimitry Andric     Entry->setName(StringRef());
2644f22ef01cSRoman Divacky 
2645f22ef01cSRoman Divacky     // Make a new global with the correct type, this is now guaranteed to work.
2646e7145dcbSDimitry Andric     GV = cast<llvm::GlobalVariable>(
264744290647SDimitry Andric         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
2648f22ef01cSRoman Divacky 
2649f22ef01cSRoman Divacky     // Replace all uses of the old global with the new global
2650f22ef01cSRoman Divacky     llvm::Constant *NewPtrForOldDecl =
2651f22ef01cSRoman Divacky         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2652f22ef01cSRoman Divacky     Entry->replaceAllUsesWith(NewPtrForOldDecl);
2653f22ef01cSRoman Divacky 
2654f22ef01cSRoman Divacky     // Erase the old global, since it is no longer used.
2655f22ef01cSRoman Divacky     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2656f22ef01cSRoman Divacky   }
2657f22ef01cSRoman Divacky 
2658284c1978SDimitry Andric   MaybeHandleStaticInExternC(D, GV);
2659284c1978SDimitry Andric 
26606122f3e6SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
26616122f3e6SDimitry Andric     AddGlobalAnnotations(D, GV);
2662f22ef01cSRoman Divacky 
2663e7145dcbSDimitry Andric   // Set the llvm linkage type as appropriate.
2664e7145dcbSDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
2665e7145dcbSDimitry Andric       getLLVMLinkageVarDefinition(D, GV->isConstant());
2666e7145dcbSDimitry Andric 
26670623d748SDimitry Andric   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
26680623d748SDimitry Andric   // the device. [...]"
26690623d748SDimitry Andric   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
26700623d748SDimitry Andric   // __device__, declares a variable that: [...]
26710623d748SDimitry Andric   // Is accessible from all the threads within the grid and from the host
26720623d748SDimitry Andric   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
26730623d748SDimitry Andric   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
2674e7145dcbSDimitry Andric   if (GV && LangOpts.CUDA) {
2675e7145dcbSDimitry Andric     if (LangOpts.CUDAIsDevice) {
2676e7145dcbSDimitry Andric       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
26770623d748SDimitry Andric         GV->setExternallyInitialized(true);
2678e7145dcbSDimitry Andric     } else {
2679e7145dcbSDimitry Andric       // Host-side shadows of external declarations of device-side
2680e7145dcbSDimitry Andric       // global variables become internal definitions. These have to
2681e7145dcbSDimitry Andric       // be internal in order to prevent name conflicts with global
2682e7145dcbSDimitry Andric       // host variables with the same name in a different TUs.
2683e7145dcbSDimitry Andric       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
2684e7145dcbSDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
2685e7145dcbSDimitry Andric 
2686e7145dcbSDimitry Andric         // Shadow variables and their properties must be registered
2687e7145dcbSDimitry Andric         // with CUDA runtime.
2688e7145dcbSDimitry Andric         unsigned Flags = 0;
2689e7145dcbSDimitry Andric         if (!D->hasDefinition())
2690e7145dcbSDimitry Andric           Flags |= CGCUDARuntime::ExternDeviceVar;
2691e7145dcbSDimitry Andric         if (D->hasAttr<CUDAConstantAttr>())
2692e7145dcbSDimitry Andric           Flags |= CGCUDARuntime::ConstantDeviceVar;
2693e7145dcbSDimitry Andric         getCUDARuntime().registerDeviceVar(*GV, Flags);
2694e7145dcbSDimitry Andric       } else if (D->hasAttr<CUDASharedAttr>())
2695e7145dcbSDimitry Andric         // __shared__ variables are odd. Shadows do get created, but
2696e7145dcbSDimitry Andric         // they are not registered with the CUDA runtime, so they
2697e7145dcbSDimitry Andric         // can't really be used to access their device-side
2698e7145dcbSDimitry Andric         // counterparts. It's not clear yet whether it's nvcc's bug or
2699e7145dcbSDimitry Andric         // a feature, but we've got to do the same for compatibility.
2700e7145dcbSDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
2701e7145dcbSDimitry Andric     }
27020623d748SDimitry Andric   }
2703f22ef01cSRoman Divacky   GV->setInitializer(Init);
2704f22ef01cSRoman Divacky 
2705f22ef01cSRoman Divacky   // If it is safe to mark the global 'constant', do so now.
2706dff0c46cSDimitry Andric   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2707dff0c46cSDimitry Andric                   isTypeConstant(D->getType(), true));
2708f22ef01cSRoman Divacky 
270939d628a0SDimitry Andric   // If it is in a read-only section, mark it 'constant'.
271039d628a0SDimitry Andric   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
271139d628a0SDimitry Andric     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
271239d628a0SDimitry Andric     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
271339d628a0SDimitry Andric       GV->setConstant(true);
271439d628a0SDimitry Andric   }
271539d628a0SDimitry Andric 
2716f22ef01cSRoman Divacky   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2717f22ef01cSRoman Divacky 
2718f785676fSDimitry Andric 
27190623d748SDimitry Andric   // On Darwin, if the normal linkage of a C++ thread_local variable is
27200623d748SDimitry Andric   // LinkOnce or Weak, we keep the normal linkage to prevent multiple
27210623d748SDimitry Andric   // copies within a linkage unit; otherwise, the backing variable has
27220623d748SDimitry Andric   // internal linkage and all accesses should just be calls to the
272359d1ed5bSDimitry Andric   // Itanium-specified entry point, which has the normal linkage of the
27240623d748SDimitry Andric   // variable. This is to preserve the ability to change the implementation
27250623d748SDimitry Andric   // behind the scenes.
272639d628a0SDimitry Andric   if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
27270623d748SDimitry Andric       Context.getTargetInfo().getTriple().isOSDarwin() &&
27280623d748SDimitry Andric       !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
27290623d748SDimitry Andric       !llvm::GlobalVariable::isWeakLinkage(Linkage))
273059d1ed5bSDimitry Andric     Linkage = llvm::GlobalValue::InternalLinkage;
273159d1ed5bSDimitry Andric 
273259d1ed5bSDimitry Andric   GV->setLinkage(Linkage);
273359d1ed5bSDimitry Andric   if (D->hasAttr<DLLImportAttr>())
273459d1ed5bSDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
273559d1ed5bSDimitry Andric   else if (D->hasAttr<DLLExportAttr>())
273659d1ed5bSDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
273739d628a0SDimitry Andric   else
273839d628a0SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2739f785676fSDimitry Andric 
274044290647SDimitry Andric   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
2741f22ef01cSRoman Divacky     // common vars aren't constant even if declared const.
2742f22ef01cSRoman Divacky     GV->setConstant(false);
274344290647SDimitry Andric     // Tentative definition of global variables may be initialized with
274444290647SDimitry Andric     // non-zero null pointers. In this case they should have weak linkage
274544290647SDimitry Andric     // since common linkage must have zero initializer and must not have
274644290647SDimitry Andric     // explicit section therefore cannot have non-zero initial value.
274744290647SDimitry Andric     if (!GV->getInitializer()->isNullValue())
274844290647SDimitry Andric       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
274944290647SDimitry Andric   }
2750f22ef01cSRoman Divacky 
275159d1ed5bSDimitry Andric   setNonAliasAttributes(D, GV);
2752f22ef01cSRoman Divacky 
275339d628a0SDimitry Andric   if (D->getTLSKind() && !GV->isThreadLocal()) {
275439d628a0SDimitry Andric     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
27550623d748SDimitry Andric       CXXThreadLocals.push_back(D);
275639d628a0SDimitry Andric     setTLSMode(GV, *D);
275739d628a0SDimitry Andric   }
275839d628a0SDimitry Andric 
275933956c43SDimitry Andric   maybeSetTrivialComdat(*D, *GV);
276033956c43SDimitry Andric 
27612754fe60SDimitry Andric   // Emit the initializer function if necessary.
2762dff0c46cSDimitry Andric   if (NeedsGlobalCtor || NeedsGlobalDtor)
2763dff0c46cSDimitry Andric     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
27642754fe60SDimitry Andric 
276539d628a0SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
27663861d79fSDimitry Andric 
2767f22ef01cSRoman Divacky   // Emit global variable debug information.
27686122f3e6SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
2769e7145dcbSDimitry Andric     if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
2770f22ef01cSRoman Divacky       DI->EmitGlobalVariable(GV, D);
2771f22ef01cSRoman Divacky }
2772f22ef01cSRoman Divacky 
277339d628a0SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context,
277433956c43SDimitry Andric                                       CodeGenModule &CGM, const VarDecl *D,
277533956c43SDimitry Andric                                       bool NoCommon) {
277659d1ed5bSDimitry Andric   // Don't give variables common linkage if -fno-common was specified unless it
277759d1ed5bSDimitry Andric   // was overridden by a NoCommon attribute.
277859d1ed5bSDimitry Andric   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
277959d1ed5bSDimitry Andric     return true;
278059d1ed5bSDimitry Andric 
278159d1ed5bSDimitry Andric   // C11 6.9.2/2:
278259d1ed5bSDimitry Andric   //   A declaration of an identifier for an object that has file scope without
278359d1ed5bSDimitry Andric   //   an initializer, and without a storage-class specifier or with the
278459d1ed5bSDimitry Andric   //   storage-class specifier static, constitutes a tentative definition.
278559d1ed5bSDimitry Andric   if (D->getInit() || D->hasExternalStorage())
278659d1ed5bSDimitry Andric     return true;
278759d1ed5bSDimitry Andric 
278859d1ed5bSDimitry Andric   // A variable cannot be both common and exist in a section.
278959d1ed5bSDimitry Andric   if (D->hasAttr<SectionAttr>())
279059d1ed5bSDimitry Andric     return true;
279159d1ed5bSDimitry Andric 
279259d1ed5bSDimitry Andric   // Thread local vars aren't considered common linkage.
279359d1ed5bSDimitry Andric   if (D->getTLSKind())
279459d1ed5bSDimitry Andric     return true;
279559d1ed5bSDimitry Andric 
279659d1ed5bSDimitry Andric   // Tentative definitions marked with WeakImportAttr are true definitions.
279759d1ed5bSDimitry Andric   if (D->hasAttr<WeakImportAttr>())
279859d1ed5bSDimitry Andric     return true;
279959d1ed5bSDimitry Andric 
280033956c43SDimitry Andric   // A variable cannot be both common and exist in a comdat.
280133956c43SDimitry Andric   if (shouldBeInCOMDAT(CGM, *D))
280233956c43SDimitry Andric     return true;
280333956c43SDimitry Andric 
2804e7145dcbSDimitry Andric   // Declarations with a required alignment do not have common linkage in MSVC
280539d628a0SDimitry Andric   // mode.
28060623d748SDimitry Andric   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
280733956c43SDimitry Andric     if (D->hasAttr<AlignedAttr>())
280839d628a0SDimitry Andric       return true;
280933956c43SDimitry Andric     QualType VarType = D->getType();
281033956c43SDimitry Andric     if (Context.isAlignmentRequired(VarType))
281133956c43SDimitry Andric       return true;
281233956c43SDimitry Andric 
281333956c43SDimitry Andric     if (const auto *RT = VarType->getAs<RecordType>()) {
281433956c43SDimitry Andric       const RecordDecl *RD = RT->getDecl();
281533956c43SDimitry Andric       for (const FieldDecl *FD : RD->fields()) {
281633956c43SDimitry Andric         if (FD->isBitField())
281733956c43SDimitry Andric           continue;
281833956c43SDimitry Andric         if (FD->hasAttr<AlignedAttr>())
281933956c43SDimitry Andric           return true;
282033956c43SDimitry Andric         if (Context.isAlignmentRequired(FD->getType()))
282133956c43SDimitry Andric           return true;
282233956c43SDimitry Andric       }
282333956c43SDimitry Andric     }
282433956c43SDimitry Andric   }
282539d628a0SDimitry Andric 
282659d1ed5bSDimitry Andric   return false;
282759d1ed5bSDimitry Andric }
282859d1ed5bSDimitry Andric 
282959d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
283059d1ed5bSDimitry Andric     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
28312754fe60SDimitry Andric   if (Linkage == GVA_Internal)
28322754fe60SDimitry Andric     return llvm::Function::InternalLinkage;
283359d1ed5bSDimitry Andric 
283459d1ed5bSDimitry Andric   if (D->hasAttr<WeakAttr>()) {
283559d1ed5bSDimitry Andric     if (IsConstantVariable)
283659d1ed5bSDimitry Andric       return llvm::GlobalVariable::WeakODRLinkage;
283759d1ed5bSDimitry Andric     else
283859d1ed5bSDimitry Andric       return llvm::GlobalVariable::WeakAnyLinkage;
283959d1ed5bSDimitry Andric   }
284059d1ed5bSDimitry Andric 
284159d1ed5bSDimitry Andric   // We are guaranteed to have a strong definition somewhere else,
284259d1ed5bSDimitry Andric   // so we can use available_externally linkage.
284359d1ed5bSDimitry Andric   if (Linkage == GVA_AvailableExternally)
284420e90f04SDimitry Andric     return llvm::GlobalValue::AvailableExternallyLinkage;
284559d1ed5bSDimitry Andric 
284659d1ed5bSDimitry Andric   // Note that Apple's kernel linker doesn't support symbol
284759d1ed5bSDimitry Andric   // coalescing, so we need to avoid linkonce and weak linkages there.
284859d1ed5bSDimitry Andric   // Normally, this means we just map to internal, but for explicit
284959d1ed5bSDimitry Andric   // instantiations we'll map to external.
285059d1ed5bSDimitry Andric 
285159d1ed5bSDimitry Andric   // In C++, the compiler has to emit a definition in every translation unit
285259d1ed5bSDimitry Andric   // that references the function.  We should use linkonce_odr because
285359d1ed5bSDimitry Andric   // a) if all references in this translation unit are optimized away, we
285459d1ed5bSDimitry Andric   // don't need to codegen it.  b) if the function persists, it needs to be
285559d1ed5bSDimitry Andric   // merged with other definitions. c) C++ has the ODR, so we know the
285659d1ed5bSDimitry Andric   // definition is dependable.
285759d1ed5bSDimitry Andric   if (Linkage == GVA_DiscardableODR)
285859d1ed5bSDimitry Andric     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
285959d1ed5bSDimitry Andric                                             : llvm::Function::InternalLinkage;
286059d1ed5bSDimitry Andric 
286159d1ed5bSDimitry Andric   // An explicit instantiation of a template has weak linkage, since
286259d1ed5bSDimitry Andric   // explicit instantiations can occur in multiple translation units
286359d1ed5bSDimitry Andric   // and must all be equivalent. However, we are not allowed to
286459d1ed5bSDimitry Andric   // throw away these explicit instantiations.
2865e7145dcbSDimitry Andric   //
2866e7145dcbSDimitry Andric   // We don't currently support CUDA device code spread out across multiple TUs,
2867e7145dcbSDimitry Andric   // so say that CUDA templates are either external (for kernels) or internal.
2868e7145dcbSDimitry Andric   // This lets llvm perform aggressive inter-procedural optimizations.
2869e7145dcbSDimitry Andric   if (Linkage == GVA_StrongODR) {
2870e7145dcbSDimitry Andric     if (Context.getLangOpts().AppleKext)
2871e7145dcbSDimitry Andric       return llvm::Function::ExternalLinkage;
2872e7145dcbSDimitry Andric     if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
2873e7145dcbSDimitry Andric       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
2874e7145dcbSDimitry Andric                                           : llvm::Function::InternalLinkage;
2875e7145dcbSDimitry Andric     return llvm::Function::WeakODRLinkage;
2876e7145dcbSDimitry Andric   }
287759d1ed5bSDimitry Andric 
287859d1ed5bSDimitry Andric   // C++ doesn't have tentative definitions and thus cannot have common
287959d1ed5bSDimitry Andric   // linkage.
288059d1ed5bSDimitry Andric   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
288133956c43SDimitry Andric       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
288239d628a0SDimitry Andric                                  CodeGenOpts.NoCommon))
288359d1ed5bSDimitry Andric     return llvm::GlobalVariable::CommonLinkage;
288459d1ed5bSDimitry Andric 
2885f785676fSDimitry Andric   // selectany symbols are externally visible, so use weak instead of
2886f785676fSDimitry Andric   // linkonce.  MSVC optimizes away references to const selectany globals, so
2887f785676fSDimitry Andric   // all definitions should be the same and ODR linkage should be used.
2888f785676fSDimitry Andric   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
288959d1ed5bSDimitry Andric   if (D->hasAttr<SelectAnyAttr>())
2890f785676fSDimitry Andric     return llvm::GlobalVariable::WeakODRLinkage;
289159d1ed5bSDimitry Andric 
289259d1ed5bSDimitry Andric   // Otherwise, we have strong external linkage.
289359d1ed5bSDimitry Andric   assert(Linkage == GVA_StrongExternal);
28942754fe60SDimitry Andric   return llvm::GlobalVariable::ExternalLinkage;
28952754fe60SDimitry Andric }
28962754fe60SDimitry Andric 
289759d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
289859d1ed5bSDimitry Andric     const VarDecl *VD, bool IsConstant) {
289959d1ed5bSDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
290059d1ed5bSDimitry Andric   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
290159d1ed5bSDimitry Andric }
290259d1ed5bSDimitry Andric 
2903139f7f9bSDimitry Andric /// Replace the uses of a function that was declared with a non-proto type.
2904139f7f9bSDimitry Andric /// We want to silently drop extra arguments from call sites
2905139f7f9bSDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2906139f7f9bSDimitry Andric                                           llvm::Function *newFn) {
2907139f7f9bSDimitry Andric   // Fast path.
2908139f7f9bSDimitry Andric   if (old->use_empty()) return;
2909139f7f9bSDimitry Andric 
2910139f7f9bSDimitry Andric   llvm::Type *newRetTy = newFn->getReturnType();
2911139f7f9bSDimitry Andric   SmallVector<llvm::Value*, 4> newArgs;
29120623d748SDimitry Andric   SmallVector<llvm::OperandBundleDef, 1> newBundles;
2913139f7f9bSDimitry Andric 
2914139f7f9bSDimitry Andric   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2915139f7f9bSDimitry Andric          ui != ue; ) {
2916139f7f9bSDimitry Andric     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
291759d1ed5bSDimitry Andric     llvm::User *user = use->getUser();
2918139f7f9bSDimitry Andric 
2919139f7f9bSDimitry Andric     // Recognize and replace uses of bitcasts.  Most calls to
2920139f7f9bSDimitry Andric     // unprototyped functions will use bitcasts.
292159d1ed5bSDimitry Andric     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
2922139f7f9bSDimitry Andric       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2923139f7f9bSDimitry Andric         replaceUsesOfNonProtoConstant(bitcast, newFn);
2924139f7f9bSDimitry Andric       continue;
2925139f7f9bSDimitry Andric     }
2926139f7f9bSDimitry Andric 
2927139f7f9bSDimitry Andric     // Recognize calls to the function.
2928139f7f9bSDimitry Andric     llvm::CallSite callSite(user);
2929139f7f9bSDimitry Andric     if (!callSite) continue;
293059d1ed5bSDimitry Andric     if (!callSite.isCallee(&*use)) continue;
2931139f7f9bSDimitry Andric 
2932139f7f9bSDimitry Andric     // If the return types don't match exactly, then we can't
2933139f7f9bSDimitry Andric     // transform this call unless it's dead.
2934139f7f9bSDimitry Andric     if (callSite->getType() != newRetTy && !callSite->use_empty())
2935139f7f9bSDimitry Andric       continue;
2936139f7f9bSDimitry Andric 
2937139f7f9bSDimitry Andric     // Get the call site's attribute list.
293820e90f04SDimitry Andric     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
293920e90f04SDimitry Andric     llvm::AttributeList oldAttrs = callSite.getAttributes();
2940139f7f9bSDimitry Andric 
2941139f7f9bSDimitry Andric     // If the function was passed too few arguments, don't transform.
2942139f7f9bSDimitry Andric     unsigned newNumArgs = newFn->arg_size();
2943139f7f9bSDimitry Andric     if (callSite.arg_size() < newNumArgs) continue;
2944139f7f9bSDimitry Andric 
2945139f7f9bSDimitry Andric     // If extra arguments were passed, we silently drop them.
2946139f7f9bSDimitry Andric     // If any of the types mismatch, we don't transform.
2947139f7f9bSDimitry Andric     unsigned argNo = 0;
2948139f7f9bSDimitry Andric     bool dontTransform = false;
294920e90f04SDimitry Andric     for (llvm::Argument &A : newFn->args()) {
295020e90f04SDimitry Andric       if (callSite.getArgument(argNo)->getType() != A.getType()) {
2951139f7f9bSDimitry Andric         dontTransform = true;
2952139f7f9bSDimitry Andric         break;
2953139f7f9bSDimitry Andric       }
2954139f7f9bSDimitry Andric 
2955139f7f9bSDimitry Andric       // Add any parameter attributes.
295620e90f04SDimitry Andric       newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
295720e90f04SDimitry Andric       argNo++;
2958139f7f9bSDimitry Andric     }
2959139f7f9bSDimitry Andric     if (dontTransform)
2960139f7f9bSDimitry Andric       continue;
2961139f7f9bSDimitry Andric 
2962139f7f9bSDimitry Andric     // Okay, we can transform this.  Create the new call instruction and copy
2963139f7f9bSDimitry Andric     // over the required information.
2964139f7f9bSDimitry Andric     newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2965139f7f9bSDimitry Andric 
29660623d748SDimitry Andric     // Copy over any operand bundles.
29670623d748SDimitry Andric     callSite.getOperandBundlesAsDefs(newBundles);
29680623d748SDimitry Andric 
2969139f7f9bSDimitry Andric     llvm::CallSite newCall;
2970139f7f9bSDimitry Andric     if (callSite.isCall()) {
29710623d748SDimitry Andric       newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
2972139f7f9bSDimitry Andric                                        callSite.getInstruction());
2973139f7f9bSDimitry Andric     } else {
297459d1ed5bSDimitry Andric       auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
2975139f7f9bSDimitry Andric       newCall = llvm::InvokeInst::Create(newFn,
2976139f7f9bSDimitry Andric                                          oldInvoke->getNormalDest(),
2977139f7f9bSDimitry Andric                                          oldInvoke->getUnwindDest(),
29780623d748SDimitry Andric                                          newArgs, newBundles, "",
2979139f7f9bSDimitry Andric                                          callSite.getInstruction());
2980139f7f9bSDimitry Andric     }
2981139f7f9bSDimitry Andric     newArgs.clear(); // for the next iteration
2982139f7f9bSDimitry Andric 
2983139f7f9bSDimitry Andric     if (!newCall->getType()->isVoidTy())
2984139f7f9bSDimitry Andric       newCall->takeName(callSite.getInstruction());
298520e90f04SDimitry Andric     newCall.setAttributes(llvm::AttributeList::get(
298620e90f04SDimitry Andric         newFn->getContext(), oldAttrs.getFnAttributes(),
298720e90f04SDimitry Andric         oldAttrs.getRetAttributes(), newArgAttrs));
2988139f7f9bSDimitry Andric     newCall.setCallingConv(callSite.getCallingConv());
2989139f7f9bSDimitry Andric 
2990139f7f9bSDimitry Andric     // Finally, remove the old call, replacing any uses with the new one.
2991139f7f9bSDimitry Andric     if (!callSite->use_empty())
2992139f7f9bSDimitry Andric       callSite->replaceAllUsesWith(newCall.getInstruction());
2993139f7f9bSDimitry Andric 
2994139f7f9bSDimitry Andric     // Copy debug location attached to CI.
299533956c43SDimitry Andric     if (callSite->getDebugLoc())
2996139f7f9bSDimitry Andric       newCall->setDebugLoc(callSite->getDebugLoc());
29970623d748SDimitry Andric 
2998139f7f9bSDimitry Andric     callSite->eraseFromParent();
2999139f7f9bSDimitry Andric   }
3000139f7f9bSDimitry Andric }
3001139f7f9bSDimitry Andric 
3002f22ef01cSRoman Divacky /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
3003f22ef01cSRoman Divacky /// implement a function with no prototype, e.g. "int foo() {}".  If there are
3004f22ef01cSRoman Divacky /// existing call uses of the old function in the module, this adjusts them to
3005f22ef01cSRoman Divacky /// call the new function directly.
3006f22ef01cSRoman Divacky ///
3007f22ef01cSRoman Divacky /// This is not just a cleanup: the always_inline pass requires direct calls to
3008f22ef01cSRoman Divacky /// functions to be able to inline them.  If there is a bitcast in the way, it
3009f22ef01cSRoman Divacky /// won't inline them.  Instcombine normally deletes these calls, but it isn't
3010f22ef01cSRoman Divacky /// run at -O0.
3011f22ef01cSRoman Divacky static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3012f22ef01cSRoman Divacky                                                       llvm::Function *NewFn) {
3013f22ef01cSRoman Divacky   // If we're redefining a global as a function, don't transform it.
3014139f7f9bSDimitry Andric   if (!isa<llvm::Function>(Old)) return;
3015f22ef01cSRoman Divacky 
3016139f7f9bSDimitry Andric   replaceUsesOfNonProtoConstant(Old, NewFn);
3017f22ef01cSRoman Divacky }
3018f22ef01cSRoman Divacky 
3019dff0c46cSDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
3020e7145dcbSDimitry Andric   auto DK = VD->isThisDeclarationADefinition();
3021e7145dcbSDimitry Andric   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
3022e7145dcbSDimitry Andric     return;
3023e7145dcbSDimitry Andric 
3024dff0c46cSDimitry Andric   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
3025dff0c46cSDimitry Andric   // If we have a definition, this might be a deferred decl. If the
3026dff0c46cSDimitry Andric   // instantiation is explicit, make sure we emit it at the end.
3027dff0c46cSDimitry Andric   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
3028dff0c46cSDimitry Andric     GetAddrOfGlobalVar(VD);
3029139f7f9bSDimitry Andric 
3030139f7f9bSDimitry Andric   EmitTopLevelDecl(VD);
3031dff0c46cSDimitry Andric }
3032f22ef01cSRoman Divacky 
303359d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
303459d1ed5bSDimitry Andric                                                  llvm::GlobalValue *GV) {
303559d1ed5bSDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
30363b0f4066SDimitry Andric 
30373b0f4066SDimitry Andric   // Compute the function info and LLVM type.
3038dff0c46cSDimitry Andric   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3039dff0c46cSDimitry Andric   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
30403b0f4066SDimitry Andric 
3041f22ef01cSRoman Divacky   // Get or create the prototype for the function.
30420623d748SDimitry Andric   if (!GV || (GV->getType()->getElementType() != Ty))
30430623d748SDimitry Andric     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
30440623d748SDimitry Andric                                                    /*DontDefer=*/true,
304544290647SDimitry Andric                                                    ForDefinition));
3046f22ef01cSRoman Divacky 
30470623d748SDimitry Andric   // Already emitted.
30480623d748SDimitry Andric   if (!GV->isDeclaration())
3049f785676fSDimitry Andric     return;
3050f22ef01cSRoman Divacky 
30512754fe60SDimitry Andric   // We need to set linkage and visibility on the function before
30522754fe60SDimitry Andric   // generating code for it because various parts of IR generation
30532754fe60SDimitry Andric   // want to propagate this information down (e.g. to local static
30542754fe60SDimitry Andric   // declarations).
305559d1ed5bSDimitry Andric   auto *Fn = cast<llvm::Function>(GV);
3056f785676fSDimitry Andric   setFunctionLinkage(GD, Fn);
305797bc6c73SDimitry Andric   setFunctionDLLStorageClass(GD, Fn);
3058f22ef01cSRoman Divacky 
305959d1ed5bSDimitry Andric   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
30602754fe60SDimitry Andric   setGlobalVisibility(Fn, D);
30612754fe60SDimitry Andric 
3062284c1978SDimitry Andric   MaybeHandleStaticInExternC(D, Fn);
3063284c1978SDimitry Andric 
306433956c43SDimitry Andric   maybeSetTrivialComdat(*D, *Fn);
306533956c43SDimitry Andric 
30663b0f4066SDimitry Andric   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
3067f22ef01cSRoman Divacky 
306859d1ed5bSDimitry Andric   setFunctionDefinitionAttributes(D, Fn);
3069f22ef01cSRoman Divacky   SetLLVMFunctionAttributesForDefinition(D, Fn);
3070f22ef01cSRoman Divacky 
3071f22ef01cSRoman Divacky   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
3072f22ef01cSRoman Divacky     AddGlobalCtor(Fn, CA->getPriority());
3073f22ef01cSRoman Divacky   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
3074f22ef01cSRoman Divacky     AddGlobalDtor(Fn, DA->getPriority());
30756122f3e6SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
30766122f3e6SDimitry Andric     AddGlobalAnnotations(D, Fn);
3077f22ef01cSRoman Divacky }
3078f22ef01cSRoman Divacky 
3079f22ef01cSRoman Divacky void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
308059d1ed5bSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
3081f22ef01cSRoman Divacky   const AliasAttr *AA = D->getAttr<AliasAttr>();
3082f22ef01cSRoman Divacky   assert(AA && "Not an alias?");
3083f22ef01cSRoman Divacky 
30846122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
3085f22ef01cSRoman Divacky 
30869a4b3118SDimitry Andric   if (AA->getAliasee() == MangledName) {
3087e7145dcbSDimitry Andric     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
30889a4b3118SDimitry Andric     return;
30899a4b3118SDimitry Andric   }
30909a4b3118SDimitry Andric 
3091f22ef01cSRoman Divacky   // If there is a definition in the module, then it wins over the alias.
3092f22ef01cSRoman Divacky   // This is dubious, but allow it to be safe.  Just ignore the alias.
3093f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3094f22ef01cSRoman Divacky   if (Entry && !Entry->isDeclaration())
3095f22ef01cSRoman Divacky     return;
3096f22ef01cSRoman Divacky 
3097f785676fSDimitry Andric   Aliases.push_back(GD);
3098f785676fSDimitry Andric 
30996122f3e6SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3100f22ef01cSRoman Divacky 
3101f22ef01cSRoman Divacky   // Create a reference to the named value.  This ensures that it is emitted
3102f22ef01cSRoman Divacky   // if a deferred decl.
3103f22ef01cSRoman Divacky   llvm::Constant *Aliasee;
3104f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(DeclTy))
31053861d79fSDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
31062754fe60SDimitry Andric                                       /*ForVTable=*/false);
3107f22ef01cSRoman Divacky   else
3108f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
310959d1ed5bSDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
311039d628a0SDimitry Andric                                     /*D=*/nullptr);
3111f22ef01cSRoman Divacky 
3112f22ef01cSRoman Divacky   // Create the new alias itself, but don't set a name yet.
311359d1ed5bSDimitry Andric   auto *GA = llvm::GlobalAlias::create(
31140623d748SDimitry Andric       DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
3115f22ef01cSRoman Divacky 
3116f22ef01cSRoman Divacky   if (Entry) {
311759d1ed5bSDimitry Andric     if (GA->getAliasee() == Entry) {
3118e7145dcbSDimitry Andric       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
311959d1ed5bSDimitry Andric       return;
312059d1ed5bSDimitry Andric     }
312159d1ed5bSDimitry Andric 
3122f22ef01cSRoman Divacky     assert(Entry->isDeclaration());
3123f22ef01cSRoman Divacky 
3124f22ef01cSRoman Divacky     // If there is a declaration in the module, then we had an extern followed
3125f22ef01cSRoman Divacky     // by the alias, as in:
3126f22ef01cSRoman Divacky     //   extern int test6();
3127f22ef01cSRoman Divacky     //   ...
3128f22ef01cSRoman Divacky     //   int test6() __attribute__((alias("test7")));
3129f22ef01cSRoman Divacky     //
3130f22ef01cSRoman Divacky     // Remove it and replace uses of it with the alias.
3131f22ef01cSRoman Divacky     GA->takeName(Entry);
3132f22ef01cSRoman Divacky 
3133f22ef01cSRoman Divacky     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
3134f22ef01cSRoman Divacky                                                           Entry->getType()));
3135f22ef01cSRoman Divacky     Entry->eraseFromParent();
3136f22ef01cSRoman Divacky   } else {
3137ffd1746dSEd Schouten     GA->setName(MangledName);
3138f22ef01cSRoman Divacky   }
3139f22ef01cSRoman Divacky 
3140f22ef01cSRoman Divacky   // Set attributes which are particular to an alias; this is a
3141f22ef01cSRoman Divacky   // specialization of the attributes which may be set on a global
3142f22ef01cSRoman Divacky   // variable/function.
314339d628a0SDimitry Andric   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
31443b0f4066SDimitry Andric       D->isWeakImported()) {
3145f22ef01cSRoman Divacky     GA->setLinkage(llvm::Function::WeakAnyLinkage);
3146f22ef01cSRoman Divacky   }
3147f22ef01cSRoman Divacky 
314839d628a0SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
314939d628a0SDimitry Andric     if (VD->getTLSKind())
315039d628a0SDimitry Andric       setTLSMode(GA, *VD);
315139d628a0SDimitry Andric 
315239d628a0SDimitry Andric   setAliasAttributes(D, GA);
3153f22ef01cSRoman Divacky }
3154f22ef01cSRoman Divacky 
3155e7145dcbSDimitry Andric void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
3156e7145dcbSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
3157e7145dcbSDimitry Andric   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
3158e7145dcbSDimitry Andric   assert(IFA && "Not an ifunc?");
3159e7145dcbSDimitry Andric 
3160e7145dcbSDimitry Andric   StringRef MangledName = getMangledName(GD);
3161e7145dcbSDimitry Andric 
3162e7145dcbSDimitry Andric   if (IFA->getResolver() == MangledName) {
3163e7145dcbSDimitry Andric     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3164e7145dcbSDimitry Andric     return;
3165e7145dcbSDimitry Andric   }
3166e7145dcbSDimitry Andric 
3167e7145dcbSDimitry Andric   // Report an error if some definition overrides ifunc.
3168e7145dcbSDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3169e7145dcbSDimitry Andric   if (Entry && !Entry->isDeclaration()) {
3170e7145dcbSDimitry Andric     GlobalDecl OtherGD;
3171e7145dcbSDimitry Andric     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3172e7145dcbSDimitry Andric         DiagnosedConflictingDefinitions.insert(GD).second) {
3173e7145dcbSDimitry Andric       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
3174e7145dcbSDimitry Andric       Diags.Report(OtherGD.getDecl()->getLocation(),
3175e7145dcbSDimitry Andric                    diag::note_previous_definition);
3176e7145dcbSDimitry Andric     }
3177e7145dcbSDimitry Andric     return;
3178e7145dcbSDimitry Andric   }
3179e7145dcbSDimitry Andric 
3180e7145dcbSDimitry Andric   Aliases.push_back(GD);
3181e7145dcbSDimitry Andric 
3182e7145dcbSDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3183e7145dcbSDimitry Andric   llvm::Constant *Resolver =
3184e7145dcbSDimitry Andric       GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3185e7145dcbSDimitry Andric                               /*ForVTable=*/false);
3186e7145dcbSDimitry Andric   llvm::GlobalIFunc *GIF =
3187e7145dcbSDimitry Andric       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
3188e7145dcbSDimitry Andric                                 "", Resolver, &getModule());
3189e7145dcbSDimitry Andric   if (Entry) {
3190e7145dcbSDimitry Andric     if (GIF->getResolver() == Entry) {
3191e7145dcbSDimitry Andric       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3192e7145dcbSDimitry Andric       return;
3193e7145dcbSDimitry Andric     }
3194e7145dcbSDimitry Andric     assert(Entry->isDeclaration());
3195e7145dcbSDimitry Andric 
3196e7145dcbSDimitry Andric     // If there is a declaration in the module, then we had an extern followed
3197e7145dcbSDimitry Andric     // by the ifunc, as in:
3198e7145dcbSDimitry Andric     //   extern int test();
3199e7145dcbSDimitry Andric     //   ...
3200e7145dcbSDimitry Andric     //   int test() __attribute__((ifunc("resolver")));
3201e7145dcbSDimitry Andric     //
3202e7145dcbSDimitry Andric     // Remove it and replace uses of it with the ifunc.
3203e7145dcbSDimitry Andric     GIF->takeName(Entry);
3204e7145dcbSDimitry Andric 
3205e7145dcbSDimitry Andric     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3206e7145dcbSDimitry Andric                                                           Entry->getType()));
3207e7145dcbSDimitry Andric     Entry->eraseFromParent();
3208e7145dcbSDimitry Andric   } else
3209e7145dcbSDimitry Andric     GIF->setName(MangledName);
3210e7145dcbSDimitry Andric 
3211e7145dcbSDimitry Andric   SetCommonAttributes(D, GIF);
3212e7145dcbSDimitry Andric }
3213e7145dcbSDimitry Andric 
321417a519f9SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
32156122f3e6SDimitry Andric                                             ArrayRef<llvm::Type*> Tys) {
321617a519f9SDimitry Andric   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
321717a519f9SDimitry Andric                                          Tys);
3218f22ef01cSRoman Divacky }
3219f22ef01cSRoman Divacky 
322033956c43SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> &
322133956c43SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
322233956c43SDimitry Andric                          const StringLiteral *Literal, bool TargetIsLSB,
322333956c43SDimitry Andric                          bool &IsUTF16, unsigned &StringLength) {
32246122f3e6SDimitry Andric   StringRef String = Literal->getString();
3225e580952dSDimitry Andric   unsigned NumBytes = String.size();
3226f22ef01cSRoman Divacky 
3227f22ef01cSRoman Divacky   // Check for simple case.
3228f22ef01cSRoman Divacky   if (!Literal->containsNonAsciiOrNull()) {
3229f22ef01cSRoman Divacky     StringLength = NumBytes;
323039d628a0SDimitry Andric     return *Map.insert(std::make_pair(String, nullptr)).first;
3231f22ef01cSRoman Divacky   }
3232f22ef01cSRoman Divacky 
3233dff0c46cSDimitry Andric   // Otherwise, convert the UTF8 literals into a string of shorts.
3234dff0c46cSDimitry Andric   IsUTF16 = true;
3235dff0c46cSDimitry Andric 
323644290647SDimitry Andric   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
323744290647SDimitry Andric   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
323844290647SDimitry Andric   llvm::UTF16 *ToPtr = &ToBuf[0];
3239f22ef01cSRoman Divacky 
324044290647SDimitry Andric   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
324144290647SDimitry Andric                                  ToPtr + NumBytes, llvm::strictConversion);
3242f22ef01cSRoman Divacky 
3243f22ef01cSRoman Divacky   // ConvertUTF8toUTF16 returns the length in ToPtr.
3244f22ef01cSRoman Divacky   StringLength = ToPtr - &ToBuf[0];
3245f22ef01cSRoman Divacky 
3246dff0c46cSDimitry Andric   // Add an explicit null.
3247dff0c46cSDimitry Andric   *ToPtr = 0;
324839d628a0SDimitry Andric   return *Map.insert(std::make_pair(
324939d628a0SDimitry Andric                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
325039d628a0SDimitry Andric                                    (StringLength + 1) * 2),
325139d628a0SDimitry Andric                          nullptr)).first;
3252f22ef01cSRoman Divacky }
3253f22ef01cSRoman Divacky 
32540623d748SDimitry Andric ConstantAddress
3255f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
3256f22ef01cSRoman Divacky   unsigned StringLength = 0;
3257f22ef01cSRoman Divacky   bool isUTF16 = false;
325833956c43SDimitry Andric   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3259f22ef01cSRoman Divacky       GetConstantCFStringEntry(CFConstantStringMap, Literal,
326033956c43SDimitry Andric                                getDataLayout().isLittleEndian(), isUTF16,
326133956c43SDimitry Andric                                StringLength);
3262f22ef01cSRoman Divacky 
326339d628a0SDimitry Andric   if (auto *C = Entry.second)
32640623d748SDimitry Andric     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
3265f22ef01cSRoman Divacky 
3266dff0c46cSDimitry Andric   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
3267f22ef01cSRoman Divacky   llvm::Constant *Zeros[] = { Zero, Zero };
3268f22ef01cSRoman Divacky 
3269f22ef01cSRoman Divacky   // If we don't already have it, get __CFConstantStringClassReference.
3270f22ef01cSRoman Divacky   if (!CFConstantStringClassRef) {
32716122f3e6SDimitry Andric     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
3272f22ef01cSRoman Divacky     Ty = llvm::ArrayType::get(Ty, 0);
3273e7145dcbSDimitry Andric     llvm::Constant *GV =
3274e7145dcbSDimitry Andric         CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
3275e7145dcbSDimitry Andric 
327644290647SDimitry Andric     if (getTriple().isOSBinFormatCOFF()) {
3277e7145dcbSDimitry Andric       IdentifierInfo &II = getContext().Idents.get(GV->getName());
3278e7145dcbSDimitry Andric       TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
3279e7145dcbSDimitry Andric       DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3280e7145dcbSDimitry Andric       llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
3281e7145dcbSDimitry Andric 
3282e7145dcbSDimitry Andric       const VarDecl *VD = nullptr;
3283e7145dcbSDimitry Andric       for (const auto &Result : DC->lookup(&II))
3284e7145dcbSDimitry Andric         if ((VD = dyn_cast<VarDecl>(Result)))
3285e7145dcbSDimitry Andric           break;
3286e7145dcbSDimitry Andric 
3287e7145dcbSDimitry Andric       if (!VD || !VD->hasAttr<DLLExportAttr>()) {
3288e7145dcbSDimitry Andric         CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3289e7145dcbSDimitry Andric         CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3290e7145dcbSDimitry Andric       } else {
3291e7145dcbSDimitry Andric         CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3292e7145dcbSDimitry Andric         CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3293e7145dcbSDimitry Andric       }
3294e7145dcbSDimitry Andric     }
3295e7145dcbSDimitry Andric 
3296f22ef01cSRoman Divacky     // Decay array -> ptr
329744290647SDimitry Andric     CFConstantStringClassRef =
329844290647SDimitry Andric         llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
3299e7145dcbSDimitry Andric   }
3300f22ef01cSRoman Divacky 
3301f22ef01cSRoman Divacky   QualType CFTy = getContext().getCFConstantStringType();
3302f22ef01cSRoman Divacky 
330359d1ed5bSDimitry Andric   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
3304f22ef01cSRoman Divacky 
330544290647SDimitry Andric   ConstantInitBuilder Builder(*this);
330644290647SDimitry Andric   auto Fields = Builder.beginStruct(STy);
3307f22ef01cSRoman Divacky 
3308f22ef01cSRoman Divacky   // Class pointer.
330944290647SDimitry Andric   Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
3310f22ef01cSRoman Divacky 
3311f22ef01cSRoman Divacky   // Flags.
331244290647SDimitry Andric   Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
3313f22ef01cSRoman Divacky 
3314f22ef01cSRoman Divacky   // String pointer.
331559d1ed5bSDimitry Andric   llvm::Constant *C = nullptr;
3316dff0c46cSDimitry Andric   if (isUTF16) {
33170623d748SDimitry Andric     auto Arr = llvm::makeArrayRef(
331839d628a0SDimitry Andric         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
331939d628a0SDimitry Andric         Entry.first().size() / 2);
3320dff0c46cSDimitry Andric     C = llvm::ConstantDataArray::get(VMContext, Arr);
3321dff0c46cSDimitry Andric   } else {
332239d628a0SDimitry Andric     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
3323dff0c46cSDimitry Andric   }
3324f22ef01cSRoman Divacky 
3325dff0c46cSDimitry Andric   // Note: -fwritable-strings doesn't make the backing store strings of
3326dff0c46cSDimitry Andric   // CFStrings writable. (See <rdar://problem/10657500>)
332759d1ed5bSDimitry Andric   auto *GV =
3328dff0c46cSDimitry Andric       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
332959d1ed5bSDimitry Andric                                llvm::GlobalValue::PrivateLinkage, C, ".str");
3330e7145dcbSDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3331284c1978SDimitry Andric   // Don't enforce the target's minimum global alignment, since the only use
3332284c1978SDimitry Andric   // of the string is via this class initializer.
3333e7145dcbSDimitry Andric   CharUnits Align = isUTF16
3334e7145dcbSDimitry Andric                         ? getContext().getTypeAlignInChars(getContext().ShortTy)
3335e7145dcbSDimitry Andric                         : getContext().getTypeAlignInChars(getContext().CharTy);
3336f22ef01cSRoman Divacky   GV->setAlignment(Align.getQuantity());
3337e7145dcbSDimitry Andric 
3338e7145dcbSDimitry Andric   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
3339e7145dcbSDimitry Andric   // Without it LLVM can merge the string with a non unnamed_addr one during
3340e7145dcbSDimitry Andric   // LTO.  Doing that changes the section it ends in, which surprises ld64.
334144290647SDimitry Andric   if (getTriple().isOSBinFormatMachO())
3342e7145dcbSDimitry Andric     GV->setSection(isUTF16 ? "__TEXT,__ustring"
3343e7145dcbSDimitry Andric                            : "__TEXT,__cstring,cstring_literals");
3344dff0c46cSDimitry Andric 
3345dff0c46cSDimitry Andric   // String.
334644290647SDimitry Andric   llvm::Constant *Str =
334733956c43SDimitry Andric       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3348f22ef01cSRoman Divacky 
3349dff0c46cSDimitry Andric   if (isUTF16)
3350dff0c46cSDimitry Andric     // Cast the UTF16 string to the correct type.
335144290647SDimitry Andric     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
335244290647SDimitry Andric   Fields.add(Str);
3353dff0c46cSDimitry Andric 
3354f22ef01cSRoman Divacky   // String length.
335544290647SDimitry Andric   auto Ty = getTypes().ConvertType(getContext().LongTy);
335644290647SDimitry Andric   Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
3357f22ef01cSRoman Divacky 
33580623d748SDimitry Andric   CharUnits Alignment = getPointerAlign();
33590623d748SDimitry Andric 
3360f22ef01cSRoman Divacky   // The struct.
336144290647SDimitry Andric   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
336244290647SDimitry Andric                                     /*isConstant=*/false,
336344290647SDimitry Andric                                     llvm::GlobalVariable::PrivateLinkage);
336444290647SDimitry Andric   switch (getTriple().getObjectFormat()) {
3365e7145dcbSDimitry Andric   case llvm::Triple::UnknownObjectFormat:
3366e7145dcbSDimitry Andric     llvm_unreachable("unknown file format");
3367e7145dcbSDimitry Andric   case llvm::Triple::COFF:
3368e7145dcbSDimitry Andric   case llvm::Triple::ELF:
336920e90f04SDimitry Andric   case llvm::Triple::Wasm:
3370e7145dcbSDimitry Andric     GV->setSection("cfstring");
3371e7145dcbSDimitry Andric     break;
3372e7145dcbSDimitry Andric   case llvm::Triple::MachO:
3373e7145dcbSDimitry Andric     GV->setSection("__DATA,__cfstring");
3374e7145dcbSDimitry Andric     break;
3375e7145dcbSDimitry Andric   }
337639d628a0SDimitry Andric   Entry.second = GV;
3377f22ef01cSRoman Divacky 
33780623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
3379f22ef01cSRoman Divacky }
3380f22ef01cSRoman Divacky 
33816122f3e6SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() {
33826122f3e6SDimitry Andric   if (ObjCFastEnumerationStateType.isNull()) {
338359d1ed5bSDimitry Andric     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
33846122f3e6SDimitry Andric     D->startDefinition();
33856122f3e6SDimitry Andric 
33866122f3e6SDimitry Andric     QualType FieldTypes[] = {
33876122f3e6SDimitry Andric       Context.UnsignedLongTy,
33886122f3e6SDimitry Andric       Context.getPointerType(Context.getObjCIdType()),
33896122f3e6SDimitry Andric       Context.getPointerType(Context.UnsignedLongTy),
33906122f3e6SDimitry Andric       Context.getConstantArrayType(Context.UnsignedLongTy,
33916122f3e6SDimitry Andric                            llvm::APInt(32, 5), ArrayType::Normal, 0)
33926122f3e6SDimitry Andric     };
33936122f3e6SDimitry Andric 
33946122f3e6SDimitry Andric     for (size_t i = 0; i < 4; ++i) {
33956122f3e6SDimitry Andric       FieldDecl *Field = FieldDecl::Create(Context,
33966122f3e6SDimitry Andric                                            D,
33976122f3e6SDimitry Andric                                            SourceLocation(),
339859d1ed5bSDimitry Andric                                            SourceLocation(), nullptr,
339959d1ed5bSDimitry Andric                                            FieldTypes[i], /*TInfo=*/nullptr,
340059d1ed5bSDimitry Andric                                            /*BitWidth=*/nullptr,
34016122f3e6SDimitry Andric                                            /*Mutable=*/false,
34027ae0e2c9SDimitry Andric                                            ICIS_NoInit);
34036122f3e6SDimitry Andric       Field->setAccess(AS_public);
34046122f3e6SDimitry Andric       D->addDecl(Field);
34056122f3e6SDimitry Andric     }
34066122f3e6SDimitry Andric 
34076122f3e6SDimitry Andric     D->completeDefinition();
34086122f3e6SDimitry Andric     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
34096122f3e6SDimitry Andric   }
34106122f3e6SDimitry Andric 
34116122f3e6SDimitry Andric   return ObjCFastEnumerationStateType;
34126122f3e6SDimitry Andric }
34136122f3e6SDimitry Andric 
3414dff0c46cSDimitry Andric llvm::Constant *
3415dff0c46cSDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
3416dff0c46cSDimitry Andric   assert(!E->getType()->isPointerType() && "Strings are always arrays");
3417f22ef01cSRoman Divacky 
3418dff0c46cSDimitry Andric   // Don't emit it as the address of the string, emit the string data itself
3419dff0c46cSDimitry Andric   // as an inline array.
3420dff0c46cSDimitry Andric   if (E->getCharByteWidth() == 1) {
3421dff0c46cSDimitry Andric     SmallString<64> Str(E->getString());
3422f22ef01cSRoman Divacky 
3423dff0c46cSDimitry Andric     // Resize the string to the right size, which is indicated by its type.
3424dff0c46cSDimitry Andric     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
3425dff0c46cSDimitry Andric     Str.resize(CAT->getSize().getZExtValue());
3426dff0c46cSDimitry Andric     return llvm::ConstantDataArray::getString(VMContext, Str, false);
34276122f3e6SDimitry Andric   }
3428f22ef01cSRoman Divacky 
342959d1ed5bSDimitry Andric   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
3430dff0c46cSDimitry Andric   llvm::Type *ElemTy = AType->getElementType();
3431dff0c46cSDimitry Andric   unsigned NumElements = AType->getNumElements();
3432f22ef01cSRoman Divacky 
3433dff0c46cSDimitry Andric   // Wide strings have either 2-byte or 4-byte elements.
3434dff0c46cSDimitry Andric   if (ElemTy->getPrimitiveSizeInBits() == 16) {
3435dff0c46cSDimitry Andric     SmallVector<uint16_t, 32> Elements;
3436dff0c46cSDimitry Andric     Elements.reserve(NumElements);
3437dff0c46cSDimitry Andric 
3438dff0c46cSDimitry Andric     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3439dff0c46cSDimitry Andric       Elements.push_back(E->getCodeUnit(i));
3440dff0c46cSDimitry Andric     Elements.resize(NumElements);
3441dff0c46cSDimitry Andric     return llvm::ConstantDataArray::get(VMContext, Elements);
3442dff0c46cSDimitry Andric   }
3443dff0c46cSDimitry Andric 
3444dff0c46cSDimitry Andric   assert(ElemTy->getPrimitiveSizeInBits() == 32);
3445dff0c46cSDimitry Andric   SmallVector<uint32_t, 32> Elements;
3446dff0c46cSDimitry Andric   Elements.reserve(NumElements);
3447dff0c46cSDimitry Andric 
3448dff0c46cSDimitry Andric   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3449dff0c46cSDimitry Andric     Elements.push_back(E->getCodeUnit(i));
3450dff0c46cSDimitry Andric   Elements.resize(NumElements);
3451dff0c46cSDimitry Andric   return llvm::ConstantDataArray::get(VMContext, Elements);
3452f22ef01cSRoman Divacky }
3453f22ef01cSRoman Divacky 
345459d1ed5bSDimitry Andric static llvm::GlobalVariable *
345559d1ed5bSDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
345659d1ed5bSDimitry Andric                       CodeGenModule &CGM, StringRef GlobalName,
34570623d748SDimitry Andric                       CharUnits Alignment) {
345859d1ed5bSDimitry Andric   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
345959d1ed5bSDimitry Andric   unsigned AddrSpace = 0;
346059d1ed5bSDimitry Andric   if (CGM.getLangOpts().OpenCL)
346159d1ed5bSDimitry Andric     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
3462dff0c46cSDimitry Andric 
346333956c43SDimitry Andric   llvm::Module &M = CGM.getModule();
346459d1ed5bSDimitry Andric   // Create a global variable for this string
346559d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
346633956c43SDimitry Andric       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
346733956c43SDimitry Andric       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
34680623d748SDimitry Andric   GV->setAlignment(Alignment.getQuantity());
3469e7145dcbSDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
347033956c43SDimitry Andric   if (GV->isWeakForLinker()) {
347133956c43SDimitry Andric     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
347233956c43SDimitry Andric     GV->setComdat(M.getOrInsertComdat(GV->getName()));
347333956c43SDimitry Andric   }
347433956c43SDimitry Andric 
347559d1ed5bSDimitry Andric   return GV;
3476f22ef01cSRoman Divacky }
3477dff0c46cSDimitry Andric 
347859d1ed5bSDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
347959d1ed5bSDimitry Andric /// constant array for the given string literal.
34800623d748SDimitry Andric ConstantAddress
348139d628a0SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
348239d628a0SDimitry Andric                                                   StringRef Name) {
34830623d748SDimitry Andric   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
3484dff0c46cSDimitry Andric 
348559d1ed5bSDimitry Andric   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
348659d1ed5bSDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
348759d1ed5bSDimitry Andric   if (!LangOpts.WritableStrings) {
348859d1ed5bSDimitry Andric     Entry = &ConstantStringMap[C];
348959d1ed5bSDimitry Andric     if (auto GV = *Entry) {
34900623d748SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
34910623d748SDimitry Andric         GV->setAlignment(Alignment.getQuantity());
34920623d748SDimitry Andric       return ConstantAddress(GV, Alignment);
349359d1ed5bSDimitry Andric     }
349459d1ed5bSDimitry Andric   }
349559d1ed5bSDimitry Andric 
349659d1ed5bSDimitry Andric   SmallString<256> MangledNameBuffer;
349759d1ed5bSDimitry Andric   StringRef GlobalVariableName;
349859d1ed5bSDimitry Andric   llvm::GlobalValue::LinkageTypes LT;
349959d1ed5bSDimitry Andric 
350059d1ed5bSDimitry Andric   // Mangle the string literal if the ABI allows for it.  However, we cannot
350159d1ed5bSDimitry Andric   // do this if  we are compiling with ASan or -fwritable-strings because they
350259d1ed5bSDimitry Andric   // rely on strings having normal linkage.
350339d628a0SDimitry Andric   if (!LangOpts.WritableStrings &&
350439d628a0SDimitry Andric       !LangOpts.Sanitize.has(SanitizerKind::Address) &&
350559d1ed5bSDimitry Andric       getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
350659d1ed5bSDimitry Andric     llvm::raw_svector_ostream Out(MangledNameBuffer);
350759d1ed5bSDimitry Andric     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
350859d1ed5bSDimitry Andric 
350959d1ed5bSDimitry Andric     LT = llvm::GlobalValue::LinkOnceODRLinkage;
351059d1ed5bSDimitry Andric     GlobalVariableName = MangledNameBuffer;
351159d1ed5bSDimitry Andric   } else {
351259d1ed5bSDimitry Andric     LT = llvm::GlobalValue::PrivateLinkage;
351339d628a0SDimitry Andric     GlobalVariableName = Name;
351459d1ed5bSDimitry Andric   }
351559d1ed5bSDimitry Andric 
351659d1ed5bSDimitry Andric   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
351759d1ed5bSDimitry Andric   if (Entry)
351859d1ed5bSDimitry Andric     *Entry = GV;
351959d1ed5bSDimitry Andric 
352039d628a0SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
352139d628a0SDimitry Andric                                   QualType());
35220623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
3523f22ef01cSRoman Divacky }
3524f22ef01cSRoman Divacky 
3525f22ef01cSRoman Divacky /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
3526f22ef01cSRoman Divacky /// array for the given ObjCEncodeExpr node.
35270623d748SDimitry Andric ConstantAddress
3528f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
3529f22ef01cSRoman Divacky   std::string Str;
3530f22ef01cSRoman Divacky   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
3531f22ef01cSRoman Divacky 
3532f22ef01cSRoman Divacky   return GetAddrOfConstantCString(Str);
3533f22ef01cSRoman Divacky }
3534f22ef01cSRoman Divacky 
353559d1ed5bSDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing
353659d1ed5bSDimitry Andric /// the literal and a terminating '\0' character.
353759d1ed5bSDimitry Andric /// The result has pointer to array type.
35380623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString(
35390623d748SDimitry Andric     const std::string &Str, const char *GlobalName) {
354059d1ed5bSDimitry Andric   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
35410623d748SDimitry Andric   CharUnits Alignment =
35420623d748SDimitry Andric     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
3543f22ef01cSRoman Divacky 
354459d1ed5bSDimitry Andric   llvm::Constant *C =
354559d1ed5bSDimitry Andric       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
354659d1ed5bSDimitry Andric 
354759d1ed5bSDimitry Andric   // Don't share any string literals if strings aren't constant.
354859d1ed5bSDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
354959d1ed5bSDimitry Andric   if (!LangOpts.WritableStrings) {
355059d1ed5bSDimitry Andric     Entry = &ConstantStringMap[C];
355159d1ed5bSDimitry Andric     if (auto GV = *Entry) {
35520623d748SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
35530623d748SDimitry Andric         GV->setAlignment(Alignment.getQuantity());
35540623d748SDimitry Andric       return ConstantAddress(GV, Alignment);
355559d1ed5bSDimitry Andric     }
355659d1ed5bSDimitry Andric   }
355759d1ed5bSDimitry Andric 
3558f22ef01cSRoman Divacky   // Get the default prefix if a name wasn't specified.
3559f22ef01cSRoman Divacky   if (!GlobalName)
3560f22ef01cSRoman Divacky     GlobalName = ".str";
3561f22ef01cSRoman Divacky   // Create a global variable for this.
356259d1ed5bSDimitry Andric   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
356359d1ed5bSDimitry Andric                                   GlobalName, Alignment);
356459d1ed5bSDimitry Andric   if (Entry)
356559d1ed5bSDimitry Andric     *Entry = GV;
35660623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
3567f22ef01cSRoman Divacky }
3568f22ef01cSRoman Divacky 
35690623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
3570f785676fSDimitry Andric     const MaterializeTemporaryExpr *E, const Expr *Init) {
3571f785676fSDimitry Andric   assert((E->getStorageDuration() == SD_Static ||
3572f785676fSDimitry Andric           E->getStorageDuration() == SD_Thread) && "not a global temporary");
357359d1ed5bSDimitry Andric   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
3574f785676fSDimitry Andric 
3575f785676fSDimitry Andric   // If we're not materializing a subobject of the temporary, keep the
3576f785676fSDimitry Andric   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
3577f785676fSDimitry Andric   QualType MaterializedType = Init->getType();
3578f785676fSDimitry Andric   if (Init == E->GetTemporaryExpr())
3579f785676fSDimitry Andric     MaterializedType = E->getType();
3580f785676fSDimitry Andric 
35810623d748SDimitry Andric   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
35820623d748SDimitry Andric 
35830623d748SDimitry Andric   if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
35840623d748SDimitry Andric     return ConstantAddress(Slot, Align);
3585f785676fSDimitry Andric 
3586f785676fSDimitry Andric   // FIXME: If an externally-visible declaration extends multiple temporaries,
3587f785676fSDimitry Andric   // we need to give each temporary the same name in every translation unit (and
3588f785676fSDimitry Andric   // we also need to make the temporaries externally-visible).
3589f785676fSDimitry Andric   SmallString<256> Name;
3590f785676fSDimitry Andric   llvm::raw_svector_ostream Out(Name);
359159d1ed5bSDimitry Andric   getCXXABI().getMangleContext().mangleReferenceTemporary(
359259d1ed5bSDimitry Andric       VD, E->getManglingNumber(), Out);
3593f785676fSDimitry Andric 
359459d1ed5bSDimitry Andric   APValue *Value = nullptr;
3595f785676fSDimitry Andric   if (E->getStorageDuration() == SD_Static) {
3596f785676fSDimitry Andric     // We might have a cached constant initializer for this temporary. Note
3597f785676fSDimitry Andric     // that this might have a different value from the value computed by
3598f785676fSDimitry Andric     // evaluating the initializer if the surrounding constant expression
3599f785676fSDimitry Andric     // modifies the temporary.
3600f785676fSDimitry Andric     Value = getContext().getMaterializedTemporaryValue(E, false);
3601f785676fSDimitry Andric     if (Value && Value->isUninit())
360259d1ed5bSDimitry Andric       Value = nullptr;
3603f785676fSDimitry Andric   }
3604f785676fSDimitry Andric 
3605f785676fSDimitry Andric   // Try evaluating it now, it might have a constant initializer.
3606f785676fSDimitry Andric   Expr::EvalResult EvalResult;
3607f785676fSDimitry Andric   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3608f785676fSDimitry Andric       !EvalResult.hasSideEffects())
3609f785676fSDimitry Andric     Value = &EvalResult.Val;
3610f785676fSDimitry Andric 
361159d1ed5bSDimitry Andric   llvm::Constant *InitialValue = nullptr;
3612f785676fSDimitry Andric   bool Constant = false;
3613f785676fSDimitry Andric   llvm::Type *Type;
3614f785676fSDimitry Andric   if (Value) {
3615f785676fSDimitry Andric     // The temporary has a constant initializer, use it.
361659d1ed5bSDimitry Andric     InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
3617f785676fSDimitry Andric     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3618f785676fSDimitry Andric     Type = InitialValue->getType();
3619f785676fSDimitry Andric   } else {
3620f785676fSDimitry Andric     // No initializer, the initialization will be provided when we
3621f785676fSDimitry Andric     // initialize the declaration which performed lifetime extension.
3622f785676fSDimitry Andric     Type = getTypes().ConvertTypeForMem(MaterializedType);
3623f785676fSDimitry Andric   }
3624f785676fSDimitry Andric 
3625f785676fSDimitry Andric   // Create a global variable for this lifetime-extended temporary.
362659d1ed5bSDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
362759d1ed5bSDimitry Andric       getLLVMLinkageVarDefinition(VD, Constant);
362833956c43SDimitry Andric   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
362933956c43SDimitry Andric     const VarDecl *InitVD;
363033956c43SDimitry Andric     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
363133956c43SDimitry Andric         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
363233956c43SDimitry Andric       // Temporaries defined inside a class get linkonce_odr linkage because the
363333956c43SDimitry Andric       // class can be defined in multipe translation units.
363433956c43SDimitry Andric       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
363533956c43SDimitry Andric     } else {
363633956c43SDimitry Andric       // There is no need for this temporary to have external linkage if the
363733956c43SDimitry Andric       // VarDecl has external linkage.
363833956c43SDimitry Andric       Linkage = llvm::GlobalVariable::InternalLinkage;
363933956c43SDimitry Andric     }
364033956c43SDimitry Andric   }
364159d1ed5bSDimitry Andric   unsigned AddrSpace = GetGlobalVarAddressSpace(
364259d1ed5bSDimitry Andric       VD, getContext().getTargetAddressSpace(MaterializedType));
364359d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
364459d1ed5bSDimitry Andric       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
364559d1ed5bSDimitry Andric       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
364659d1ed5bSDimitry Andric       AddrSpace);
364759d1ed5bSDimitry Andric   setGlobalVisibility(GV, VD);
36480623d748SDimitry Andric   GV->setAlignment(Align.getQuantity());
364933956c43SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker())
365033956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3651f785676fSDimitry Andric   if (VD->getTLSKind())
3652f785676fSDimitry Andric     setTLSMode(GV, *VD);
36530623d748SDimitry Andric   MaterializedGlobalTemporaryMap[E] = GV;
36540623d748SDimitry Andric   return ConstantAddress(GV, Align);
3655f785676fSDimitry Andric }
3656f785676fSDimitry Andric 
3657f22ef01cSRoman Divacky /// EmitObjCPropertyImplementations - Emit information for synthesized
3658f22ef01cSRoman Divacky /// properties for an implementation.
3659f22ef01cSRoman Divacky void CodeGenModule::EmitObjCPropertyImplementations(const
3660f22ef01cSRoman Divacky                                                     ObjCImplementationDecl *D) {
366159d1ed5bSDimitry Andric   for (const auto *PID : D->property_impls()) {
3662f22ef01cSRoman Divacky     // Dynamic is just for type-checking.
3663f22ef01cSRoman Divacky     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3664f22ef01cSRoman Divacky       ObjCPropertyDecl *PD = PID->getPropertyDecl();
3665f22ef01cSRoman Divacky 
3666f22ef01cSRoman Divacky       // Determine which methods need to be implemented, some may have
36673861d79fSDimitry Andric       // been overridden. Note that ::isPropertyAccessor is not the method
3668f22ef01cSRoman Divacky       // we want, that just indicates if the decl came from a
3669f22ef01cSRoman Divacky       // property. What we want to know is if the method is defined in
3670f22ef01cSRoman Divacky       // this implementation.
3671f22ef01cSRoman Divacky       if (!D->getInstanceMethod(PD->getGetterName()))
3672f22ef01cSRoman Divacky         CodeGenFunction(*this).GenerateObjCGetter(
3673f22ef01cSRoman Divacky                                  const_cast<ObjCImplementationDecl *>(D), PID);
3674f22ef01cSRoman Divacky       if (!PD->isReadOnly() &&
3675f22ef01cSRoman Divacky           !D->getInstanceMethod(PD->getSetterName()))
3676f22ef01cSRoman Divacky         CodeGenFunction(*this).GenerateObjCSetter(
3677f22ef01cSRoman Divacky                                  const_cast<ObjCImplementationDecl *>(D), PID);
3678f22ef01cSRoman Divacky     }
3679f22ef01cSRoman Divacky   }
3680f22ef01cSRoman Divacky }
3681f22ef01cSRoman Divacky 
36823b0f4066SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) {
36836122f3e6SDimitry Andric   const ObjCInterfaceDecl *iface = impl->getClassInterface();
36846122f3e6SDimitry Andric   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
36853b0f4066SDimitry Andric        ivar; ivar = ivar->getNextIvar())
36863b0f4066SDimitry Andric     if (ivar->getType().isDestructedType())
36873b0f4066SDimitry Andric       return true;
36883b0f4066SDimitry Andric 
36893b0f4066SDimitry Andric   return false;
36903b0f4066SDimitry Andric }
36913b0f4066SDimitry Andric 
369239d628a0SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM,
369339d628a0SDimitry Andric                                    ObjCImplementationDecl *D) {
369439d628a0SDimitry Andric   CodeGenFunction CGF(CGM);
369539d628a0SDimitry Andric   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
369639d628a0SDimitry Andric        E = D->init_end(); B != E; ++B) {
369739d628a0SDimitry Andric     CXXCtorInitializer *CtorInitExp = *B;
369839d628a0SDimitry Andric     Expr *Init = CtorInitExp->getInit();
369939d628a0SDimitry Andric     if (!CGF.isTrivialInitializer(Init))
370039d628a0SDimitry Andric       return false;
370139d628a0SDimitry Andric   }
370239d628a0SDimitry Andric   return true;
370339d628a0SDimitry Andric }
370439d628a0SDimitry Andric 
3705f22ef01cSRoman Divacky /// EmitObjCIvarInitializations - Emit information for ivar initialization
3706f22ef01cSRoman Divacky /// for an implementation.
3707f22ef01cSRoman Divacky void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
37083b0f4066SDimitry Andric   // We might need a .cxx_destruct even if we don't have any ivar initializers.
37093b0f4066SDimitry Andric   if (needsDestructMethod(D)) {
3710f22ef01cSRoman Divacky     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3711f22ef01cSRoman Divacky     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
37123b0f4066SDimitry Andric     ObjCMethodDecl *DTORMethod =
37133b0f4066SDimitry Andric       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
371459d1ed5bSDimitry Andric                              cxxSelector, getContext().VoidTy, nullptr, D,
37156122f3e6SDimitry Andric                              /*isInstance=*/true, /*isVariadic=*/false,
37163861d79fSDimitry Andric                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
37176122f3e6SDimitry Andric                              /*isDefined=*/false, ObjCMethodDecl::Required);
3718f22ef01cSRoman Divacky     D->addInstanceMethod(DTORMethod);
3719f22ef01cSRoman Divacky     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
37203861d79fSDimitry Andric     D->setHasDestructors(true);
37213b0f4066SDimitry Andric   }
3722f22ef01cSRoman Divacky 
37233b0f4066SDimitry Andric   // If the implementation doesn't have any ivar initializers, we don't need
37243b0f4066SDimitry Andric   // a .cxx_construct.
372539d628a0SDimitry Andric   if (D->getNumIvarInitializers() == 0 ||
372639d628a0SDimitry Andric       AllTrivialInitializers(*this, D))
37273b0f4066SDimitry Andric     return;
37283b0f4066SDimitry Andric 
37293b0f4066SDimitry Andric   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
37303b0f4066SDimitry Andric   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3731f22ef01cSRoman Divacky   // The constructor returns 'self'.
3732f22ef01cSRoman Divacky   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3733f22ef01cSRoman Divacky                                                 D->getLocation(),
37346122f3e6SDimitry Andric                                                 D->getLocation(),
37356122f3e6SDimitry Andric                                                 cxxSelector,
373659d1ed5bSDimitry Andric                                                 getContext().getObjCIdType(),
373759d1ed5bSDimitry Andric                                                 nullptr, D, /*isInstance=*/true,
37386122f3e6SDimitry Andric                                                 /*isVariadic=*/false,
37393861d79fSDimitry Andric                                                 /*isPropertyAccessor=*/true,
37406122f3e6SDimitry Andric                                                 /*isImplicitlyDeclared=*/true,
37416122f3e6SDimitry Andric                                                 /*isDefined=*/false,
3742f22ef01cSRoman Divacky                                                 ObjCMethodDecl::Required);
3743f22ef01cSRoman Divacky   D->addInstanceMethod(CTORMethod);
3744f22ef01cSRoman Divacky   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
37453861d79fSDimitry Andric   D->setHasNonZeroConstructors(true);
3746f22ef01cSRoman Divacky }
3747f22ef01cSRoman Divacky 
3748f22ef01cSRoman Divacky // EmitLinkageSpec - Emit all declarations in a linkage spec.
3749f22ef01cSRoman Divacky void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
3750f22ef01cSRoman Divacky   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3751f22ef01cSRoman Divacky       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
3752f22ef01cSRoman Divacky     ErrorUnsupported(LSD, "linkage spec");
3753f22ef01cSRoman Divacky     return;
3754f22ef01cSRoman Divacky   }
3755f22ef01cSRoman Divacky 
375644290647SDimitry Andric   EmitDeclContext(LSD);
375744290647SDimitry Andric }
375844290647SDimitry Andric 
375944290647SDimitry Andric void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
376044290647SDimitry Andric   for (auto *I : DC->decls()) {
376144290647SDimitry Andric     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
376244290647SDimitry Andric     // are themselves considered "top-level", so EmitTopLevelDecl on an
376344290647SDimitry Andric     // ObjCImplDecl does not recursively visit them. We need to do that in
376444290647SDimitry Andric     // case they're nested inside another construct (LinkageSpecDecl /
376544290647SDimitry Andric     // ExportDecl) that does stop them from being considered "top-level".
376659d1ed5bSDimitry Andric     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
376759d1ed5bSDimitry Andric       for (auto *M : OID->methods())
376859d1ed5bSDimitry Andric         EmitTopLevelDecl(M);
37693861d79fSDimitry Andric     }
377044290647SDimitry Andric 
377159d1ed5bSDimitry Andric     EmitTopLevelDecl(I);
3772f22ef01cSRoman Divacky   }
37733861d79fSDimitry Andric }
3774f22ef01cSRoman Divacky 
3775f22ef01cSRoman Divacky /// EmitTopLevelDecl - Emit code for a single top level declaration.
3776f22ef01cSRoman Divacky void CodeGenModule::EmitTopLevelDecl(Decl *D) {
3777f22ef01cSRoman Divacky   // Ignore dependent declarations.
3778f22ef01cSRoman Divacky   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3779f22ef01cSRoman Divacky     return;
3780f22ef01cSRoman Divacky 
3781f22ef01cSRoman Divacky   switch (D->getKind()) {
3782f22ef01cSRoman Divacky   case Decl::CXXConversion:
3783f22ef01cSRoman Divacky   case Decl::CXXMethod:
3784f22ef01cSRoman Divacky   case Decl::Function:
3785f22ef01cSRoman Divacky     // Skip function templates
37863b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
37873b0f4066SDimitry Andric         cast<FunctionDecl>(D)->isLateTemplateParsed())
3788f22ef01cSRoman Divacky       return;
3789f22ef01cSRoman Divacky 
3790f22ef01cSRoman Divacky     EmitGlobal(cast<FunctionDecl>(D));
379139d628a0SDimitry Andric     // Always provide some coverage mapping
379239d628a0SDimitry Andric     // even for the functions that aren't emitted.
379339d628a0SDimitry Andric     AddDeferredUnusedCoverageMapping(D);
3794f22ef01cSRoman Divacky     break;
3795f22ef01cSRoman Divacky 
3796f22ef01cSRoman Divacky   case Decl::Var:
379744290647SDimitry Andric   case Decl::Decomposition:
3798f785676fSDimitry Andric     // Skip variable templates
3799f785676fSDimitry Andric     if (cast<VarDecl>(D)->getDescribedVarTemplate())
3800f785676fSDimitry Andric       return;
3801f785676fSDimitry Andric   case Decl::VarTemplateSpecialization:
3802f22ef01cSRoman Divacky     EmitGlobal(cast<VarDecl>(D));
380344290647SDimitry Andric     if (auto *DD = dyn_cast<DecompositionDecl>(D))
380444290647SDimitry Andric       for (auto *B : DD->bindings())
380544290647SDimitry Andric         if (auto *HD = B->getHoldingVar())
380644290647SDimitry Andric           EmitGlobal(HD);
3807f22ef01cSRoman Divacky     break;
3808f22ef01cSRoman Divacky 
38093b0f4066SDimitry Andric   // Indirect fields from global anonymous structs and unions can be
38103b0f4066SDimitry Andric   // ignored; only the actual variable requires IR gen support.
38113b0f4066SDimitry Andric   case Decl::IndirectField:
38123b0f4066SDimitry Andric     break;
38133b0f4066SDimitry Andric 
3814f22ef01cSRoman Divacky   // C++ Decls
3815f22ef01cSRoman Divacky   case Decl::Namespace:
381644290647SDimitry Andric     EmitDeclContext(cast<NamespaceDecl>(D));
3817f22ef01cSRoman Divacky     break;
3818e7145dcbSDimitry Andric   case Decl::CXXRecord:
381920e90f04SDimitry Andric     if (DebugInfo) {
382020e90f04SDimitry Andric       if (auto *ES = D->getASTContext().getExternalSource())
382120e90f04SDimitry Andric         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
382220e90f04SDimitry Andric           DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
382320e90f04SDimitry Andric     }
3824e7145dcbSDimitry Andric     // Emit any static data members, they may be definitions.
3825e7145dcbSDimitry Andric     for (auto *I : cast<CXXRecordDecl>(D)->decls())
3826e7145dcbSDimitry Andric       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
3827e7145dcbSDimitry Andric         EmitTopLevelDecl(I);
3828e7145dcbSDimitry Andric     break;
3829f22ef01cSRoman Divacky     // No code generation needed.
3830f22ef01cSRoman Divacky   case Decl::UsingShadow:
3831f22ef01cSRoman Divacky   case Decl::ClassTemplate:
3832f785676fSDimitry Andric   case Decl::VarTemplate:
3833f785676fSDimitry Andric   case Decl::VarTemplatePartialSpecialization:
3834f22ef01cSRoman Divacky   case Decl::FunctionTemplate:
3835bd5abe19SDimitry Andric   case Decl::TypeAliasTemplate:
3836bd5abe19SDimitry Andric   case Decl::Block:
3837139f7f9bSDimitry Andric   case Decl::Empty:
3838f22ef01cSRoman Divacky     break;
383959d1ed5bSDimitry Andric   case Decl::Using:          // using X; [C++]
384059d1ed5bSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
384159d1ed5bSDimitry Andric         DI->EmitUsingDecl(cast<UsingDecl>(*D));
384259d1ed5bSDimitry Andric     return;
3843f785676fSDimitry Andric   case Decl::NamespaceAlias:
3844f785676fSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
3845f785676fSDimitry Andric         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3846f785676fSDimitry Andric     return;
3847284c1978SDimitry Andric   case Decl::UsingDirective: // using namespace X; [C++]
3848284c1978SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
3849284c1978SDimitry Andric       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3850284c1978SDimitry Andric     return;
3851f22ef01cSRoman Divacky   case Decl::CXXConstructor:
3852f22ef01cSRoman Divacky     // Skip function templates
38533b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
38543b0f4066SDimitry Andric         cast<FunctionDecl>(D)->isLateTemplateParsed())
3855f22ef01cSRoman Divacky       return;
3856f22ef01cSRoman Divacky 
3857f785676fSDimitry Andric     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
3858f22ef01cSRoman Divacky     break;
3859f22ef01cSRoman Divacky   case Decl::CXXDestructor:
38603b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
38613b0f4066SDimitry Andric       return;
3862f785676fSDimitry Andric     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
3863f22ef01cSRoman Divacky     break;
3864f22ef01cSRoman Divacky 
3865f22ef01cSRoman Divacky   case Decl::StaticAssert:
3866f22ef01cSRoman Divacky     // Nothing to do.
3867f22ef01cSRoman Divacky     break;
3868f22ef01cSRoman Divacky 
3869f22ef01cSRoman Divacky   // Objective-C Decls
3870f22ef01cSRoman Divacky 
3871f22ef01cSRoman Divacky   // Forward declarations, no (immediate) code generation.
3872f22ef01cSRoman Divacky   case Decl::ObjCInterface:
38737ae0e2c9SDimitry Andric   case Decl::ObjCCategory:
3874f22ef01cSRoman Divacky     break;
3875f22ef01cSRoman Divacky 
3876dff0c46cSDimitry Andric   case Decl::ObjCProtocol: {
387759d1ed5bSDimitry Andric     auto *Proto = cast<ObjCProtocolDecl>(D);
3878dff0c46cSDimitry Andric     if (Proto->isThisDeclarationADefinition())
3879dff0c46cSDimitry Andric       ObjCRuntime->GenerateProtocol(Proto);
3880f22ef01cSRoman Divacky     break;
3881dff0c46cSDimitry Andric   }
3882f22ef01cSRoman Divacky 
3883f22ef01cSRoman Divacky   case Decl::ObjCCategoryImpl:
3884f22ef01cSRoman Divacky     // Categories have properties but don't support synthesize so we
3885f22ef01cSRoman Divacky     // can ignore them here.
38866122f3e6SDimitry Andric     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
3887f22ef01cSRoman Divacky     break;
3888f22ef01cSRoman Divacky 
3889f22ef01cSRoman Divacky   case Decl::ObjCImplementation: {
389059d1ed5bSDimitry Andric     auto *OMD = cast<ObjCImplementationDecl>(D);
3891f22ef01cSRoman Divacky     EmitObjCPropertyImplementations(OMD);
3892f22ef01cSRoman Divacky     EmitObjCIvarInitializations(OMD);
38936122f3e6SDimitry Andric     ObjCRuntime->GenerateClass(OMD);
3894dff0c46cSDimitry Andric     // Emit global variable debug information.
3895dff0c46cSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
3896e7145dcbSDimitry Andric       if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
3897139f7f9bSDimitry Andric         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3898139f7f9bSDimitry Andric             OMD->getClassInterface()), OMD->getLocation());
3899f22ef01cSRoman Divacky     break;
3900f22ef01cSRoman Divacky   }
3901f22ef01cSRoman Divacky   case Decl::ObjCMethod: {
390259d1ed5bSDimitry Andric     auto *OMD = cast<ObjCMethodDecl>(D);
3903f22ef01cSRoman Divacky     // If this is not a prototype, emit the body.
3904f22ef01cSRoman Divacky     if (OMD->getBody())
3905f22ef01cSRoman Divacky       CodeGenFunction(*this).GenerateObjCMethod(OMD);
3906f22ef01cSRoman Divacky     break;
3907f22ef01cSRoman Divacky   }
3908f22ef01cSRoman Divacky   case Decl::ObjCCompatibleAlias:
3909dff0c46cSDimitry Andric     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3910f22ef01cSRoman Divacky     break;
3911f22ef01cSRoman Divacky 
3912e7145dcbSDimitry Andric   case Decl::PragmaComment: {
3913e7145dcbSDimitry Andric     const auto *PCD = cast<PragmaCommentDecl>(D);
3914e7145dcbSDimitry Andric     switch (PCD->getCommentKind()) {
3915e7145dcbSDimitry Andric     case PCK_Unknown:
3916e7145dcbSDimitry Andric       llvm_unreachable("unexpected pragma comment kind");
3917e7145dcbSDimitry Andric     case PCK_Linker:
3918e7145dcbSDimitry Andric       AppendLinkerOptions(PCD->getArg());
3919e7145dcbSDimitry Andric       break;
3920e7145dcbSDimitry Andric     case PCK_Lib:
3921e7145dcbSDimitry Andric       AddDependentLib(PCD->getArg());
3922e7145dcbSDimitry Andric       break;
3923e7145dcbSDimitry Andric     case PCK_Compiler:
3924e7145dcbSDimitry Andric     case PCK_ExeStr:
3925e7145dcbSDimitry Andric     case PCK_User:
3926e7145dcbSDimitry Andric       break; // We ignore all of these.
3927e7145dcbSDimitry Andric     }
3928e7145dcbSDimitry Andric     break;
3929e7145dcbSDimitry Andric   }
3930e7145dcbSDimitry Andric 
3931e7145dcbSDimitry Andric   case Decl::PragmaDetectMismatch: {
3932e7145dcbSDimitry Andric     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
3933e7145dcbSDimitry Andric     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
3934e7145dcbSDimitry Andric     break;
3935e7145dcbSDimitry Andric   }
3936e7145dcbSDimitry Andric 
3937f22ef01cSRoman Divacky   case Decl::LinkageSpec:
3938f22ef01cSRoman Divacky     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
3939f22ef01cSRoman Divacky     break;
3940f22ef01cSRoman Divacky 
3941f22ef01cSRoman Divacky   case Decl::FileScopeAsm: {
394233956c43SDimitry Andric     // File-scope asm is ignored during device-side CUDA compilation.
394333956c43SDimitry Andric     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
394433956c43SDimitry Andric       break;
3945ea942507SDimitry Andric     // File-scope asm is ignored during device-side OpenMP compilation.
3946ea942507SDimitry Andric     if (LangOpts.OpenMPIsDevice)
3947ea942507SDimitry Andric       break;
394859d1ed5bSDimitry Andric     auto *AD = cast<FileScopeAsmDecl>(D);
394933956c43SDimitry Andric     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
3950f22ef01cSRoman Divacky     break;
3951f22ef01cSRoman Divacky   }
3952f22ef01cSRoman Divacky 
3953139f7f9bSDimitry Andric   case Decl::Import: {
395459d1ed5bSDimitry Andric     auto *Import = cast<ImportDecl>(D);
3955139f7f9bSDimitry Andric 
395644290647SDimitry Andric     // If we've already imported this module, we're done.
395744290647SDimitry Andric     if (!ImportedModules.insert(Import->getImportedModule()))
3958139f7f9bSDimitry Andric       break;
395944290647SDimitry Andric 
396044290647SDimitry Andric     // Emit debug information for direct imports.
396144290647SDimitry Andric     if (!Import->getImportedOwningModule()) {
39623dac3a9bSDimitry Andric       if (CGDebugInfo *DI = getModuleDebugInfo())
39633dac3a9bSDimitry Andric         DI->EmitImportDecl(*Import);
396444290647SDimitry Andric     }
3965139f7f9bSDimitry Andric 
396644290647SDimitry Andric     // Find all of the submodules and emit the module initializers.
396744290647SDimitry Andric     llvm::SmallPtrSet<clang::Module *, 16> Visited;
396844290647SDimitry Andric     SmallVector<clang::Module *, 16> Stack;
396944290647SDimitry Andric     Visited.insert(Import->getImportedModule());
397044290647SDimitry Andric     Stack.push_back(Import->getImportedModule());
397144290647SDimitry Andric 
397244290647SDimitry Andric     while (!Stack.empty()) {
397344290647SDimitry Andric       clang::Module *Mod = Stack.pop_back_val();
397444290647SDimitry Andric       if (!EmittedModuleInitializers.insert(Mod).second)
397544290647SDimitry Andric         continue;
397644290647SDimitry Andric 
397744290647SDimitry Andric       for (auto *D : Context.getModuleInitializers(Mod))
397844290647SDimitry Andric         EmitTopLevelDecl(D);
397944290647SDimitry Andric 
398044290647SDimitry Andric       // Visit the submodules of this module.
398144290647SDimitry Andric       for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
398244290647SDimitry Andric                                              SubEnd = Mod->submodule_end();
398344290647SDimitry Andric            Sub != SubEnd; ++Sub) {
398444290647SDimitry Andric         // Skip explicit children; they need to be explicitly imported to emit
398544290647SDimitry Andric         // the initializers.
398644290647SDimitry Andric         if ((*Sub)->IsExplicit)
398744290647SDimitry Andric           continue;
398844290647SDimitry Andric 
398944290647SDimitry Andric         if (Visited.insert(*Sub).second)
399044290647SDimitry Andric           Stack.push_back(*Sub);
399144290647SDimitry Andric       }
399244290647SDimitry Andric     }
3993139f7f9bSDimitry Andric     break;
3994139f7f9bSDimitry Andric   }
3995139f7f9bSDimitry Andric 
399644290647SDimitry Andric   case Decl::Export:
399744290647SDimitry Andric     EmitDeclContext(cast<ExportDecl>(D));
399844290647SDimitry Andric     break;
399944290647SDimitry Andric 
400039d628a0SDimitry Andric   case Decl::OMPThreadPrivate:
400139d628a0SDimitry Andric     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
400239d628a0SDimitry Andric     break;
400339d628a0SDimitry Andric 
400459d1ed5bSDimitry Andric   case Decl::ClassTemplateSpecialization: {
400559d1ed5bSDimitry Andric     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
400659d1ed5bSDimitry Andric     if (DebugInfo &&
400739d628a0SDimitry Andric         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
400839d628a0SDimitry Andric         Spec->hasDefinition())
400959d1ed5bSDimitry Andric       DebugInfo->completeTemplateDefinition(*Spec);
401039d628a0SDimitry Andric     break;
401159d1ed5bSDimitry Andric   }
401259d1ed5bSDimitry Andric 
4013e7145dcbSDimitry Andric   case Decl::OMPDeclareReduction:
4014e7145dcbSDimitry Andric     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
4015e7145dcbSDimitry Andric     break;
4016e7145dcbSDimitry Andric 
4017f22ef01cSRoman Divacky   default:
4018f22ef01cSRoman Divacky     // Make sure we handled everything we should, every other kind is a
4019f22ef01cSRoman Divacky     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
4020f22ef01cSRoman Divacky     // function. Need to recode Decl::Kind to do that easily.
4021f22ef01cSRoman Divacky     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
402239d628a0SDimitry Andric     break;
402339d628a0SDimitry Andric   }
402439d628a0SDimitry Andric }
402539d628a0SDimitry Andric 
402639d628a0SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
402739d628a0SDimitry Andric   // Do we need to generate coverage mapping?
402839d628a0SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
402939d628a0SDimitry Andric     return;
403039d628a0SDimitry Andric   switch (D->getKind()) {
403139d628a0SDimitry Andric   case Decl::CXXConversion:
403239d628a0SDimitry Andric   case Decl::CXXMethod:
403339d628a0SDimitry Andric   case Decl::Function:
403439d628a0SDimitry Andric   case Decl::ObjCMethod:
403539d628a0SDimitry Andric   case Decl::CXXConstructor:
403639d628a0SDimitry Andric   case Decl::CXXDestructor: {
40370623d748SDimitry Andric     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
403839d628a0SDimitry Andric       return;
403939d628a0SDimitry Andric     auto I = DeferredEmptyCoverageMappingDecls.find(D);
404039d628a0SDimitry Andric     if (I == DeferredEmptyCoverageMappingDecls.end())
404139d628a0SDimitry Andric       DeferredEmptyCoverageMappingDecls[D] = true;
404239d628a0SDimitry Andric     break;
404339d628a0SDimitry Andric   }
404439d628a0SDimitry Andric   default:
404539d628a0SDimitry Andric     break;
404639d628a0SDimitry Andric   };
404739d628a0SDimitry Andric }
404839d628a0SDimitry Andric 
404939d628a0SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
405039d628a0SDimitry Andric   // Do we need to generate coverage mapping?
405139d628a0SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
405239d628a0SDimitry Andric     return;
405339d628a0SDimitry Andric   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
405439d628a0SDimitry Andric     if (Fn->isTemplateInstantiation())
405539d628a0SDimitry Andric       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
405639d628a0SDimitry Andric   }
405739d628a0SDimitry Andric   auto I = DeferredEmptyCoverageMappingDecls.find(D);
405839d628a0SDimitry Andric   if (I == DeferredEmptyCoverageMappingDecls.end())
405939d628a0SDimitry Andric     DeferredEmptyCoverageMappingDecls[D] = false;
406039d628a0SDimitry Andric   else
406139d628a0SDimitry Andric     I->second = false;
406239d628a0SDimitry Andric }
406339d628a0SDimitry Andric 
406439d628a0SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
406539d628a0SDimitry Andric   std::vector<const Decl *> DeferredDecls;
406633956c43SDimitry Andric   for (const auto &I : DeferredEmptyCoverageMappingDecls) {
406739d628a0SDimitry Andric     if (!I.second)
406839d628a0SDimitry Andric       continue;
406939d628a0SDimitry Andric     DeferredDecls.push_back(I.first);
407039d628a0SDimitry Andric   }
407139d628a0SDimitry Andric   // Sort the declarations by their location to make sure that the tests get a
407239d628a0SDimitry Andric   // predictable order for the coverage mapping for the unused declarations.
407339d628a0SDimitry Andric   if (CodeGenOpts.DumpCoverageMapping)
407439d628a0SDimitry Andric     std::sort(DeferredDecls.begin(), DeferredDecls.end(),
407539d628a0SDimitry Andric               [] (const Decl *LHS, const Decl *RHS) {
407639d628a0SDimitry Andric       return LHS->getLocStart() < RHS->getLocStart();
407739d628a0SDimitry Andric     });
407839d628a0SDimitry Andric   for (const auto *D : DeferredDecls) {
407939d628a0SDimitry Andric     switch (D->getKind()) {
408039d628a0SDimitry Andric     case Decl::CXXConversion:
408139d628a0SDimitry Andric     case Decl::CXXMethod:
408239d628a0SDimitry Andric     case Decl::Function:
408339d628a0SDimitry Andric     case Decl::ObjCMethod: {
408439d628a0SDimitry Andric       CodeGenPGO PGO(*this);
408539d628a0SDimitry Andric       GlobalDecl GD(cast<FunctionDecl>(D));
408639d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
408739d628a0SDimitry Andric                                   getFunctionLinkage(GD));
408839d628a0SDimitry Andric       break;
408939d628a0SDimitry Andric     }
409039d628a0SDimitry Andric     case Decl::CXXConstructor: {
409139d628a0SDimitry Andric       CodeGenPGO PGO(*this);
409239d628a0SDimitry Andric       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
409339d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
409439d628a0SDimitry Andric                                   getFunctionLinkage(GD));
409539d628a0SDimitry Andric       break;
409639d628a0SDimitry Andric     }
409739d628a0SDimitry Andric     case Decl::CXXDestructor: {
409839d628a0SDimitry Andric       CodeGenPGO PGO(*this);
409939d628a0SDimitry Andric       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
410039d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
410139d628a0SDimitry Andric                                   getFunctionLinkage(GD));
410239d628a0SDimitry Andric       break;
410339d628a0SDimitry Andric     }
410439d628a0SDimitry Andric     default:
410539d628a0SDimitry Andric       break;
410639d628a0SDimitry Andric     };
4107f22ef01cSRoman Divacky   }
4108f22ef01cSRoman Divacky }
4109ffd1746dSEd Schouten 
4110ffd1746dSEd Schouten /// Turns the given pointer into a constant.
4111ffd1746dSEd Schouten static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4112ffd1746dSEd Schouten                                           const void *Ptr) {
4113ffd1746dSEd Schouten   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
41146122f3e6SDimitry Andric   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
4115ffd1746dSEd Schouten   return llvm::ConstantInt::get(i64, PtrInt);
4116ffd1746dSEd Schouten }
4117ffd1746dSEd Schouten 
4118ffd1746dSEd Schouten static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
4119ffd1746dSEd Schouten                                    llvm::NamedMDNode *&GlobalMetadata,
4120ffd1746dSEd Schouten                                    GlobalDecl D,
4121ffd1746dSEd Schouten                                    llvm::GlobalValue *Addr) {
4122ffd1746dSEd Schouten   if (!GlobalMetadata)
4123ffd1746dSEd Schouten     GlobalMetadata =
4124ffd1746dSEd Schouten       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4125ffd1746dSEd Schouten 
4126ffd1746dSEd Schouten   // TODO: should we report variant information for ctors/dtors?
412739d628a0SDimitry Andric   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
412839d628a0SDimitry Andric                            llvm::ConstantAsMetadata::get(GetPointerConstant(
412939d628a0SDimitry Andric                                CGM.getLLVMContext(), D.getDecl()))};
41303b0f4066SDimitry Andric   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
4131ffd1746dSEd Schouten }
4132ffd1746dSEd Schouten 
4133284c1978SDimitry Andric /// For each function which is declared within an extern "C" region and marked
4134284c1978SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled
4135284c1978SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer
4136284c1978SDimitry Andric /// to such functions with an unmangled name from inline assembly within the
4137284c1978SDimitry Andric /// same translation unit.
4138284c1978SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() {
4139e7145dcbSDimitry Andric   // Don't do anything if we're generating CUDA device code -- the NVPTX
4140e7145dcbSDimitry Andric   // assembly target doesn't support aliases.
4141e7145dcbSDimitry Andric   if (Context.getTargetInfo().getTriple().isNVPTX())
4142e7145dcbSDimitry Andric     return;
41438f0fd8f6SDimitry Andric   for (auto &I : StaticExternCValues) {
41448f0fd8f6SDimitry Andric     IdentifierInfo *Name = I.first;
41458f0fd8f6SDimitry Andric     llvm::GlobalValue *Val = I.second;
4146284c1978SDimitry Andric     if (Val && !getModule().getNamedValue(Name->getName()))
414759d1ed5bSDimitry Andric       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
4148284c1978SDimitry Andric   }
4149284c1978SDimitry Andric }
4150284c1978SDimitry Andric 
415159d1ed5bSDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
415259d1ed5bSDimitry Andric                                              GlobalDecl &Result) const {
415359d1ed5bSDimitry Andric   auto Res = Manglings.find(MangledName);
415459d1ed5bSDimitry Andric   if (Res == Manglings.end())
415559d1ed5bSDimitry Andric     return false;
415659d1ed5bSDimitry Andric   Result = Res->getValue();
415759d1ed5bSDimitry Andric   return true;
415859d1ed5bSDimitry Andric }
415959d1ed5bSDimitry Andric 
4160ffd1746dSEd Schouten /// Emits metadata nodes associating all the global values in the
4161ffd1746dSEd Schouten /// current module with the Decls they came from.  This is useful for
4162ffd1746dSEd Schouten /// projects using IR gen as a subroutine.
4163ffd1746dSEd Schouten ///
4164ffd1746dSEd Schouten /// Since there's currently no way to associate an MDNode directly
4165ffd1746dSEd Schouten /// with an llvm::GlobalValue, we create a global named metadata
4166ffd1746dSEd Schouten /// with the name 'clang.global.decl.ptrs'.
4167ffd1746dSEd Schouten void CodeGenModule::EmitDeclMetadata() {
416859d1ed5bSDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
4169ffd1746dSEd Schouten 
417059d1ed5bSDimitry Andric   for (auto &I : MangledDeclNames) {
417159d1ed5bSDimitry Andric     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
41720623d748SDimitry Andric     // Some mangled names don't necessarily have an associated GlobalValue
41730623d748SDimitry Andric     // in this module, e.g. if we mangled it for DebugInfo.
41740623d748SDimitry Andric     if (Addr)
417559d1ed5bSDimitry Andric       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
4176ffd1746dSEd Schouten   }
4177ffd1746dSEd Schouten }
4178ffd1746dSEd Schouten 
4179ffd1746dSEd Schouten /// Emits metadata nodes for all the local variables in the current
4180ffd1746dSEd Schouten /// function.
4181ffd1746dSEd Schouten void CodeGenFunction::EmitDeclMetadata() {
4182ffd1746dSEd Schouten   if (LocalDeclMap.empty()) return;
4183ffd1746dSEd Schouten 
4184ffd1746dSEd Schouten   llvm::LLVMContext &Context = getLLVMContext();
4185ffd1746dSEd Schouten 
4186ffd1746dSEd Schouten   // Find the unique metadata ID for this name.
4187ffd1746dSEd Schouten   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
4188ffd1746dSEd Schouten 
418959d1ed5bSDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
4190ffd1746dSEd Schouten 
419159d1ed5bSDimitry Andric   for (auto &I : LocalDeclMap) {
419259d1ed5bSDimitry Andric     const Decl *D = I.first;
41930623d748SDimitry Andric     llvm::Value *Addr = I.second.getPointer();
419459d1ed5bSDimitry Andric     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
4195ffd1746dSEd Schouten       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
419639d628a0SDimitry Andric       Alloca->setMetadata(
419739d628a0SDimitry Andric           DeclPtrKind, llvm::MDNode::get(
419839d628a0SDimitry Andric                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
419959d1ed5bSDimitry Andric     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
4200ffd1746dSEd Schouten       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
4201ffd1746dSEd Schouten       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
4202ffd1746dSEd Schouten     }
4203ffd1746dSEd Schouten   }
4204ffd1746dSEd Schouten }
4205e580952dSDimitry Andric 
4206f785676fSDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() {
4207f785676fSDimitry Andric   llvm::NamedMDNode *IdentMetadata =
4208f785676fSDimitry Andric     TheModule.getOrInsertNamedMetadata("llvm.ident");
4209f785676fSDimitry Andric   std::string Version = getClangFullVersion();
4210f785676fSDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
4211f785676fSDimitry Andric 
421239d628a0SDimitry Andric   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
4213f785676fSDimitry Andric   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4214f785676fSDimitry Andric }
4215f785676fSDimitry Andric 
421659d1ed5bSDimitry Andric void CodeGenModule::EmitTargetMetadata() {
421739d628a0SDimitry Andric   // Warning, new MangledDeclNames may be appended within this loop.
421839d628a0SDimitry Andric   // We rely on MapVector insertions adding new elements to the end
421939d628a0SDimitry Andric   // of the container.
422039d628a0SDimitry Andric   // FIXME: Move this loop into the one target that needs it, and only
422139d628a0SDimitry Andric   // loop over those declarations for which we couldn't emit the target
422239d628a0SDimitry Andric   // metadata when we emitted the declaration.
422339d628a0SDimitry Andric   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
422439d628a0SDimitry Andric     auto Val = *(MangledDeclNames.begin() + I);
422539d628a0SDimitry Andric     const Decl *D = Val.first.getDecl()->getMostRecentDecl();
422639d628a0SDimitry Andric     llvm::GlobalValue *GV = GetGlobalValue(Val.second);
422759d1ed5bSDimitry Andric     getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
422859d1ed5bSDimitry Andric   }
422959d1ed5bSDimitry Andric }
423059d1ed5bSDimitry Andric 
4231bd5abe19SDimitry Andric void CodeGenModule::EmitCoverageFile() {
423244290647SDimitry Andric   if (getCodeGenOpts().CoverageDataFile.empty() &&
423344290647SDimitry Andric       getCodeGenOpts().CoverageNotesFile.empty())
423444290647SDimitry Andric     return;
423544290647SDimitry Andric 
423644290647SDimitry Andric   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
423744290647SDimitry Andric   if (!CUNode)
423844290647SDimitry Andric     return;
423944290647SDimitry Andric 
4240bd5abe19SDimitry Andric   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
4241bd5abe19SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
424244290647SDimitry Andric   auto *CoverageDataFile =
424344290647SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
424444290647SDimitry Andric   auto *CoverageNotesFile =
424544290647SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
4246bd5abe19SDimitry Andric   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
4247bd5abe19SDimitry Andric     llvm::MDNode *CU = CUNode->getOperand(i);
424844290647SDimitry Andric     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
424939d628a0SDimitry Andric     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
4250bd5abe19SDimitry Andric   }
4251bd5abe19SDimitry Andric }
42523861d79fSDimitry Andric 
425339d628a0SDimitry Andric llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
42543861d79fSDimitry Andric   // Sema has checked that all uuid strings are of the form
42553861d79fSDimitry Andric   // "12345678-1234-1234-1234-1234567890ab".
42563861d79fSDimitry Andric   assert(Uuid.size() == 36);
4257f785676fSDimitry Andric   for (unsigned i = 0; i < 36; ++i) {
4258f785676fSDimitry Andric     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
4259f785676fSDimitry Andric     else                                         assert(isHexDigit(Uuid[i]));
42603861d79fSDimitry Andric   }
42613861d79fSDimitry Andric 
426239d628a0SDimitry Andric   // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
4263f785676fSDimitry Andric   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
42643861d79fSDimitry Andric 
4265f785676fSDimitry Andric   llvm::Constant *Field3[8];
4266f785676fSDimitry Andric   for (unsigned Idx = 0; Idx < 8; ++Idx)
4267f785676fSDimitry Andric     Field3[Idx] = llvm::ConstantInt::get(
4268f785676fSDimitry Andric         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
42693861d79fSDimitry Andric 
4270f785676fSDimitry Andric   llvm::Constant *Fields[4] = {
4271f785676fSDimitry Andric     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
4272f785676fSDimitry Andric     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
4273f785676fSDimitry Andric     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
4274f785676fSDimitry Andric     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
4275f785676fSDimitry Andric   };
4276f785676fSDimitry Andric 
4277f785676fSDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
42783861d79fSDimitry Andric }
427959d1ed5bSDimitry Andric 
428059d1ed5bSDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
428159d1ed5bSDimitry Andric                                                        bool ForEH) {
428259d1ed5bSDimitry Andric   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
428359d1ed5bSDimitry Andric   // FIXME: should we even be calling this method if RTTI is disabled
428459d1ed5bSDimitry Andric   // and it's not for EH?
428559d1ed5bSDimitry Andric   if (!ForEH && !getLangOpts().RTTI)
428659d1ed5bSDimitry Andric     return llvm::Constant::getNullValue(Int8PtrTy);
428759d1ed5bSDimitry Andric 
428859d1ed5bSDimitry Andric   if (ForEH && Ty->isObjCObjectPointerType() &&
428959d1ed5bSDimitry Andric       LangOpts.ObjCRuntime.isGNUFamily())
429059d1ed5bSDimitry Andric     return ObjCRuntime->GetEHType(Ty);
429159d1ed5bSDimitry Andric 
429259d1ed5bSDimitry Andric   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
429359d1ed5bSDimitry Andric }
429459d1ed5bSDimitry Andric 
429539d628a0SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
429639d628a0SDimitry Andric   for (auto RefExpr : D->varlists()) {
429739d628a0SDimitry Andric     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
429839d628a0SDimitry Andric     bool PerformInit =
429939d628a0SDimitry Andric         VD->getAnyInitializer() &&
430039d628a0SDimitry Andric         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
430139d628a0SDimitry Andric                                                         /*ForRef=*/false);
43020623d748SDimitry Andric 
43030623d748SDimitry Andric     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
430433956c43SDimitry Andric     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
43050623d748SDimitry Andric             VD, Addr, RefExpr->getLocStart(), PerformInit))
430639d628a0SDimitry Andric       CXXGlobalInits.push_back(InitFunction);
430739d628a0SDimitry Andric   }
430839d628a0SDimitry Andric }
43098f0fd8f6SDimitry Andric 
43100623d748SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
43110623d748SDimitry Andric   llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
43120623d748SDimitry Andric   if (InternalId)
43130623d748SDimitry Andric     return InternalId;
43140623d748SDimitry Andric 
43150623d748SDimitry Andric   if (isExternallyVisible(T->getLinkage())) {
43168f0fd8f6SDimitry Andric     std::string OutName;
43178f0fd8f6SDimitry Andric     llvm::raw_string_ostream Out(OutName);
43180623d748SDimitry Andric     getCXXABI().getMangleContext().mangleTypeName(T, Out);
43198f0fd8f6SDimitry Andric 
43200623d748SDimitry Andric     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
43210623d748SDimitry Andric   } else {
43220623d748SDimitry Andric     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
43230623d748SDimitry Andric                                            llvm::ArrayRef<llvm::Metadata *>());
43240623d748SDimitry Andric   }
43250623d748SDimitry Andric 
43260623d748SDimitry Andric   return InternalId;
43270623d748SDimitry Andric }
43280623d748SDimitry Andric 
4329e7145dcbSDimitry Andric /// Returns whether this module needs the "all-vtables" type identifier.
4330e7145dcbSDimitry Andric bool CodeGenModule::NeedAllVtablesTypeId() const {
4331e7145dcbSDimitry Andric   // Returns true if at least one of vtable-based CFI checkers is enabled and
4332e7145dcbSDimitry Andric   // is not in the trapping mode.
4333e7145dcbSDimitry Andric   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
4334e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
4335e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
4336e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
4337e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
4338e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
4339e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
4340e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
4341e7145dcbSDimitry Andric }
4342e7145dcbSDimitry Andric 
4343e7145dcbSDimitry Andric void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
43440623d748SDimitry Andric                                           CharUnits Offset,
43450623d748SDimitry Andric                                           const CXXRecordDecl *RD) {
43460623d748SDimitry Andric   llvm::Metadata *MD =
43470623d748SDimitry Andric       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
4348e7145dcbSDimitry Andric   VTable->addTypeMetadata(Offset.getQuantity(), MD);
43490623d748SDimitry Andric 
4350e7145dcbSDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
4351e7145dcbSDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
4352e7145dcbSDimitry Andric       VTable->addTypeMetadata(Offset.getQuantity(),
4353e7145dcbSDimitry Andric                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
4354e7145dcbSDimitry Andric 
4355e7145dcbSDimitry Andric   if (NeedAllVtablesTypeId()) {
4356e7145dcbSDimitry Andric     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
4357e7145dcbSDimitry Andric     VTable->addTypeMetadata(Offset.getQuantity(), MD);
43580623d748SDimitry Andric   }
43590623d748SDimitry Andric }
43600623d748SDimitry Andric 
43610623d748SDimitry Andric // Fills in the supplied string map with the set of target features for the
43620623d748SDimitry Andric // passed in function.
43630623d748SDimitry Andric void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
43640623d748SDimitry Andric                                           const FunctionDecl *FD) {
43650623d748SDimitry Andric   StringRef TargetCPU = Target.getTargetOpts().CPU;
43660623d748SDimitry Andric   if (const auto *TD = FD->getAttr<TargetAttr>()) {
43670623d748SDimitry Andric     // If we have a TargetAttr build up the feature map based on that.
43680623d748SDimitry Andric     TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
43690623d748SDimitry Andric 
43700623d748SDimitry Andric     // Make a copy of the features as passed on the command line into the
43710623d748SDimitry Andric     // beginning of the additional features from the function to override.
43720623d748SDimitry Andric     ParsedAttr.first.insert(ParsedAttr.first.begin(),
43730623d748SDimitry Andric                             Target.getTargetOpts().FeaturesAsWritten.begin(),
43740623d748SDimitry Andric                             Target.getTargetOpts().FeaturesAsWritten.end());
43750623d748SDimitry Andric 
43760623d748SDimitry Andric     if (ParsedAttr.second != "")
43770623d748SDimitry Andric       TargetCPU = ParsedAttr.second;
43780623d748SDimitry Andric 
43790623d748SDimitry Andric     // Now populate the feature map, first with the TargetCPU which is either
43800623d748SDimitry Andric     // the default or a new one from the target attribute string. Then we'll use
43810623d748SDimitry Andric     // the passed in features (FeaturesAsWritten) along with the new ones from
43820623d748SDimitry Andric     // the attribute.
43830623d748SDimitry Andric     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first);
43840623d748SDimitry Andric   } else {
43850623d748SDimitry Andric     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
43860623d748SDimitry Andric                           Target.getTargetOpts().Features);
43870623d748SDimitry Andric   }
43888f0fd8f6SDimitry Andric }
4389e7145dcbSDimitry Andric 
4390e7145dcbSDimitry Andric llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
4391e7145dcbSDimitry Andric   if (!SanStats)
4392e7145dcbSDimitry Andric     SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
4393e7145dcbSDimitry Andric 
4394e7145dcbSDimitry Andric   return *SanStats;
4395e7145dcbSDimitry Andric }
439644290647SDimitry Andric llvm::Value *
439744290647SDimitry Andric CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
439844290647SDimitry Andric                                                   CodeGenFunction &CGF) {
439944290647SDimitry Andric   llvm::Constant *C = EmitConstantExpr(E, E->getType(), &CGF);
440044290647SDimitry Andric   auto SamplerT = getOpenCLRuntime().getSamplerType();
440144290647SDimitry Andric   auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
440244290647SDimitry Andric   return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
440344290647SDimitry Andric                                 "__translate_sampler_initializer"),
440444290647SDimitry Andric                                 {C});
440544290647SDimitry Andric }
4406