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"
269a199699SDimitry Andric #include "ConstantEmitter.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"
48d8866befSDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
4959d1ed5bSDimitry Andric #include "llvm/IR/CallSite.h"
50139f7f9bSDimitry Andric #include "llvm/IR/CallingConv.h"
51139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h"
52139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h"
53139f7f9bSDimitry Andric #include "llvm/IR/LLVMContext.h"
54139f7f9bSDimitry Andric #include "llvm/IR/Module.h"
5559d1ed5bSDimitry Andric #include "llvm/ProfileData/InstrProfReader.h"
56139f7f9bSDimitry Andric #include "llvm/Support/ConvertUTF.h"
57f22ef01cSRoman Divacky #include "llvm/Support/ErrorHandling.h"
580623d748SDimitry Andric #include "llvm/Support/MD5.h"
59139f7f9bSDimitry Andric 
60f22ef01cSRoman Divacky using namespace clang;
61f22ef01cSRoman Divacky using namespace CodeGen;
62f22ef01cSRoman Divacky 
639a199699SDimitry Andric static llvm::cl::opt<bool> LimitedCoverage(
649a199699SDimitry Andric     "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
659a199699SDimitry Andric     llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
669a199699SDimitry Andric     llvm::cl::init(false));
679a199699SDimitry Andric 
686122f3e6SDimitry Andric static const char AnnotationSection[] = "llvm.metadata";
696122f3e6SDimitry Andric 
7059d1ed5bSDimitry Andric static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
71284c1978SDimitry Andric   switch (CGM.getTarget().getCXXABI().getKind()) {
72139f7f9bSDimitry Andric   case TargetCXXABI::GenericAArch64:
73139f7f9bSDimitry Andric   case TargetCXXABI::GenericARM:
74139f7f9bSDimitry Andric   case TargetCXXABI::iOS:
7559d1ed5bSDimitry Andric   case TargetCXXABI::iOS64:
760623d748SDimitry Andric   case TargetCXXABI::WatchOS:
77ef6fa9e2SDimitry Andric   case TargetCXXABI::GenericMIPS:
78139f7f9bSDimitry Andric   case TargetCXXABI::GenericItanium:
790623d748SDimitry Andric   case TargetCXXABI::WebAssembly:
8059d1ed5bSDimitry Andric     return CreateItaniumCXXABI(CGM);
81139f7f9bSDimitry Andric   case TargetCXXABI::Microsoft:
8259d1ed5bSDimitry Andric     return CreateMicrosoftCXXABI(CGM);
83e580952dSDimitry Andric   }
84e580952dSDimitry Andric 
85e580952dSDimitry Andric   llvm_unreachable("invalid C++ ABI kind");
86e580952dSDimitry Andric }
87e580952dSDimitry Andric 
883dac3a9bSDimitry Andric CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
893dac3a9bSDimitry Andric                              const PreprocessorOptions &PPO,
903dac3a9bSDimitry Andric                              const CodeGenOptions &CGO, llvm::Module &M,
9139d628a0SDimitry Andric                              DiagnosticsEngine &diags,
9239d628a0SDimitry Andric                              CoverageSourceInfo *CoverageInfo)
933dac3a9bSDimitry Andric     : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
943dac3a9bSDimitry Andric       PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
950623d748SDimitry Andric       Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
96e7145dcbSDimitry Andric       VMContext(M.getContext()), Types(*this), VTables(*this),
97e7145dcbSDimitry Andric       SanitizerMD(new SanitizerMetadata(*this)) {
98dff0c46cSDimitry Andric 
99dff0c46cSDimitry Andric   // Initialize the type cache.
100dff0c46cSDimitry Andric   llvm::LLVMContext &LLVMContext = M.getContext();
101dff0c46cSDimitry Andric   VoidTy = llvm::Type::getVoidTy(LLVMContext);
102dff0c46cSDimitry Andric   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
103dff0c46cSDimitry Andric   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
104dff0c46cSDimitry Andric   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
105dff0c46cSDimitry Andric   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
106dff0c46cSDimitry Andric   FloatTy = llvm::Type::getFloatTy(LLVMContext);
107dff0c46cSDimitry Andric   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
108dff0c46cSDimitry Andric   PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
109dff0c46cSDimitry Andric   PointerAlignInBytes =
110dff0c46cSDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
11144290647SDimitry Andric   SizeSizeInBytes =
11244290647SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
1130623d748SDimitry Andric   IntAlignInBytes =
1140623d748SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
115dff0c46cSDimitry Andric   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
11644290647SDimitry Andric   IntPtrTy = llvm::IntegerType::get(LLVMContext,
11744290647SDimitry Andric     C.getTargetInfo().getMaxPointerWidth());
118dff0c46cSDimitry Andric   Int8PtrTy = Int8Ty->getPointerTo(0);
119dff0c46cSDimitry Andric   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
1206bc11b14SDimitry Andric   AllocaInt8PtrTy = Int8Ty->getPointerTo(
1216bc11b14SDimitry Andric       M.getDataLayout().getAllocaAddrSpace());
122d8866befSDimitry Andric   ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
123dff0c46cSDimitry Andric 
124139f7f9bSDimitry Andric   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
12539d628a0SDimitry Andric   BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
126139f7f9bSDimitry Andric 
127dff0c46cSDimitry Andric   if (LangOpts.ObjC1)
1283b0f4066SDimitry Andric     createObjCRuntime();
129dff0c46cSDimitry Andric   if (LangOpts.OpenCL)
1306122f3e6SDimitry Andric     createOpenCLRuntime();
13159d1ed5bSDimitry Andric   if (LangOpts.OpenMP)
13259d1ed5bSDimitry Andric     createOpenMPRuntime();
133dff0c46cSDimitry Andric   if (LangOpts.CUDA)
1346122f3e6SDimitry Andric     createCUDARuntime();
135f22ef01cSRoman Divacky 
1367ae0e2c9SDimitry Andric   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
13739d628a0SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
1387ae0e2c9SDimitry Andric       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
1399a199699SDimitry Andric     TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
140e7145dcbSDimitry Andric                                getCXXABI().getMangleContext()));
1412754fe60SDimitry Andric 
1423b0f4066SDimitry Andric   // If debug info or coverage generation is enabled, create the CGDebugInfo
1433b0f4066SDimitry Andric   // object.
144e7145dcbSDimitry Andric   if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
145e7145dcbSDimitry Andric       CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
146e7145dcbSDimitry Andric     DebugInfo.reset(new CGDebugInfo(*this));
1472754fe60SDimitry Andric 
1482754fe60SDimitry Andric   Block.GlobalUniqueCount = 0;
1492754fe60SDimitry Andric 
1500623d748SDimitry Andric   if (C.getLangOpts().ObjC1)
151e7145dcbSDimitry Andric     ObjCData.reset(new ObjCEntrypoints());
15259d1ed5bSDimitry Andric 
153e7145dcbSDimitry Andric   if (CodeGenOpts.hasProfileClangUse()) {
154e7145dcbSDimitry Andric     auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
155e7145dcbSDimitry Andric         CodeGenOpts.ProfileInstrumentUsePath);
156e7145dcbSDimitry Andric     if (auto E = ReaderOrErr.takeError()) {
15759d1ed5bSDimitry Andric       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1583dac3a9bSDimitry Andric                                               "Could not read profile %0: %1");
159e7145dcbSDimitry Andric       llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
160e7145dcbSDimitry Andric         getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
161e7145dcbSDimitry Andric                                   << EI.message();
162e7145dcbSDimitry Andric       });
16333956c43SDimitry Andric     } else
16433956c43SDimitry Andric       PGOReader = std::move(ReaderOrErr.get());
16559d1ed5bSDimitry Andric   }
16639d628a0SDimitry Andric 
16739d628a0SDimitry Andric   // If coverage mapping generation is enabled, create the
16839d628a0SDimitry Andric   // CoverageMappingModuleGen object.
16939d628a0SDimitry Andric   if (CodeGenOpts.CoverageMapping)
17039d628a0SDimitry Andric     CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
171f22ef01cSRoman Divacky }
172f22ef01cSRoman Divacky 
173e7145dcbSDimitry Andric CodeGenModule::~CodeGenModule() {}
174f22ef01cSRoman Divacky 
175f22ef01cSRoman Divacky void CodeGenModule::createObjCRuntime() {
1767ae0e2c9SDimitry Andric   // This is just isGNUFamily(), but we want to force implementors of
1777ae0e2c9SDimitry Andric   // new ABIs to decide how best to do this.
1787ae0e2c9SDimitry Andric   switch (LangOpts.ObjCRuntime.getKind()) {
1797ae0e2c9SDimitry Andric   case ObjCRuntime::GNUstep:
1807ae0e2c9SDimitry Andric   case ObjCRuntime::GCC:
1817ae0e2c9SDimitry Andric   case ObjCRuntime::ObjFW:
182e7145dcbSDimitry Andric     ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
1837ae0e2c9SDimitry Andric     return;
1847ae0e2c9SDimitry Andric 
1857ae0e2c9SDimitry Andric   case ObjCRuntime::FragileMacOSX:
1867ae0e2c9SDimitry Andric   case ObjCRuntime::MacOSX:
1877ae0e2c9SDimitry Andric   case ObjCRuntime::iOS:
1880623d748SDimitry Andric   case ObjCRuntime::WatchOS:
189e7145dcbSDimitry Andric     ObjCRuntime.reset(CreateMacObjCRuntime(*this));
1907ae0e2c9SDimitry Andric     return;
1917ae0e2c9SDimitry Andric   }
1927ae0e2c9SDimitry Andric   llvm_unreachable("bad runtime kind");
1936122f3e6SDimitry Andric }
1946122f3e6SDimitry Andric 
1956122f3e6SDimitry Andric void CodeGenModule::createOpenCLRuntime() {
196e7145dcbSDimitry Andric   OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
1976122f3e6SDimitry Andric }
1986122f3e6SDimitry Andric 
19959d1ed5bSDimitry Andric void CodeGenModule::createOpenMPRuntime() {
200e7145dcbSDimitry Andric   // Select a specialized code generation class based on the target, if any.
201e7145dcbSDimitry Andric   // If it does not exist use the default implementation.
20244290647SDimitry Andric   switch (getTriple().getArch()) {
203e7145dcbSDimitry Andric   case llvm::Triple::nvptx:
204e7145dcbSDimitry Andric   case llvm::Triple::nvptx64:
205e7145dcbSDimitry Andric     assert(getLangOpts().OpenMPIsDevice &&
206e7145dcbSDimitry Andric            "OpenMP NVPTX is only prepared to deal with device code.");
207e7145dcbSDimitry Andric     OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
208e7145dcbSDimitry Andric     break;
209e7145dcbSDimitry Andric   default:
210e7145dcbSDimitry Andric     OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
211e7145dcbSDimitry Andric     break;
212e7145dcbSDimitry Andric   }
21359d1ed5bSDimitry Andric }
21459d1ed5bSDimitry Andric 
2156122f3e6SDimitry Andric void CodeGenModule::createCUDARuntime() {
216e7145dcbSDimitry Andric   CUDARuntime.reset(CreateNVCUDARuntime(*this));
217f22ef01cSRoman Divacky }
218f22ef01cSRoman Divacky 
21939d628a0SDimitry Andric void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
22039d628a0SDimitry Andric   Replacements[Name] = C;
22139d628a0SDimitry Andric }
22239d628a0SDimitry Andric 
223f785676fSDimitry Andric void CodeGenModule::applyReplacements() {
2248f0fd8f6SDimitry Andric   for (auto &I : Replacements) {
2258f0fd8f6SDimitry Andric     StringRef MangledName = I.first();
2268f0fd8f6SDimitry Andric     llvm::Constant *Replacement = I.second;
227f785676fSDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
228f785676fSDimitry Andric     if (!Entry)
229f785676fSDimitry Andric       continue;
23059d1ed5bSDimitry Andric     auto *OldF = cast<llvm::Function>(Entry);
23159d1ed5bSDimitry Andric     auto *NewF = dyn_cast<llvm::Function>(Replacement);
232f785676fSDimitry Andric     if (!NewF) {
23359d1ed5bSDimitry Andric       if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
23459d1ed5bSDimitry Andric         NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
23559d1ed5bSDimitry Andric       } else {
23659d1ed5bSDimitry Andric         auto *CE = cast<llvm::ConstantExpr>(Replacement);
237f785676fSDimitry Andric         assert(CE->getOpcode() == llvm::Instruction::BitCast ||
238f785676fSDimitry Andric                CE->getOpcode() == llvm::Instruction::GetElementPtr);
239f785676fSDimitry Andric         NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
240f785676fSDimitry Andric       }
24159d1ed5bSDimitry Andric     }
242f785676fSDimitry Andric 
243f785676fSDimitry Andric     // Replace old with new, but keep the old order.
244f785676fSDimitry Andric     OldF->replaceAllUsesWith(Replacement);
245f785676fSDimitry Andric     if (NewF) {
246f785676fSDimitry Andric       NewF->removeFromParent();
2470623d748SDimitry Andric       OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
2480623d748SDimitry Andric                                                        NewF);
249f785676fSDimitry Andric     }
250f785676fSDimitry Andric     OldF->eraseFromParent();
251f785676fSDimitry Andric   }
252f785676fSDimitry Andric }
253f785676fSDimitry Andric 
2540623d748SDimitry Andric void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
2550623d748SDimitry Andric   GlobalValReplacements.push_back(std::make_pair(GV, C));
2560623d748SDimitry Andric }
2570623d748SDimitry Andric 
2580623d748SDimitry Andric void CodeGenModule::applyGlobalValReplacements() {
2590623d748SDimitry Andric   for (auto &I : GlobalValReplacements) {
2600623d748SDimitry Andric     llvm::GlobalValue *GV = I.first;
2610623d748SDimitry Andric     llvm::Constant *C = I.second;
2620623d748SDimitry Andric 
2630623d748SDimitry Andric     GV->replaceAllUsesWith(C);
2640623d748SDimitry Andric     GV->eraseFromParent();
2650623d748SDimitry Andric   }
2660623d748SDimitry Andric }
2670623d748SDimitry Andric 
26859d1ed5bSDimitry Andric // This is only used in aliases that we created and we know they have a
26959d1ed5bSDimitry Andric // linear structure.
270e7145dcbSDimitry Andric static const llvm::GlobalObject *getAliasedGlobal(
271e7145dcbSDimitry Andric     const llvm::GlobalIndirectSymbol &GIS) {
272e7145dcbSDimitry Andric   llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
273e7145dcbSDimitry Andric   const llvm::Constant *C = &GIS;
27459d1ed5bSDimitry Andric   for (;;) {
27559d1ed5bSDimitry Andric     C = C->stripPointerCasts();
27659d1ed5bSDimitry Andric     if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
27759d1ed5bSDimitry Andric       return GO;
27859d1ed5bSDimitry Andric     // stripPointerCasts will not walk over weak aliases.
279e7145dcbSDimitry Andric     auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
280e7145dcbSDimitry Andric     if (!GIS2)
28159d1ed5bSDimitry Andric       return nullptr;
282e7145dcbSDimitry Andric     if (!Visited.insert(GIS2).second)
28359d1ed5bSDimitry Andric       return nullptr;
284e7145dcbSDimitry Andric     C = GIS2->getIndirectSymbol();
28559d1ed5bSDimitry Andric   }
28659d1ed5bSDimitry Andric }
28759d1ed5bSDimitry Andric 
288f785676fSDimitry Andric void CodeGenModule::checkAliases() {
28959d1ed5bSDimitry Andric   // Check if the constructed aliases are well formed. It is really unfortunate
29059d1ed5bSDimitry Andric   // that we have to do this in CodeGen, but we only construct mangled names
29159d1ed5bSDimitry Andric   // and aliases during codegen.
292f785676fSDimitry Andric   bool Error = false;
29359d1ed5bSDimitry Andric   DiagnosticsEngine &Diags = getDiags();
2948f0fd8f6SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
29559d1ed5bSDimitry Andric     const auto *D = cast<ValueDecl>(GD.getDecl());
296e7145dcbSDimitry Andric     SourceLocation Location;
297e7145dcbSDimitry Andric     bool IsIFunc = D->hasAttr<IFuncAttr>();
298e7145dcbSDimitry Andric     if (const Attr *A = D->getDefiningAttr())
299e7145dcbSDimitry Andric       Location = A->getLocation();
300e7145dcbSDimitry Andric     else
301e7145dcbSDimitry Andric       llvm_unreachable("Not an alias or ifunc?");
302f785676fSDimitry Andric     StringRef MangledName = getMangledName(GD);
303f785676fSDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
304e7145dcbSDimitry Andric     auto *Alias  = cast<llvm::GlobalIndirectSymbol>(Entry);
30559d1ed5bSDimitry Andric     const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
30659d1ed5bSDimitry Andric     if (!GV) {
307f785676fSDimitry Andric       Error = true;
308e7145dcbSDimitry Andric       Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
30959d1ed5bSDimitry Andric     } else if (GV->isDeclaration()) {
310f785676fSDimitry Andric       Error = true;
311e7145dcbSDimitry Andric       Diags.Report(Location, diag::err_alias_to_undefined)
312e7145dcbSDimitry Andric           << IsIFunc << IsIFunc;
313e7145dcbSDimitry Andric     } else if (IsIFunc) {
314e7145dcbSDimitry Andric       // Check resolver function type.
315e7145dcbSDimitry Andric       llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
316e7145dcbSDimitry Andric           GV->getType()->getPointerElementType());
317e7145dcbSDimitry Andric       assert(FTy);
318e7145dcbSDimitry Andric       if (!FTy->getReturnType()->isPointerTy())
319e7145dcbSDimitry Andric         Diags.Report(Location, diag::err_ifunc_resolver_return);
320e7145dcbSDimitry Andric       if (FTy->getNumParams())
321e7145dcbSDimitry Andric         Diags.Report(Location, diag::err_ifunc_resolver_params);
32259d1ed5bSDimitry Andric     }
32359d1ed5bSDimitry Andric 
324e7145dcbSDimitry Andric     llvm::Constant *Aliasee = Alias->getIndirectSymbol();
32559d1ed5bSDimitry Andric     llvm::GlobalValue *AliaseeGV;
32659d1ed5bSDimitry Andric     if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
32759d1ed5bSDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
32859d1ed5bSDimitry Andric     else
32959d1ed5bSDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
33059d1ed5bSDimitry Andric 
33159d1ed5bSDimitry Andric     if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
33259d1ed5bSDimitry Andric       StringRef AliasSection = SA->getName();
33359d1ed5bSDimitry Andric       if (AliasSection != AliaseeGV->getSection())
33459d1ed5bSDimitry Andric         Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
335e7145dcbSDimitry Andric             << AliasSection << IsIFunc << IsIFunc;
33659d1ed5bSDimitry Andric     }
33759d1ed5bSDimitry Andric 
33859d1ed5bSDimitry Andric     // We have to handle alias to weak aliases in here. LLVM itself disallows
33959d1ed5bSDimitry Andric     // this since the object semantics would not match the IL one. For
34059d1ed5bSDimitry Andric     // compatibility with gcc we implement it by just pointing the alias
34159d1ed5bSDimitry Andric     // to its aliasee's aliasee. We also warn, since the user is probably
34259d1ed5bSDimitry Andric     // expecting the link to be weak.
343e7145dcbSDimitry Andric     if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
344e7145dcbSDimitry Andric       if (GA->isInterposable()) {
345e7145dcbSDimitry Andric         Diags.Report(Location, diag::warn_alias_to_weak_alias)
346e7145dcbSDimitry Andric             << GV->getName() << GA->getName() << IsIFunc;
34759d1ed5bSDimitry Andric         Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
348e7145dcbSDimitry Andric             GA->getIndirectSymbol(), Alias->getType());
349e7145dcbSDimitry Andric         Alias->setIndirectSymbol(Aliasee);
35059d1ed5bSDimitry Andric       }
351f785676fSDimitry Andric     }
352f785676fSDimitry Andric   }
353f785676fSDimitry Andric   if (!Error)
354f785676fSDimitry Andric     return;
355f785676fSDimitry Andric 
3568f0fd8f6SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
357f785676fSDimitry Andric     StringRef MangledName = getMangledName(GD);
358f785676fSDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
359e7145dcbSDimitry Andric     auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
360f785676fSDimitry Andric     Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
361f785676fSDimitry Andric     Alias->eraseFromParent();
362f785676fSDimitry Andric   }
363f785676fSDimitry Andric }
364f785676fSDimitry Andric 
36559d1ed5bSDimitry Andric void CodeGenModule::clear() {
36659d1ed5bSDimitry Andric   DeferredDeclsToEmit.clear();
36733956c43SDimitry Andric   if (OpenMPRuntime)
36833956c43SDimitry Andric     OpenMPRuntime->clear();
36959d1ed5bSDimitry Andric }
37059d1ed5bSDimitry Andric 
37159d1ed5bSDimitry Andric void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
37259d1ed5bSDimitry Andric                                        StringRef MainFile) {
37359d1ed5bSDimitry Andric   if (!hasDiagnostics())
37459d1ed5bSDimitry Andric     return;
37559d1ed5bSDimitry Andric   if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
37659d1ed5bSDimitry Andric     if (MainFile.empty())
37759d1ed5bSDimitry Andric       MainFile = "<stdin>";
37859d1ed5bSDimitry Andric     Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
379f37b6182SDimitry Andric   } else {
380f37b6182SDimitry Andric     if (Mismatched > 0)
381f37b6182SDimitry Andric       Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
382f37b6182SDimitry Andric 
383f37b6182SDimitry Andric     if (Missing > 0)
384f37b6182SDimitry Andric       Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
385f37b6182SDimitry Andric   }
38659d1ed5bSDimitry Andric }
38759d1ed5bSDimitry Andric 
388f22ef01cSRoman Divacky void CodeGenModule::Release() {
389f22ef01cSRoman Divacky   EmitDeferred();
390f9448bf3SDimitry Andric   EmitVTablesOpportunistically();
3910623d748SDimitry Andric   applyGlobalValReplacements();
392f785676fSDimitry Andric   applyReplacements();
393f785676fSDimitry Andric   checkAliases();
394f22ef01cSRoman Divacky   EmitCXXGlobalInitFunc();
395f22ef01cSRoman Divacky   EmitCXXGlobalDtorFunc();
396284c1978SDimitry Andric   EmitCXXThreadLocalInitFunc();
3976122f3e6SDimitry Andric   if (ObjCRuntime)
3986122f3e6SDimitry Andric     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
399f22ef01cSRoman Divacky       AddGlobalCtor(ObjCInitFunction);
40033956c43SDimitry Andric   if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
40133956c43SDimitry Andric       CUDARuntime) {
40233956c43SDimitry Andric     if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
40333956c43SDimitry Andric       AddGlobalCtor(CudaCtorFunction);
40433956c43SDimitry Andric     if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
40533956c43SDimitry Andric       AddGlobalDtor(CudaDtorFunction);
40633956c43SDimitry Andric   }
407ea942507SDimitry Andric   if (OpenMPRuntime)
408ea942507SDimitry Andric     if (llvm::Function *OpenMPRegistrationFunction =
409302affcbSDimitry Andric             OpenMPRuntime->emitRegistrationFunction()) {
410302affcbSDimitry Andric       auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
411302affcbSDimitry Andric         OpenMPRegistrationFunction : nullptr;
412302affcbSDimitry Andric       AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
413302affcbSDimitry Andric     }
4140623d748SDimitry Andric   if (PGOReader) {
415e7145dcbSDimitry Andric     getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
4160623d748SDimitry Andric     if (PGOStats.hasDiagnostics())
41759d1ed5bSDimitry Andric       PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
4180623d748SDimitry Andric   }
419f22ef01cSRoman Divacky   EmitCtorList(GlobalCtors, "llvm.global_ctors");
420f22ef01cSRoman Divacky   EmitCtorList(GlobalDtors, "llvm.global_dtors");
4216122f3e6SDimitry Andric   EmitGlobalAnnotations();
422284c1978SDimitry Andric   EmitStaticExternCAliases();
42339d628a0SDimitry Andric   EmitDeferredUnusedCoverageMappings();
42439d628a0SDimitry Andric   if (CoverageMapping)
42539d628a0SDimitry Andric     CoverageMapping->emit();
42620e90f04SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
427e7145dcbSDimitry Andric     CodeGenFunction(*this).EmitCfiCheckFail();
42820e90f04SDimitry Andric     CodeGenFunction(*this).EmitCfiCheckStub();
42920e90f04SDimitry Andric   }
43020e90f04SDimitry Andric   emitAtAvailableLinkGuard();
43159d1ed5bSDimitry Andric   emitLLVMUsed();
432e7145dcbSDimitry Andric   if (SanStats)
433e7145dcbSDimitry Andric     SanStats->finish();
434ffd1746dSEd Schouten 
435f785676fSDimitry Andric   if (CodeGenOpts.Autolink &&
436f785676fSDimitry Andric       (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
437139f7f9bSDimitry Andric     EmitModuleLinkOptions();
438139f7f9bSDimitry Andric   }
43920e90f04SDimitry Andric 
44020e90f04SDimitry Andric   // Record mregparm value now so it is visible through rest of codegen.
44120e90f04SDimitry Andric   if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
44220e90f04SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
44320e90f04SDimitry Andric                               CodeGenOpts.NumRegisterParameters);
44420e90f04SDimitry Andric 
4450623d748SDimitry Andric   if (CodeGenOpts.DwarfVersion) {
446f785676fSDimitry Andric     // We actually want the latest version when there are conflicts.
447f785676fSDimitry Andric     // We can change from Warning to Latest if such mode is supported.
448f785676fSDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
449f785676fSDimitry Andric                               CodeGenOpts.DwarfVersion);
4500623d748SDimitry Andric   }
4510623d748SDimitry Andric   if (CodeGenOpts.EmitCodeView) {
4520623d748SDimitry Andric     // Indicate that we want CodeView in the metadata.
4530623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
4540623d748SDimitry Andric   }
4550623d748SDimitry Andric   if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
4560623d748SDimitry Andric     // We don't support LTO with 2 with different StrictVTablePointers
4570623d748SDimitry Andric     // FIXME: we could support it by stripping all the information introduced
4580623d748SDimitry Andric     // by StrictVTablePointers.
4590623d748SDimitry Andric 
4600623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
4610623d748SDimitry Andric 
4620623d748SDimitry Andric     llvm::Metadata *Ops[2] = {
4630623d748SDimitry Andric               llvm::MDString::get(VMContext, "StrictVTablePointers"),
4640623d748SDimitry Andric               llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
4650623d748SDimitry Andric                   llvm::Type::getInt32Ty(VMContext), 1))};
4660623d748SDimitry Andric 
4670623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Require,
4680623d748SDimitry Andric                               "StrictVTablePointersRequirement",
4690623d748SDimitry Andric                               llvm::MDNode::get(VMContext, Ops));
4700623d748SDimitry Andric   }
471f785676fSDimitry Andric   if (DebugInfo)
47259d1ed5bSDimitry Andric     // We support a single version in the linked module. The LLVM
47359d1ed5bSDimitry Andric     // parser will drop debug info with a different version number
47459d1ed5bSDimitry Andric     // (and warn about it, too).
47559d1ed5bSDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
476f785676fSDimitry Andric                               llvm::DEBUG_METADATA_VERSION);
477139f7f9bSDimitry Andric 
47859d1ed5bSDimitry Andric   // We need to record the widths of enums and wchar_t, so that we can generate
479d8866befSDimitry Andric   // the correct build attributes in the ARM backend. wchar_size is also used by
480d8866befSDimitry Andric   // TargetLibraryInfo.
4819a199699SDimitry Andric   uint64_t WCharWidth =
4829a199699SDimitry Andric       Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
483d8866befSDimitry Andric   getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
484d8866befSDimitry Andric 
48559d1ed5bSDimitry Andric   llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
48659d1ed5bSDimitry Andric   if (   Arch == llvm::Triple::arm
48759d1ed5bSDimitry Andric       || Arch == llvm::Triple::armeb
48859d1ed5bSDimitry Andric       || Arch == llvm::Triple::thumb
48959d1ed5bSDimitry Andric       || Arch == llvm::Triple::thumbeb) {
49059d1ed5bSDimitry Andric     // The minimum width of an enum in bytes
49159d1ed5bSDimitry Andric     uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
49259d1ed5bSDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
49359d1ed5bSDimitry Andric   }
49459d1ed5bSDimitry Andric 
4950623d748SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
4960623d748SDimitry Andric     // Indicate that we want cross-DSO control flow integrity checks.
4970623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
4980623d748SDimitry Andric   }
4990623d748SDimitry Andric 
50044290647SDimitry Andric   if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
501e7145dcbSDimitry Andric     // Indicate whether __nvvm_reflect should be configured to flush denormal
502e7145dcbSDimitry Andric     // floating point values to 0.  (This corresponds to its "__CUDA_FTZ"
503e7145dcbSDimitry Andric     // property.)
504e7145dcbSDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
505e7145dcbSDimitry Andric                               LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
50639d628a0SDimitry Andric   }
50739d628a0SDimitry Andric 
508edd7eaddSDimitry Andric   // Emit OpenCL specific module metadata: OpenCL/SPIR version.
509edd7eaddSDimitry Andric   if (LangOpts.OpenCL) {
510edd7eaddSDimitry Andric     EmitOpenCLMetadata();
511edd7eaddSDimitry Andric     // Emit SPIR version.
512edd7eaddSDimitry Andric     if (getTriple().getArch() == llvm::Triple::spir ||
513edd7eaddSDimitry Andric         getTriple().getArch() == llvm::Triple::spir64) {
514edd7eaddSDimitry Andric       // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
515edd7eaddSDimitry Andric       // opencl.spir.version named metadata.
516edd7eaddSDimitry Andric       llvm::Metadata *SPIRVerElts[] = {
517edd7eaddSDimitry Andric           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
518edd7eaddSDimitry Andric               Int32Ty, LangOpts.OpenCLVersion / 100)),
519edd7eaddSDimitry Andric           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
520edd7eaddSDimitry Andric               Int32Ty, (LangOpts.OpenCLVersion / 100 > 1) ? 0 : 2))};
521edd7eaddSDimitry Andric       llvm::NamedMDNode *SPIRVerMD =
522edd7eaddSDimitry Andric           TheModule.getOrInsertNamedMetadata("opencl.spir.version");
523edd7eaddSDimitry Andric       llvm::LLVMContext &Ctx = TheModule.getContext();
524edd7eaddSDimitry Andric       SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
525edd7eaddSDimitry Andric     }
526edd7eaddSDimitry Andric   }
527edd7eaddSDimitry Andric 
528e7145dcbSDimitry Andric   if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
529e7145dcbSDimitry Andric     assert(PLevel < 3 && "Invalid PIC Level");
530e7145dcbSDimitry Andric     getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
531e7145dcbSDimitry Andric     if (Context.getLangOpts().PIE)
532e7145dcbSDimitry Andric       getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
53339d628a0SDimitry Andric   }
53439d628a0SDimitry Andric 
5352754fe60SDimitry Andric   SimplifyPersonality();
5362754fe60SDimitry Andric 
537ffd1746dSEd Schouten   if (getCodeGenOpts().EmitDeclMetadata)
538ffd1746dSEd Schouten     EmitDeclMetadata();
539bd5abe19SDimitry Andric 
540bd5abe19SDimitry Andric   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
541bd5abe19SDimitry Andric     EmitCoverageFile();
5426122f3e6SDimitry Andric 
5436122f3e6SDimitry Andric   if (DebugInfo)
5446122f3e6SDimitry Andric     DebugInfo->finalize();
545f785676fSDimitry Andric 
546f785676fSDimitry Andric   EmitVersionIdentMetadata();
54759d1ed5bSDimitry Andric 
54859d1ed5bSDimitry Andric   EmitTargetMetadata();
549f22ef01cSRoman Divacky }
550f22ef01cSRoman Divacky 
551edd7eaddSDimitry Andric void CodeGenModule::EmitOpenCLMetadata() {
552edd7eaddSDimitry Andric   // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
553edd7eaddSDimitry Andric   // opencl.ocl.version named metadata node.
554edd7eaddSDimitry Andric   llvm::Metadata *OCLVerElts[] = {
555edd7eaddSDimitry Andric       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
556edd7eaddSDimitry Andric           Int32Ty, LangOpts.OpenCLVersion / 100)),
557edd7eaddSDimitry Andric       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
558edd7eaddSDimitry Andric           Int32Ty, (LangOpts.OpenCLVersion % 100) / 10))};
559edd7eaddSDimitry Andric   llvm::NamedMDNode *OCLVerMD =
560edd7eaddSDimitry Andric       TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
561edd7eaddSDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
562edd7eaddSDimitry Andric   OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
563edd7eaddSDimitry Andric }
564edd7eaddSDimitry Andric 
5653b0f4066SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
5663b0f4066SDimitry Andric   // Make sure that this type is translated.
5673b0f4066SDimitry Andric   Types.UpdateCompletedType(TD);
5683b0f4066SDimitry Andric }
5693b0f4066SDimitry Andric 
570e7145dcbSDimitry Andric void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
571e7145dcbSDimitry Andric   // Make sure that this type is translated.
572e7145dcbSDimitry Andric   Types.RefreshTypeCacheForClass(RD);
573e7145dcbSDimitry Andric }
574e7145dcbSDimitry Andric 
5759a199699SDimitry Andric llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
5762754fe60SDimitry Andric   if (!TBAA)
57759d1ed5bSDimitry Andric     return nullptr;
5789a199699SDimitry Andric   return TBAA->getTypeInfo(QTy);
5792754fe60SDimitry Andric }
5802754fe60SDimitry Andric 
5819a199699SDimitry Andric TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
5829a199699SDimitry Andric   // Pointee values may have incomplete types, but they shall never be
5839a199699SDimitry Andric   // dereferenced.
5849a199699SDimitry Andric   if (AccessType->isIncompleteType())
5859a199699SDimitry Andric     return TBAAAccessInfo::getIncompleteInfo();
5869a199699SDimitry Andric 
5879a199699SDimitry Andric   uint64_t Size = Context.getTypeSizeInChars(AccessType).getQuantity();
5889a199699SDimitry Andric   return TBAAAccessInfo(getTBAATypeInfo(AccessType), Size);
5899a199699SDimitry Andric }
5909a199699SDimitry Andric 
5919a199699SDimitry Andric TBAAAccessInfo
5929a199699SDimitry Andric CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
593dff0c46cSDimitry Andric   if (!TBAA)
5949a199699SDimitry Andric     return TBAAAccessInfo();
5959a199699SDimitry Andric   return TBAA->getVTablePtrAccessInfo(VTablePtrType);
596dff0c46cSDimitry Andric }
597dff0c46cSDimitry Andric 
5983861d79fSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
5993861d79fSDimitry Andric   if (!TBAA)
60059d1ed5bSDimitry Andric     return nullptr;
6013861d79fSDimitry Andric   return TBAA->getTBAAStructInfo(QTy);
6023861d79fSDimitry Andric }
6033861d79fSDimitry Andric 
6049a199699SDimitry Andric llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
605139f7f9bSDimitry Andric   if (!TBAA)
60659d1ed5bSDimitry Andric     return nullptr;
6079a199699SDimitry Andric   return TBAA->getBaseTypeInfo(QTy);
608139f7f9bSDimitry Andric }
609139f7f9bSDimitry Andric 
6109a199699SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
6119a199699SDimitry Andric   if (!TBAA)
6129a199699SDimitry Andric     return nullptr;
6139a199699SDimitry Andric   return TBAA->getAccessTagInfo(Info);
6149a199699SDimitry Andric }
6159a199699SDimitry Andric 
6169a199699SDimitry Andric TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
6179a199699SDimitry Andric                                                    TBAAAccessInfo TargetInfo) {
6189a199699SDimitry Andric   if (!TBAA)
6199a199699SDimitry Andric     return TBAAAccessInfo();
6209a199699SDimitry Andric   return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
6219a199699SDimitry Andric }
6229a199699SDimitry Andric 
6239a199699SDimitry Andric TBAAAccessInfo
6249a199699SDimitry Andric CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
6259a199699SDimitry Andric                                                    TBAAAccessInfo InfoB) {
6269a199699SDimitry Andric   if (!TBAA)
6279a199699SDimitry Andric     return TBAAAccessInfo();
6289a199699SDimitry Andric   return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
6299a199699SDimitry Andric }
6309a199699SDimitry Andric 
6310623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
6329a199699SDimitry Andric                                                 TBAAAccessInfo TBAAInfo) {
6339a199699SDimitry Andric   if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
6349a199699SDimitry Andric     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
6352754fe60SDimitry Andric }
6362754fe60SDimitry Andric 
6370623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup(
6380623d748SDimitry Andric     llvm::Instruction *I, const CXXRecordDecl *RD) {
63951690af2SDimitry Andric   I->setMetadata(llvm::LLVMContext::MD_invariant_group,
64051690af2SDimitry Andric                  llvm::MDNode::get(getLLVMContext(), {}));
6410623d748SDimitry Andric }
6420623d748SDimitry Andric 
64359d1ed5bSDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) {
64459d1ed5bSDimitry Andric   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
64559d1ed5bSDimitry Andric   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
646f22ef01cSRoman Divacky }
647f22ef01cSRoman Divacky 
648f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
649f22ef01cSRoman Divacky /// specified stmt yet.
650f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
6516122f3e6SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
652f22ef01cSRoman Divacky                                                "cannot compile this %0 yet");
653f22ef01cSRoman Divacky   std::string Msg = Type;
654f22ef01cSRoman Divacky   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
655f22ef01cSRoman Divacky     << Msg << S->getSourceRange();
656f22ef01cSRoman Divacky }
657f22ef01cSRoman Divacky 
658f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
659f22ef01cSRoman Divacky /// specified decl yet.
660f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
6616122f3e6SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
662f22ef01cSRoman Divacky                                                "cannot compile this %0 yet");
663f22ef01cSRoman Divacky   std::string Msg = Type;
664f22ef01cSRoman Divacky   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
665f22ef01cSRoman Divacky }
666f22ef01cSRoman Divacky 
66717a519f9SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
66817a519f9SDimitry Andric   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
66917a519f9SDimitry Andric }
67017a519f9SDimitry Andric 
671f22ef01cSRoman Divacky void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
6729a199699SDimitry Andric                                         const NamedDecl *D,
6739a199699SDimitry Andric                                         ForDefinition_t IsForDefinition) const {
674f22ef01cSRoman Divacky   // Internal definitions always have default visibility.
675f22ef01cSRoman Divacky   if (GV->hasLocalLinkage()) {
676f22ef01cSRoman Divacky     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
677f22ef01cSRoman Divacky     return;
678f22ef01cSRoman Divacky   }
679f22ef01cSRoman Divacky 
6802754fe60SDimitry Andric   // Set visibility for definitions.
681139f7f9bSDimitry Andric   LinkageInfo LV = D->getLinkageAndVisibility();
6829a199699SDimitry Andric   if (LV.isVisibilityExplicit() ||
6839a199699SDimitry Andric       (IsForDefinition && !GV->hasAvailableExternallyLinkage()))
684139f7f9bSDimitry Andric     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
685f22ef01cSRoman Divacky }
686f22ef01cSRoman Divacky 
6877ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
6887ae0e2c9SDimitry Andric   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
6897ae0e2c9SDimitry Andric       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
6907ae0e2c9SDimitry Andric       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
6917ae0e2c9SDimitry Andric       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
6927ae0e2c9SDimitry Andric       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
6937ae0e2c9SDimitry Andric }
6947ae0e2c9SDimitry Andric 
6957ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
6967ae0e2c9SDimitry Andric     CodeGenOptions::TLSModel M) {
6977ae0e2c9SDimitry Andric   switch (M) {
6987ae0e2c9SDimitry Andric   case CodeGenOptions::GeneralDynamicTLSModel:
6997ae0e2c9SDimitry Andric     return llvm::GlobalVariable::GeneralDynamicTLSModel;
7007ae0e2c9SDimitry Andric   case CodeGenOptions::LocalDynamicTLSModel:
7017ae0e2c9SDimitry Andric     return llvm::GlobalVariable::LocalDynamicTLSModel;
7027ae0e2c9SDimitry Andric   case CodeGenOptions::InitialExecTLSModel:
7037ae0e2c9SDimitry Andric     return llvm::GlobalVariable::InitialExecTLSModel;
7047ae0e2c9SDimitry Andric   case CodeGenOptions::LocalExecTLSModel:
7057ae0e2c9SDimitry Andric     return llvm::GlobalVariable::LocalExecTLSModel;
7067ae0e2c9SDimitry Andric   }
7077ae0e2c9SDimitry Andric   llvm_unreachable("Invalid TLS model!");
7087ae0e2c9SDimitry Andric }
7097ae0e2c9SDimitry Andric 
71039d628a0SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
711284c1978SDimitry Andric   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
7127ae0e2c9SDimitry Andric 
71339d628a0SDimitry Andric   llvm::GlobalValue::ThreadLocalMode TLM;
7143861d79fSDimitry Andric   TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
7157ae0e2c9SDimitry Andric 
7167ae0e2c9SDimitry Andric   // Override the TLS model if it is explicitly specified.
71759d1ed5bSDimitry Andric   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
7187ae0e2c9SDimitry Andric     TLM = GetLLVMTLSModel(Attr->getModel());
7197ae0e2c9SDimitry Andric   }
7207ae0e2c9SDimitry Andric 
7217ae0e2c9SDimitry Andric   GV->setThreadLocalMode(TLM);
7227ae0e2c9SDimitry Andric }
7237ae0e2c9SDimitry Andric 
7246122f3e6SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
725444ed5c5SDimitry Andric   GlobalDecl CanonicalGD = GD.getCanonicalDecl();
726444ed5c5SDimitry Andric 
727444ed5c5SDimitry Andric   // Some ABIs don't have constructor variants.  Make sure that base and
728444ed5c5SDimitry Andric   // complete constructors get mangled the same.
729444ed5c5SDimitry Andric   if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
730444ed5c5SDimitry Andric     if (!getTarget().getCXXABI().hasConstructorVariants()) {
731444ed5c5SDimitry Andric       CXXCtorType OrigCtorType = GD.getCtorType();
732444ed5c5SDimitry Andric       assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
733444ed5c5SDimitry Andric       if (OrigCtorType == Ctor_Base)
734444ed5c5SDimitry Andric         CanonicalGD = GlobalDecl(CD, Ctor_Complete);
735444ed5c5SDimitry Andric     }
736444ed5c5SDimitry Andric   }
737444ed5c5SDimitry Andric 
7389a199699SDimitry Andric   auto FoundName = MangledDeclNames.find(CanonicalGD);
7399a199699SDimitry Andric   if (FoundName != MangledDeclNames.end())
7409a199699SDimitry Andric     return FoundName->second;
741f22ef01cSRoman Divacky 
74259d1ed5bSDimitry Andric   const auto *ND = cast<NamedDecl>(GD.getDecl());
743dff0c46cSDimitry Andric   SmallString<256> Buffer;
74459d1ed5bSDimitry Andric   StringRef Str;
74559d1ed5bSDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
7462754fe60SDimitry Andric     llvm::raw_svector_ostream Out(Buffer);
74759d1ed5bSDimitry Andric     if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
7482754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
74959d1ed5bSDimitry Andric     else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
7502754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
751ffd1746dSEd Schouten     else
7522754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleName(ND, Out);
75359d1ed5bSDimitry Andric     Str = Out.str();
75459d1ed5bSDimitry Andric   } else {
75559d1ed5bSDimitry Andric     IdentifierInfo *II = ND->getIdentifier();
75659d1ed5bSDimitry Andric     assert(II && "Attempt to mangle unnamed decl.");
75744290647SDimitry Andric     const auto *FD = dyn_cast<FunctionDecl>(ND);
75844290647SDimitry Andric 
75944290647SDimitry Andric     if (FD &&
76044290647SDimitry Andric         FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
76144290647SDimitry Andric       llvm::raw_svector_ostream Out(Buffer);
76244290647SDimitry Andric       Out << "__regcall3__" << II->getName();
76344290647SDimitry Andric       Str = Out.str();
76444290647SDimitry Andric     } else {
76559d1ed5bSDimitry Andric       Str = II->getName();
766ffd1746dSEd Schouten     }
76744290647SDimitry Andric   }
768ffd1746dSEd Schouten 
76939d628a0SDimitry Andric   // Keep the first result in the case of a mangling collision.
77039d628a0SDimitry Andric   auto Result = Manglings.insert(std::make_pair(Str, GD));
7719a199699SDimitry Andric   return MangledDeclNames[CanonicalGD] = Result.first->first();
77259d1ed5bSDimitry Andric }
77359d1ed5bSDimitry Andric 
77459d1ed5bSDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
775ffd1746dSEd Schouten                                              const BlockDecl *BD) {
7762754fe60SDimitry Andric   MangleContext &MangleCtx = getCXXABI().getMangleContext();
7772754fe60SDimitry Andric   const Decl *D = GD.getDecl();
77859d1ed5bSDimitry Andric 
77959d1ed5bSDimitry Andric   SmallString<256> Buffer;
78059d1ed5bSDimitry Andric   llvm::raw_svector_ostream Out(Buffer);
78159d1ed5bSDimitry Andric   if (!D)
7827ae0e2c9SDimitry Andric     MangleCtx.mangleGlobalBlock(BD,
7837ae0e2c9SDimitry Andric       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
78459d1ed5bSDimitry Andric   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
7852754fe60SDimitry Andric     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
78659d1ed5bSDimitry Andric   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
7872754fe60SDimitry Andric     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
7882754fe60SDimitry Andric   else
7892754fe60SDimitry Andric     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
79059d1ed5bSDimitry Andric 
79139d628a0SDimitry Andric   auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
79239d628a0SDimitry Andric   return Result.first->first();
793f22ef01cSRoman Divacky }
794f22ef01cSRoman Divacky 
7956122f3e6SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
796f22ef01cSRoman Divacky   return getModule().getNamedValue(Name);
797f22ef01cSRoman Divacky }
798f22ef01cSRoman Divacky 
799f22ef01cSRoman Divacky /// AddGlobalCtor - Add a function to the list that will be called before
800f22ef01cSRoman Divacky /// main() runs.
80159d1ed5bSDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
80259d1ed5bSDimitry Andric                                   llvm::Constant *AssociatedData) {
803f22ef01cSRoman Divacky   // FIXME: Type coercion of void()* types.
80459d1ed5bSDimitry Andric   GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
805f22ef01cSRoman Divacky }
806f22ef01cSRoman Divacky 
807f22ef01cSRoman Divacky /// AddGlobalDtor - Add a function to the list that will be called
808f22ef01cSRoman Divacky /// when the module is unloaded.
809f22ef01cSRoman Divacky void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
810f22ef01cSRoman Divacky   // FIXME: Type coercion of void()* types.
81159d1ed5bSDimitry Andric   GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
812f22ef01cSRoman Divacky }
813f22ef01cSRoman Divacky 
81444290647SDimitry Andric void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
81544290647SDimitry Andric   if (Fns.empty()) return;
81644290647SDimitry Andric 
817f22ef01cSRoman Divacky   // Ctor function type is void()*.
818bd5abe19SDimitry Andric   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
819f22ef01cSRoman Divacky   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
820f22ef01cSRoman Divacky 
82159d1ed5bSDimitry Andric   // Get the type of a ctor entry, { i32, void ()*, i8* }.
82259d1ed5bSDimitry Andric   llvm::StructType *CtorStructTy = llvm::StructType::get(
8235517e702SDimitry Andric       Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy);
824f22ef01cSRoman Divacky 
825f22ef01cSRoman Divacky   // Construct the constructor and destructor arrays.
82644290647SDimitry Andric   ConstantInitBuilder builder(*this);
82744290647SDimitry Andric   auto ctors = builder.beginArray(CtorStructTy);
8288f0fd8f6SDimitry Andric   for (const auto &I : Fns) {
82944290647SDimitry Andric     auto ctor = ctors.beginStruct(CtorStructTy);
83044290647SDimitry Andric     ctor.addInt(Int32Ty, I.Priority);
83144290647SDimitry Andric     ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
83244290647SDimitry Andric     if (I.AssociatedData)
83344290647SDimitry Andric       ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
83444290647SDimitry Andric     else
83544290647SDimitry Andric       ctor.addNullPointer(VoidPtrTy);
83644290647SDimitry Andric     ctor.finishAndAddTo(ctors);
837f22ef01cSRoman Divacky   }
838f22ef01cSRoman Divacky 
83944290647SDimitry Andric   auto list =
84044290647SDimitry Andric     ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
84144290647SDimitry Andric                                 /*constant*/ false,
84244290647SDimitry Andric                                 llvm::GlobalValue::AppendingLinkage);
84344290647SDimitry Andric 
84444290647SDimitry Andric   // The LTO linker doesn't seem to like it when we set an alignment
84544290647SDimitry Andric   // on appending variables.  Take it off as a workaround.
84644290647SDimitry Andric   list->setAlignment(0);
84744290647SDimitry Andric 
84844290647SDimitry Andric   Fns.clear();
849f22ef01cSRoman Divacky }
850f22ef01cSRoman Divacky 
851f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes
852f785676fSDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
85359d1ed5bSDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
854f785676fSDimitry Andric 
855e580952dSDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
856f22ef01cSRoman Divacky 
85759d1ed5bSDimitry Andric   if (isa<CXXDestructorDecl>(D) &&
85859d1ed5bSDimitry Andric       getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
85959d1ed5bSDimitry Andric                                          GD.getDtorType())) {
86059d1ed5bSDimitry Andric     // Destructor variants in the Microsoft C++ ABI are always internal or
86159d1ed5bSDimitry Andric     // linkonce_odr thunks emitted on an as-needed basis.
86259d1ed5bSDimitry Andric     return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
86359d1ed5bSDimitry Andric                                    : llvm::GlobalValue::LinkOnceODRLinkage;
864f22ef01cSRoman Divacky   }
865f22ef01cSRoman Divacky 
866e7145dcbSDimitry Andric   if (isa<CXXConstructorDecl>(D) &&
867e7145dcbSDimitry Andric       cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
868e7145dcbSDimitry Andric       Context.getTargetInfo().getCXXABI().isMicrosoft()) {
869e7145dcbSDimitry Andric     // Our approach to inheriting constructors is fundamentally different from
870e7145dcbSDimitry Andric     // that used by the MS ABI, so keep our inheriting constructor thunks
871e7145dcbSDimitry Andric     // internal rather than trying to pick an unambiguous mangling for them.
872e7145dcbSDimitry Andric     return llvm::GlobalValue::InternalLinkage;
873e7145dcbSDimitry Andric   }
874e7145dcbSDimitry Andric 
87559d1ed5bSDimitry Andric   return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
87659d1ed5bSDimitry Andric }
877f22ef01cSRoman Divacky 
87897bc6c73SDimitry Andric void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
87997bc6c73SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
88097bc6c73SDimitry Andric 
88197bc6c73SDimitry Andric   if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
88297bc6c73SDimitry Andric     if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
88397bc6c73SDimitry Andric       // Don't dllexport/import destructor thunks.
88497bc6c73SDimitry Andric       F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
88597bc6c73SDimitry Andric       return;
88697bc6c73SDimitry Andric     }
88797bc6c73SDimitry Andric   }
88897bc6c73SDimitry Andric 
88997bc6c73SDimitry Andric   if (FD->hasAttr<DLLImportAttr>())
89097bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
89197bc6c73SDimitry Andric   else if (FD->hasAttr<DLLExportAttr>())
89297bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
89397bc6c73SDimitry Andric   else
89497bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
89597bc6c73SDimitry Andric }
89697bc6c73SDimitry Andric 
897e7145dcbSDimitry Andric llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
8980623d748SDimitry Andric   llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
8990623d748SDimitry Andric   if (!MDS) return nullptr;
9000623d748SDimitry Andric 
90144290647SDimitry Andric   return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
9020623d748SDimitry Andric }
9030623d748SDimitry Andric 
90459d1ed5bSDimitry Andric void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
90559d1ed5bSDimitry Andric                                                     llvm::Function *F) {
90659d1ed5bSDimitry Andric   setNonAliasAttributes(D, F);
907f22ef01cSRoman Divacky }
908f22ef01cSRoman Divacky 
909f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
910f22ef01cSRoman Divacky                                               const CGFunctionInfo &Info,
911f22ef01cSRoman Divacky                                               llvm::Function *F) {
912f22ef01cSRoman Divacky   unsigned CallingConv;
9136bc11b14SDimitry Andric   llvm::AttributeList PAL;
9146bc11b14SDimitry Andric   ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false);
9156bc11b14SDimitry Andric   F->setAttributes(PAL);
916f22ef01cSRoman Divacky   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
917f22ef01cSRoman Divacky }
918f22ef01cSRoman Divacky 
9196122f3e6SDimitry Andric /// Determines whether the language options require us to model
9206122f3e6SDimitry Andric /// unwind exceptions.  We treat -fexceptions as mandating this
9216122f3e6SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions
9226122f3e6SDimitry Andric /// enabled.  This means, for example, that C with -fexceptions
9236122f3e6SDimitry Andric /// enables this.
924dff0c46cSDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) {
9256122f3e6SDimitry Andric   // If exceptions are completely disabled, obviously this is false.
926dff0c46cSDimitry Andric   if (!LangOpts.Exceptions) return false;
9276122f3e6SDimitry Andric 
9286122f3e6SDimitry Andric   // If C++ exceptions are enabled, this is true.
929dff0c46cSDimitry Andric   if (LangOpts.CXXExceptions) return true;
9306122f3e6SDimitry Andric 
9316122f3e6SDimitry Andric   // If ObjC exceptions are enabled, this depends on the ABI.
932dff0c46cSDimitry Andric   if (LangOpts.ObjCExceptions) {
9337ae0e2c9SDimitry Andric     return LangOpts.ObjCRuntime.hasUnwindExceptions();
9346122f3e6SDimitry Andric   }
9356122f3e6SDimitry Andric 
9366122f3e6SDimitry Andric   return true;
9376122f3e6SDimitry Andric }
9386122f3e6SDimitry Andric 
939f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
940f22ef01cSRoman Divacky                                                            llvm::Function *F) {
941f785676fSDimitry Andric   llvm::AttrBuilder B;
942f785676fSDimitry Andric 
943bd5abe19SDimitry Andric   if (CodeGenOpts.UnwindTables)
944f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::UWTable);
945bd5abe19SDimitry Andric 
946dff0c46cSDimitry Andric   if (!hasUnwindExceptions(LangOpts))
947f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoUnwind);
948f22ef01cSRoman Divacky 
9490623d748SDimitry Andric   if (LangOpts.getStackProtector() == LangOptions::SSPOn)
9500623d748SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtect);
9510623d748SDimitry Andric   else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
9520623d748SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtectStrong);
9530623d748SDimitry Andric   else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
9540623d748SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtectReq);
9550623d748SDimitry Andric 
9560623d748SDimitry Andric   if (!D) {
95744290647SDimitry Andric     // If we don't have a declaration to control inlining, the function isn't
95844290647SDimitry Andric     // explicitly marked as alwaysinline for semantic reasons, and inlining is
95944290647SDimitry Andric     // disabled, mark the function as noinline.
96044290647SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
96144290647SDimitry Andric         CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
96244290647SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
96344290647SDimitry Andric 
964f37b6182SDimitry Andric     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
9650623d748SDimitry Andric     return;
9660623d748SDimitry Andric   }
9670623d748SDimitry Andric 
968302affcbSDimitry Andric   // Track whether we need to add the optnone LLVM attribute,
969302affcbSDimitry Andric   // starting with the default for this optimization level.
970302affcbSDimitry Andric   bool ShouldAddOptNone =
971302affcbSDimitry Andric       !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
972302affcbSDimitry Andric   // We can't add optnone in the following cases, it won't pass the verifier.
973302affcbSDimitry Andric   ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
974302affcbSDimitry Andric   ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
975302affcbSDimitry Andric   ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
976302affcbSDimitry Andric 
977302affcbSDimitry Andric   if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
97844290647SDimitry Andric     B.addAttribute(llvm::Attribute::OptimizeNone);
97944290647SDimitry Andric 
98044290647SDimitry Andric     // OptimizeNone implies noinline; we should not be inlining such functions.
98144290647SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
98244290647SDimitry Andric     assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
98344290647SDimitry Andric            "OptimizeNone and AlwaysInline on same function!");
98444290647SDimitry Andric 
98544290647SDimitry Andric     // We still need to handle naked functions even though optnone subsumes
98644290647SDimitry Andric     // much of their semantics.
98744290647SDimitry Andric     if (D->hasAttr<NakedAttr>())
98844290647SDimitry Andric       B.addAttribute(llvm::Attribute::Naked);
98944290647SDimitry Andric 
99044290647SDimitry Andric     // OptimizeNone wins over OptimizeForSize and MinSize.
99144290647SDimitry Andric     F->removeFnAttr(llvm::Attribute::OptimizeForSize);
99244290647SDimitry Andric     F->removeFnAttr(llvm::Attribute::MinSize);
99344290647SDimitry Andric   } else if (D->hasAttr<NakedAttr>()) {
9946122f3e6SDimitry Andric     // Naked implies noinline: we should not be inlining such functions.
995f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::Naked);
996f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
99759d1ed5bSDimitry Andric   } else if (D->hasAttr<NoDuplicateAttr>()) {
99859d1ed5bSDimitry Andric     B.addAttribute(llvm::Attribute::NoDuplicate);
999f785676fSDimitry Andric   } else if (D->hasAttr<NoInlineAttr>()) {
1000f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
100159d1ed5bSDimitry Andric   } else if (D->hasAttr<AlwaysInlineAttr>() &&
100244290647SDimitry Andric              !F->hasFnAttribute(llvm::Attribute::NoInline)) {
1003f785676fSDimitry Andric     // (noinline wins over always_inline, and we can't specify both in IR)
1004f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::AlwaysInline);
100544290647SDimitry Andric   } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
100644290647SDimitry Andric     // If we're not inlining, then force everything that isn't always_inline to
100744290647SDimitry Andric     // carry an explicit noinline attribute.
100844290647SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
100944290647SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
101044290647SDimitry Andric   } else {
101144290647SDimitry Andric     // Otherwise, propagate the inline hint attribute and potentially use its
101244290647SDimitry Andric     // absence to mark things as noinline.
101344290647SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
101444290647SDimitry Andric       if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
101544290647SDimitry Andric             return Redecl->isInlineSpecified();
101644290647SDimitry Andric           })) {
101744290647SDimitry Andric         B.addAttribute(llvm::Attribute::InlineHint);
101844290647SDimitry Andric       } else if (CodeGenOpts.getInlining() ==
101944290647SDimitry Andric                      CodeGenOptions::OnlyHintInlining &&
102044290647SDimitry Andric                  !FD->isInlined() &&
102144290647SDimitry Andric                  !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
102244290647SDimitry Andric         B.addAttribute(llvm::Attribute::NoInline);
102344290647SDimitry Andric       }
102444290647SDimitry Andric     }
10256122f3e6SDimitry Andric   }
10262754fe60SDimitry Andric 
102744290647SDimitry Andric   // Add other optimization related attributes if we are optimizing this
102844290647SDimitry Andric   // function.
102944290647SDimitry Andric   if (!D->hasAttr<OptimizeNoneAttr>()) {
1030f785676fSDimitry Andric     if (D->hasAttr<ColdAttr>()) {
1031302affcbSDimitry Andric       if (!ShouldAddOptNone)
1032f785676fSDimitry Andric         B.addAttribute(llvm::Attribute::OptimizeForSize);
1033f785676fSDimitry Andric       B.addAttribute(llvm::Attribute::Cold);
1034f785676fSDimitry Andric     }
10353861d79fSDimitry Andric 
10363861d79fSDimitry Andric     if (D->hasAttr<MinSizeAttr>())
1037f785676fSDimitry Andric       B.addAttribute(llvm::Attribute::MinSize);
103844290647SDimitry Andric   }
1039f22ef01cSRoman Divacky 
1040f37b6182SDimitry Andric   F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1041f785676fSDimitry Andric 
1042e580952dSDimitry Andric   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
1043e580952dSDimitry Andric   if (alignment)
1044e580952dSDimitry Andric     F->setAlignment(alignment);
1045e580952dSDimitry Andric 
10460623d748SDimitry Andric   // Some C++ ABIs require 2-byte alignment for member functions, in order to
10470623d748SDimitry Andric   // reserve a bit for differentiating between virtual and non-virtual member
10480623d748SDimitry Andric   // functions. If the current target's C++ ABI requires this and this is a
10490623d748SDimitry Andric   // member function, set its alignment accordingly.
10500623d748SDimitry Andric   if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
1051f22ef01cSRoman Divacky     if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1052f22ef01cSRoman Divacky       F->setAlignment(2);
1053f22ef01cSRoman Divacky   }
105444290647SDimitry Andric 
105544290647SDimitry Andric   // In the cross-dso CFI mode, we want !type attributes on definitions only.
105644290647SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
105744290647SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D))
105844290647SDimitry Andric       CreateFunctionTypeMetadata(FD, F);
10590623d748SDimitry Andric }
1060f22ef01cSRoman Divacky 
1061f22ef01cSRoman Divacky void CodeGenModule::SetCommonAttributes(const Decl *D,
1062f22ef01cSRoman Divacky                                         llvm::GlobalValue *GV) {
10630623d748SDimitry Andric   if (const auto *ND = dyn_cast_or_null<NamedDecl>(D))
10649a199699SDimitry Andric     setGlobalVisibility(GV, ND, ForDefinition);
10652754fe60SDimitry Andric   else
10662754fe60SDimitry Andric     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1067f22ef01cSRoman Divacky 
10680623d748SDimitry Andric   if (D && D->hasAttr<UsedAttr>())
106959d1ed5bSDimitry Andric     addUsedGlobal(GV);
107059d1ed5bSDimitry Andric }
107159d1ed5bSDimitry Andric 
107239d628a0SDimitry Andric void CodeGenModule::setAliasAttributes(const Decl *D,
107339d628a0SDimitry Andric                                        llvm::GlobalValue *GV) {
107439d628a0SDimitry Andric   SetCommonAttributes(D, GV);
107539d628a0SDimitry Andric 
107639d628a0SDimitry Andric   // Process the dllexport attribute based on whether the original definition
107739d628a0SDimitry Andric   // (not necessarily the aliasee) was exported.
107839d628a0SDimitry Andric   if (D->hasAttr<DLLExportAttr>())
107939d628a0SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
108039d628a0SDimitry Andric }
108139d628a0SDimitry Andric 
108259d1ed5bSDimitry Andric void CodeGenModule::setNonAliasAttributes(const Decl *D,
108359d1ed5bSDimitry Andric                                           llvm::GlobalObject *GO) {
108459d1ed5bSDimitry Andric   SetCommonAttributes(D, GO);
1085f22ef01cSRoman Divacky 
1086db17bf38SDimitry Andric   if (D) {
1087db17bf38SDimitry Andric     if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
1088db17bf38SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
1089db17bf38SDimitry Andric         GV->addAttribute("bss-section", SA->getName());
1090db17bf38SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
1091db17bf38SDimitry Andric         GV->addAttribute("data-section", SA->getName());
1092db17bf38SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
1093db17bf38SDimitry Andric         GV->addAttribute("rodata-section", SA->getName());
1094db17bf38SDimitry Andric     }
1095db17bf38SDimitry Andric 
1096db17bf38SDimitry Andric     if (auto *F = dyn_cast<llvm::Function>(GO)) {
1097db17bf38SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
1098db17bf38SDimitry Andric        if (!D->getAttr<SectionAttr>())
1099db17bf38SDimitry Andric          F->addFnAttr("implicit-section-name", SA->getName());
1100db17bf38SDimitry Andric     }
1101db17bf38SDimitry Andric 
1102f22ef01cSRoman Divacky     if (const SectionAttr *SA = D->getAttr<SectionAttr>())
110359d1ed5bSDimitry Andric       GO->setSection(SA->getName());
1104db17bf38SDimitry Andric   }
1105f22ef01cSRoman Divacky 
11069a199699SDimitry Andric   getTargetCodeGenInfo().setTargetAttributes(D, GO, *this, ForDefinition);
1107f22ef01cSRoman Divacky }
1108f22ef01cSRoman Divacky 
1109f22ef01cSRoman Divacky void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
1110f22ef01cSRoman Divacky                                                   llvm::Function *F,
1111f22ef01cSRoman Divacky                                                   const CGFunctionInfo &FI) {
1112f22ef01cSRoman Divacky   SetLLVMFunctionAttributes(D, FI, F);
1113f22ef01cSRoman Divacky   SetLLVMFunctionAttributesForDefinition(D, F);
1114f22ef01cSRoman Divacky 
1115f22ef01cSRoman Divacky   F->setLinkage(llvm::Function::InternalLinkage);
1116f22ef01cSRoman Divacky 
111759d1ed5bSDimitry Andric   setNonAliasAttributes(D, F);
111859d1ed5bSDimitry Andric }
111959d1ed5bSDimitry Andric 
11209a199699SDimitry Andric static void setLinkageForGV(llvm::GlobalValue *GV,
112159d1ed5bSDimitry Andric                             const NamedDecl *ND) {
112259d1ed5bSDimitry Andric   // Set linkage and visibility in case we never see a definition.
112359d1ed5bSDimitry Andric   LinkageInfo LV = ND->getLinkageAndVisibility();
1124c4394386SDimitry Andric   if (!isExternallyVisible(LV.getLinkage())) {
112559d1ed5bSDimitry Andric     // Don't set internal linkage on declarations.
112659d1ed5bSDimitry Andric   } else {
112759d1ed5bSDimitry Andric     if (ND->hasAttr<DLLImportAttr>()) {
112859d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
112959d1ed5bSDimitry Andric       GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
113059d1ed5bSDimitry Andric     } else if (ND->hasAttr<DLLExportAttr>()) {
113159d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
113259d1ed5bSDimitry Andric     } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
113359d1ed5bSDimitry Andric       // "extern_weak" is overloaded in LLVM; we probably should have
113459d1ed5bSDimitry Andric       // separate linkage types for this.
113559d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
113659d1ed5bSDimitry Andric     }
113759d1ed5bSDimitry Andric   }
1138f22ef01cSRoman Divacky }
1139f22ef01cSRoman Divacky 
1140e7145dcbSDimitry Andric void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD,
11410623d748SDimitry Andric                                                llvm::Function *F) {
11420623d748SDimitry Andric   // Only if we are checking indirect calls.
11430623d748SDimitry Andric   if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
11440623d748SDimitry Andric     return;
11450623d748SDimitry Andric 
11460623d748SDimitry Andric   // Non-static class methods are handled via vtable pointer checks elsewhere.
11470623d748SDimitry Andric   if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
11480623d748SDimitry Andric     return;
11490623d748SDimitry Andric 
11500623d748SDimitry Andric   // Additionally, if building with cross-DSO support...
11510623d748SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
11520623d748SDimitry Andric     // Skip available_externally functions. They won't be codegen'ed in the
11530623d748SDimitry Andric     // current module anyway.
11540623d748SDimitry Andric     if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
11550623d748SDimitry Andric       return;
11560623d748SDimitry Andric   }
11570623d748SDimitry Andric 
11580623d748SDimitry Andric   llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
1159e7145dcbSDimitry Andric   F->addTypeMetadata(0, MD);
11609a199699SDimitry Andric   F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
11610623d748SDimitry Andric 
11620623d748SDimitry Andric   // Emit a hash-based bit set entry for cross-DSO calls.
1163e7145dcbSDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
1164e7145dcbSDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1165e7145dcbSDimitry Andric       F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
11660623d748SDimitry Andric }
11670623d748SDimitry Andric 
116839d628a0SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
116939d628a0SDimitry Andric                                           bool IsIncompleteFunction,
11709a199699SDimitry Andric                                           bool IsThunk,
11719a199699SDimitry Andric                                           ForDefinition_t IsForDefinition) {
11729a199699SDimitry Andric 
117333956c43SDimitry Andric   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
11743b0f4066SDimitry Andric     // If this is an intrinsic function, set the function's attributes
11753b0f4066SDimitry Andric     // to the intrinsic's attributes.
117633956c43SDimitry Andric     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
11773b0f4066SDimitry Andric     return;
11783b0f4066SDimitry Andric   }
11793b0f4066SDimitry Andric 
118059d1ed5bSDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
1181f22ef01cSRoman Divacky 
11829a199699SDimitry Andric   if (!IsIncompleteFunction) {
1183dff0c46cSDimitry Andric     SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
11849a199699SDimitry Andric     // Setup target-specific attributes.
11859a199699SDimitry Andric     if (!IsForDefinition)
11869a199699SDimitry Andric       getTargetCodeGenInfo().setTargetAttributes(FD, F, *this,
11879a199699SDimitry Andric                                                  NotForDefinition);
11889a199699SDimitry Andric   }
1189f22ef01cSRoman Divacky 
119059d1ed5bSDimitry Andric   // Add the Returned attribute for "this", except for iOS 5 and earlier
119159d1ed5bSDimitry Andric   // where substantial code, including the libstdc++ dylib, was compiled with
119259d1ed5bSDimitry Andric   // GCC and does not actually return "this".
119339d628a0SDimitry Andric   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
119444290647SDimitry Andric       !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
1195f785676fSDimitry Andric     assert(!F->arg_empty() &&
1196f785676fSDimitry Andric            F->arg_begin()->getType()
1197f785676fSDimitry Andric              ->canLosslesslyBitCastTo(F->getReturnType()) &&
1198f785676fSDimitry Andric            "unexpected this return");
1199f785676fSDimitry Andric     F->addAttribute(1, llvm::Attribute::Returned);
1200f785676fSDimitry Andric   }
1201f785676fSDimitry Andric 
1202f22ef01cSRoman Divacky   // Only a few attributes are set on declarations; these may later be
1203f22ef01cSRoman Divacky   // overridden by a definition.
1204f22ef01cSRoman Divacky 
12059a199699SDimitry Andric   setLinkageForGV(F, FD);
12069a199699SDimitry Andric   setGlobalVisibility(F, FD, NotForDefinition);
12072754fe60SDimitry Andric 
1208db17bf38SDimitry Andric   if (FD->getAttr<PragmaClangTextSectionAttr>()) {
1209db17bf38SDimitry Andric     F->addFnAttr("implicit-section-name");
1210db17bf38SDimitry Andric   }
1211db17bf38SDimitry Andric 
1212f22ef01cSRoman Divacky   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
1213f22ef01cSRoman Divacky     F->setSection(SA->getName());
1214f785676fSDimitry Andric 
1215e7145dcbSDimitry Andric   if (FD->isReplaceableGlobalAllocationFunction()) {
1216f785676fSDimitry Andric     // A replaceable global allocation function does not act like a builtin by
1217f785676fSDimitry Andric     // default, only if it is invoked by a new-expression or delete-expression.
121820e90f04SDimitry Andric     F->addAttribute(llvm::AttributeList::FunctionIndex,
1219f785676fSDimitry Andric                     llvm::Attribute::NoBuiltin);
12200623d748SDimitry Andric 
1221e7145dcbSDimitry Andric     // A sane operator new returns a non-aliasing pointer.
1222e7145dcbSDimitry Andric     // FIXME: Also add NonNull attribute to the return value
1223e7145dcbSDimitry Andric     // for the non-nothrow forms?
1224e7145dcbSDimitry Andric     auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1225e7145dcbSDimitry Andric     if (getCodeGenOpts().AssumeSaneOperatorNew &&
1226e7145dcbSDimitry Andric         (Kind == OO_New || Kind == OO_Array_New))
122720e90f04SDimitry Andric       F->addAttribute(llvm::AttributeList::ReturnIndex,
1228e7145dcbSDimitry Andric                       llvm::Attribute::NoAlias);
1229e7145dcbSDimitry Andric   }
1230e7145dcbSDimitry Andric 
1231e7145dcbSDimitry Andric   if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1232e7145dcbSDimitry Andric     F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1233e7145dcbSDimitry Andric   else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1234e7145dcbSDimitry Andric     if (MD->isVirtual())
1235e7145dcbSDimitry Andric       F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1236e7145dcbSDimitry Andric 
123744290647SDimitry Andric   // Don't emit entries for function declarations in the cross-DSO mode. This
123844290647SDimitry Andric   // is handled with better precision by the receiving DSO.
123944290647SDimitry Andric   if (!CodeGenOpts.SanitizeCfiCrossDso)
1240e7145dcbSDimitry Andric     CreateFunctionTypeMetadata(FD, F);
12419a199699SDimitry Andric 
12429a199699SDimitry Andric   if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
12439a199699SDimitry Andric     getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
1244f22ef01cSRoman Divacky }
1245f22ef01cSRoman Divacky 
124659d1ed5bSDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
1247f22ef01cSRoman Divacky   assert(!GV->isDeclaration() &&
1248f22ef01cSRoman Divacky          "Only globals with definition can force usage.");
124997bc6c73SDimitry Andric   LLVMUsed.emplace_back(GV);
1250f22ef01cSRoman Divacky }
1251f22ef01cSRoman Divacky 
125259d1ed5bSDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
125359d1ed5bSDimitry Andric   assert(!GV->isDeclaration() &&
125459d1ed5bSDimitry Andric          "Only globals with definition can force usage.");
125597bc6c73SDimitry Andric   LLVMCompilerUsed.emplace_back(GV);
125659d1ed5bSDimitry Andric }
125759d1ed5bSDimitry Andric 
125859d1ed5bSDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name,
1259f37b6182SDimitry Andric                      std::vector<llvm::WeakTrackingVH> &List) {
1260f22ef01cSRoman Divacky   // Don't create llvm.used if there is no need.
126159d1ed5bSDimitry Andric   if (List.empty())
1262f22ef01cSRoman Divacky     return;
1263f22ef01cSRoman Divacky 
126459d1ed5bSDimitry Andric   // Convert List to what ConstantArray needs.
1265dff0c46cSDimitry Andric   SmallVector<llvm::Constant*, 8> UsedArray;
126659d1ed5bSDimitry Andric   UsedArray.resize(List.size());
126759d1ed5bSDimitry Andric   for (unsigned i = 0, e = List.size(); i != e; ++i) {
1268f22ef01cSRoman Divacky     UsedArray[i] =
126944f7b0dcSDimitry Andric         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
127044f7b0dcSDimitry Andric             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
1271f22ef01cSRoman Divacky   }
1272f22ef01cSRoman Divacky 
1273f22ef01cSRoman Divacky   if (UsedArray.empty())
1274f22ef01cSRoman Divacky     return;
127559d1ed5bSDimitry Andric   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
1276f22ef01cSRoman Divacky 
127759d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
127859d1ed5bSDimitry Andric       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
127959d1ed5bSDimitry Andric       llvm::ConstantArray::get(ATy, UsedArray), Name);
1280f22ef01cSRoman Divacky 
1281f22ef01cSRoman Divacky   GV->setSection("llvm.metadata");
1282f22ef01cSRoman Divacky }
1283f22ef01cSRoman Divacky 
128459d1ed5bSDimitry Andric void CodeGenModule::emitLLVMUsed() {
128559d1ed5bSDimitry Andric   emitUsed(*this, "llvm.used", LLVMUsed);
128659d1ed5bSDimitry Andric   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
128759d1ed5bSDimitry Andric }
128859d1ed5bSDimitry Andric 
1289f785676fSDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
129039d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
1291f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1292f785676fSDimitry Andric }
1293f785676fSDimitry Andric 
1294f785676fSDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1295f785676fSDimitry Andric   llvm::SmallString<32> Opt;
1296f785676fSDimitry Andric   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
129739d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1298f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1299f785676fSDimitry Andric }
1300f785676fSDimitry Andric 
1301f785676fSDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) {
1302f785676fSDimitry Andric   llvm::SmallString<24> Opt;
1303f785676fSDimitry Andric   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
130439d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1305f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1306f785676fSDimitry Andric }
1307f785676fSDimitry Andric 
1308139f7f9bSDimitry Andric /// \brief Add link options implied by the given module, including modules
1309139f7f9bSDimitry Andric /// it depends on, using a postorder walk.
131039d628a0SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
131124d58133SDimitry Andric                                     SmallVectorImpl<llvm::MDNode *> &Metadata,
1312139f7f9bSDimitry Andric                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
1313139f7f9bSDimitry Andric   // Import this module's parent.
131439d628a0SDimitry Andric   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
1315f785676fSDimitry Andric     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
1316139f7f9bSDimitry Andric   }
1317139f7f9bSDimitry Andric 
1318139f7f9bSDimitry Andric   // Import this module's dependencies.
1319139f7f9bSDimitry Andric   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
132039d628a0SDimitry Andric     if (Visited.insert(Mod->Imports[I - 1]).second)
1321f785676fSDimitry Andric       addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
1322139f7f9bSDimitry Andric   }
1323139f7f9bSDimitry Andric 
1324139f7f9bSDimitry Andric   // Add linker options to link against the libraries/frameworks
1325139f7f9bSDimitry Andric   // described by this module.
1326f785676fSDimitry Andric   llvm::LLVMContext &Context = CGM.getLLVMContext();
1327139f7f9bSDimitry Andric   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
1328f785676fSDimitry Andric     // Link against a framework.  Frameworks are currently Darwin only, so we
1329f785676fSDimitry Andric     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
1330139f7f9bSDimitry Andric     if (Mod->LinkLibraries[I-1].IsFramework) {
133139d628a0SDimitry Andric       llvm::Metadata *Args[2] = {
1332139f7f9bSDimitry Andric           llvm::MDString::get(Context, "-framework"),
133339d628a0SDimitry Andric           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1334139f7f9bSDimitry Andric 
1335139f7f9bSDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, Args));
1336139f7f9bSDimitry Andric       continue;
1337139f7f9bSDimitry Andric     }
1338139f7f9bSDimitry Andric 
1339139f7f9bSDimitry Andric     // Link against a library.
1340f785676fSDimitry Andric     llvm::SmallString<24> Opt;
1341f785676fSDimitry Andric     CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1342f785676fSDimitry Andric       Mod->LinkLibraries[I-1].Library, Opt);
134339d628a0SDimitry Andric     auto *OptString = llvm::MDString::get(Context, Opt);
1344139f7f9bSDimitry Andric     Metadata.push_back(llvm::MDNode::get(Context, OptString));
1345139f7f9bSDimitry Andric   }
1346139f7f9bSDimitry Andric }
1347139f7f9bSDimitry Andric 
1348139f7f9bSDimitry Andric void CodeGenModule::EmitModuleLinkOptions() {
1349139f7f9bSDimitry Andric   // Collect the set of all of the modules we want to visit to emit link
1350139f7f9bSDimitry Andric   // options, which is essentially the imported modules and all of their
1351139f7f9bSDimitry Andric   // non-explicit child modules.
1352139f7f9bSDimitry Andric   llvm::SetVector<clang::Module *> LinkModules;
1353139f7f9bSDimitry Andric   llvm::SmallPtrSet<clang::Module *, 16> Visited;
1354139f7f9bSDimitry Andric   SmallVector<clang::Module *, 16> Stack;
1355139f7f9bSDimitry Andric 
1356139f7f9bSDimitry Andric   // Seed the stack with imported modules.
1357f1a29dd3SDimitry Andric   for (Module *M : ImportedModules) {
1358f1a29dd3SDimitry Andric     // Do not add any link flags when an implementation TU of a module imports
1359f1a29dd3SDimitry Andric     // a header of that same module.
1360f1a29dd3SDimitry Andric     if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
1361f1a29dd3SDimitry Andric         !getLangOpts().isCompilingModule())
1362f1a29dd3SDimitry Andric       continue;
13638f0fd8f6SDimitry Andric     if (Visited.insert(M).second)
13648f0fd8f6SDimitry Andric       Stack.push_back(M);
1365f1a29dd3SDimitry Andric   }
1366139f7f9bSDimitry Andric 
1367139f7f9bSDimitry Andric   // Find all of the modules to import, making a little effort to prune
1368139f7f9bSDimitry Andric   // non-leaf modules.
1369139f7f9bSDimitry Andric   while (!Stack.empty()) {
1370f785676fSDimitry Andric     clang::Module *Mod = Stack.pop_back_val();
1371139f7f9bSDimitry Andric 
1372139f7f9bSDimitry Andric     bool AnyChildren = false;
1373139f7f9bSDimitry Andric 
1374139f7f9bSDimitry Andric     // Visit the submodules of this module.
1375139f7f9bSDimitry Andric     for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1376139f7f9bSDimitry Andric                                         SubEnd = Mod->submodule_end();
1377139f7f9bSDimitry Andric          Sub != SubEnd; ++Sub) {
1378139f7f9bSDimitry Andric       // Skip explicit children; they need to be explicitly imported to be
1379139f7f9bSDimitry Andric       // linked against.
1380139f7f9bSDimitry Andric       if ((*Sub)->IsExplicit)
1381139f7f9bSDimitry Andric         continue;
1382139f7f9bSDimitry Andric 
138339d628a0SDimitry Andric       if (Visited.insert(*Sub).second) {
1384139f7f9bSDimitry Andric         Stack.push_back(*Sub);
1385139f7f9bSDimitry Andric         AnyChildren = true;
1386139f7f9bSDimitry Andric       }
1387139f7f9bSDimitry Andric     }
1388139f7f9bSDimitry Andric 
1389139f7f9bSDimitry Andric     // We didn't find any children, so add this module to the list of
1390139f7f9bSDimitry Andric     // modules to link against.
1391139f7f9bSDimitry Andric     if (!AnyChildren) {
1392139f7f9bSDimitry Andric       LinkModules.insert(Mod);
1393139f7f9bSDimitry Andric     }
1394139f7f9bSDimitry Andric   }
1395139f7f9bSDimitry Andric 
1396139f7f9bSDimitry Andric   // Add link options for all of the imported modules in reverse topological
1397f785676fSDimitry Andric   // order.  We don't do anything to try to order import link flags with respect
1398f785676fSDimitry Andric   // to linker options inserted by things like #pragma comment().
139924d58133SDimitry Andric   SmallVector<llvm::MDNode *, 16> MetadataArgs;
1400139f7f9bSDimitry Andric   Visited.clear();
14018f0fd8f6SDimitry Andric   for (Module *M : LinkModules)
14028f0fd8f6SDimitry Andric     if (Visited.insert(M).second)
14038f0fd8f6SDimitry Andric       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
1404139f7f9bSDimitry Andric   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1405f785676fSDimitry Andric   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1406139f7f9bSDimitry Andric 
1407139f7f9bSDimitry Andric   // Add the linker options metadata flag.
140824d58133SDimitry Andric   auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
140924d58133SDimitry Andric   for (auto *MD : LinkerOptionsMetadata)
141024d58133SDimitry Andric     NMD->addOperand(MD);
1411139f7f9bSDimitry Andric }
1412139f7f9bSDimitry Andric 
1413f22ef01cSRoman Divacky void CodeGenModule::EmitDeferred() {
1414f22ef01cSRoman Divacky   // Emit code for any potentially referenced deferred decls.  Since a
1415f22ef01cSRoman Divacky   // previously unused static decl may become used during the generation of code
1416f22ef01cSRoman Divacky   // for a static function, iterate until no changes are made.
1417f22ef01cSRoman Divacky 
1418f22ef01cSRoman Divacky   if (!DeferredVTables.empty()) {
1419139f7f9bSDimitry Andric     EmitDeferredVTables();
1420139f7f9bSDimitry Andric 
1421e7145dcbSDimitry Andric     // Emitting a vtable doesn't directly cause more vtables to
1422139f7f9bSDimitry Andric     // become deferred, although it can cause functions to be
1423e7145dcbSDimitry Andric     // emitted that then need those vtables.
1424139f7f9bSDimitry Andric     assert(DeferredVTables.empty());
1425f22ef01cSRoman Divacky   }
1426f22ef01cSRoman Divacky 
1427e7145dcbSDimitry Andric   // Stop if we're out of both deferred vtables and deferred declarations.
142833956c43SDimitry Andric   if (DeferredDeclsToEmit.empty())
142933956c43SDimitry Andric     return;
1430139f7f9bSDimitry Andric 
143133956c43SDimitry Andric   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
143233956c43SDimitry Andric   // work, it will not interfere with this.
1433f37b6182SDimitry Andric   std::vector<GlobalDecl> CurDeclsToEmit;
143433956c43SDimitry Andric   CurDeclsToEmit.swap(DeferredDeclsToEmit);
143533956c43SDimitry Andric 
1436f37b6182SDimitry Andric   for (GlobalDecl &D : CurDeclsToEmit) {
14370623d748SDimitry Andric     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
14380623d748SDimitry Andric     // to get GlobalValue with exactly the type we need, not something that
14390623d748SDimitry Andric     // might had been created for another decl with the same mangled name but
14400623d748SDimitry Andric     // different type.
1441e7145dcbSDimitry Andric     llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
144244290647SDimitry Andric         GetAddrOfGlobal(D, ForDefinition));
1443e7145dcbSDimitry Andric 
1444e7145dcbSDimitry Andric     // In case of different address spaces, we may still get a cast, even with
1445e7145dcbSDimitry Andric     // IsForDefinition equal to true. Query mangled names table to get
1446e7145dcbSDimitry Andric     // GlobalValue.
144739d628a0SDimitry Andric     if (!GV)
144839d628a0SDimitry Andric       GV = GetGlobalValue(getMangledName(D));
144939d628a0SDimitry Andric 
1450e7145dcbSDimitry Andric     // Make sure GetGlobalValue returned non-null.
1451e7145dcbSDimitry Andric     assert(GV);
1452e7145dcbSDimitry Andric 
1453f22ef01cSRoman Divacky     // Check to see if we've already emitted this.  This is necessary
1454f22ef01cSRoman Divacky     // for a couple of reasons: first, decls can end up in the
1455f22ef01cSRoman Divacky     // deferred-decls queue multiple times, and second, decls can end
1456f22ef01cSRoman Divacky     // up with definitions in unusual ways (e.g. by an extern inline
1457f22ef01cSRoman Divacky     // function acquiring a strong function redefinition).  Just
1458f22ef01cSRoman Divacky     // ignore these cases.
1459e7145dcbSDimitry Andric     if (!GV->isDeclaration())
1460f22ef01cSRoman Divacky       continue;
1461f22ef01cSRoman Divacky 
1462f22ef01cSRoman Divacky     // Otherwise, emit the definition and move on to the next one.
146359d1ed5bSDimitry Andric     EmitGlobalDefinition(D, GV);
146433956c43SDimitry Andric 
146533956c43SDimitry Andric     // If we found out that we need to emit more decls, do that recursively.
146633956c43SDimitry Andric     // This has the advantage that the decls are emitted in a DFS and related
146733956c43SDimitry Andric     // ones are close together, which is convenient for testing.
146833956c43SDimitry Andric     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
146933956c43SDimitry Andric       EmitDeferred();
147033956c43SDimitry Andric       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
147133956c43SDimitry Andric     }
1472f22ef01cSRoman Divacky   }
1473f22ef01cSRoman Divacky }
1474f22ef01cSRoman Divacky 
1475f9448bf3SDimitry Andric void CodeGenModule::EmitVTablesOpportunistically() {
1476f9448bf3SDimitry Andric   // Try to emit external vtables as available_externally if they have emitted
1477f9448bf3SDimitry Andric   // all inlined virtual functions.  It runs after EmitDeferred() and therefore
1478f9448bf3SDimitry Andric   // is not allowed to create new references to things that need to be emitted
1479f9448bf3SDimitry Andric   // lazily. Note that it also uses fact that we eagerly emitting RTTI.
1480f9448bf3SDimitry Andric 
1481f9448bf3SDimitry Andric   assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
1482f9448bf3SDimitry Andric          && "Only emit opportunistic vtables with optimizations");
1483f9448bf3SDimitry Andric 
1484f9448bf3SDimitry Andric   for (const CXXRecordDecl *RD : OpportunisticVTables) {
1485f9448bf3SDimitry Andric     assert(getVTables().isVTableExternal(RD) &&
1486f9448bf3SDimitry Andric            "This queue should only contain external vtables");
1487f9448bf3SDimitry Andric     if (getCXXABI().canSpeculativelyEmitVTable(RD))
1488f9448bf3SDimitry Andric       VTables.GenerateClassData(RD);
1489f9448bf3SDimitry Andric   }
1490f9448bf3SDimitry Andric   OpportunisticVTables.clear();
1491f9448bf3SDimitry Andric }
1492f9448bf3SDimitry Andric 
14936122f3e6SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() {
14946122f3e6SDimitry Andric   if (Annotations.empty())
14956122f3e6SDimitry Andric     return;
14966122f3e6SDimitry Andric 
14976122f3e6SDimitry Andric   // Create a new global variable for the ConstantStruct in the Module.
14986122f3e6SDimitry Andric   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
14996122f3e6SDimitry Andric     Annotations[0]->getType(), Annotations.size()), Annotations);
150059d1ed5bSDimitry Andric   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
150159d1ed5bSDimitry Andric                                       llvm::GlobalValue::AppendingLinkage,
150259d1ed5bSDimitry Andric                                       Array, "llvm.global.annotations");
15036122f3e6SDimitry Andric   gv->setSection(AnnotationSection);
15046122f3e6SDimitry Andric }
15056122f3e6SDimitry Andric 
1506139f7f9bSDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1507f785676fSDimitry Andric   llvm::Constant *&AStr = AnnotationStrings[Str];
1508f785676fSDimitry Andric   if (AStr)
1509f785676fSDimitry Andric     return AStr;
15106122f3e6SDimitry Andric 
15116122f3e6SDimitry Andric   // Not found yet, create a new global.
1512dff0c46cSDimitry Andric   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
151359d1ed5bSDimitry Andric   auto *gv =
151459d1ed5bSDimitry Andric       new llvm::GlobalVariable(getModule(), s->getType(), true,
151559d1ed5bSDimitry Andric                                llvm::GlobalValue::PrivateLinkage, s, ".str");
15166122f3e6SDimitry Andric   gv->setSection(AnnotationSection);
1517e7145dcbSDimitry Andric   gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1518f785676fSDimitry Andric   AStr = gv;
15196122f3e6SDimitry Andric   return gv;
15206122f3e6SDimitry Andric }
15216122f3e6SDimitry Andric 
15226122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
15236122f3e6SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
15246122f3e6SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
15256122f3e6SDimitry Andric   if (PLoc.isValid())
15266122f3e6SDimitry Andric     return EmitAnnotationString(PLoc.getFilename());
15276122f3e6SDimitry Andric   return EmitAnnotationString(SM.getBufferName(Loc));
15286122f3e6SDimitry Andric }
15296122f3e6SDimitry Andric 
15306122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
15316122f3e6SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
15326122f3e6SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(L);
15336122f3e6SDimitry Andric   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
15346122f3e6SDimitry Andric     SM.getExpansionLineNumber(L);
15356122f3e6SDimitry Andric   return llvm::ConstantInt::get(Int32Ty, LineNo);
15366122f3e6SDimitry Andric }
15376122f3e6SDimitry Andric 
1538f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1539f22ef01cSRoman Divacky                                                 const AnnotateAttr *AA,
15406122f3e6SDimitry Andric                                                 SourceLocation L) {
15416122f3e6SDimitry Andric   // Get the globals for file name, annotation, and the line number.
15426122f3e6SDimitry Andric   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
15436122f3e6SDimitry Andric                  *UnitGV = EmitAnnotationUnit(L),
15446122f3e6SDimitry Andric                  *LineNoCst = EmitAnnotationLineNo(L);
1545f22ef01cSRoman Divacky 
1546f22ef01cSRoman Divacky   // Create the ConstantStruct for the global annotation.
1547f22ef01cSRoman Divacky   llvm::Constant *Fields[4] = {
15486122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
15496122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
15506122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
15516122f3e6SDimitry Andric     LineNoCst
1552f22ef01cSRoman Divacky   };
155317a519f9SDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
1554f22ef01cSRoman Divacky }
1555f22ef01cSRoman Divacky 
15566122f3e6SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
15576122f3e6SDimitry Andric                                          llvm::GlobalValue *GV) {
15586122f3e6SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
15596122f3e6SDimitry Andric   // Get the struct elements for these annotations.
156059d1ed5bSDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>())
156159d1ed5bSDimitry Andric     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
15626122f3e6SDimitry Andric }
15636122f3e6SDimitry Andric 
15649a199699SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
15659a199699SDimitry Andric                                            llvm::Function *Fn,
156639d628a0SDimitry Andric                                            SourceLocation Loc) const {
156739d628a0SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
156839d628a0SDimitry Andric   // Blacklist by function name.
15699a199699SDimitry Andric   if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
157039d628a0SDimitry Andric     return true;
157139d628a0SDimitry Andric   // Blacklist by location.
15720623d748SDimitry Andric   if (Loc.isValid())
15739a199699SDimitry Andric     return SanitizerBL.isBlacklistedLocation(Kind, Loc);
157439d628a0SDimitry Andric   // If location is unknown, this may be a compiler-generated function. Assume
157539d628a0SDimitry Andric   // it's located in the main file.
157639d628a0SDimitry Andric   auto &SM = Context.getSourceManager();
157739d628a0SDimitry Andric   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
15789a199699SDimitry Andric     return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
157939d628a0SDimitry Andric   }
158039d628a0SDimitry Andric   return false;
158139d628a0SDimitry Andric }
158239d628a0SDimitry Andric 
158339d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
158439d628a0SDimitry Andric                                            SourceLocation Loc, QualType Ty,
158539d628a0SDimitry Andric                                            StringRef Category) const {
15868f0fd8f6SDimitry Andric   // For now globals can be blacklisted only in ASan and KASan.
15879a199699SDimitry Andric   const SanitizerMask EnabledAsanMask = LangOpts.Sanitize.Mask &
15889a199699SDimitry Andric       (SanitizerKind::Address | SanitizerKind::KernelAddress | SanitizerKind::HWAddress);
15899a199699SDimitry Andric   if (!EnabledAsanMask)
159039d628a0SDimitry Andric     return false;
159139d628a0SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
15929a199699SDimitry Andric   if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
159339d628a0SDimitry Andric     return true;
15949a199699SDimitry Andric   if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
159539d628a0SDimitry Andric     return true;
159639d628a0SDimitry Andric   // Check global type.
159739d628a0SDimitry Andric   if (!Ty.isNull()) {
159839d628a0SDimitry Andric     // Drill down the array types: if global variable of a fixed type is
159939d628a0SDimitry Andric     // blacklisted, we also don't instrument arrays of them.
160039d628a0SDimitry Andric     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
160139d628a0SDimitry Andric       Ty = AT->getElementType();
160239d628a0SDimitry Andric     Ty = Ty.getCanonicalType().getUnqualifiedType();
160339d628a0SDimitry Andric     // We allow to blacklist only record types (classes, structs etc.)
160439d628a0SDimitry Andric     if (Ty->isRecordType()) {
160539d628a0SDimitry Andric       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
16069a199699SDimitry Andric       if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
160739d628a0SDimitry Andric         return true;
160839d628a0SDimitry Andric     }
160939d628a0SDimitry Andric   }
161039d628a0SDimitry Andric   return false;
161139d628a0SDimitry Andric }
161239d628a0SDimitry Andric 
161320e90f04SDimitry Andric bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
161420e90f04SDimitry Andric                                    StringRef Category) const {
161520e90f04SDimitry Andric   if (!LangOpts.XRayInstrument)
161620e90f04SDimitry Andric     return false;
161720e90f04SDimitry Andric   const auto &XRayFilter = getContext().getXRayFilter();
161820e90f04SDimitry Andric   using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
161920e90f04SDimitry Andric   auto Attr = XRayFunctionFilter::ImbueAttribute::NONE;
162020e90f04SDimitry Andric   if (Loc.isValid())
162120e90f04SDimitry Andric     Attr = XRayFilter.shouldImbueLocation(Loc, Category);
162220e90f04SDimitry Andric   if (Attr == ImbueAttr::NONE)
162320e90f04SDimitry Andric     Attr = XRayFilter.shouldImbueFunction(Fn->getName());
162420e90f04SDimitry Andric   switch (Attr) {
162520e90f04SDimitry Andric   case ImbueAttr::NONE:
162620e90f04SDimitry Andric     return false;
162720e90f04SDimitry Andric   case ImbueAttr::ALWAYS:
162820e90f04SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-always");
162920e90f04SDimitry Andric     break;
1630302affcbSDimitry Andric   case ImbueAttr::ALWAYS_ARG1:
1631302affcbSDimitry Andric     Fn->addFnAttr("function-instrument", "xray-always");
1632302affcbSDimitry Andric     Fn->addFnAttr("xray-log-args", "1");
1633302affcbSDimitry Andric     break;
163420e90f04SDimitry Andric   case ImbueAttr::NEVER:
163520e90f04SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-never");
163620e90f04SDimitry Andric     break;
163720e90f04SDimitry Andric   }
163820e90f04SDimitry Andric   return true;
163920e90f04SDimitry Andric }
164020e90f04SDimitry Andric 
164139d628a0SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
1642e580952dSDimitry Andric   // Never defer when EmitAllDecls is specified.
1643dff0c46cSDimitry Andric   if (LangOpts.EmitAllDecls)
164439d628a0SDimitry Andric     return true;
164539d628a0SDimitry Andric 
164639d628a0SDimitry Andric   return getContext().DeclMustBeEmitted(Global);
164739d628a0SDimitry Andric }
164839d628a0SDimitry Andric 
164939d628a0SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
165039d628a0SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global))
165139d628a0SDimitry Andric     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
165239d628a0SDimitry Andric       // Implicit template instantiations may change linkage if they are later
165339d628a0SDimitry Andric       // explicitly instantiated, so they should not be emitted eagerly.
1654f22ef01cSRoman Divacky       return false;
1655e7145dcbSDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(Global))
1656e7145dcbSDimitry Andric     if (Context.getInlineVariableDefinitionKind(VD) ==
1657e7145dcbSDimitry Andric         ASTContext::InlineVariableDefinitionKind::WeakUnknown)
1658e7145dcbSDimitry Andric       // A definition of an inline constexpr static data member may change
1659e7145dcbSDimitry Andric       // linkage later if it's redeclared outside the class.
1660e7145dcbSDimitry Andric       return false;
1661875ed548SDimitry Andric   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
1662875ed548SDimitry Andric   // codegen for global variables, because they may be marked as threadprivate.
1663875ed548SDimitry Andric   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1664875ed548SDimitry Andric       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
1665875ed548SDimitry Andric     return false;
1666f22ef01cSRoman Divacky 
166739d628a0SDimitry Andric   return true;
1668f22ef01cSRoman Divacky }
1669f22ef01cSRoman Divacky 
16700623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
16713861d79fSDimitry Andric     const CXXUuidofExpr* E) {
16723861d79fSDimitry Andric   // Sema has verified that IIDSource has a __declspec(uuid()), and that its
16733861d79fSDimitry Andric   // well-formed.
1674e7145dcbSDimitry Andric   StringRef Uuid = E->getUuidStr();
1675f785676fSDimitry Andric   std::string Name = "_GUID_" + Uuid.lower();
1676f785676fSDimitry Andric   std::replace(Name.begin(), Name.end(), '-', '_');
16773861d79fSDimitry Andric 
1678e7145dcbSDimitry Andric   // The UUID descriptor should be pointer aligned.
1679e7145dcbSDimitry Andric   CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
16800623d748SDimitry Andric 
16813861d79fSDimitry Andric   // Look for an existing global.
16823861d79fSDimitry Andric   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
16830623d748SDimitry Andric     return ConstantAddress(GV, Alignment);
16843861d79fSDimitry Andric 
168539d628a0SDimitry Andric   llvm::Constant *Init = EmitUuidofInitializer(Uuid);
16863861d79fSDimitry Andric   assert(Init && "failed to initialize as constant");
16873861d79fSDimitry Andric 
168859d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
1689f785676fSDimitry Andric       getModule(), Init->getType(),
1690f785676fSDimitry Andric       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
169133956c43SDimitry Andric   if (supportsCOMDAT())
169233956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
16930623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
16943861d79fSDimitry Andric }
16953861d79fSDimitry Andric 
16960623d748SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1697f22ef01cSRoman Divacky   const AliasAttr *AA = VD->getAttr<AliasAttr>();
1698f22ef01cSRoman Divacky   assert(AA && "No alias?");
1699f22ef01cSRoman Divacky 
17000623d748SDimitry Andric   CharUnits Alignment = getContext().getDeclAlign(VD);
17016122f3e6SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1702f22ef01cSRoman Divacky 
1703f22ef01cSRoman Divacky   // See if there is already something with the target's name in the module.
1704f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
17053861d79fSDimitry Andric   if (Entry) {
17063861d79fSDimitry Andric     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
17070623d748SDimitry Andric     auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
17080623d748SDimitry Andric     return ConstantAddress(Ptr, Alignment);
17093861d79fSDimitry Andric   }
1710f22ef01cSRoman Divacky 
1711f22ef01cSRoman Divacky   llvm::Constant *Aliasee;
1712f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(DeclTy))
17133861d79fSDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
17143861d79fSDimitry Andric                                       GlobalDecl(cast<FunctionDecl>(VD)),
17152754fe60SDimitry Andric                                       /*ForVTable=*/false);
1716f22ef01cSRoman Divacky   else
1717f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
171859d1ed5bSDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
171959d1ed5bSDimitry Andric                                     nullptr);
17203861d79fSDimitry Andric 
172159d1ed5bSDimitry Andric   auto *F = cast<llvm::GlobalValue>(Aliasee);
1722f22ef01cSRoman Divacky   F->setLinkage(llvm::Function::ExternalWeakLinkage);
1723f22ef01cSRoman Divacky   WeakRefReferences.insert(F);
1724f22ef01cSRoman Divacky 
17250623d748SDimitry Andric   return ConstantAddress(Aliasee, Alignment);
1726f22ef01cSRoman Divacky }
1727f22ef01cSRoman Divacky 
1728f22ef01cSRoman Divacky void CodeGenModule::EmitGlobal(GlobalDecl GD) {
172959d1ed5bSDimitry Andric   const auto *Global = cast<ValueDecl>(GD.getDecl());
1730f22ef01cSRoman Divacky 
1731f22ef01cSRoman Divacky   // Weak references don't produce any output by themselves.
1732f22ef01cSRoman Divacky   if (Global->hasAttr<WeakRefAttr>())
1733f22ef01cSRoman Divacky     return;
1734f22ef01cSRoman Divacky 
1735f22ef01cSRoman Divacky   // If this is an alias definition (which otherwise looks like a declaration)
1736f22ef01cSRoman Divacky   // emit it now.
1737f22ef01cSRoman Divacky   if (Global->hasAttr<AliasAttr>())
1738f22ef01cSRoman Divacky     return EmitAliasDefinition(GD);
1739f22ef01cSRoman Divacky 
1740e7145dcbSDimitry Andric   // IFunc like an alias whose value is resolved at runtime by calling resolver.
1741e7145dcbSDimitry Andric   if (Global->hasAttr<IFuncAttr>())
1742e7145dcbSDimitry Andric     return emitIFuncDefinition(GD);
1743e7145dcbSDimitry Andric 
17446122f3e6SDimitry Andric   // If this is CUDA, be selective about which declarations we emit.
1745dff0c46cSDimitry Andric   if (LangOpts.CUDA) {
174633956c43SDimitry Andric     if (LangOpts.CUDAIsDevice) {
17476122f3e6SDimitry Andric       if (!Global->hasAttr<CUDADeviceAttr>() &&
17486122f3e6SDimitry Andric           !Global->hasAttr<CUDAGlobalAttr>() &&
17496122f3e6SDimitry Andric           !Global->hasAttr<CUDAConstantAttr>() &&
17506122f3e6SDimitry Andric           !Global->hasAttr<CUDASharedAttr>())
17516122f3e6SDimitry Andric         return;
17526122f3e6SDimitry Andric     } else {
1753e7145dcbSDimitry Andric       // We need to emit host-side 'shadows' for all global
1754e7145dcbSDimitry Andric       // device-side variables because the CUDA runtime needs their
1755e7145dcbSDimitry Andric       // size and host-side address in order to provide access to
1756e7145dcbSDimitry Andric       // their device-side incarnations.
1757e7145dcbSDimitry Andric 
1758e7145dcbSDimitry Andric       // So device-only functions are the only things we skip.
1759e7145dcbSDimitry Andric       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
1760e7145dcbSDimitry Andric           Global->hasAttr<CUDADeviceAttr>())
17616122f3e6SDimitry Andric         return;
1762e7145dcbSDimitry Andric 
1763e7145dcbSDimitry Andric       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
1764e7145dcbSDimitry Andric              "Expected Variable or Function");
1765e580952dSDimitry Andric     }
1766e580952dSDimitry Andric   }
1767e580952dSDimitry Andric 
1768e7145dcbSDimitry Andric   if (LangOpts.OpenMP) {
1769ea942507SDimitry Andric     // If this is OpenMP device, check if it is legal to emit this global
1770ea942507SDimitry Andric     // normally.
1771ea942507SDimitry Andric     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
1772ea942507SDimitry Andric       return;
1773e7145dcbSDimitry Andric     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
1774e7145dcbSDimitry Andric       if (MustBeEmitted(Global))
1775e7145dcbSDimitry Andric         EmitOMPDeclareReduction(DRD);
1776e7145dcbSDimitry Andric       return;
1777e7145dcbSDimitry Andric     }
1778e7145dcbSDimitry Andric   }
1779ea942507SDimitry Andric 
17806122f3e6SDimitry Andric   // Ignore declarations, they will be emitted on their first use.
178159d1ed5bSDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1782f22ef01cSRoman Divacky     // Forward declarations are emitted lazily on first use.
17836122f3e6SDimitry Andric     if (!FD->doesThisDeclarationHaveABody()) {
17846122f3e6SDimitry Andric       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1785f22ef01cSRoman Divacky         return;
17866122f3e6SDimitry Andric 
17876122f3e6SDimitry Andric       StringRef MangledName = getMangledName(GD);
178859d1ed5bSDimitry Andric 
178959d1ed5bSDimitry Andric       // Compute the function info and LLVM type.
179059d1ed5bSDimitry Andric       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
179159d1ed5bSDimitry Andric       llvm::Type *Ty = getTypes().GetFunctionType(FI);
179259d1ed5bSDimitry Andric 
179359d1ed5bSDimitry Andric       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
179459d1ed5bSDimitry Andric                               /*DontDefer=*/false);
17956122f3e6SDimitry Andric       return;
17966122f3e6SDimitry Andric     }
1797f22ef01cSRoman Divacky   } else {
179859d1ed5bSDimitry Andric     const auto *VD = cast<VarDecl>(Global);
1799f22ef01cSRoman Divacky     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1800e7145dcbSDimitry Andric     // We need to emit device-side global CUDA variables even if a
1801e7145dcbSDimitry Andric     // variable does not have a definition -- we still need to define
1802e7145dcbSDimitry Andric     // host-side shadow for it.
1803e7145dcbSDimitry Andric     bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
1804e7145dcbSDimitry Andric                            !VD->hasDefinition() &&
1805e7145dcbSDimitry Andric                            (VD->hasAttr<CUDAConstantAttr>() ||
1806e7145dcbSDimitry Andric                             VD->hasAttr<CUDADeviceAttr>());
1807e7145dcbSDimitry Andric     if (!MustEmitForCuda &&
1808e7145dcbSDimitry Andric         VD->isThisDeclarationADefinition() != VarDecl::Definition &&
1809e7145dcbSDimitry Andric         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
1810e7145dcbSDimitry Andric       // If this declaration may have caused an inline variable definition to
1811e7145dcbSDimitry Andric       // change linkage, make sure that it's emitted.
1812e7145dcbSDimitry Andric       if (Context.getInlineVariableDefinitionKind(VD) ==
1813e7145dcbSDimitry Andric           ASTContext::InlineVariableDefinitionKind::Strong)
1814e7145dcbSDimitry Andric         GetAddrOfGlobalVar(VD);
1815f22ef01cSRoman Divacky       return;
1816f22ef01cSRoman Divacky     }
1817e7145dcbSDimitry Andric   }
1818f22ef01cSRoman Divacky 
181939d628a0SDimitry Andric   // Defer code generation to first use when possible, e.g. if this is an inline
182039d628a0SDimitry Andric   // function. If the global must always be emitted, do it eagerly if possible
182139d628a0SDimitry Andric   // to benefit from cache locality.
182239d628a0SDimitry Andric   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
1823f22ef01cSRoman Divacky     // Emit the definition if it can't be deferred.
1824f22ef01cSRoman Divacky     EmitGlobalDefinition(GD);
1825f22ef01cSRoman Divacky     return;
1826f22ef01cSRoman Divacky   }
1827f22ef01cSRoman Divacky 
1828e580952dSDimitry Andric   // If we're deferring emission of a C++ variable with an
1829e580952dSDimitry Andric   // initializer, remember the order in which it appeared in the file.
1830dff0c46cSDimitry Andric   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1831e580952dSDimitry Andric       cast<VarDecl>(Global)->hasInit()) {
1832e580952dSDimitry Andric     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
183359d1ed5bSDimitry Andric     CXXGlobalInits.push_back(nullptr);
1834e580952dSDimitry Andric   }
1835e580952dSDimitry Andric 
18366122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
1837f37b6182SDimitry Andric   if (GetGlobalValue(MangledName) != nullptr) {
183839d628a0SDimitry Andric     // The value has already been used and should therefore be emitted.
1839f37b6182SDimitry Andric     addDeferredDeclToEmit(GD);
184039d628a0SDimitry Andric   } else if (MustBeEmitted(Global)) {
184139d628a0SDimitry Andric     // The value must be emitted, but cannot be emitted eagerly.
184239d628a0SDimitry Andric     assert(!MayBeEmittedEagerly(Global));
1843f37b6182SDimitry Andric     addDeferredDeclToEmit(GD);
184439d628a0SDimitry Andric   } else {
1845f22ef01cSRoman Divacky     // Otherwise, remember that we saw a deferred decl with this name.  The
1846f22ef01cSRoman Divacky     // first use of the mangled name will cause it to move into
1847f22ef01cSRoman Divacky     // DeferredDeclsToEmit.
1848f22ef01cSRoman Divacky     DeferredDecls[MangledName] = GD;
1849f22ef01cSRoman Divacky   }
1850f22ef01cSRoman Divacky }
1851f22ef01cSRoman Divacky 
185220e90f04SDimitry Andric // Check if T is a class type with a destructor that's not dllimport.
185320e90f04SDimitry Andric static bool HasNonDllImportDtor(QualType T) {
185420e90f04SDimitry Andric   if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
185520e90f04SDimitry Andric     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
185620e90f04SDimitry Andric       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
185720e90f04SDimitry Andric         return true;
185820e90f04SDimitry Andric 
185920e90f04SDimitry Andric   return false;
186020e90f04SDimitry Andric }
186120e90f04SDimitry Andric 
1862f8254f43SDimitry Andric namespace {
1863f8254f43SDimitry Andric   struct FunctionIsDirectlyRecursive :
1864f8254f43SDimitry Andric     public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1865f8254f43SDimitry Andric     const StringRef Name;
1866dff0c46cSDimitry Andric     const Builtin::Context &BI;
1867f8254f43SDimitry Andric     bool Result;
1868dff0c46cSDimitry Andric     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1869dff0c46cSDimitry Andric       Name(N), BI(C), Result(false) {
1870f8254f43SDimitry Andric     }
1871f8254f43SDimitry Andric     typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1872f8254f43SDimitry Andric 
1873f8254f43SDimitry Andric     bool TraverseCallExpr(CallExpr *E) {
1874dff0c46cSDimitry Andric       const FunctionDecl *FD = E->getDirectCallee();
1875dff0c46cSDimitry Andric       if (!FD)
1876f8254f43SDimitry Andric         return true;
1877dff0c46cSDimitry Andric       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1878dff0c46cSDimitry Andric       if (Attr && Name == Attr->getLabel()) {
1879dff0c46cSDimitry Andric         Result = true;
1880dff0c46cSDimitry Andric         return false;
1881dff0c46cSDimitry Andric       }
1882dff0c46cSDimitry Andric       unsigned BuiltinID = FD->getBuiltinID();
18833dac3a9bSDimitry Andric       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
1884f8254f43SDimitry Andric         return true;
18850623d748SDimitry Andric       StringRef BuiltinName = BI.getName(BuiltinID);
1886dff0c46cSDimitry Andric       if (BuiltinName.startswith("__builtin_") &&
1887dff0c46cSDimitry Andric           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1888f8254f43SDimitry Andric         Result = true;
1889f8254f43SDimitry Andric         return false;
1890f8254f43SDimitry Andric       }
1891f8254f43SDimitry Andric       return true;
1892f8254f43SDimitry Andric     }
1893f8254f43SDimitry Andric   };
18940623d748SDimitry Andric 
189520e90f04SDimitry Andric   // Make sure we're not referencing non-imported vars or functions.
18960623d748SDimitry Andric   struct DLLImportFunctionVisitor
18970623d748SDimitry Andric       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
18980623d748SDimitry Andric     bool SafeToInline = true;
18990623d748SDimitry Andric 
190044290647SDimitry Andric     bool shouldVisitImplicitCode() const { return true; }
190144290647SDimitry Andric 
19020623d748SDimitry Andric     bool VisitVarDecl(VarDecl *VD) {
190320e90f04SDimitry Andric       if (VD->getTLSKind()) {
19040623d748SDimitry Andric         // A thread-local variable cannot be imported.
190520e90f04SDimitry Andric         SafeToInline = false;
19060623d748SDimitry Andric         return SafeToInline;
19070623d748SDimitry Andric       }
19080623d748SDimitry Andric 
190920e90f04SDimitry Andric       // A variable definition might imply a destructor call.
191020e90f04SDimitry Andric       if (VD->isThisDeclarationADefinition())
191120e90f04SDimitry Andric         SafeToInline = !HasNonDllImportDtor(VD->getType());
191220e90f04SDimitry Andric 
191320e90f04SDimitry Andric       return SafeToInline;
191420e90f04SDimitry Andric     }
191520e90f04SDimitry Andric 
191620e90f04SDimitry Andric     bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
191720e90f04SDimitry Andric       if (const auto *D = E->getTemporary()->getDestructor())
191820e90f04SDimitry Andric         SafeToInline = D->hasAttr<DLLImportAttr>();
191920e90f04SDimitry Andric       return SafeToInline;
192020e90f04SDimitry Andric     }
192120e90f04SDimitry Andric 
19220623d748SDimitry Andric     bool VisitDeclRefExpr(DeclRefExpr *E) {
19230623d748SDimitry Andric       ValueDecl *VD = E->getDecl();
19240623d748SDimitry Andric       if (isa<FunctionDecl>(VD))
19250623d748SDimitry Andric         SafeToInline = VD->hasAttr<DLLImportAttr>();
19260623d748SDimitry Andric       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
19270623d748SDimitry Andric         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
19280623d748SDimitry Andric       return SafeToInline;
19290623d748SDimitry Andric     }
193020e90f04SDimitry Andric 
193144290647SDimitry Andric     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
193244290647SDimitry Andric       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
193344290647SDimitry Andric       return SafeToInline;
193444290647SDimitry Andric     }
193520e90f04SDimitry Andric 
193620e90f04SDimitry Andric     bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
193720e90f04SDimitry Andric       CXXMethodDecl *M = E->getMethodDecl();
193820e90f04SDimitry Andric       if (!M) {
193920e90f04SDimitry Andric         // Call through a pointer to member function. This is safe to inline.
194020e90f04SDimitry Andric         SafeToInline = true;
194120e90f04SDimitry Andric       } else {
194220e90f04SDimitry Andric         SafeToInline = M->hasAttr<DLLImportAttr>();
194320e90f04SDimitry Andric       }
194420e90f04SDimitry Andric       return SafeToInline;
194520e90f04SDimitry Andric     }
194620e90f04SDimitry Andric 
19470623d748SDimitry Andric     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
19480623d748SDimitry Andric       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
19490623d748SDimitry Andric       return SafeToInline;
19500623d748SDimitry Andric     }
195120e90f04SDimitry Andric 
19520623d748SDimitry Andric     bool VisitCXXNewExpr(CXXNewExpr *E) {
19530623d748SDimitry Andric       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
19540623d748SDimitry Andric       return SafeToInline;
19550623d748SDimitry Andric     }
19560623d748SDimitry Andric   };
1957f8254f43SDimitry Andric }
1958f8254f43SDimitry Andric 
1959dff0c46cSDimitry Andric // isTriviallyRecursive - Check if this function calls another
1960dff0c46cSDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin,
1961dff0c46cSDimitry Andric // ends up pointing to itself.
1962f8254f43SDimitry Andric bool
1963dff0c46cSDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1964dff0c46cSDimitry Andric   StringRef Name;
1965dff0c46cSDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1966dff0c46cSDimitry Andric     // asm labels are a special kind of mangling we have to support.
1967dff0c46cSDimitry Andric     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1968dff0c46cSDimitry Andric     if (!Attr)
1969f8254f43SDimitry Andric       return false;
1970dff0c46cSDimitry Andric     Name = Attr->getLabel();
1971dff0c46cSDimitry Andric   } else {
1972dff0c46cSDimitry Andric     Name = FD->getName();
1973dff0c46cSDimitry Andric   }
1974f8254f43SDimitry Andric 
1975dff0c46cSDimitry Andric   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1976dff0c46cSDimitry Andric   Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1977f8254f43SDimitry Andric   return Walker.Result;
1978f8254f43SDimitry Andric }
1979f8254f43SDimitry Andric 
198044290647SDimitry Andric bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1981f785676fSDimitry Andric   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1982f8254f43SDimitry Andric     return true;
198359d1ed5bSDimitry Andric   const auto *F = cast<FunctionDecl>(GD.getDecl());
198459d1ed5bSDimitry Andric   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1985f8254f43SDimitry Andric     return false;
19860623d748SDimitry Andric 
19870623d748SDimitry Andric   if (F->hasAttr<DLLImportAttr>()) {
19880623d748SDimitry Andric     // Check whether it would be safe to inline this dllimport function.
19890623d748SDimitry Andric     DLLImportFunctionVisitor Visitor;
19900623d748SDimitry Andric     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
19910623d748SDimitry Andric     if (!Visitor.SafeToInline)
19920623d748SDimitry Andric       return false;
199344290647SDimitry Andric 
199444290647SDimitry Andric     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
199544290647SDimitry Andric       // Implicit destructor invocations aren't captured in the AST, so the
199644290647SDimitry Andric       // check above can't see them. Check for them manually here.
199744290647SDimitry Andric       for (const Decl *Member : Dtor->getParent()->decls())
199844290647SDimitry Andric         if (isa<FieldDecl>(Member))
199944290647SDimitry Andric           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
200044290647SDimitry Andric             return false;
200144290647SDimitry Andric       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
200244290647SDimitry Andric         if (HasNonDllImportDtor(B.getType()))
200344290647SDimitry Andric           return false;
200444290647SDimitry Andric     }
20050623d748SDimitry Andric   }
20060623d748SDimitry Andric 
2007f8254f43SDimitry Andric   // PR9614. Avoid cases where the source code is lying to us. An available
2008f8254f43SDimitry Andric   // externally function should have an equivalent function somewhere else,
2009f8254f43SDimitry Andric   // but a function that calls itself is clearly not equivalent to the real
2010f8254f43SDimitry Andric   // implementation.
2011f8254f43SDimitry Andric   // This happens in glibc's btowc and in some configure checks.
2012dff0c46cSDimitry Andric   return !isTriviallyRecursive(F);
2013f8254f43SDimitry Andric }
2014f8254f43SDimitry Andric 
2015f9448bf3SDimitry Andric bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
2016f9448bf3SDimitry Andric   return CodeGenOpts.OptimizationLevel > 0;
2017f9448bf3SDimitry Andric }
2018f9448bf3SDimitry Andric 
201959d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
202059d1ed5bSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
2021f22ef01cSRoman Divacky 
2022f22ef01cSRoman Divacky   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
2023f22ef01cSRoman Divacky                                  Context.getSourceManager(),
2024f22ef01cSRoman Divacky                                  "Generating code for declaration");
2025f22ef01cSRoman Divacky 
2026f785676fSDimitry Andric   if (isa<FunctionDecl>(D)) {
2027ffd1746dSEd Schouten     // At -O0, don't generate IR for functions with available_externally
2028ffd1746dSEd Schouten     // linkage.
2029f785676fSDimitry Andric     if (!shouldEmitFunction(GD))
2030ffd1746dSEd Schouten       return;
2031ffd1746dSEd Schouten 
203259d1ed5bSDimitry Andric     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
2033bd5abe19SDimitry Andric       // Make sure to emit the definition(s) before we emit the thunks.
2034bd5abe19SDimitry Andric       // This is necessary for the generation of certain thunks.
203559d1ed5bSDimitry Andric       if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
203639d628a0SDimitry Andric         ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
203759d1ed5bSDimitry Andric       else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
203839d628a0SDimitry Andric         ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
2039bd5abe19SDimitry Andric       else
204059d1ed5bSDimitry Andric         EmitGlobalFunctionDefinition(GD, GV);
2041bd5abe19SDimitry Andric 
2042f22ef01cSRoman Divacky       if (Method->isVirtual())
2043f22ef01cSRoman Divacky         getVTables().EmitThunks(GD);
2044f22ef01cSRoman Divacky 
2045bd5abe19SDimitry Andric       return;
2046ffd1746dSEd Schouten     }
2047f22ef01cSRoman Divacky 
204859d1ed5bSDimitry Andric     return EmitGlobalFunctionDefinition(GD, GV);
2049ffd1746dSEd Schouten   }
2050f22ef01cSRoman Divacky 
205159d1ed5bSDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
2052e7145dcbSDimitry Andric     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
2053f22ef01cSRoman Divacky 
20546122f3e6SDimitry Andric   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
2055f22ef01cSRoman Divacky }
2056f22ef01cSRoman Divacky 
20570623d748SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
20580623d748SDimitry Andric                                                       llvm::Function *NewFn);
20590623d748SDimitry Andric 
2060f22ef01cSRoman Divacky /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
2061f22ef01cSRoman Divacky /// module, create and return an llvm Function with the specified type. If there
2062f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially
2063f22ef01cSRoman Divacky /// bitcasted to the right type.
2064f22ef01cSRoman Divacky ///
2065f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this.  This is used
2066f22ef01cSRoman Divacky /// to set the attributes on the function when it is first created.
206720e90f04SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
206820e90f04SDimitry Andric     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
206920e90f04SDimitry Andric     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
207044290647SDimitry Andric     ForDefinition_t IsForDefinition) {
2071f785676fSDimitry Andric   const Decl *D = GD.getDecl();
2072f785676fSDimitry Andric 
2073f22ef01cSRoman Divacky   // Lookup the entry, lazily creating it if necessary.
2074f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2075f22ef01cSRoman Divacky   if (Entry) {
20763861d79fSDimitry Andric     if (WeakRefReferences.erase(Entry)) {
2077f785676fSDimitry Andric       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
2078f22ef01cSRoman Divacky       if (FD && !FD->hasAttr<WeakAttr>())
2079f22ef01cSRoman Divacky         Entry->setLinkage(llvm::Function::ExternalLinkage);
2080f22ef01cSRoman Divacky     }
2081f22ef01cSRoman Divacky 
208239d628a0SDimitry Andric     // Handle dropped DLL attributes.
208339d628a0SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
208439d628a0SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
208539d628a0SDimitry Andric 
20860623d748SDimitry Andric     // If there are two attempts to define the same mangled name, issue an
20870623d748SDimitry Andric     // error.
20880623d748SDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
20890623d748SDimitry Andric       GlobalDecl OtherGD;
2090e7145dcbSDimitry Andric       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
2091e7145dcbSDimitry Andric       // to make sure that we issue an error only once.
20920623d748SDimitry Andric       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
20930623d748SDimitry Andric           (GD.getCanonicalDecl().getDecl() !=
20940623d748SDimitry Andric            OtherGD.getCanonicalDecl().getDecl()) &&
20950623d748SDimitry Andric           DiagnosedConflictingDefinitions.insert(GD).second) {
20960623d748SDimitry Andric         getDiags().Report(D->getLocation(),
20970623d748SDimitry Andric                           diag::err_duplicate_mangled_name);
20980623d748SDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
20990623d748SDimitry Andric                           diag::note_previous_definition);
21000623d748SDimitry Andric       }
21010623d748SDimitry Andric     }
21020623d748SDimitry Andric 
21030623d748SDimitry Andric     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
21040623d748SDimitry Andric         (Entry->getType()->getElementType() == Ty)) {
2105f22ef01cSRoman Divacky       return Entry;
21060623d748SDimitry Andric     }
2107f22ef01cSRoman Divacky 
2108f22ef01cSRoman Divacky     // Make sure the result is of the correct type.
21090623d748SDimitry Andric     // (If function is requested for a definition, we always need to create a new
21100623d748SDimitry Andric     // function, not just return a bitcast.)
21110623d748SDimitry Andric     if (!IsForDefinition)
211217a519f9SDimitry Andric       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
2113f22ef01cSRoman Divacky   }
2114f22ef01cSRoman Divacky 
2115f22ef01cSRoman Divacky   // This function doesn't have a complete type (for example, the return
2116f22ef01cSRoman Divacky   // type is an incomplete struct). Use a fake type instead, and make
2117f22ef01cSRoman Divacky   // sure not to try to set attributes.
2118f22ef01cSRoman Divacky   bool IsIncompleteFunction = false;
2119f22ef01cSRoman Divacky 
21206122f3e6SDimitry Andric   llvm::FunctionType *FTy;
2121f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(Ty)) {
2122f22ef01cSRoman Divacky     FTy = cast<llvm::FunctionType>(Ty);
2123f22ef01cSRoman Divacky   } else {
2124bd5abe19SDimitry Andric     FTy = llvm::FunctionType::get(VoidTy, false);
2125f22ef01cSRoman Divacky     IsIncompleteFunction = true;
2126f22ef01cSRoman Divacky   }
2127ffd1746dSEd Schouten 
21280623d748SDimitry Andric   llvm::Function *F =
21290623d748SDimitry Andric       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
21300623d748SDimitry Andric                              Entry ? StringRef() : MangledName, &getModule());
21310623d748SDimitry Andric 
21320623d748SDimitry Andric   // If we already created a function with the same mangled name (but different
21330623d748SDimitry Andric   // type) before, take its name and add it to the list of functions to be
21340623d748SDimitry Andric   // replaced with F at the end of CodeGen.
21350623d748SDimitry Andric   //
21360623d748SDimitry Andric   // This happens if there is a prototype for a function (e.g. "int f()") and
21370623d748SDimitry Andric   // then a definition of a different type (e.g. "int f(int x)").
21380623d748SDimitry Andric   if (Entry) {
21390623d748SDimitry Andric     F->takeName(Entry);
21400623d748SDimitry Andric 
21410623d748SDimitry Andric     // This might be an implementation of a function without a prototype, in
21420623d748SDimitry Andric     // which case, try to do special replacement of calls which match the new
21430623d748SDimitry Andric     // prototype.  The really key thing here is that we also potentially drop
21440623d748SDimitry Andric     // arguments from the call site so as to make a direct call, which makes the
21450623d748SDimitry Andric     // inliner happier and suppresses a number of optimizer warnings (!) about
21460623d748SDimitry Andric     // dropping arguments.
21470623d748SDimitry Andric     if (!Entry->use_empty()) {
21480623d748SDimitry Andric       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
21490623d748SDimitry Andric       Entry->removeDeadConstantUsers();
21500623d748SDimitry Andric     }
21510623d748SDimitry Andric 
21520623d748SDimitry Andric     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
21530623d748SDimitry Andric         F, Entry->getType()->getElementType()->getPointerTo());
21540623d748SDimitry Andric     addGlobalValReplacement(Entry, BC);
21550623d748SDimitry Andric   }
21560623d748SDimitry Andric 
2157f22ef01cSRoman Divacky   assert(F->getName() == MangledName && "name was uniqued!");
2158f785676fSDimitry Andric   if (D)
21599a199699SDimitry Andric     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk,
21609a199699SDimitry Andric                           IsForDefinition);
216120e90f04SDimitry Andric   if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
216220e90f04SDimitry Andric     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
2163f37b6182SDimitry Andric     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
2164139f7f9bSDimitry Andric   }
2165f22ef01cSRoman Divacky 
216659d1ed5bSDimitry Andric   if (!DontDefer) {
216759d1ed5bSDimitry Andric     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
216859d1ed5bSDimitry Andric     // each other bottoming out with the base dtor.  Therefore we emit non-base
216959d1ed5bSDimitry Andric     // dtors on usage, even if there is no dtor definition in the TU.
217059d1ed5bSDimitry Andric     if (D && isa<CXXDestructorDecl>(D) &&
217159d1ed5bSDimitry Andric         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
217259d1ed5bSDimitry Andric                                            GD.getDtorType()))
2173f37b6182SDimitry Andric       addDeferredDeclToEmit(GD);
217459d1ed5bSDimitry Andric 
2175f22ef01cSRoman Divacky     // This is the first use or definition of a mangled name.  If there is a
2176f22ef01cSRoman Divacky     // deferred decl with this name, remember that we need to emit it at the end
2177f22ef01cSRoman Divacky     // of the file.
217859d1ed5bSDimitry Andric     auto DDI = DeferredDecls.find(MangledName);
2179f22ef01cSRoman Divacky     if (DDI != DeferredDecls.end()) {
218059d1ed5bSDimitry Andric       // Move the potentially referenced deferred decl to the
218159d1ed5bSDimitry Andric       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
218259d1ed5bSDimitry Andric       // don't need it anymore).
2183f37b6182SDimitry Andric       addDeferredDeclToEmit(DDI->second);
2184f22ef01cSRoman Divacky       DeferredDecls.erase(DDI);
21852754fe60SDimitry Andric 
21862754fe60SDimitry Andric       // Otherwise, there are cases we have to worry about where we're
21872754fe60SDimitry Andric       // using a declaration for which we must emit a definition but where
21882754fe60SDimitry Andric       // we might not find a top-level definition:
21892754fe60SDimitry Andric       //   - member functions defined inline in their classes
21902754fe60SDimitry Andric       //   - friend functions defined inline in some class
21912754fe60SDimitry Andric       //   - special member functions with implicit definitions
21922754fe60SDimitry Andric       // If we ever change our AST traversal to walk into class methods,
21932754fe60SDimitry Andric       // this will be unnecessary.
21942754fe60SDimitry Andric       //
219559d1ed5bSDimitry Andric       // We also don't emit a definition for a function if it's going to be an
219639d628a0SDimitry Andric       // entry in a vtable, unless it's already marked as used.
2197f785676fSDimitry Andric     } else if (getLangOpts().CPlusPlus && D) {
21982754fe60SDimitry Andric       // Look for a declaration that's lexically in a record.
219939d628a0SDimitry Andric       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
220039d628a0SDimitry Andric            FD = FD->getPreviousDecl()) {
22012754fe60SDimitry Andric         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
220239d628a0SDimitry Andric           if (FD->doesThisDeclarationHaveABody()) {
2203f37b6182SDimitry Andric             addDeferredDeclToEmit(GD.getWithDecl(FD));
22042754fe60SDimitry Andric             break;
2205f22ef01cSRoman Divacky           }
2206f22ef01cSRoman Divacky         }
220739d628a0SDimitry Andric       }
2208f22ef01cSRoman Divacky     }
220959d1ed5bSDimitry Andric   }
2210f22ef01cSRoman Divacky 
2211f22ef01cSRoman Divacky   // Make sure the result is of the requested type.
2212f22ef01cSRoman Divacky   if (!IsIncompleteFunction) {
2213f22ef01cSRoman Divacky     assert(F->getType()->getElementType() == Ty);
2214f22ef01cSRoman Divacky     return F;
2215f22ef01cSRoman Divacky   }
2216f22ef01cSRoman Divacky 
221717a519f9SDimitry Andric   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2218f22ef01cSRoman Divacky   return llvm::ConstantExpr::getBitCast(F, PTy);
2219f22ef01cSRoman Divacky }
2220f22ef01cSRoman Divacky 
2221f22ef01cSRoman Divacky /// GetAddrOfFunction - Return the address of the given function.  If Ty is
2222f22ef01cSRoman Divacky /// non-null, then this function will use the specified type if it has to
2223f22ef01cSRoman Divacky /// create it (this occurs when we see a definition of the function).
2224f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
22256122f3e6SDimitry Andric                                                  llvm::Type *Ty,
222659d1ed5bSDimitry Andric                                                  bool ForVTable,
22270623d748SDimitry Andric                                                  bool DontDefer,
222844290647SDimitry Andric                                               ForDefinition_t IsForDefinition) {
2229f22ef01cSRoman Divacky   // If there was no specific requested type, just convert it now.
22300623d748SDimitry Andric   if (!Ty) {
22310623d748SDimitry Andric     const auto *FD = cast<FunctionDecl>(GD.getDecl());
22320623d748SDimitry Andric     auto CanonTy = Context.getCanonicalType(FD->getType());
22330623d748SDimitry Andric     Ty = getTypes().ConvertFunctionType(CanonTy, FD);
22340623d748SDimitry Andric   }
2235ffd1746dSEd Schouten 
22366122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
22370623d748SDimitry Andric   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
223820e90f04SDimitry Andric                                  /*IsThunk=*/false, llvm::AttributeList(),
22390623d748SDimitry Andric                                  IsForDefinition);
2240f22ef01cSRoman Divacky }
2241f22ef01cSRoman Divacky 
224244290647SDimitry Andric static const FunctionDecl *
224344290647SDimitry Andric GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
224444290647SDimitry Andric   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
224544290647SDimitry Andric   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
224644290647SDimitry Andric 
224744290647SDimitry Andric   IdentifierInfo &CII = C.Idents.get(Name);
224844290647SDimitry Andric   for (const auto &Result : DC->lookup(&CII))
224944290647SDimitry Andric     if (const auto FD = dyn_cast<FunctionDecl>(Result))
225044290647SDimitry Andric       return FD;
225144290647SDimitry Andric 
225244290647SDimitry Andric   if (!C.getLangOpts().CPlusPlus)
225344290647SDimitry Andric     return nullptr;
225444290647SDimitry Andric 
225544290647SDimitry Andric   // Demangle the premangled name from getTerminateFn()
225644290647SDimitry Andric   IdentifierInfo &CXXII =
225744290647SDimitry Andric       (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ")
225844290647SDimitry Andric           ? C.Idents.get("terminate")
225944290647SDimitry Andric           : C.Idents.get(Name);
226044290647SDimitry Andric 
226144290647SDimitry Andric   for (const auto &N : {"__cxxabiv1", "std"}) {
226244290647SDimitry Andric     IdentifierInfo &NS = C.Idents.get(N);
226344290647SDimitry Andric     for (const auto &Result : DC->lookup(&NS)) {
226444290647SDimitry Andric       NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
226544290647SDimitry Andric       if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
226644290647SDimitry Andric         for (const auto &Result : LSD->lookup(&NS))
226744290647SDimitry Andric           if ((ND = dyn_cast<NamespaceDecl>(Result)))
226844290647SDimitry Andric             break;
226944290647SDimitry Andric 
227044290647SDimitry Andric       if (ND)
227144290647SDimitry Andric         for (const auto &Result : ND->lookup(&CXXII))
227244290647SDimitry Andric           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
227344290647SDimitry Andric             return FD;
227444290647SDimitry Andric     }
227544290647SDimitry Andric   }
227644290647SDimitry Andric 
227744290647SDimitry Andric   return nullptr;
227844290647SDimitry Andric }
227944290647SDimitry Andric 
2280f22ef01cSRoman Divacky /// CreateRuntimeFunction - Create a new runtime function with the specified
2281f22ef01cSRoman Divacky /// type and name.
2282f22ef01cSRoman Divacky llvm::Constant *
228344290647SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
228420e90f04SDimitry Andric                                      llvm::AttributeList ExtraAttrs,
228544290647SDimitry Andric                                      bool Local) {
228659d1ed5bSDimitry Andric   llvm::Constant *C =
228759d1ed5bSDimitry Andric       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
228844290647SDimitry Andric                               /*DontDefer=*/false, /*IsThunk=*/false,
228944290647SDimitry Andric                               ExtraAttrs);
229044290647SDimitry Andric 
229144290647SDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(C)) {
229244290647SDimitry Andric     if (F->empty()) {
2293139f7f9bSDimitry Andric       F->setCallingConv(getRuntimeCC());
229444290647SDimitry Andric 
229544290647SDimitry Andric       if (!Local && getTriple().isOSBinFormatCOFF() &&
22969a199699SDimitry Andric           !getCodeGenOpts().LTOVisibilityPublicStd &&
22979a199699SDimitry Andric           !getTriple().isWindowsGNUEnvironment()) {
229844290647SDimitry Andric         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
229944290647SDimitry Andric         if (!FD || FD->hasAttr<DLLImportAttr>()) {
230044290647SDimitry Andric           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
230144290647SDimitry Andric           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
230244290647SDimitry Andric         }
230344290647SDimitry Andric       }
230444290647SDimitry Andric     }
230544290647SDimitry Andric   }
230644290647SDimitry Andric 
2307139f7f9bSDimitry Andric   return C;
2308f22ef01cSRoman Divacky }
2309f22ef01cSRoman Divacky 
231039d628a0SDimitry Andric /// CreateBuiltinFunction - Create a new builtin function with the specified
231139d628a0SDimitry Andric /// type and name.
231239d628a0SDimitry Andric llvm::Constant *
231320e90f04SDimitry Andric CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
231420e90f04SDimitry Andric                                      llvm::AttributeList ExtraAttrs) {
231539d628a0SDimitry Andric   llvm::Constant *C =
231639d628a0SDimitry Andric       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
231739d628a0SDimitry Andric                               /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
231839d628a0SDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(C))
231939d628a0SDimitry Andric     if (F->empty())
232039d628a0SDimitry Andric       F->setCallingConv(getBuiltinCC());
232139d628a0SDimitry Andric   return C;
232239d628a0SDimitry Andric }
232339d628a0SDimitry Andric 
2324dff0c46cSDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted
2325dff0c46cSDimitry Andric /// as a constant.
2326dff0c46cSDimitry Andric ///
2327dff0c46cSDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs
2328dff0c46cSDimitry Andric /// will not be considered. The caller will need to verify that the object is
2329dff0c46cSDimitry Andric /// not written to during its construction.
2330dff0c46cSDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2331dff0c46cSDimitry Andric   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
2332f22ef01cSRoman Divacky     return false;
2333bd5abe19SDimitry Andric 
2334dff0c46cSDimitry Andric   if (Context.getLangOpts().CPlusPlus) {
2335dff0c46cSDimitry Andric     if (const CXXRecordDecl *Record
2336dff0c46cSDimitry Andric           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2337dff0c46cSDimitry Andric       return ExcludeCtor && !Record->hasMutableFields() &&
2338dff0c46cSDimitry Andric              Record->hasTrivialDestructor();
2339f22ef01cSRoman Divacky   }
2340bd5abe19SDimitry Andric 
2341f22ef01cSRoman Divacky   return true;
2342f22ef01cSRoman Divacky }
2343f22ef01cSRoman Divacky 
2344f22ef01cSRoman Divacky /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2345f22ef01cSRoman Divacky /// create and return an llvm GlobalVariable with the specified type.  If there
2346f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially
2347f22ef01cSRoman Divacky /// bitcasted to the right type.
2348f22ef01cSRoman Divacky ///
2349f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this.  This is used
2350f22ef01cSRoman Divacky /// to set the attributes on the global when it is first created.
2351e7145dcbSDimitry Andric ///
2352e7145dcbSDimitry Andric /// If IsForDefinition is true, it is guranteed that an actual global with
2353e7145dcbSDimitry Andric /// type Ty will be returned, not conversion of a variable with the same
2354e7145dcbSDimitry Andric /// mangled name but some other type.
2355f22ef01cSRoman Divacky llvm::Constant *
23566122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
23576122f3e6SDimitry Andric                                      llvm::PointerType *Ty,
2358e7145dcbSDimitry Andric                                      const VarDecl *D,
235944290647SDimitry Andric                                      ForDefinition_t IsForDefinition) {
2360f22ef01cSRoman Divacky   // Lookup the entry, lazily creating it if necessary.
2361f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2362f22ef01cSRoman Divacky   if (Entry) {
23633861d79fSDimitry Andric     if (WeakRefReferences.erase(Entry)) {
2364f22ef01cSRoman Divacky       if (D && !D->hasAttr<WeakAttr>())
2365f22ef01cSRoman Divacky         Entry->setLinkage(llvm::Function::ExternalLinkage);
2366f22ef01cSRoman Divacky     }
2367f22ef01cSRoman Divacky 
236839d628a0SDimitry Andric     // Handle dropped DLL attributes.
236939d628a0SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
237039d628a0SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
237139d628a0SDimitry Andric 
2372f22ef01cSRoman Divacky     if (Entry->getType() == Ty)
2373f22ef01cSRoman Divacky       return Entry;
2374f22ef01cSRoman Divacky 
2375e7145dcbSDimitry Andric     // If there are two attempts to define the same mangled name, issue an
2376e7145dcbSDimitry Andric     // error.
2377e7145dcbSDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
2378e7145dcbSDimitry Andric       GlobalDecl OtherGD;
2379e7145dcbSDimitry Andric       const VarDecl *OtherD;
2380e7145dcbSDimitry Andric 
2381e7145dcbSDimitry Andric       // Check that D is not yet in DiagnosedConflictingDefinitions is required
2382e7145dcbSDimitry Andric       // to make sure that we issue an error only once.
2383e7145dcbSDimitry Andric       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
2384e7145dcbSDimitry Andric           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2385e7145dcbSDimitry Andric           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2386e7145dcbSDimitry Andric           OtherD->hasInit() &&
2387e7145dcbSDimitry Andric           DiagnosedConflictingDefinitions.insert(D).second) {
2388e7145dcbSDimitry Andric         getDiags().Report(D->getLocation(),
2389e7145dcbSDimitry Andric                           diag::err_duplicate_mangled_name);
2390e7145dcbSDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
2391e7145dcbSDimitry Andric                           diag::note_previous_definition);
2392e7145dcbSDimitry Andric       }
2393e7145dcbSDimitry Andric     }
2394e7145dcbSDimitry Andric 
2395f22ef01cSRoman Divacky     // Make sure the result is of the correct type.
2396f785676fSDimitry Andric     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2397f785676fSDimitry Andric       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2398f785676fSDimitry Andric 
2399e7145dcbSDimitry Andric     // (If global is requested for a definition, we always need to create a new
2400e7145dcbSDimitry Andric     // global, not just return a bitcast.)
2401e7145dcbSDimitry Andric     if (!IsForDefinition)
2402f22ef01cSRoman Divacky       return llvm::ConstantExpr::getBitCast(Entry, Ty);
2403f22ef01cSRoman Divacky   }
2404f22ef01cSRoman Divacky 
2405c4394386SDimitry Andric   auto AddrSpace = GetGlobalVarAddressSpace(D);
2406c4394386SDimitry Andric   auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
2407c4394386SDimitry Andric 
240859d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
240959d1ed5bSDimitry Andric       getModule(), Ty->getElementType(), false,
241059d1ed5bSDimitry Andric       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
2411c4394386SDimitry Andric       llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
241259d1ed5bSDimitry Andric 
2413e7145dcbSDimitry Andric   // If we already created a global with the same mangled name (but different
2414e7145dcbSDimitry Andric   // type) before, take its name and remove it from its parent.
2415e7145dcbSDimitry Andric   if (Entry) {
2416e7145dcbSDimitry Andric     GV->takeName(Entry);
2417e7145dcbSDimitry Andric 
2418e7145dcbSDimitry Andric     if (!Entry->use_empty()) {
2419e7145dcbSDimitry Andric       llvm::Constant *NewPtrForOldDecl =
2420e7145dcbSDimitry Andric           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2421e7145dcbSDimitry Andric       Entry->replaceAllUsesWith(NewPtrForOldDecl);
2422e7145dcbSDimitry Andric     }
2423e7145dcbSDimitry Andric 
2424e7145dcbSDimitry Andric     Entry->eraseFromParent();
2425e7145dcbSDimitry Andric   }
2426e7145dcbSDimitry Andric 
2427f22ef01cSRoman Divacky   // This is the first use or definition of a mangled name.  If there is a
2428f22ef01cSRoman Divacky   // deferred decl with this name, remember that we need to emit it at the end
2429f22ef01cSRoman Divacky   // of the file.
243059d1ed5bSDimitry Andric   auto DDI = DeferredDecls.find(MangledName);
2431f22ef01cSRoman Divacky   if (DDI != DeferredDecls.end()) {
2432f22ef01cSRoman Divacky     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2433f22ef01cSRoman Divacky     // list, and remove it from DeferredDecls (since we don't need it anymore).
2434f37b6182SDimitry Andric     addDeferredDeclToEmit(DDI->second);
2435f22ef01cSRoman Divacky     DeferredDecls.erase(DDI);
2436f22ef01cSRoman Divacky   }
2437f22ef01cSRoman Divacky 
2438f22ef01cSRoman Divacky   // Handle things which are present even on external declarations.
2439f22ef01cSRoman Divacky   if (D) {
2440f22ef01cSRoman Divacky     // FIXME: This code is overly simple and should be merged with other global
2441f22ef01cSRoman Divacky     // handling.
2442dff0c46cSDimitry Andric     GV->setConstant(isTypeConstant(D->getType(), false));
2443f22ef01cSRoman Divacky 
244433956c43SDimitry Andric     GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
244533956c43SDimitry Andric 
24469a199699SDimitry Andric     setLinkageForGV(GV, D);
24479a199699SDimitry Andric     setGlobalVisibility(GV, D, NotForDefinition);
24482754fe60SDimitry Andric 
2449284c1978SDimitry Andric     if (D->getTLSKind()) {
2450284c1978SDimitry Andric       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
24510623d748SDimitry Andric         CXXThreadLocals.push_back(D);
24527ae0e2c9SDimitry Andric       setTLSMode(GV, *D);
2453f22ef01cSRoman Divacky     }
2454f785676fSDimitry Andric 
2455f785676fSDimitry Andric     // If required by the ABI, treat declarations of static data members with
2456f785676fSDimitry Andric     // inline initializers as definitions.
245759d1ed5bSDimitry Andric     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
2458f785676fSDimitry Andric       EmitGlobalVarDefinition(D);
2459284c1978SDimitry Andric     }
2460f22ef01cSRoman Divacky 
24619a199699SDimitry Andric     // Emit section information for extern variables.
24629a199699SDimitry Andric     if (D->hasExternalStorage()) {
24639a199699SDimitry Andric       if (const SectionAttr *SA = D->getAttr<SectionAttr>())
24649a199699SDimitry Andric         GV->setSection(SA->getName());
24659a199699SDimitry Andric     }
24669a199699SDimitry Andric 
246759d1ed5bSDimitry Andric     // Handle XCore specific ABI requirements.
246844290647SDimitry Andric     if (getTriple().getArch() == llvm::Triple::xcore &&
246959d1ed5bSDimitry Andric         D->getLanguageLinkage() == CLanguageLinkage &&
247059d1ed5bSDimitry Andric         D->getType().isConstant(Context) &&
247159d1ed5bSDimitry Andric         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
247259d1ed5bSDimitry Andric       GV->setSection(".cp.rodata");
24739a199699SDimitry Andric 
24749a199699SDimitry Andric     // Check if we a have a const declaration with an initializer, we may be
24759a199699SDimitry Andric     // able to emit it as available_externally to expose it's value to the
24769a199699SDimitry Andric     // optimizer.
24779a199699SDimitry Andric     if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
24789a199699SDimitry Andric         D->getType().isConstQualified() && !GV->hasInitializer() &&
24799a199699SDimitry Andric         !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
24809a199699SDimitry Andric       const auto *Record =
24819a199699SDimitry Andric           Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
24829a199699SDimitry Andric       bool HasMutableFields = Record && Record->hasMutableFields();
24839a199699SDimitry Andric       if (!HasMutableFields) {
24849a199699SDimitry Andric         const VarDecl *InitDecl;
24859a199699SDimitry Andric         const Expr *InitExpr = D->getAnyInitializer(InitDecl);
24869a199699SDimitry Andric         if (InitExpr) {
24879a199699SDimitry Andric           ConstantEmitter emitter(*this);
24889a199699SDimitry Andric           llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
24899a199699SDimitry Andric           if (Init) {
24909a199699SDimitry Andric             auto *InitType = Init->getType();
24919a199699SDimitry Andric             if (GV->getType()->getElementType() != InitType) {
24929a199699SDimitry Andric               // The type of the initializer does not match the definition.
24939a199699SDimitry Andric               // This happens when an initializer has a different type from
24949a199699SDimitry Andric               // the type of the global (because of padding at the end of a
24959a199699SDimitry Andric               // structure for instance).
24969a199699SDimitry Andric               GV->setName(StringRef());
24979a199699SDimitry Andric               // Make a new global with the correct type, this is now guaranteed
24989a199699SDimitry Andric               // to work.
24999a199699SDimitry Andric               auto *NewGV = cast<llvm::GlobalVariable>(
25009a199699SDimitry Andric                   GetAddrOfGlobalVar(D, InitType, IsForDefinition));
25019a199699SDimitry Andric 
25029a199699SDimitry Andric               // Erase the old global, since it is no longer used.
25039a199699SDimitry Andric               cast<llvm::GlobalValue>(GV)->eraseFromParent();
25049a199699SDimitry Andric               GV = NewGV;
25059a199699SDimitry Andric             } else {
25069a199699SDimitry Andric               GV->setInitializer(Init);
25079a199699SDimitry Andric               GV->setConstant(true);
25089a199699SDimitry Andric               GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
25099a199699SDimitry Andric             }
25109a199699SDimitry Andric             emitter.finalize(GV);
25119a199699SDimitry Andric           }
25129a199699SDimitry Andric         }
25139a199699SDimitry Andric       }
25149a199699SDimitry Andric     }
251559d1ed5bSDimitry Andric   }
251659d1ed5bSDimitry Andric 
25179a199699SDimitry Andric   LangAS ExpectedAS =
2518c4394386SDimitry Andric       D ? D->getType().getAddressSpace()
25199a199699SDimitry Andric         : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
2520c4394386SDimitry Andric   assert(getContext().getTargetAddressSpace(ExpectedAS) ==
2521c4394386SDimitry Andric          Ty->getPointerAddressSpace());
2522c4394386SDimitry Andric   if (AddrSpace != ExpectedAS)
2523c4394386SDimitry Andric     return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
2524c4394386SDimitry Andric                                                        ExpectedAS, Ty);
2525f785676fSDimitry Andric 
2526f22ef01cSRoman Divacky   return GV;
2527f22ef01cSRoman Divacky }
2528f22ef01cSRoman Divacky 
25290623d748SDimitry Andric llvm::Constant *
25300623d748SDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
253144290647SDimitry Andric                                ForDefinition_t IsForDefinition) {
253244290647SDimitry Andric   const Decl *D = GD.getDecl();
253344290647SDimitry Andric   if (isa<CXXConstructorDecl>(D))
253444290647SDimitry Andric     return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
25350623d748SDimitry Andric                                 getFromCtorType(GD.getCtorType()),
25360623d748SDimitry Andric                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
25370623d748SDimitry Andric                                 /*DontDefer=*/false, IsForDefinition);
253844290647SDimitry Andric   else if (isa<CXXDestructorDecl>(D))
253944290647SDimitry Andric     return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
25400623d748SDimitry Andric                                 getFromDtorType(GD.getDtorType()),
25410623d748SDimitry Andric                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
25420623d748SDimitry Andric                                 /*DontDefer=*/false, IsForDefinition);
254344290647SDimitry Andric   else if (isa<CXXMethodDecl>(D)) {
25440623d748SDimitry Andric     auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
254544290647SDimitry Andric         cast<CXXMethodDecl>(D));
25460623d748SDimitry Andric     auto Ty = getTypes().GetFunctionType(*FInfo);
25470623d748SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
25480623d748SDimitry Andric                              IsForDefinition);
254944290647SDimitry Andric   } else if (isa<FunctionDecl>(D)) {
25500623d748SDimitry Andric     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
25510623d748SDimitry Andric     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
25520623d748SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
25530623d748SDimitry Andric                              IsForDefinition);
25540623d748SDimitry Andric   } else
255544290647SDimitry Andric     return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
2556e7145dcbSDimitry Andric                               IsForDefinition);
25570623d748SDimitry Andric }
2558f22ef01cSRoman Divacky 
25592754fe60SDimitry Andric llvm::GlobalVariable *
25606122f3e6SDimitry Andric CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
25616122f3e6SDimitry Andric                                       llvm::Type *Ty,
25622754fe60SDimitry Andric                                       llvm::GlobalValue::LinkageTypes Linkage) {
25632754fe60SDimitry Andric   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
256459d1ed5bSDimitry Andric   llvm::GlobalVariable *OldGV = nullptr;
25652754fe60SDimitry Andric 
25662754fe60SDimitry Andric   if (GV) {
25672754fe60SDimitry Andric     // Check if the variable has the right type.
25682754fe60SDimitry Andric     if (GV->getType()->getElementType() == Ty)
25692754fe60SDimitry Andric       return GV;
25702754fe60SDimitry Andric 
25712754fe60SDimitry Andric     // Because C++ name mangling, the only way we can end up with an already
25722754fe60SDimitry Andric     // existing global with the same name is if it has been declared extern "C".
25732754fe60SDimitry Andric     assert(GV->isDeclaration() && "Declaration has wrong type!");
25742754fe60SDimitry Andric     OldGV = GV;
25752754fe60SDimitry Andric   }
25762754fe60SDimitry Andric 
25772754fe60SDimitry Andric   // Create a new variable.
25782754fe60SDimitry Andric   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
257959d1ed5bSDimitry Andric                                 Linkage, nullptr, Name);
25802754fe60SDimitry Andric 
25812754fe60SDimitry Andric   if (OldGV) {
25822754fe60SDimitry Andric     // Replace occurrences of the old variable if needed.
25832754fe60SDimitry Andric     GV->takeName(OldGV);
25842754fe60SDimitry Andric 
25852754fe60SDimitry Andric     if (!OldGV->use_empty()) {
25862754fe60SDimitry Andric       llvm::Constant *NewPtrForOldDecl =
25872754fe60SDimitry Andric       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
25882754fe60SDimitry Andric       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
25892754fe60SDimitry Andric     }
25902754fe60SDimitry Andric 
25912754fe60SDimitry Andric     OldGV->eraseFromParent();
25922754fe60SDimitry Andric   }
25932754fe60SDimitry Andric 
259433956c43SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker() &&
259533956c43SDimitry Andric       !GV->hasAvailableExternallyLinkage())
259633956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
259733956c43SDimitry Andric 
25982754fe60SDimitry Andric   return GV;
25992754fe60SDimitry Andric }
26002754fe60SDimitry Andric 
2601f22ef01cSRoman Divacky /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
2602f22ef01cSRoman Divacky /// given global variable.  If Ty is non-null and if the global doesn't exist,
2603cb4dff85SDimitry Andric /// then it will be created with the specified type instead of whatever the
2604e7145dcbSDimitry Andric /// normal requested type would be. If IsForDefinition is true, it is guranteed
2605e7145dcbSDimitry Andric /// that an actual global with type Ty will be returned, not conversion of a
2606e7145dcbSDimitry Andric /// variable with the same mangled name but some other type.
2607f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
2608e7145dcbSDimitry Andric                                                   llvm::Type *Ty,
260944290647SDimitry Andric                                            ForDefinition_t IsForDefinition) {
2610f22ef01cSRoman Divacky   assert(D->hasGlobalStorage() && "Not a global variable");
2611f22ef01cSRoman Divacky   QualType ASTTy = D->getType();
261259d1ed5bSDimitry Andric   if (!Ty)
2613f22ef01cSRoman Divacky     Ty = getTypes().ConvertTypeForMem(ASTTy);
2614f22ef01cSRoman Divacky 
26156122f3e6SDimitry Andric   llvm::PointerType *PTy =
26163b0f4066SDimitry Andric     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
2617f22ef01cSRoman Divacky 
26186122f3e6SDimitry Andric   StringRef MangledName = getMangledName(D);
2619e7145dcbSDimitry Andric   return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
2620f22ef01cSRoman Divacky }
2621f22ef01cSRoman Divacky 
2622f22ef01cSRoman Divacky /// CreateRuntimeVariable - Create a new runtime global variable with the
2623f22ef01cSRoman Divacky /// specified type and name.
2624f22ef01cSRoman Divacky llvm::Constant *
26256122f3e6SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
26266122f3e6SDimitry Andric                                      StringRef Name) {
262759d1ed5bSDimitry Andric   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
2628f22ef01cSRoman Divacky }
2629f22ef01cSRoman Divacky 
2630f22ef01cSRoman Divacky void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
2631f22ef01cSRoman Divacky   assert(!D->getInit() && "Cannot emit definite definitions here!");
2632f22ef01cSRoman Divacky 
26336122f3e6SDimitry Andric   StringRef MangledName = getMangledName(D);
2634e7145dcbSDimitry Andric   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
2635e7145dcbSDimitry Andric 
2636e7145dcbSDimitry Andric   // We already have a definition, not declaration, with the same mangled name.
2637e7145dcbSDimitry Andric   // Emitting of declaration is not required (and actually overwrites emitted
2638e7145dcbSDimitry Andric   // definition).
2639e7145dcbSDimitry Andric   if (GV && !GV->isDeclaration())
2640e7145dcbSDimitry Andric     return;
2641e7145dcbSDimitry Andric 
2642e7145dcbSDimitry Andric   // If we have not seen a reference to this variable yet, place it into the
2643e7145dcbSDimitry Andric   // deferred declarations table to be emitted if needed later.
2644e7145dcbSDimitry Andric   if (!MustBeEmitted(D) && !GV) {
2645f22ef01cSRoman Divacky       DeferredDecls[MangledName] = D;
2646f22ef01cSRoman Divacky       return;
2647f22ef01cSRoman Divacky   }
2648f22ef01cSRoman Divacky 
2649f22ef01cSRoman Divacky   // The tentative definition is the only definition.
2650f22ef01cSRoman Divacky   EmitGlobalVarDefinition(D);
2651f22ef01cSRoman Divacky }
2652f22ef01cSRoman Divacky 
26536122f3e6SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
26542754fe60SDimitry Andric   return Context.toCharUnitsFromBits(
26550623d748SDimitry Andric       getDataLayout().getTypeStoreSizeInBits(Ty));
2656f22ef01cSRoman Divacky }
2657f22ef01cSRoman Divacky 
26589a199699SDimitry Andric LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
26599a199699SDimitry Andric   LangAS AddrSpace = LangAS::Default;
2660c4394386SDimitry Andric   if (LangOpts.OpenCL) {
26619a199699SDimitry Andric     AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
2662c4394386SDimitry Andric     assert(AddrSpace == LangAS::opencl_global ||
2663c4394386SDimitry Andric            AddrSpace == LangAS::opencl_constant ||
2664c4394386SDimitry Andric            AddrSpace == LangAS::opencl_local ||
2665c4394386SDimitry Andric            AddrSpace >= LangAS::FirstTargetAddressSpace);
2666c4394386SDimitry Andric     return AddrSpace;
26677ae0e2c9SDimitry Andric   }
26687ae0e2c9SDimitry Andric 
2669c4394386SDimitry Andric   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
2670c4394386SDimitry Andric     if (D && D->hasAttr<CUDAConstantAttr>())
2671c4394386SDimitry Andric       return LangAS::cuda_constant;
2672c4394386SDimitry Andric     else if (D && D->hasAttr<CUDASharedAttr>())
2673c4394386SDimitry Andric       return LangAS::cuda_shared;
2674c4394386SDimitry Andric     else
2675c4394386SDimitry Andric       return LangAS::cuda_device;
2676c4394386SDimitry Andric   }
2677c4394386SDimitry Andric 
2678c4394386SDimitry Andric   return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
26797ae0e2c9SDimitry Andric }
26807ae0e2c9SDimitry Andric 
2681284c1978SDimitry Andric template<typename SomeDecl>
2682284c1978SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
2683284c1978SDimitry Andric                                                llvm::GlobalValue *GV) {
2684284c1978SDimitry Andric   if (!getLangOpts().CPlusPlus)
2685284c1978SDimitry Andric     return;
2686284c1978SDimitry Andric 
2687284c1978SDimitry Andric   // Must have 'used' attribute, or else inline assembly can't rely on
2688284c1978SDimitry Andric   // the name existing.
2689284c1978SDimitry Andric   if (!D->template hasAttr<UsedAttr>())
2690284c1978SDimitry Andric     return;
2691284c1978SDimitry Andric 
2692284c1978SDimitry Andric   // Must have internal linkage and an ordinary name.
2693f785676fSDimitry Andric   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
2694284c1978SDimitry Andric     return;
2695284c1978SDimitry Andric 
2696284c1978SDimitry Andric   // Must be in an extern "C" context. Entities declared directly within
2697284c1978SDimitry Andric   // a record are not extern "C" even if the record is in such a context.
2698f785676fSDimitry Andric   const SomeDecl *First = D->getFirstDecl();
2699284c1978SDimitry Andric   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
2700284c1978SDimitry Andric     return;
2701284c1978SDimitry Andric 
2702284c1978SDimitry Andric   // OK, this is an internal linkage entity inside an extern "C" linkage
2703284c1978SDimitry Andric   // specification. Make a note of that so we can give it the "expected"
2704284c1978SDimitry Andric   // mangled name if nothing else is using that name.
2705284c1978SDimitry Andric   std::pair<StaticExternCMap::iterator, bool> R =
2706284c1978SDimitry Andric       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
2707284c1978SDimitry Andric 
2708284c1978SDimitry Andric   // If we have multiple internal linkage entities with the same name
2709284c1978SDimitry Andric   // in extern "C" regions, none of them gets that name.
2710284c1978SDimitry Andric   if (!R.second)
271159d1ed5bSDimitry Andric     R.first->second = nullptr;
2712284c1978SDimitry Andric }
2713284c1978SDimitry Andric 
271433956c43SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
271533956c43SDimitry Andric   if (!CGM.supportsCOMDAT())
271633956c43SDimitry Andric     return false;
271733956c43SDimitry Andric 
271833956c43SDimitry Andric   if (D.hasAttr<SelectAnyAttr>())
271933956c43SDimitry Andric     return true;
272033956c43SDimitry Andric 
272133956c43SDimitry Andric   GVALinkage Linkage;
272233956c43SDimitry Andric   if (auto *VD = dyn_cast<VarDecl>(&D))
272333956c43SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
272433956c43SDimitry Andric   else
272533956c43SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
272633956c43SDimitry Andric 
272733956c43SDimitry Andric   switch (Linkage) {
272833956c43SDimitry Andric   case GVA_Internal:
272933956c43SDimitry Andric   case GVA_AvailableExternally:
273033956c43SDimitry Andric   case GVA_StrongExternal:
273133956c43SDimitry Andric     return false;
273233956c43SDimitry Andric   case GVA_DiscardableODR:
273333956c43SDimitry Andric   case GVA_StrongODR:
273433956c43SDimitry Andric     return true;
273533956c43SDimitry Andric   }
273633956c43SDimitry Andric   llvm_unreachable("No such linkage");
273733956c43SDimitry Andric }
273833956c43SDimitry Andric 
273933956c43SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
274033956c43SDimitry Andric                                           llvm::GlobalObject &GO) {
274133956c43SDimitry Andric   if (!shouldBeInCOMDAT(*this, D))
274233956c43SDimitry Andric     return;
274333956c43SDimitry Andric   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
274433956c43SDimitry Andric }
274533956c43SDimitry Andric 
2746e7145dcbSDimitry Andric /// Pass IsTentative as true if you want to create a tentative definition.
2747e7145dcbSDimitry Andric void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
2748e7145dcbSDimitry Andric                                             bool IsTentative) {
274944290647SDimitry Andric   // OpenCL global variables of sampler type are translated to function calls,
275044290647SDimitry Andric   // therefore no need to be translated.
2751f22ef01cSRoman Divacky   QualType ASTTy = D->getType();
275244290647SDimitry Andric   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
275344290647SDimitry Andric     return;
275444290647SDimitry Andric 
275544290647SDimitry Andric   llvm::Constant *Init = nullptr;
2756dff0c46cSDimitry Andric   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2757dff0c46cSDimitry Andric   bool NeedsGlobalCtor = false;
2758dff0c46cSDimitry Andric   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
2759f22ef01cSRoman Divacky 
2760dff0c46cSDimitry Andric   const VarDecl *InitDecl;
2761dff0c46cSDimitry Andric   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2762f22ef01cSRoman Divacky 
27639a199699SDimitry Andric   Optional<ConstantEmitter> emitter;
27649a199699SDimitry Andric 
2765e7145dcbSDimitry Andric   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
2766e7145dcbSDimitry Andric   // as part of their declaration."  Sema has already checked for
2767e7145dcbSDimitry Andric   // error cases, so we just need to set Init to UndefValue.
2768e7145dcbSDimitry Andric   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
2769e7145dcbSDimitry Andric       D->hasAttr<CUDASharedAttr>())
27700623d748SDimitry Andric     Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
2771e7145dcbSDimitry Andric   else if (!InitExpr) {
2772f22ef01cSRoman Divacky     // This is a tentative definition; tentative definitions are
2773f22ef01cSRoman Divacky     // implicitly initialized with { 0 }.
2774f22ef01cSRoman Divacky     //
2775f22ef01cSRoman Divacky     // Note that tentative definitions are only emitted at the end of
2776f22ef01cSRoman Divacky     // a translation unit, so they should never have incomplete
2777f22ef01cSRoman Divacky     // type. In addition, EmitTentativeDefinition makes sure that we
2778f22ef01cSRoman Divacky     // never attempt to emit a tentative definition if a real one
2779f22ef01cSRoman Divacky     // exists. A use may still exists, however, so we still may need
2780f22ef01cSRoman Divacky     // to do a RAUW.
2781f22ef01cSRoman Divacky     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
2782f22ef01cSRoman Divacky     Init = EmitNullConstant(D->getType());
2783f22ef01cSRoman Divacky   } else {
27847ae0e2c9SDimitry Andric     initializedGlobalDecl = GlobalDecl(D);
27859a199699SDimitry Andric     emitter.emplace(*this);
27869a199699SDimitry Andric     Init = emitter->tryEmitForInitializer(*InitDecl);
2787f785676fSDimitry Andric 
2788f22ef01cSRoman Divacky     if (!Init) {
2789f22ef01cSRoman Divacky       QualType T = InitExpr->getType();
2790f22ef01cSRoman Divacky       if (D->getType()->isReferenceType())
2791f22ef01cSRoman Divacky         T = D->getType();
2792f22ef01cSRoman Divacky 
2793dff0c46cSDimitry Andric       if (getLangOpts().CPlusPlus) {
2794f22ef01cSRoman Divacky         Init = EmitNullConstant(T);
2795dff0c46cSDimitry Andric         NeedsGlobalCtor = true;
2796f22ef01cSRoman Divacky       } else {
2797f22ef01cSRoman Divacky         ErrorUnsupported(D, "static initializer");
2798f22ef01cSRoman Divacky         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2799f22ef01cSRoman Divacky       }
2800e580952dSDimitry Andric     } else {
2801e580952dSDimitry Andric       // We don't need an initializer, so remove the entry for the delayed
2802dff0c46cSDimitry Andric       // initializer position (just in case this entry was delayed) if we
2803dff0c46cSDimitry Andric       // also don't need to register a destructor.
2804dff0c46cSDimitry Andric       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
2805e580952dSDimitry Andric         DelayedCXXInitPosition.erase(D);
2806f22ef01cSRoman Divacky     }
2807f22ef01cSRoman Divacky   }
2808f22ef01cSRoman Divacky 
28096122f3e6SDimitry Andric   llvm::Type* InitType = Init->getType();
2810e7145dcbSDimitry Andric   llvm::Constant *Entry =
281144290647SDimitry Andric       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
2812f22ef01cSRoman Divacky 
2813f22ef01cSRoman Divacky   // Strip off a bitcast if we got one back.
281459d1ed5bSDimitry Andric   if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2815f22ef01cSRoman Divacky     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2816f785676fSDimitry Andric            CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2817f785676fSDimitry Andric            // All zero index gep.
2818f22ef01cSRoman Divacky            CE->getOpcode() == llvm::Instruction::GetElementPtr);
2819f22ef01cSRoman Divacky     Entry = CE->getOperand(0);
2820f22ef01cSRoman Divacky   }
2821f22ef01cSRoman Divacky 
2822f22ef01cSRoman Divacky   // Entry is now either a Function or GlobalVariable.
282359d1ed5bSDimitry Andric   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2824f22ef01cSRoman Divacky 
2825f22ef01cSRoman Divacky   // We have a definition after a declaration with the wrong type.
2826f22ef01cSRoman Divacky   // We must make a new GlobalVariable* and update everything that used OldGV
2827f22ef01cSRoman Divacky   // (a declaration or tentative definition) with the new GlobalVariable*
2828f22ef01cSRoman Divacky   // (which will be a definition).
2829f22ef01cSRoman Divacky   //
2830f22ef01cSRoman Divacky   // This happens if there is a prototype for a global (e.g.
2831f22ef01cSRoman Divacky   // "extern int x[];") and then a definition of a different type (e.g.
2832f22ef01cSRoman Divacky   // "int x[10];"). This also happens when an initializer has a different type
2833f22ef01cSRoman Divacky   // from the type of the global (this happens with unions).
2834c4394386SDimitry Andric   if (!GV || GV->getType()->getElementType() != InitType ||
28353b0f4066SDimitry Andric       GV->getType()->getAddressSpace() !=
2836c4394386SDimitry Andric           getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
2837f22ef01cSRoman Divacky 
2838f22ef01cSRoman Divacky     // Move the old entry aside so that we'll create a new one.
28396122f3e6SDimitry Andric     Entry->setName(StringRef());
2840f22ef01cSRoman Divacky 
2841f22ef01cSRoman Divacky     // Make a new global with the correct type, this is now guaranteed to work.
2842e7145dcbSDimitry Andric     GV = cast<llvm::GlobalVariable>(
284344290647SDimitry Andric         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
2844f22ef01cSRoman Divacky 
2845f22ef01cSRoman Divacky     // Replace all uses of the old global with the new global
2846f22ef01cSRoman Divacky     llvm::Constant *NewPtrForOldDecl =
2847f22ef01cSRoman Divacky         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2848f22ef01cSRoman Divacky     Entry->replaceAllUsesWith(NewPtrForOldDecl);
2849f22ef01cSRoman Divacky 
2850f22ef01cSRoman Divacky     // Erase the old global, since it is no longer used.
2851f22ef01cSRoman Divacky     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2852f22ef01cSRoman Divacky   }
2853f22ef01cSRoman Divacky 
2854284c1978SDimitry Andric   MaybeHandleStaticInExternC(D, GV);
2855284c1978SDimitry Andric 
28566122f3e6SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
28576122f3e6SDimitry Andric     AddGlobalAnnotations(D, GV);
2858f22ef01cSRoman Divacky 
2859e7145dcbSDimitry Andric   // Set the llvm linkage type as appropriate.
2860e7145dcbSDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
2861e7145dcbSDimitry Andric       getLLVMLinkageVarDefinition(D, GV->isConstant());
2862e7145dcbSDimitry Andric 
28630623d748SDimitry Andric   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
28640623d748SDimitry Andric   // the device. [...]"
28650623d748SDimitry Andric   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
28660623d748SDimitry Andric   // __device__, declares a variable that: [...]
28670623d748SDimitry Andric   // Is accessible from all the threads within the grid and from the host
28680623d748SDimitry Andric   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
28690623d748SDimitry Andric   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
2870e7145dcbSDimitry Andric   if (GV && LangOpts.CUDA) {
2871e7145dcbSDimitry Andric     if (LangOpts.CUDAIsDevice) {
2872e7145dcbSDimitry Andric       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
28730623d748SDimitry Andric         GV->setExternallyInitialized(true);
2874e7145dcbSDimitry Andric     } else {
2875e7145dcbSDimitry Andric       // Host-side shadows of external declarations of device-side
2876e7145dcbSDimitry Andric       // global variables become internal definitions. These have to
2877e7145dcbSDimitry Andric       // be internal in order to prevent name conflicts with global
2878e7145dcbSDimitry Andric       // host variables with the same name in a different TUs.
2879e7145dcbSDimitry Andric       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
2880e7145dcbSDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
2881e7145dcbSDimitry Andric 
2882e7145dcbSDimitry Andric         // Shadow variables and their properties must be registered
2883e7145dcbSDimitry Andric         // with CUDA runtime.
2884e7145dcbSDimitry Andric         unsigned Flags = 0;
2885e7145dcbSDimitry Andric         if (!D->hasDefinition())
2886e7145dcbSDimitry Andric           Flags |= CGCUDARuntime::ExternDeviceVar;
2887e7145dcbSDimitry Andric         if (D->hasAttr<CUDAConstantAttr>())
2888e7145dcbSDimitry Andric           Flags |= CGCUDARuntime::ConstantDeviceVar;
2889e7145dcbSDimitry Andric         getCUDARuntime().registerDeviceVar(*GV, Flags);
2890e7145dcbSDimitry Andric       } else if (D->hasAttr<CUDASharedAttr>())
2891e7145dcbSDimitry Andric         // __shared__ variables are odd. Shadows do get created, but
2892e7145dcbSDimitry Andric         // they are not registered with the CUDA runtime, so they
2893e7145dcbSDimitry Andric         // can't really be used to access their device-side
2894e7145dcbSDimitry Andric         // counterparts. It's not clear yet whether it's nvcc's bug or
2895e7145dcbSDimitry Andric         // a feature, but we've got to do the same for compatibility.
2896e7145dcbSDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
2897e7145dcbSDimitry Andric     }
28980623d748SDimitry Andric   }
28999a199699SDimitry Andric 
2900f22ef01cSRoman Divacky   GV->setInitializer(Init);
29019a199699SDimitry Andric   if (emitter) emitter->finalize(GV);
2902f22ef01cSRoman Divacky 
2903f22ef01cSRoman Divacky   // If it is safe to mark the global 'constant', do so now.
2904dff0c46cSDimitry Andric   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2905dff0c46cSDimitry Andric                   isTypeConstant(D->getType(), true));
2906f22ef01cSRoman Divacky 
290739d628a0SDimitry Andric   // If it is in a read-only section, mark it 'constant'.
290839d628a0SDimitry Andric   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
290939d628a0SDimitry Andric     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
291039d628a0SDimitry Andric     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
291139d628a0SDimitry Andric       GV->setConstant(true);
291239d628a0SDimitry Andric   }
291339d628a0SDimitry Andric 
2914f22ef01cSRoman Divacky   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2915f22ef01cSRoman Divacky 
2916f785676fSDimitry Andric 
29170623d748SDimitry Andric   // On Darwin, if the normal linkage of a C++ thread_local variable is
29180623d748SDimitry Andric   // LinkOnce or Weak, we keep the normal linkage to prevent multiple
29190623d748SDimitry Andric   // copies within a linkage unit; otherwise, the backing variable has
29200623d748SDimitry Andric   // internal linkage and all accesses should just be calls to the
292159d1ed5bSDimitry Andric   // Itanium-specified entry point, which has the normal linkage of the
29220623d748SDimitry Andric   // variable. This is to preserve the ability to change the implementation
29230623d748SDimitry Andric   // behind the scenes.
292439d628a0SDimitry Andric   if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
29250623d748SDimitry Andric       Context.getTargetInfo().getTriple().isOSDarwin() &&
29260623d748SDimitry Andric       !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
29270623d748SDimitry Andric       !llvm::GlobalVariable::isWeakLinkage(Linkage))
292859d1ed5bSDimitry Andric     Linkage = llvm::GlobalValue::InternalLinkage;
292959d1ed5bSDimitry Andric 
293059d1ed5bSDimitry Andric   GV->setLinkage(Linkage);
293159d1ed5bSDimitry Andric   if (D->hasAttr<DLLImportAttr>())
293259d1ed5bSDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
293359d1ed5bSDimitry Andric   else if (D->hasAttr<DLLExportAttr>())
293459d1ed5bSDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
293539d628a0SDimitry Andric   else
293639d628a0SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2937f785676fSDimitry Andric 
293844290647SDimitry Andric   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
2939f22ef01cSRoman Divacky     // common vars aren't constant even if declared const.
2940f22ef01cSRoman Divacky     GV->setConstant(false);
294144290647SDimitry Andric     // Tentative definition of global variables may be initialized with
294244290647SDimitry Andric     // non-zero null pointers. In this case they should have weak linkage
294344290647SDimitry Andric     // since common linkage must have zero initializer and must not have
294444290647SDimitry Andric     // explicit section therefore cannot have non-zero initial value.
294544290647SDimitry Andric     if (!GV->getInitializer()->isNullValue())
294644290647SDimitry Andric       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
294744290647SDimitry Andric   }
2948f22ef01cSRoman Divacky 
294959d1ed5bSDimitry Andric   setNonAliasAttributes(D, GV);
2950f22ef01cSRoman Divacky 
295139d628a0SDimitry Andric   if (D->getTLSKind() && !GV->isThreadLocal()) {
295239d628a0SDimitry Andric     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
29530623d748SDimitry Andric       CXXThreadLocals.push_back(D);
295439d628a0SDimitry Andric     setTLSMode(GV, *D);
295539d628a0SDimitry Andric   }
295639d628a0SDimitry Andric 
295733956c43SDimitry Andric   maybeSetTrivialComdat(*D, *GV);
295833956c43SDimitry Andric 
29592754fe60SDimitry Andric   // Emit the initializer function if necessary.
2960dff0c46cSDimitry Andric   if (NeedsGlobalCtor || NeedsGlobalDtor)
2961dff0c46cSDimitry Andric     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
29622754fe60SDimitry Andric 
296339d628a0SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
29643861d79fSDimitry Andric 
2965f22ef01cSRoman Divacky   // Emit global variable debug information.
29666122f3e6SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
2967e7145dcbSDimitry Andric     if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
2968f22ef01cSRoman Divacky       DI->EmitGlobalVariable(GV, D);
2969f22ef01cSRoman Divacky }
2970f22ef01cSRoman Divacky 
297139d628a0SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context,
297233956c43SDimitry Andric                                       CodeGenModule &CGM, const VarDecl *D,
297333956c43SDimitry Andric                                       bool NoCommon) {
297459d1ed5bSDimitry Andric   // Don't give variables common linkage if -fno-common was specified unless it
297559d1ed5bSDimitry Andric   // was overridden by a NoCommon attribute.
297659d1ed5bSDimitry Andric   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
297759d1ed5bSDimitry Andric     return true;
297859d1ed5bSDimitry Andric 
297959d1ed5bSDimitry Andric   // C11 6.9.2/2:
298059d1ed5bSDimitry Andric   //   A declaration of an identifier for an object that has file scope without
298159d1ed5bSDimitry Andric   //   an initializer, and without a storage-class specifier or with the
298259d1ed5bSDimitry Andric   //   storage-class specifier static, constitutes a tentative definition.
298359d1ed5bSDimitry Andric   if (D->getInit() || D->hasExternalStorage())
298459d1ed5bSDimitry Andric     return true;
298559d1ed5bSDimitry Andric 
298659d1ed5bSDimitry Andric   // A variable cannot be both common and exist in a section.
298759d1ed5bSDimitry Andric   if (D->hasAttr<SectionAttr>())
298859d1ed5bSDimitry Andric     return true;
298959d1ed5bSDimitry Andric 
2990db17bf38SDimitry Andric   // A variable cannot be both common and exist in a section.
2991db17bf38SDimitry Andric   // We dont try to determine which is the right section in the front-end.
2992db17bf38SDimitry Andric   // If no specialized section name is applicable, it will resort to default.
2993db17bf38SDimitry Andric   if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
2994db17bf38SDimitry Andric       D->hasAttr<PragmaClangDataSectionAttr>() ||
2995db17bf38SDimitry Andric       D->hasAttr<PragmaClangRodataSectionAttr>())
2996db17bf38SDimitry Andric     return true;
2997db17bf38SDimitry Andric 
299859d1ed5bSDimitry Andric   // Thread local vars aren't considered common linkage.
299959d1ed5bSDimitry Andric   if (D->getTLSKind())
300059d1ed5bSDimitry Andric     return true;
300159d1ed5bSDimitry Andric 
300259d1ed5bSDimitry Andric   // Tentative definitions marked with WeakImportAttr are true definitions.
300359d1ed5bSDimitry Andric   if (D->hasAttr<WeakImportAttr>())
300459d1ed5bSDimitry Andric     return true;
300559d1ed5bSDimitry Andric 
300633956c43SDimitry Andric   // A variable cannot be both common and exist in a comdat.
300733956c43SDimitry Andric   if (shouldBeInCOMDAT(CGM, *D))
300833956c43SDimitry Andric     return true;
300933956c43SDimitry Andric 
3010e7145dcbSDimitry Andric   // Declarations with a required alignment do not have common linkage in MSVC
301139d628a0SDimitry Andric   // mode.
30120623d748SDimitry Andric   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
301333956c43SDimitry Andric     if (D->hasAttr<AlignedAttr>())
301439d628a0SDimitry Andric       return true;
301533956c43SDimitry Andric     QualType VarType = D->getType();
301633956c43SDimitry Andric     if (Context.isAlignmentRequired(VarType))
301733956c43SDimitry Andric       return true;
301833956c43SDimitry Andric 
301933956c43SDimitry Andric     if (const auto *RT = VarType->getAs<RecordType>()) {
302033956c43SDimitry Andric       const RecordDecl *RD = RT->getDecl();
302133956c43SDimitry Andric       for (const FieldDecl *FD : RD->fields()) {
302233956c43SDimitry Andric         if (FD->isBitField())
302333956c43SDimitry Andric           continue;
302433956c43SDimitry Andric         if (FD->hasAttr<AlignedAttr>())
302533956c43SDimitry Andric           return true;
302633956c43SDimitry Andric         if (Context.isAlignmentRequired(FD->getType()))
302733956c43SDimitry Andric           return true;
302833956c43SDimitry Andric       }
302933956c43SDimitry Andric     }
303033956c43SDimitry Andric   }
303139d628a0SDimitry Andric 
303259d1ed5bSDimitry Andric   return false;
303359d1ed5bSDimitry Andric }
303459d1ed5bSDimitry Andric 
303559d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
303659d1ed5bSDimitry Andric     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
30372754fe60SDimitry Andric   if (Linkage == GVA_Internal)
30382754fe60SDimitry Andric     return llvm::Function::InternalLinkage;
303959d1ed5bSDimitry Andric 
304059d1ed5bSDimitry Andric   if (D->hasAttr<WeakAttr>()) {
304159d1ed5bSDimitry Andric     if (IsConstantVariable)
304259d1ed5bSDimitry Andric       return llvm::GlobalVariable::WeakODRLinkage;
304359d1ed5bSDimitry Andric     else
304459d1ed5bSDimitry Andric       return llvm::GlobalVariable::WeakAnyLinkage;
304559d1ed5bSDimitry Andric   }
304659d1ed5bSDimitry Andric 
304759d1ed5bSDimitry Andric   // We are guaranteed to have a strong definition somewhere else,
304859d1ed5bSDimitry Andric   // so we can use available_externally linkage.
304959d1ed5bSDimitry Andric   if (Linkage == GVA_AvailableExternally)
305020e90f04SDimitry Andric     return llvm::GlobalValue::AvailableExternallyLinkage;
305159d1ed5bSDimitry Andric 
305259d1ed5bSDimitry Andric   // Note that Apple's kernel linker doesn't support symbol
305359d1ed5bSDimitry Andric   // coalescing, so we need to avoid linkonce and weak linkages there.
305459d1ed5bSDimitry Andric   // Normally, this means we just map to internal, but for explicit
305559d1ed5bSDimitry Andric   // instantiations we'll map to external.
305659d1ed5bSDimitry Andric 
305759d1ed5bSDimitry Andric   // In C++, the compiler has to emit a definition in every translation unit
305859d1ed5bSDimitry Andric   // that references the function.  We should use linkonce_odr because
305959d1ed5bSDimitry Andric   // a) if all references in this translation unit are optimized away, we
306059d1ed5bSDimitry Andric   // don't need to codegen it.  b) if the function persists, it needs to be
306159d1ed5bSDimitry Andric   // merged with other definitions. c) C++ has the ODR, so we know the
306259d1ed5bSDimitry Andric   // definition is dependable.
306359d1ed5bSDimitry Andric   if (Linkage == GVA_DiscardableODR)
306459d1ed5bSDimitry Andric     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
306559d1ed5bSDimitry Andric                                             : llvm::Function::InternalLinkage;
306659d1ed5bSDimitry Andric 
306759d1ed5bSDimitry Andric   // An explicit instantiation of a template has weak linkage, since
306859d1ed5bSDimitry Andric   // explicit instantiations can occur in multiple translation units
306959d1ed5bSDimitry Andric   // and must all be equivalent. However, we are not allowed to
307059d1ed5bSDimitry Andric   // throw away these explicit instantiations.
3071e7145dcbSDimitry Andric   //
3072e7145dcbSDimitry Andric   // We don't currently support CUDA device code spread out across multiple TUs,
3073e7145dcbSDimitry Andric   // so say that CUDA templates are either external (for kernels) or internal.
3074e7145dcbSDimitry Andric   // This lets llvm perform aggressive inter-procedural optimizations.
3075e7145dcbSDimitry Andric   if (Linkage == GVA_StrongODR) {
3076e7145dcbSDimitry Andric     if (Context.getLangOpts().AppleKext)
3077e7145dcbSDimitry Andric       return llvm::Function::ExternalLinkage;
3078e7145dcbSDimitry Andric     if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
3079e7145dcbSDimitry Andric       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
3080e7145dcbSDimitry Andric                                           : llvm::Function::InternalLinkage;
3081e7145dcbSDimitry Andric     return llvm::Function::WeakODRLinkage;
3082e7145dcbSDimitry Andric   }
308359d1ed5bSDimitry Andric 
308459d1ed5bSDimitry Andric   // C++ doesn't have tentative definitions and thus cannot have common
308559d1ed5bSDimitry Andric   // linkage.
308659d1ed5bSDimitry Andric   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
308733956c43SDimitry Andric       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
308839d628a0SDimitry Andric                                  CodeGenOpts.NoCommon))
308959d1ed5bSDimitry Andric     return llvm::GlobalVariable::CommonLinkage;
309059d1ed5bSDimitry Andric 
3091f785676fSDimitry Andric   // selectany symbols are externally visible, so use weak instead of
3092f785676fSDimitry Andric   // linkonce.  MSVC optimizes away references to const selectany globals, so
3093f785676fSDimitry Andric   // all definitions should be the same and ODR linkage should be used.
3094f785676fSDimitry Andric   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
309559d1ed5bSDimitry Andric   if (D->hasAttr<SelectAnyAttr>())
3096f785676fSDimitry Andric     return llvm::GlobalVariable::WeakODRLinkage;
309759d1ed5bSDimitry Andric 
309859d1ed5bSDimitry Andric   // Otherwise, we have strong external linkage.
309959d1ed5bSDimitry Andric   assert(Linkage == GVA_StrongExternal);
31002754fe60SDimitry Andric   return llvm::GlobalVariable::ExternalLinkage;
31012754fe60SDimitry Andric }
31022754fe60SDimitry Andric 
310359d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
310459d1ed5bSDimitry Andric     const VarDecl *VD, bool IsConstant) {
310559d1ed5bSDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
310659d1ed5bSDimitry Andric   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
310759d1ed5bSDimitry Andric }
310859d1ed5bSDimitry Andric 
3109139f7f9bSDimitry Andric /// Replace the uses of a function that was declared with a non-proto type.
3110139f7f9bSDimitry Andric /// We want to silently drop extra arguments from call sites
3111139f7f9bSDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
3112139f7f9bSDimitry Andric                                           llvm::Function *newFn) {
3113139f7f9bSDimitry Andric   // Fast path.
3114139f7f9bSDimitry Andric   if (old->use_empty()) return;
3115139f7f9bSDimitry Andric 
3116139f7f9bSDimitry Andric   llvm::Type *newRetTy = newFn->getReturnType();
3117139f7f9bSDimitry Andric   SmallVector<llvm::Value*, 4> newArgs;
31180623d748SDimitry Andric   SmallVector<llvm::OperandBundleDef, 1> newBundles;
3119139f7f9bSDimitry Andric 
3120139f7f9bSDimitry Andric   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
3121139f7f9bSDimitry Andric          ui != ue; ) {
3122139f7f9bSDimitry Andric     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
312359d1ed5bSDimitry Andric     llvm::User *user = use->getUser();
3124139f7f9bSDimitry Andric 
3125139f7f9bSDimitry Andric     // Recognize and replace uses of bitcasts.  Most calls to
3126139f7f9bSDimitry Andric     // unprototyped functions will use bitcasts.
312759d1ed5bSDimitry Andric     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
3128139f7f9bSDimitry Andric       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
3129139f7f9bSDimitry Andric         replaceUsesOfNonProtoConstant(bitcast, newFn);
3130139f7f9bSDimitry Andric       continue;
3131139f7f9bSDimitry Andric     }
3132139f7f9bSDimitry Andric 
3133139f7f9bSDimitry Andric     // Recognize calls to the function.
3134139f7f9bSDimitry Andric     llvm::CallSite callSite(user);
3135139f7f9bSDimitry Andric     if (!callSite) continue;
313659d1ed5bSDimitry Andric     if (!callSite.isCallee(&*use)) continue;
3137139f7f9bSDimitry Andric 
3138139f7f9bSDimitry Andric     // If the return types don't match exactly, then we can't
3139139f7f9bSDimitry Andric     // transform this call unless it's dead.
3140139f7f9bSDimitry Andric     if (callSite->getType() != newRetTy && !callSite->use_empty())
3141139f7f9bSDimitry Andric       continue;
3142139f7f9bSDimitry Andric 
3143139f7f9bSDimitry Andric     // Get the call site's attribute list.
314420e90f04SDimitry Andric     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
314520e90f04SDimitry Andric     llvm::AttributeList oldAttrs = callSite.getAttributes();
3146139f7f9bSDimitry Andric 
3147139f7f9bSDimitry Andric     // If the function was passed too few arguments, don't transform.
3148139f7f9bSDimitry Andric     unsigned newNumArgs = newFn->arg_size();
3149139f7f9bSDimitry Andric     if (callSite.arg_size() < newNumArgs) continue;
3150139f7f9bSDimitry Andric 
3151139f7f9bSDimitry Andric     // If extra arguments were passed, we silently drop them.
3152139f7f9bSDimitry Andric     // If any of the types mismatch, we don't transform.
3153139f7f9bSDimitry Andric     unsigned argNo = 0;
3154139f7f9bSDimitry Andric     bool dontTransform = false;
315520e90f04SDimitry Andric     for (llvm::Argument &A : newFn->args()) {
315620e90f04SDimitry Andric       if (callSite.getArgument(argNo)->getType() != A.getType()) {
3157139f7f9bSDimitry Andric         dontTransform = true;
3158139f7f9bSDimitry Andric         break;
3159139f7f9bSDimitry Andric       }
3160139f7f9bSDimitry Andric 
3161139f7f9bSDimitry Andric       // Add any parameter attributes.
316220e90f04SDimitry Andric       newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
316320e90f04SDimitry Andric       argNo++;
3164139f7f9bSDimitry Andric     }
3165139f7f9bSDimitry Andric     if (dontTransform)
3166139f7f9bSDimitry Andric       continue;
3167139f7f9bSDimitry Andric 
3168139f7f9bSDimitry Andric     // Okay, we can transform this.  Create the new call instruction and copy
3169139f7f9bSDimitry Andric     // over the required information.
3170139f7f9bSDimitry Andric     newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
3171139f7f9bSDimitry Andric 
31720623d748SDimitry Andric     // Copy over any operand bundles.
31730623d748SDimitry Andric     callSite.getOperandBundlesAsDefs(newBundles);
31740623d748SDimitry Andric 
3175139f7f9bSDimitry Andric     llvm::CallSite newCall;
3176139f7f9bSDimitry Andric     if (callSite.isCall()) {
31770623d748SDimitry Andric       newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
3178139f7f9bSDimitry Andric                                        callSite.getInstruction());
3179139f7f9bSDimitry Andric     } else {
318059d1ed5bSDimitry Andric       auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
3181139f7f9bSDimitry Andric       newCall = llvm::InvokeInst::Create(newFn,
3182139f7f9bSDimitry Andric                                          oldInvoke->getNormalDest(),
3183139f7f9bSDimitry Andric                                          oldInvoke->getUnwindDest(),
31840623d748SDimitry Andric                                          newArgs, newBundles, "",
3185139f7f9bSDimitry Andric                                          callSite.getInstruction());
3186139f7f9bSDimitry Andric     }
3187139f7f9bSDimitry Andric     newArgs.clear(); // for the next iteration
3188139f7f9bSDimitry Andric 
3189139f7f9bSDimitry Andric     if (!newCall->getType()->isVoidTy())
3190139f7f9bSDimitry Andric       newCall->takeName(callSite.getInstruction());
319120e90f04SDimitry Andric     newCall.setAttributes(llvm::AttributeList::get(
319220e90f04SDimitry Andric         newFn->getContext(), oldAttrs.getFnAttributes(),
319320e90f04SDimitry Andric         oldAttrs.getRetAttributes(), newArgAttrs));
3194139f7f9bSDimitry Andric     newCall.setCallingConv(callSite.getCallingConv());
3195139f7f9bSDimitry Andric 
3196139f7f9bSDimitry Andric     // Finally, remove the old call, replacing any uses with the new one.
3197139f7f9bSDimitry Andric     if (!callSite->use_empty())
3198139f7f9bSDimitry Andric       callSite->replaceAllUsesWith(newCall.getInstruction());
3199139f7f9bSDimitry Andric 
3200139f7f9bSDimitry Andric     // Copy debug location attached to CI.
320133956c43SDimitry Andric     if (callSite->getDebugLoc())
3202139f7f9bSDimitry Andric       newCall->setDebugLoc(callSite->getDebugLoc());
32030623d748SDimitry Andric 
3204139f7f9bSDimitry Andric     callSite->eraseFromParent();
3205139f7f9bSDimitry Andric   }
3206139f7f9bSDimitry Andric }
3207139f7f9bSDimitry Andric 
3208f22ef01cSRoman Divacky /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
3209f22ef01cSRoman Divacky /// implement a function with no prototype, e.g. "int foo() {}".  If there are
3210f22ef01cSRoman Divacky /// existing call uses of the old function in the module, this adjusts them to
3211f22ef01cSRoman Divacky /// call the new function directly.
3212f22ef01cSRoman Divacky ///
3213f22ef01cSRoman Divacky /// This is not just a cleanup: the always_inline pass requires direct calls to
3214f22ef01cSRoman Divacky /// functions to be able to inline them.  If there is a bitcast in the way, it
3215f22ef01cSRoman Divacky /// won't inline them.  Instcombine normally deletes these calls, but it isn't
3216f22ef01cSRoman Divacky /// run at -O0.
3217f22ef01cSRoman Divacky static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3218f22ef01cSRoman Divacky                                                       llvm::Function *NewFn) {
3219f22ef01cSRoman Divacky   // If we're redefining a global as a function, don't transform it.
3220139f7f9bSDimitry Andric   if (!isa<llvm::Function>(Old)) return;
3221f22ef01cSRoman Divacky 
3222139f7f9bSDimitry Andric   replaceUsesOfNonProtoConstant(Old, NewFn);
3223f22ef01cSRoman Divacky }
3224f22ef01cSRoman Divacky 
3225dff0c46cSDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
3226e7145dcbSDimitry Andric   auto DK = VD->isThisDeclarationADefinition();
3227e7145dcbSDimitry Andric   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
3228e7145dcbSDimitry Andric     return;
3229e7145dcbSDimitry Andric 
3230dff0c46cSDimitry Andric   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
3231dff0c46cSDimitry Andric   // If we have a definition, this might be a deferred decl. If the
3232dff0c46cSDimitry Andric   // instantiation is explicit, make sure we emit it at the end.
3233dff0c46cSDimitry Andric   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
3234dff0c46cSDimitry Andric     GetAddrOfGlobalVar(VD);
3235139f7f9bSDimitry Andric 
3236139f7f9bSDimitry Andric   EmitTopLevelDecl(VD);
3237dff0c46cSDimitry Andric }
3238f22ef01cSRoman Divacky 
323959d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
324059d1ed5bSDimitry Andric                                                  llvm::GlobalValue *GV) {
324159d1ed5bSDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
32423b0f4066SDimitry Andric 
32433b0f4066SDimitry Andric   // Compute the function info and LLVM type.
3244dff0c46cSDimitry Andric   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3245dff0c46cSDimitry Andric   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
32463b0f4066SDimitry Andric 
3247f22ef01cSRoman Divacky   // Get or create the prototype for the function.
32480623d748SDimitry Andric   if (!GV || (GV->getType()->getElementType() != Ty))
32490623d748SDimitry Andric     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
32500623d748SDimitry Andric                                                    /*DontDefer=*/true,
325144290647SDimitry Andric                                                    ForDefinition));
3252f22ef01cSRoman Divacky 
32530623d748SDimitry Andric   // Already emitted.
32540623d748SDimitry Andric   if (!GV->isDeclaration())
3255f785676fSDimitry Andric     return;
3256f22ef01cSRoman Divacky 
32572754fe60SDimitry Andric   // We need to set linkage and visibility on the function before
32582754fe60SDimitry Andric   // generating code for it because various parts of IR generation
32592754fe60SDimitry Andric   // want to propagate this information down (e.g. to local static
32602754fe60SDimitry Andric   // declarations).
326159d1ed5bSDimitry Andric   auto *Fn = cast<llvm::Function>(GV);
3262f785676fSDimitry Andric   setFunctionLinkage(GD, Fn);
326397bc6c73SDimitry Andric   setFunctionDLLStorageClass(GD, Fn);
3264f22ef01cSRoman Divacky 
326559d1ed5bSDimitry Andric   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
32669a199699SDimitry Andric   setGlobalVisibility(Fn, D, ForDefinition);
32672754fe60SDimitry Andric 
3268284c1978SDimitry Andric   MaybeHandleStaticInExternC(D, Fn);
3269284c1978SDimitry Andric 
327033956c43SDimitry Andric   maybeSetTrivialComdat(*D, *Fn);
327133956c43SDimitry Andric 
32723b0f4066SDimitry Andric   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
3273f22ef01cSRoman Divacky 
327459d1ed5bSDimitry Andric   setFunctionDefinitionAttributes(D, Fn);
3275f22ef01cSRoman Divacky   SetLLVMFunctionAttributesForDefinition(D, Fn);
3276f22ef01cSRoman Divacky 
3277f22ef01cSRoman Divacky   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
3278f22ef01cSRoman Divacky     AddGlobalCtor(Fn, CA->getPriority());
3279f22ef01cSRoman Divacky   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
3280f22ef01cSRoman Divacky     AddGlobalDtor(Fn, DA->getPriority());
32816122f3e6SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
32826122f3e6SDimitry Andric     AddGlobalAnnotations(D, Fn);
3283f22ef01cSRoman Divacky }
3284f22ef01cSRoman Divacky 
3285f22ef01cSRoman Divacky void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
328659d1ed5bSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
3287f22ef01cSRoman Divacky   const AliasAttr *AA = D->getAttr<AliasAttr>();
3288f22ef01cSRoman Divacky   assert(AA && "Not an alias?");
3289f22ef01cSRoman Divacky 
32906122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
3291f22ef01cSRoman Divacky 
32929a4b3118SDimitry Andric   if (AA->getAliasee() == MangledName) {
3293e7145dcbSDimitry Andric     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
32949a4b3118SDimitry Andric     return;
32959a4b3118SDimitry Andric   }
32969a4b3118SDimitry Andric 
3297f22ef01cSRoman Divacky   // If there is a definition in the module, then it wins over the alias.
3298f22ef01cSRoman Divacky   // This is dubious, but allow it to be safe.  Just ignore the alias.
3299f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3300f22ef01cSRoman Divacky   if (Entry && !Entry->isDeclaration())
3301f22ef01cSRoman Divacky     return;
3302f22ef01cSRoman Divacky 
3303f785676fSDimitry Andric   Aliases.push_back(GD);
3304f785676fSDimitry Andric 
33056122f3e6SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3306f22ef01cSRoman Divacky 
3307f22ef01cSRoman Divacky   // Create a reference to the named value.  This ensures that it is emitted
3308f22ef01cSRoman Divacky   // if a deferred decl.
3309f22ef01cSRoman Divacky   llvm::Constant *Aliasee;
3310f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(DeclTy))
33113861d79fSDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
33122754fe60SDimitry Andric                                       /*ForVTable=*/false);
3313f22ef01cSRoman Divacky   else
3314f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
331559d1ed5bSDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
331639d628a0SDimitry Andric                                     /*D=*/nullptr);
3317f22ef01cSRoman Divacky 
3318f22ef01cSRoman Divacky   // Create the new alias itself, but don't set a name yet.
331959d1ed5bSDimitry Andric   auto *GA = llvm::GlobalAlias::create(
33200623d748SDimitry Andric       DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
3321f22ef01cSRoman Divacky 
3322f22ef01cSRoman Divacky   if (Entry) {
332359d1ed5bSDimitry Andric     if (GA->getAliasee() == Entry) {
3324e7145dcbSDimitry Andric       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
332559d1ed5bSDimitry Andric       return;
332659d1ed5bSDimitry Andric     }
332759d1ed5bSDimitry Andric 
3328f22ef01cSRoman Divacky     assert(Entry->isDeclaration());
3329f22ef01cSRoman Divacky 
3330f22ef01cSRoman Divacky     // If there is a declaration in the module, then we had an extern followed
3331f22ef01cSRoman Divacky     // by the alias, as in:
3332f22ef01cSRoman Divacky     //   extern int test6();
3333f22ef01cSRoman Divacky     //   ...
3334f22ef01cSRoman Divacky     //   int test6() __attribute__((alias("test7")));
3335f22ef01cSRoman Divacky     //
3336f22ef01cSRoman Divacky     // Remove it and replace uses of it with the alias.
3337f22ef01cSRoman Divacky     GA->takeName(Entry);
3338f22ef01cSRoman Divacky 
3339f22ef01cSRoman Divacky     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
3340f22ef01cSRoman Divacky                                                           Entry->getType()));
3341f22ef01cSRoman Divacky     Entry->eraseFromParent();
3342f22ef01cSRoman Divacky   } else {
3343ffd1746dSEd Schouten     GA->setName(MangledName);
3344f22ef01cSRoman Divacky   }
3345f22ef01cSRoman Divacky 
3346f22ef01cSRoman Divacky   // Set attributes which are particular to an alias; this is a
3347f22ef01cSRoman Divacky   // specialization of the attributes which may be set on a global
3348f22ef01cSRoman Divacky   // variable/function.
334939d628a0SDimitry Andric   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
33503b0f4066SDimitry Andric       D->isWeakImported()) {
3351f22ef01cSRoman Divacky     GA->setLinkage(llvm::Function::WeakAnyLinkage);
3352f22ef01cSRoman Divacky   }
3353f22ef01cSRoman Divacky 
335439d628a0SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
335539d628a0SDimitry Andric     if (VD->getTLSKind())
335639d628a0SDimitry Andric       setTLSMode(GA, *VD);
335739d628a0SDimitry Andric 
335839d628a0SDimitry Andric   setAliasAttributes(D, GA);
3359f22ef01cSRoman Divacky }
3360f22ef01cSRoman Divacky 
3361e7145dcbSDimitry Andric void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
3362e7145dcbSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
3363e7145dcbSDimitry Andric   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
3364e7145dcbSDimitry Andric   assert(IFA && "Not an ifunc?");
3365e7145dcbSDimitry Andric 
3366e7145dcbSDimitry Andric   StringRef MangledName = getMangledName(GD);
3367e7145dcbSDimitry Andric 
3368e7145dcbSDimitry Andric   if (IFA->getResolver() == MangledName) {
3369e7145dcbSDimitry Andric     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3370e7145dcbSDimitry Andric     return;
3371e7145dcbSDimitry Andric   }
3372e7145dcbSDimitry Andric 
3373e7145dcbSDimitry Andric   // Report an error if some definition overrides ifunc.
3374e7145dcbSDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3375e7145dcbSDimitry Andric   if (Entry && !Entry->isDeclaration()) {
3376e7145dcbSDimitry Andric     GlobalDecl OtherGD;
3377e7145dcbSDimitry Andric     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3378e7145dcbSDimitry Andric         DiagnosedConflictingDefinitions.insert(GD).second) {
3379e7145dcbSDimitry Andric       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
3380e7145dcbSDimitry Andric       Diags.Report(OtherGD.getDecl()->getLocation(),
3381e7145dcbSDimitry Andric                    diag::note_previous_definition);
3382e7145dcbSDimitry Andric     }
3383e7145dcbSDimitry Andric     return;
3384e7145dcbSDimitry Andric   }
3385e7145dcbSDimitry Andric 
3386e7145dcbSDimitry Andric   Aliases.push_back(GD);
3387e7145dcbSDimitry Andric 
3388e7145dcbSDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3389e7145dcbSDimitry Andric   llvm::Constant *Resolver =
3390e7145dcbSDimitry Andric       GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3391e7145dcbSDimitry Andric                               /*ForVTable=*/false);
3392e7145dcbSDimitry Andric   llvm::GlobalIFunc *GIF =
3393e7145dcbSDimitry Andric       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
3394e7145dcbSDimitry Andric                                 "", Resolver, &getModule());
3395e7145dcbSDimitry Andric   if (Entry) {
3396e7145dcbSDimitry Andric     if (GIF->getResolver() == Entry) {
3397e7145dcbSDimitry Andric       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3398e7145dcbSDimitry Andric       return;
3399e7145dcbSDimitry Andric     }
3400e7145dcbSDimitry Andric     assert(Entry->isDeclaration());
3401e7145dcbSDimitry Andric 
3402e7145dcbSDimitry Andric     // If there is a declaration in the module, then we had an extern followed
3403e7145dcbSDimitry Andric     // by the ifunc, as in:
3404e7145dcbSDimitry Andric     //   extern int test();
3405e7145dcbSDimitry Andric     //   ...
3406e7145dcbSDimitry Andric     //   int test() __attribute__((ifunc("resolver")));
3407e7145dcbSDimitry Andric     //
3408e7145dcbSDimitry Andric     // Remove it and replace uses of it with the ifunc.
3409e7145dcbSDimitry Andric     GIF->takeName(Entry);
3410e7145dcbSDimitry Andric 
3411e7145dcbSDimitry Andric     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3412e7145dcbSDimitry Andric                                                           Entry->getType()));
3413e7145dcbSDimitry Andric     Entry->eraseFromParent();
3414e7145dcbSDimitry Andric   } else
3415e7145dcbSDimitry Andric     GIF->setName(MangledName);
3416e7145dcbSDimitry Andric 
3417e7145dcbSDimitry Andric   SetCommonAttributes(D, GIF);
3418e7145dcbSDimitry Andric }
3419e7145dcbSDimitry Andric 
342017a519f9SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
34216122f3e6SDimitry Andric                                             ArrayRef<llvm::Type*> Tys) {
342217a519f9SDimitry Andric   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
342317a519f9SDimitry Andric                                          Tys);
3424f22ef01cSRoman Divacky }
3425f22ef01cSRoman Divacky 
342633956c43SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> &
342733956c43SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
342833956c43SDimitry Andric                          const StringLiteral *Literal, bool TargetIsLSB,
342933956c43SDimitry Andric                          bool &IsUTF16, unsigned &StringLength) {
34306122f3e6SDimitry Andric   StringRef String = Literal->getString();
3431e580952dSDimitry Andric   unsigned NumBytes = String.size();
3432f22ef01cSRoman Divacky 
3433f22ef01cSRoman Divacky   // Check for simple case.
3434f22ef01cSRoman Divacky   if (!Literal->containsNonAsciiOrNull()) {
3435f22ef01cSRoman Divacky     StringLength = NumBytes;
343639d628a0SDimitry Andric     return *Map.insert(std::make_pair(String, nullptr)).first;
3437f22ef01cSRoman Divacky   }
3438f22ef01cSRoman Divacky 
3439dff0c46cSDimitry Andric   // Otherwise, convert the UTF8 literals into a string of shorts.
3440dff0c46cSDimitry Andric   IsUTF16 = true;
3441dff0c46cSDimitry Andric 
344244290647SDimitry Andric   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
344344290647SDimitry Andric   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
344444290647SDimitry Andric   llvm::UTF16 *ToPtr = &ToBuf[0];
3445f22ef01cSRoman Divacky 
344644290647SDimitry Andric   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
344744290647SDimitry Andric                                  ToPtr + NumBytes, llvm::strictConversion);
3448f22ef01cSRoman Divacky 
3449f22ef01cSRoman Divacky   // ConvertUTF8toUTF16 returns the length in ToPtr.
3450f22ef01cSRoman Divacky   StringLength = ToPtr - &ToBuf[0];
3451f22ef01cSRoman Divacky 
3452dff0c46cSDimitry Andric   // Add an explicit null.
3453dff0c46cSDimitry Andric   *ToPtr = 0;
345439d628a0SDimitry Andric   return *Map.insert(std::make_pair(
345539d628a0SDimitry Andric                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
345639d628a0SDimitry Andric                                    (StringLength + 1) * 2),
345739d628a0SDimitry Andric                          nullptr)).first;
3458f22ef01cSRoman Divacky }
3459f22ef01cSRoman Divacky 
34600623d748SDimitry Andric ConstantAddress
3461f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
3462f22ef01cSRoman Divacky   unsigned StringLength = 0;
3463f22ef01cSRoman Divacky   bool isUTF16 = false;
346433956c43SDimitry Andric   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3465f22ef01cSRoman Divacky       GetConstantCFStringEntry(CFConstantStringMap, Literal,
346633956c43SDimitry Andric                                getDataLayout().isLittleEndian(), isUTF16,
346733956c43SDimitry Andric                                StringLength);
3468f22ef01cSRoman Divacky 
346939d628a0SDimitry Andric   if (auto *C = Entry.second)
34700623d748SDimitry Andric     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
3471f22ef01cSRoman Divacky 
3472dff0c46cSDimitry Andric   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
3473f22ef01cSRoman Divacky   llvm::Constant *Zeros[] = { Zero, Zero };
3474f22ef01cSRoman Divacky 
3475f22ef01cSRoman Divacky   // If we don't already have it, get __CFConstantStringClassReference.
3476f22ef01cSRoman Divacky   if (!CFConstantStringClassRef) {
34776122f3e6SDimitry Andric     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
3478f22ef01cSRoman Divacky     Ty = llvm::ArrayType::get(Ty, 0);
3479e7145dcbSDimitry Andric     llvm::Constant *GV =
3480e7145dcbSDimitry Andric         CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
3481e7145dcbSDimitry Andric 
348244290647SDimitry Andric     if (getTriple().isOSBinFormatCOFF()) {
3483e7145dcbSDimitry Andric       IdentifierInfo &II = getContext().Idents.get(GV->getName());
3484e7145dcbSDimitry Andric       TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
3485e7145dcbSDimitry Andric       DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3486e7145dcbSDimitry Andric       llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
3487e7145dcbSDimitry Andric 
3488e7145dcbSDimitry Andric       const VarDecl *VD = nullptr;
3489e7145dcbSDimitry Andric       for (const auto &Result : DC->lookup(&II))
3490e7145dcbSDimitry Andric         if ((VD = dyn_cast<VarDecl>(Result)))
3491e7145dcbSDimitry Andric           break;
3492e7145dcbSDimitry Andric 
3493e7145dcbSDimitry Andric       if (!VD || !VD->hasAttr<DLLExportAttr>()) {
3494e7145dcbSDimitry Andric         CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3495e7145dcbSDimitry Andric         CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3496e7145dcbSDimitry Andric       } else {
3497e7145dcbSDimitry Andric         CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3498e7145dcbSDimitry Andric         CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3499e7145dcbSDimitry Andric       }
3500e7145dcbSDimitry Andric     }
3501e7145dcbSDimitry Andric 
3502f22ef01cSRoman Divacky     // Decay array -> ptr
350344290647SDimitry Andric     CFConstantStringClassRef =
350444290647SDimitry Andric         llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
3505e7145dcbSDimitry Andric   }
3506f22ef01cSRoman Divacky 
3507f22ef01cSRoman Divacky   QualType CFTy = getContext().getCFConstantStringType();
3508f22ef01cSRoman Divacky 
350959d1ed5bSDimitry Andric   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
3510f22ef01cSRoman Divacky 
351144290647SDimitry Andric   ConstantInitBuilder Builder(*this);
351244290647SDimitry Andric   auto Fields = Builder.beginStruct(STy);
3513f22ef01cSRoman Divacky 
3514f22ef01cSRoman Divacky   // Class pointer.
351544290647SDimitry Andric   Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
3516f22ef01cSRoman Divacky 
3517f22ef01cSRoman Divacky   // Flags.
351844290647SDimitry Andric   Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
3519f22ef01cSRoman Divacky 
3520f22ef01cSRoman Divacky   // String pointer.
352159d1ed5bSDimitry Andric   llvm::Constant *C = nullptr;
3522dff0c46cSDimitry Andric   if (isUTF16) {
35230623d748SDimitry Andric     auto Arr = llvm::makeArrayRef(
352439d628a0SDimitry Andric         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
352539d628a0SDimitry Andric         Entry.first().size() / 2);
3526dff0c46cSDimitry Andric     C = llvm::ConstantDataArray::get(VMContext, Arr);
3527dff0c46cSDimitry Andric   } else {
352839d628a0SDimitry Andric     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
3529dff0c46cSDimitry Andric   }
3530f22ef01cSRoman Divacky 
3531dff0c46cSDimitry Andric   // Note: -fwritable-strings doesn't make the backing store strings of
3532dff0c46cSDimitry Andric   // CFStrings writable. (See <rdar://problem/10657500>)
353359d1ed5bSDimitry Andric   auto *GV =
3534dff0c46cSDimitry Andric       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
353559d1ed5bSDimitry Andric                                llvm::GlobalValue::PrivateLinkage, C, ".str");
3536e7145dcbSDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3537284c1978SDimitry Andric   // Don't enforce the target's minimum global alignment, since the only use
3538284c1978SDimitry Andric   // of the string is via this class initializer.
3539e7145dcbSDimitry Andric   CharUnits Align = isUTF16
3540e7145dcbSDimitry Andric                         ? getContext().getTypeAlignInChars(getContext().ShortTy)
3541e7145dcbSDimitry Andric                         : getContext().getTypeAlignInChars(getContext().CharTy);
3542f22ef01cSRoman Divacky   GV->setAlignment(Align.getQuantity());
3543e7145dcbSDimitry Andric 
3544e7145dcbSDimitry Andric   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
3545e7145dcbSDimitry Andric   // Without it LLVM can merge the string with a non unnamed_addr one during
3546e7145dcbSDimitry Andric   // LTO.  Doing that changes the section it ends in, which surprises ld64.
354744290647SDimitry Andric   if (getTriple().isOSBinFormatMachO())
3548e7145dcbSDimitry Andric     GV->setSection(isUTF16 ? "__TEXT,__ustring"
3549e7145dcbSDimitry Andric                            : "__TEXT,__cstring,cstring_literals");
3550dff0c46cSDimitry Andric 
3551dff0c46cSDimitry Andric   // String.
355244290647SDimitry Andric   llvm::Constant *Str =
355333956c43SDimitry Andric       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3554f22ef01cSRoman Divacky 
3555dff0c46cSDimitry Andric   if (isUTF16)
3556dff0c46cSDimitry Andric     // Cast the UTF16 string to the correct type.
355744290647SDimitry Andric     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
355844290647SDimitry Andric   Fields.add(Str);
3559dff0c46cSDimitry Andric 
3560f22ef01cSRoman Divacky   // String length.
356144290647SDimitry Andric   auto Ty = getTypes().ConvertType(getContext().LongTy);
356244290647SDimitry Andric   Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
3563f22ef01cSRoman Divacky 
35640623d748SDimitry Andric   CharUnits Alignment = getPointerAlign();
35650623d748SDimitry Andric 
3566f22ef01cSRoman Divacky   // The struct.
356744290647SDimitry Andric   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
356844290647SDimitry Andric                                     /*isConstant=*/false,
356944290647SDimitry Andric                                     llvm::GlobalVariable::PrivateLinkage);
357044290647SDimitry Andric   switch (getTriple().getObjectFormat()) {
3571e7145dcbSDimitry Andric   case llvm::Triple::UnknownObjectFormat:
3572e7145dcbSDimitry Andric     llvm_unreachable("unknown file format");
3573e7145dcbSDimitry Andric   case llvm::Triple::COFF:
3574e7145dcbSDimitry Andric   case llvm::Triple::ELF:
357520e90f04SDimitry Andric   case llvm::Triple::Wasm:
3576e7145dcbSDimitry Andric     GV->setSection("cfstring");
3577e7145dcbSDimitry Andric     break;
3578e7145dcbSDimitry Andric   case llvm::Triple::MachO:
3579e7145dcbSDimitry Andric     GV->setSection("__DATA,__cfstring");
3580e7145dcbSDimitry Andric     break;
3581e7145dcbSDimitry Andric   }
358239d628a0SDimitry Andric   Entry.second = GV;
3583f22ef01cSRoman Divacky 
35840623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
3585f22ef01cSRoman Divacky }
3586f22ef01cSRoman Divacky 
35879a199699SDimitry Andric bool CodeGenModule::getExpressionLocationsEnabled() const {
35889a199699SDimitry Andric   return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
35899a199699SDimitry Andric }
35909a199699SDimitry Andric 
35916122f3e6SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() {
35926122f3e6SDimitry Andric   if (ObjCFastEnumerationStateType.isNull()) {
359359d1ed5bSDimitry Andric     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
35946122f3e6SDimitry Andric     D->startDefinition();
35956122f3e6SDimitry Andric 
35966122f3e6SDimitry Andric     QualType FieldTypes[] = {
35976122f3e6SDimitry Andric       Context.UnsignedLongTy,
35986122f3e6SDimitry Andric       Context.getPointerType(Context.getObjCIdType()),
35996122f3e6SDimitry Andric       Context.getPointerType(Context.UnsignedLongTy),
36006122f3e6SDimitry Andric       Context.getConstantArrayType(Context.UnsignedLongTy,
36016122f3e6SDimitry Andric                            llvm::APInt(32, 5), ArrayType::Normal, 0)
36026122f3e6SDimitry Andric     };
36036122f3e6SDimitry Andric 
36046122f3e6SDimitry Andric     for (size_t i = 0; i < 4; ++i) {
36056122f3e6SDimitry Andric       FieldDecl *Field = FieldDecl::Create(Context,
36066122f3e6SDimitry Andric                                            D,
36076122f3e6SDimitry Andric                                            SourceLocation(),
360859d1ed5bSDimitry Andric                                            SourceLocation(), nullptr,
360959d1ed5bSDimitry Andric                                            FieldTypes[i], /*TInfo=*/nullptr,
361059d1ed5bSDimitry Andric                                            /*BitWidth=*/nullptr,
36116122f3e6SDimitry Andric                                            /*Mutable=*/false,
36127ae0e2c9SDimitry Andric                                            ICIS_NoInit);
36136122f3e6SDimitry Andric       Field->setAccess(AS_public);
36146122f3e6SDimitry Andric       D->addDecl(Field);
36156122f3e6SDimitry Andric     }
36166122f3e6SDimitry Andric 
36176122f3e6SDimitry Andric     D->completeDefinition();
36186122f3e6SDimitry Andric     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
36196122f3e6SDimitry Andric   }
36206122f3e6SDimitry Andric 
36216122f3e6SDimitry Andric   return ObjCFastEnumerationStateType;
36226122f3e6SDimitry Andric }
36236122f3e6SDimitry Andric 
3624dff0c46cSDimitry Andric llvm::Constant *
3625dff0c46cSDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
3626dff0c46cSDimitry Andric   assert(!E->getType()->isPointerType() && "Strings are always arrays");
3627f22ef01cSRoman Divacky 
3628dff0c46cSDimitry Andric   // Don't emit it as the address of the string, emit the string data itself
3629dff0c46cSDimitry Andric   // as an inline array.
3630dff0c46cSDimitry Andric   if (E->getCharByteWidth() == 1) {
3631dff0c46cSDimitry Andric     SmallString<64> Str(E->getString());
3632f22ef01cSRoman Divacky 
3633dff0c46cSDimitry Andric     // Resize the string to the right size, which is indicated by its type.
3634dff0c46cSDimitry Andric     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
3635dff0c46cSDimitry Andric     Str.resize(CAT->getSize().getZExtValue());
3636dff0c46cSDimitry Andric     return llvm::ConstantDataArray::getString(VMContext, Str, false);
36376122f3e6SDimitry Andric   }
3638f22ef01cSRoman Divacky 
363959d1ed5bSDimitry Andric   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
3640dff0c46cSDimitry Andric   llvm::Type *ElemTy = AType->getElementType();
3641dff0c46cSDimitry Andric   unsigned NumElements = AType->getNumElements();
3642f22ef01cSRoman Divacky 
3643dff0c46cSDimitry Andric   // Wide strings have either 2-byte or 4-byte elements.
3644dff0c46cSDimitry Andric   if (ElemTy->getPrimitiveSizeInBits() == 16) {
3645dff0c46cSDimitry Andric     SmallVector<uint16_t, 32> Elements;
3646dff0c46cSDimitry Andric     Elements.reserve(NumElements);
3647dff0c46cSDimitry Andric 
3648dff0c46cSDimitry Andric     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3649dff0c46cSDimitry Andric       Elements.push_back(E->getCodeUnit(i));
3650dff0c46cSDimitry Andric     Elements.resize(NumElements);
3651dff0c46cSDimitry Andric     return llvm::ConstantDataArray::get(VMContext, Elements);
3652dff0c46cSDimitry Andric   }
3653dff0c46cSDimitry Andric 
3654dff0c46cSDimitry Andric   assert(ElemTy->getPrimitiveSizeInBits() == 32);
3655dff0c46cSDimitry Andric   SmallVector<uint32_t, 32> Elements;
3656dff0c46cSDimitry Andric   Elements.reserve(NumElements);
3657dff0c46cSDimitry Andric 
3658dff0c46cSDimitry Andric   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3659dff0c46cSDimitry Andric     Elements.push_back(E->getCodeUnit(i));
3660dff0c46cSDimitry Andric   Elements.resize(NumElements);
3661dff0c46cSDimitry Andric   return llvm::ConstantDataArray::get(VMContext, Elements);
3662f22ef01cSRoman Divacky }
3663f22ef01cSRoman Divacky 
366459d1ed5bSDimitry Andric static llvm::GlobalVariable *
366559d1ed5bSDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
366659d1ed5bSDimitry Andric                       CodeGenModule &CGM, StringRef GlobalName,
36670623d748SDimitry Andric                       CharUnits Alignment) {
366859d1ed5bSDimitry Andric   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
366959d1ed5bSDimitry Andric   unsigned AddrSpace = 0;
367059d1ed5bSDimitry Andric   if (CGM.getLangOpts().OpenCL)
367159d1ed5bSDimitry Andric     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
3672dff0c46cSDimitry Andric 
367333956c43SDimitry Andric   llvm::Module &M = CGM.getModule();
367459d1ed5bSDimitry Andric   // Create a global variable for this string
367559d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
367633956c43SDimitry Andric       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
367733956c43SDimitry Andric       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
36780623d748SDimitry Andric   GV->setAlignment(Alignment.getQuantity());
3679e7145dcbSDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
368033956c43SDimitry Andric   if (GV->isWeakForLinker()) {
368133956c43SDimitry Andric     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
368233956c43SDimitry Andric     GV->setComdat(M.getOrInsertComdat(GV->getName()));
368333956c43SDimitry Andric   }
368433956c43SDimitry Andric 
368559d1ed5bSDimitry Andric   return GV;
3686f22ef01cSRoman Divacky }
3687dff0c46cSDimitry Andric 
368859d1ed5bSDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
368959d1ed5bSDimitry Andric /// constant array for the given string literal.
36900623d748SDimitry Andric ConstantAddress
369139d628a0SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
369239d628a0SDimitry Andric                                                   StringRef Name) {
36930623d748SDimitry Andric   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
3694dff0c46cSDimitry Andric 
369559d1ed5bSDimitry Andric   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
369659d1ed5bSDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
369759d1ed5bSDimitry Andric   if (!LangOpts.WritableStrings) {
369859d1ed5bSDimitry Andric     Entry = &ConstantStringMap[C];
369959d1ed5bSDimitry Andric     if (auto GV = *Entry) {
37000623d748SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
37010623d748SDimitry Andric         GV->setAlignment(Alignment.getQuantity());
37020623d748SDimitry Andric       return ConstantAddress(GV, Alignment);
370359d1ed5bSDimitry Andric     }
370459d1ed5bSDimitry Andric   }
370559d1ed5bSDimitry Andric 
370659d1ed5bSDimitry Andric   SmallString<256> MangledNameBuffer;
370759d1ed5bSDimitry Andric   StringRef GlobalVariableName;
370859d1ed5bSDimitry Andric   llvm::GlobalValue::LinkageTypes LT;
370959d1ed5bSDimitry Andric 
371059d1ed5bSDimitry Andric   // Mangle the string literal if the ABI allows for it.  However, we cannot
371159d1ed5bSDimitry Andric   // do this if  we are compiling with ASan or -fwritable-strings because they
371259d1ed5bSDimitry Andric   // rely on strings having normal linkage.
371339d628a0SDimitry Andric   if (!LangOpts.WritableStrings &&
371439d628a0SDimitry Andric       !LangOpts.Sanitize.has(SanitizerKind::Address) &&
371559d1ed5bSDimitry Andric       getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
371659d1ed5bSDimitry Andric     llvm::raw_svector_ostream Out(MangledNameBuffer);
371759d1ed5bSDimitry Andric     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
371859d1ed5bSDimitry Andric 
371959d1ed5bSDimitry Andric     LT = llvm::GlobalValue::LinkOnceODRLinkage;
372059d1ed5bSDimitry Andric     GlobalVariableName = MangledNameBuffer;
372159d1ed5bSDimitry Andric   } else {
372259d1ed5bSDimitry Andric     LT = llvm::GlobalValue::PrivateLinkage;
372339d628a0SDimitry Andric     GlobalVariableName = Name;
372459d1ed5bSDimitry Andric   }
372559d1ed5bSDimitry Andric 
372659d1ed5bSDimitry Andric   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
372759d1ed5bSDimitry Andric   if (Entry)
372859d1ed5bSDimitry Andric     *Entry = GV;
372959d1ed5bSDimitry Andric 
373039d628a0SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
373139d628a0SDimitry Andric                                   QualType());
37320623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
3733f22ef01cSRoman Divacky }
3734f22ef01cSRoman Divacky 
3735f22ef01cSRoman Divacky /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
3736f22ef01cSRoman Divacky /// array for the given ObjCEncodeExpr node.
37370623d748SDimitry Andric ConstantAddress
3738f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
3739f22ef01cSRoman Divacky   std::string Str;
3740f22ef01cSRoman Divacky   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
3741f22ef01cSRoman Divacky 
3742f22ef01cSRoman Divacky   return GetAddrOfConstantCString(Str);
3743f22ef01cSRoman Divacky }
3744f22ef01cSRoman Divacky 
374559d1ed5bSDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing
374659d1ed5bSDimitry Andric /// the literal and a terminating '\0' character.
374759d1ed5bSDimitry Andric /// The result has pointer to array type.
37480623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString(
37490623d748SDimitry Andric     const std::string &Str, const char *GlobalName) {
375059d1ed5bSDimitry Andric   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
37510623d748SDimitry Andric   CharUnits Alignment =
37520623d748SDimitry Andric     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
3753f22ef01cSRoman Divacky 
375459d1ed5bSDimitry Andric   llvm::Constant *C =
375559d1ed5bSDimitry Andric       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
375659d1ed5bSDimitry Andric 
375759d1ed5bSDimitry Andric   // Don't share any string literals if strings aren't constant.
375859d1ed5bSDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
375959d1ed5bSDimitry Andric   if (!LangOpts.WritableStrings) {
376059d1ed5bSDimitry Andric     Entry = &ConstantStringMap[C];
376159d1ed5bSDimitry Andric     if (auto GV = *Entry) {
37620623d748SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
37630623d748SDimitry Andric         GV->setAlignment(Alignment.getQuantity());
37640623d748SDimitry Andric       return ConstantAddress(GV, Alignment);
376559d1ed5bSDimitry Andric     }
376659d1ed5bSDimitry Andric   }
376759d1ed5bSDimitry Andric 
3768f22ef01cSRoman Divacky   // Get the default prefix if a name wasn't specified.
3769f22ef01cSRoman Divacky   if (!GlobalName)
3770f22ef01cSRoman Divacky     GlobalName = ".str";
3771f22ef01cSRoman Divacky   // Create a global variable for this.
377259d1ed5bSDimitry Andric   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
377359d1ed5bSDimitry Andric                                   GlobalName, Alignment);
377459d1ed5bSDimitry Andric   if (Entry)
377559d1ed5bSDimitry Andric     *Entry = GV;
37760623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
3777f22ef01cSRoman Divacky }
3778f22ef01cSRoman Divacky 
37790623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
3780f785676fSDimitry Andric     const MaterializeTemporaryExpr *E, const Expr *Init) {
3781f785676fSDimitry Andric   assert((E->getStorageDuration() == SD_Static ||
3782f785676fSDimitry Andric           E->getStorageDuration() == SD_Thread) && "not a global temporary");
378359d1ed5bSDimitry Andric   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
3784f785676fSDimitry Andric 
3785f785676fSDimitry Andric   // If we're not materializing a subobject of the temporary, keep the
3786f785676fSDimitry Andric   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
3787f785676fSDimitry Andric   QualType MaterializedType = Init->getType();
3788f785676fSDimitry Andric   if (Init == E->GetTemporaryExpr())
3789f785676fSDimitry Andric     MaterializedType = E->getType();
3790f785676fSDimitry Andric 
37910623d748SDimitry Andric   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
37920623d748SDimitry Andric 
37930623d748SDimitry Andric   if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
37940623d748SDimitry Andric     return ConstantAddress(Slot, Align);
3795f785676fSDimitry Andric 
3796f785676fSDimitry Andric   // FIXME: If an externally-visible declaration extends multiple temporaries,
3797f785676fSDimitry Andric   // we need to give each temporary the same name in every translation unit (and
3798f785676fSDimitry Andric   // we also need to make the temporaries externally-visible).
3799f785676fSDimitry Andric   SmallString<256> Name;
3800f785676fSDimitry Andric   llvm::raw_svector_ostream Out(Name);
380159d1ed5bSDimitry Andric   getCXXABI().getMangleContext().mangleReferenceTemporary(
380259d1ed5bSDimitry Andric       VD, E->getManglingNumber(), Out);
3803f785676fSDimitry Andric 
380459d1ed5bSDimitry Andric   APValue *Value = nullptr;
3805f785676fSDimitry Andric   if (E->getStorageDuration() == SD_Static) {
3806f785676fSDimitry Andric     // We might have a cached constant initializer for this temporary. Note
3807f785676fSDimitry Andric     // that this might have a different value from the value computed by
3808f785676fSDimitry Andric     // evaluating the initializer if the surrounding constant expression
3809f785676fSDimitry Andric     // modifies the temporary.
3810f785676fSDimitry Andric     Value = getContext().getMaterializedTemporaryValue(E, false);
3811f785676fSDimitry Andric     if (Value && Value->isUninit())
381259d1ed5bSDimitry Andric       Value = nullptr;
3813f785676fSDimitry Andric   }
3814f785676fSDimitry Andric 
3815f785676fSDimitry Andric   // Try evaluating it now, it might have a constant initializer.
3816f785676fSDimitry Andric   Expr::EvalResult EvalResult;
3817f785676fSDimitry Andric   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3818f785676fSDimitry Andric       !EvalResult.hasSideEffects())
3819f785676fSDimitry Andric     Value = &EvalResult.Val;
3820f785676fSDimitry Andric 
38219a199699SDimitry Andric   LangAS AddrSpace =
38229a199699SDimitry Andric       VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
38239a199699SDimitry Andric 
38249a199699SDimitry Andric   Optional<ConstantEmitter> emitter;
382559d1ed5bSDimitry Andric   llvm::Constant *InitialValue = nullptr;
3826f785676fSDimitry Andric   bool Constant = false;
3827f785676fSDimitry Andric   llvm::Type *Type;
3828f785676fSDimitry Andric   if (Value) {
3829f785676fSDimitry Andric     // The temporary has a constant initializer, use it.
38309a199699SDimitry Andric     emitter.emplace(*this);
38319a199699SDimitry Andric     InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
38329a199699SDimitry Andric                                                MaterializedType);
3833f785676fSDimitry Andric     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3834f785676fSDimitry Andric     Type = InitialValue->getType();
3835f785676fSDimitry Andric   } else {
3836f785676fSDimitry Andric     // No initializer, the initialization will be provided when we
3837f785676fSDimitry Andric     // initialize the declaration which performed lifetime extension.
3838f785676fSDimitry Andric     Type = getTypes().ConvertTypeForMem(MaterializedType);
3839f785676fSDimitry Andric   }
3840f785676fSDimitry Andric 
3841f785676fSDimitry Andric   // Create a global variable for this lifetime-extended temporary.
384259d1ed5bSDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
384359d1ed5bSDimitry Andric       getLLVMLinkageVarDefinition(VD, Constant);
384433956c43SDimitry Andric   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
384533956c43SDimitry Andric     const VarDecl *InitVD;
384633956c43SDimitry Andric     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
384733956c43SDimitry Andric         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
384833956c43SDimitry Andric       // Temporaries defined inside a class get linkonce_odr linkage because the
384933956c43SDimitry Andric       // class can be defined in multipe translation units.
385033956c43SDimitry Andric       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
385133956c43SDimitry Andric     } else {
385233956c43SDimitry Andric       // There is no need for this temporary to have external linkage if the
385333956c43SDimitry Andric       // VarDecl has external linkage.
385433956c43SDimitry Andric       Linkage = llvm::GlobalVariable::InternalLinkage;
385533956c43SDimitry Andric     }
385633956c43SDimitry Andric   }
3857c4394386SDimitry Andric   auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
385859d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
385959d1ed5bSDimitry Andric       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
3860c4394386SDimitry Andric       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
38619a199699SDimitry Andric   if (emitter) emitter->finalize(GV);
38629a199699SDimitry Andric   setGlobalVisibility(GV, VD, ForDefinition);
38630623d748SDimitry Andric   GV->setAlignment(Align.getQuantity());
386433956c43SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker())
386533956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3866f785676fSDimitry Andric   if (VD->getTLSKind())
3867f785676fSDimitry Andric     setTLSMode(GV, *VD);
3868c4394386SDimitry Andric   llvm::Constant *CV = GV;
3869c4394386SDimitry Andric   if (AddrSpace != LangAS::Default)
3870c4394386SDimitry Andric     CV = getTargetCodeGenInfo().performAddrSpaceCast(
3871c4394386SDimitry Andric         *this, GV, AddrSpace, LangAS::Default,
3872c4394386SDimitry Andric         Type->getPointerTo(
3873c4394386SDimitry Andric             getContext().getTargetAddressSpace(LangAS::Default)));
3874c4394386SDimitry Andric   MaterializedGlobalTemporaryMap[E] = CV;
3875c4394386SDimitry Andric   return ConstantAddress(CV, Align);
3876f785676fSDimitry Andric }
3877f785676fSDimitry Andric 
3878f22ef01cSRoman Divacky /// EmitObjCPropertyImplementations - Emit information for synthesized
3879f22ef01cSRoman Divacky /// properties for an implementation.
3880f22ef01cSRoman Divacky void CodeGenModule::EmitObjCPropertyImplementations(const
3881f22ef01cSRoman Divacky                                                     ObjCImplementationDecl *D) {
388259d1ed5bSDimitry Andric   for (const auto *PID : D->property_impls()) {
3883f22ef01cSRoman Divacky     // Dynamic is just for type-checking.
3884f22ef01cSRoman Divacky     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3885f22ef01cSRoman Divacky       ObjCPropertyDecl *PD = PID->getPropertyDecl();
3886f22ef01cSRoman Divacky 
3887f22ef01cSRoman Divacky       // Determine which methods need to be implemented, some may have
38883861d79fSDimitry Andric       // been overridden. Note that ::isPropertyAccessor is not the method
3889f22ef01cSRoman Divacky       // we want, that just indicates if the decl came from a
3890f22ef01cSRoman Divacky       // property. What we want to know is if the method is defined in
3891f22ef01cSRoman Divacky       // this implementation.
3892f22ef01cSRoman Divacky       if (!D->getInstanceMethod(PD->getGetterName()))
3893f22ef01cSRoman Divacky         CodeGenFunction(*this).GenerateObjCGetter(
3894f22ef01cSRoman Divacky                                  const_cast<ObjCImplementationDecl *>(D), PID);
3895f22ef01cSRoman Divacky       if (!PD->isReadOnly() &&
3896f22ef01cSRoman Divacky           !D->getInstanceMethod(PD->getSetterName()))
3897f22ef01cSRoman Divacky         CodeGenFunction(*this).GenerateObjCSetter(
3898f22ef01cSRoman Divacky                                  const_cast<ObjCImplementationDecl *>(D), PID);
3899f22ef01cSRoman Divacky     }
3900f22ef01cSRoman Divacky   }
3901f22ef01cSRoman Divacky }
3902f22ef01cSRoman Divacky 
39033b0f4066SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) {
39046122f3e6SDimitry Andric   const ObjCInterfaceDecl *iface = impl->getClassInterface();
39056122f3e6SDimitry Andric   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
39063b0f4066SDimitry Andric        ivar; ivar = ivar->getNextIvar())
39073b0f4066SDimitry Andric     if (ivar->getType().isDestructedType())
39083b0f4066SDimitry Andric       return true;
39093b0f4066SDimitry Andric 
39103b0f4066SDimitry Andric   return false;
39113b0f4066SDimitry Andric }
39123b0f4066SDimitry Andric 
391339d628a0SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM,
391439d628a0SDimitry Andric                                    ObjCImplementationDecl *D) {
391539d628a0SDimitry Andric   CodeGenFunction CGF(CGM);
391639d628a0SDimitry Andric   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
391739d628a0SDimitry Andric        E = D->init_end(); B != E; ++B) {
391839d628a0SDimitry Andric     CXXCtorInitializer *CtorInitExp = *B;
391939d628a0SDimitry Andric     Expr *Init = CtorInitExp->getInit();
392039d628a0SDimitry Andric     if (!CGF.isTrivialInitializer(Init))
392139d628a0SDimitry Andric       return false;
392239d628a0SDimitry Andric   }
392339d628a0SDimitry Andric   return true;
392439d628a0SDimitry Andric }
392539d628a0SDimitry Andric 
3926f22ef01cSRoman Divacky /// EmitObjCIvarInitializations - Emit information for ivar initialization
3927f22ef01cSRoman Divacky /// for an implementation.
3928f22ef01cSRoman Divacky void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
39293b0f4066SDimitry Andric   // We might need a .cxx_destruct even if we don't have any ivar initializers.
39303b0f4066SDimitry Andric   if (needsDestructMethod(D)) {
3931f22ef01cSRoman Divacky     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3932f22ef01cSRoman Divacky     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
39333b0f4066SDimitry Andric     ObjCMethodDecl *DTORMethod =
39343b0f4066SDimitry Andric       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
393559d1ed5bSDimitry Andric                              cxxSelector, getContext().VoidTy, nullptr, D,
39366122f3e6SDimitry Andric                              /*isInstance=*/true, /*isVariadic=*/false,
39373861d79fSDimitry Andric                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
39386122f3e6SDimitry Andric                              /*isDefined=*/false, ObjCMethodDecl::Required);
3939f22ef01cSRoman Divacky     D->addInstanceMethod(DTORMethod);
3940f22ef01cSRoman Divacky     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
39413861d79fSDimitry Andric     D->setHasDestructors(true);
39423b0f4066SDimitry Andric   }
3943f22ef01cSRoman Divacky 
39443b0f4066SDimitry Andric   // If the implementation doesn't have any ivar initializers, we don't need
39453b0f4066SDimitry Andric   // a .cxx_construct.
394639d628a0SDimitry Andric   if (D->getNumIvarInitializers() == 0 ||
394739d628a0SDimitry Andric       AllTrivialInitializers(*this, D))
39483b0f4066SDimitry Andric     return;
39493b0f4066SDimitry Andric 
39503b0f4066SDimitry Andric   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
39513b0f4066SDimitry Andric   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3952f22ef01cSRoman Divacky   // The constructor returns 'self'.
3953f22ef01cSRoman Divacky   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3954f22ef01cSRoman Divacky                                                 D->getLocation(),
39556122f3e6SDimitry Andric                                                 D->getLocation(),
39566122f3e6SDimitry Andric                                                 cxxSelector,
395759d1ed5bSDimitry Andric                                                 getContext().getObjCIdType(),
395859d1ed5bSDimitry Andric                                                 nullptr, D, /*isInstance=*/true,
39596122f3e6SDimitry Andric                                                 /*isVariadic=*/false,
39603861d79fSDimitry Andric                                                 /*isPropertyAccessor=*/true,
39616122f3e6SDimitry Andric                                                 /*isImplicitlyDeclared=*/true,
39626122f3e6SDimitry Andric                                                 /*isDefined=*/false,
3963f22ef01cSRoman Divacky                                                 ObjCMethodDecl::Required);
3964f22ef01cSRoman Divacky   D->addInstanceMethod(CTORMethod);
3965f22ef01cSRoman Divacky   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
39663861d79fSDimitry Andric   D->setHasNonZeroConstructors(true);
3967f22ef01cSRoman Divacky }
3968f22ef01cSRoman Divacky 
3969f22ef01cSRoman Divacky // EmitLinkageSpec - Emit all declarations in a linkage spec.
3970f22ef01cSRoman Divacky void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
3971f22ef01cSRoman Divacky   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3972f22ef01cSRoman Divacky       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
3973f22ef01cSRoman Divacky     ErrorUnsupported(LSD, "linkage spec");
3974f22ef01cSRoman Divacky     return;
3975f22ef01cSRoman Divacky   }
3976f22ef01cSRoman Divacky 
397744290647SDimitry Andric   EmitDeclContext(LSD);
397844290647SDimitry Andric }
397944290647SDimitry Andric 
398044290647SDimitry Andric void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
398144290647SDimitry Andric   for (auto *I : DC->decls()) {
398244290647SDimitry Andric     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
398344290647SDimitry Andric     // are themselves considered "top-level", so EmitTopLevelDecl on an
398444290647SDimitry Andric     // ObjCImplDecl does not recursively visit them. We need to do that in
398544290647SDimitry Andric     // case they're nested inside another construct (LinkageSpecDecl /
398644290647SDimitry Andric     // ExportDecl) that does stop them from being considered "top-level".
398759d1ed5bSDimitry Andric     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
398859d1ed5bSDimitry Andric       for (auto *M : OID->methods())
398959d1ed5bSDimitry Andric         EmitTopLevelDecl(M);
39903861d79fSDimitry Andric     }
399144290647SDimitry Andric 
399259d1ed5bSDimitry Andric     EmitTopLevelDecl(I);
3993f22ef01cSRoman Divacky   }
39943861d79fSDimitry Andric }
3995f22ef01cSRoman Divacky 
3996f22ef01cSRoman Divacky /// EmitTopLevelDecl - Emit code for a single top level declaration.
3997f22ef01cSRoman Divacky void CodeGenModule::EmitTopLevelDecl(Decl *D) {
3998f22ef01cSRoman Divacky   // Ignore dependent declarations.
3999f22ef01cSRoman Divacky   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
4000f22ef01cSRoman Divacky     return;
4001f22ef01cSRoman Divacky 
4002f22ef01cSRoman Divacky   switch (D->getKind()) {
4003f22ef01cSRoman Divacky   case Decl::CXXConversion:
4004f22ef01cSRoman Divacky   case Decl::CXXMethod:
4005f22ef01cSRoman Divacky   case Decl::Function:
4006f22ef01cSRoman Divacky     // Skip function templates
40073b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
40083b0f4066SDimitry Andric         cast<FunctionDecl>(D)->isLateTemplateParsed())
4009f22ef01cSRoman Divacky       return;
4010f22ef01cSRoman Divacky 
4011f22ef01cSRoman Divacky     EmitGlobal(cast<FunctionDecl>(D));
401239d628a0SDimitry Andric     // Always provide some coverage mapping
401339d628a0SDimitry Andric     // even for the functions that aren't emitted.
401439d628a0SDimitry Andric     AddDeferredUnusedCoverageMapping(D);
4015f22ef01cSRoman Divacky     break;
4016f22ef01cSRoman Divacky 
40176bc11b14SDimitry Andric   case Decl::CXXDeductionGuide:
40186bc11b14SDimitry Andric     // Function-like, but does not result in code emission.
40196bc11b14SDimitry Andric     break;
40206bc11b14SDimitry Andric 
4021f22ef01cSRoman Divacky   case Decl::Var:
402244290647SDimitry Andric   case Decl::Decomposition:
4023f785676fSDimitry Andric     // Skip variable templates
4024f785676fSDimitry Andric     if (cast<VarDecl>(D)->getDescribedVarTemplate())
4025f785676fSDimitry Andric       return;
40266d97bb29SDimitry Andric     LLVM_FALLTHROUGH;
4027f785676fSDimitry Andric   case Decl::VarTemplateSpecialization:
4028f22ef01cSRoman Divacky     EmitGlobal(cast<VarDecl>(D));
402944290647SDimitry Andric     if (auto *DD = dyn_cast<DecompositionDecl>(D))
403044290647SDimitry Andric       for (auto *B : DD->bindings())
403144290647SDimitry Andric         if (auto *HD = B->getHoldingVar())
403244290647SDimitry Andric           EmitGlobal(HD);
4033f22ef01cSRoman Divacky     break;
4034f22ef01cSRoman Divacky 
40353b0f4066SDimitry Andric   // Indirect fields from global anonymous structs and unions can be
40363b0f4066SDimitry Andric   // ignored; only the actual variable requires IR gen support.
40373b0f4066SDimitry Andric   case Decl::IndirectField:
40383b0f4066SDimitry Andric     break;
40393b0f4066SDimitry Andric 
4040f22ef01cSRoman Divacky   // C++ Decls
4041f22ef01cSRoman Divacky   case Decl::Namespace:
404244290647SDimitry Andric     EmitDeclContext(cast<NamespaceDecl>(D));
4043f22ef01cSRoman Divacky     break;
40449a199699SDimitry Andric   case Decl::ClassTemplateSpecialization: {
40459a199699SDimitry Andric     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
40469a199699SDimitry Andric     if (DebugInfo &&
40479a199699SDimitry Andric         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
40489a199699SDimitry Andric         Spec->hasDefinition())
40499a199699SDimitry Andric       DebugInfo->completeTemplateDefinition(*Spec);
40509a199699SDimitry Andric   } LLVM_FALLTHROUGH;
4051e7145dcbSDimitry Andric   case Decl::CXXRecord:
405220e90f04SDimitry Andric     if (DebugInfo) {
405320e90f04SDimitry Andric       if (auto *ES = D->getASTContext().getExternalSource())
405420e90f04SDimitry Andric         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
405520e90f04SDimitry Andric           DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
405620e90f04SDimitry Andric     }
4057e7145dcbSDimitry Andric     // Emit any static data members, they may be definitions.
4058e7145dcbSDimitry Andric     for (auto *I : cast<CXXRecordDecl>(D)->decls())
4059e7145dcbSDimitry Andric       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
4060e7145dcbSDimitry Andric         EmitTopLevelDecl(I);
4061e7145dcbSDimitry Andric     break;
4062f22ef01cSRoman Divacky     // No code generation needed.
4063f22ef01cSRoman Divacky   case Decl::UsingShadow:
4064f22ef01cSRoman Divacky   case Decl::ClassTemplate:
4065f785676fSDimitry Andric   case Decl::VarTemplate:
4066f785676fSDimitry Andric   case Decl::VarTemplatePartialSpecialization:
4067f22ef01cSRoman Divacky   case Decl::FunctionTemplate:
4068bd5abe19SDimitry Andric   case Decl::TypeAliasTemplate:
4069bd5abe19SDimitry Andric   case Decl::Block:
4070139f7f9bSDimitry Andric   case Decl::Empty:
4071f22ef01cSRoman Divacky     break;
407259d1ed5bSDimitry Andric   case Decl::Using:          // using X; [C++]
407359d1ed5bSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
407459d1ed5bSDimitry Andric         DI->EmitUsingDecl(cast<UsingDecl>(*D));
407559d1ed5bSDimitry Andric     return;
4076f785676fSDimitry Andric   case Decl::NamespaceAlias:
4077f785676fSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
4078f785676fSDimitry Andric         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
4079f785676fSDimitry Andric     return;
4080284c1978SDimitry Andric   case Decl::UsingDirective: // using namespace X; [C++]
4081284c1978SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
4082284c1978SDimitry Andric       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
4083284c1978SDimitry Andric     return;
4084f22ef01cSRoman Divacky   case Decl::CXXConstructor:
4085f22ef01cSRoman Divacky     // Skip function templates
40863b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
40873b0f4066SDimitry Andric         cast<FunctionDecl>(D)->isLateTemplateParsed())
4088f22ef01cSRoman Divacky       return;
4089f22ef01cSRoman Divacky 
4090f785676fSDimitry Andric     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
4091f22ef01cSRoman Divacky     break;
4092f22ef01cSRoman Divacky   case Decl::CXXDestructor:
40933b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
40943b0f4066SDimitry Andric       return;
4095f785676fSDimitry Andric     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
4096f22ef01cSRoman Divacky     break;
4097f22ef01cSRoman Divacky 
4098f22ef01cSRoman Divacky   case Decl::StaticAssert:
4099f22ef01cSRoman Divacky     // Nothing to do.
4100f22ef01cSRoman Divacky     break;
4101f22ef01cSRoman Divacky 
4102f22ef01cSRoman Divacky   // Objective-C Decls
4103f22ef01cSRoman Divacky 
4104f22ef01cSRoman Divacky   // Forward declarations, no (immediate) code generation.
4105f22ef01cSRoman Divacky   case Decl::ObjCInterface:
41067ae0e2c9SDimitry Andric   case Decl::ObjCCategory:
4107f22ef01cSRoman Divacky     break;
4108f22ef01cSRoman Divacky 
4109dff0c46cSDimitry Andric   case Decl::ObjCProtocol: {
411059d1ed5bSDimitry Andric     auto *Proto = cast<ObjCProtocolDecl>(D);
4111dff0c46cSDimitry Andric     if (Proto->isThisDeclarationADefinition())
4112dff0c46cSDimitry Andric       ObjCRuntime->GenerateProtocol(Proto);
4113f22ef01cSRoman Divacky     break;
4114dff0c46cSDimitry Andric   }
4115f22ef01cSRoman Divacky 
4116f22ef01cSRoman Divacky   case Decl::ObjCCategoryImpl:
4117f22ef01cSRoman Divacky     // Categories have properties but don't support synthesize so we
4118f22ef01cSRoman Divacky     // can ignore them here.
41196122f3e6SDimitry Andric     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
4120f22ef01cSRoman Divacky     break;
4121f22ef01cSRoman Divacky 
4122f22ef01cSRoman Divacky   case Decl::ObjCImplementation: {
412359d1ed5bSDimitry Andric     auto *OMD = cast<ObjCImplementationDecl>(D);
4124f22ef01cSRoman Divacky     EmitObjCPropertyImplementations(OMD);
4125f22ef01cSRoman Divacky     EmitObjCIvarInitializations(OMD);
41266122f3e6SDimitry Andric     ObjCRuntime->GenerateClass(OMD);
4127dff0c46cSDimitry Andric     // Emit global variable debug information.
4128dff0c46cSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
4129e7145dcbSDimitry Andric       if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
4130139f7f9bSDimitry Andric         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
4131139f7f9bSDimitry Andric             OMD->getClassInterface()), OMD->getLocation());
4132f22ef01cSRoman Divacky     break;
4133f22ef01cSRoman Divacky   }
4134f22ef01cSRoman Divacky   case Decl::ObjCMethod: {
413559d1ed5bSDimitry Andric     auto *OMD = cast<ObjCMethodDecl>(D);
4136f22ef01cSRoman Divacky     // If this is not a prototype, emit the body.
4137f22ef01cSRoman Divacky     if (OMD->getBody())
4138f22ef01cSRoman Divacky       CodeGenFunction(*this).GenerateObjCMethod(OMD);
4139f22ef01cSRoman Divacky     break;
4140f22ef01cSRoman Divacky   }
4141f22ef01cSRoman Divacky   case Decl::ObjCCompatibleAlias:
4142dff0c46cSDimitry Andric     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
4143f22ef01cSRoman Divacky     break;
4144f22ef01cSRoman Divacky 
4145e7145dcbSDimitry Andric   case Decl::PragmaComment: {
4146e7145dcbSDimitry Andric     const auto *PCD = cast<PragmaCommentDecl>(D);
4147e7145dcbSDimitry Andric     switch (PCD->getCommentKind()) {
4148e7145dcbSDimitry Andric     case PCK_Unknown:
4149e7145dcbSDimitry Andric       llvm_unreachable("unexpected pragma comment kind");
4150e7145dcbSDimitry Andric     case PCK_Linker:
4151e7145dcbSDimitry Andric       AppendLinkerOptions(PCD->getArg());
4152e7145dcbSDimitry Andric       break;
4153e7145dcbSDimitry Andric     case PCK_Lib:
4154e7145dcbSDimitry Andric       AddDependentLib(PCD->getArg());
4155e7145dcbSDimitry Andric       break;
4156e7145dcbSDimitry Andric     case PCK_Compiler:
4157e7145dcbSDimitry Andric     case PCK_ExeStr:
4158e7145dcbSDimitry Andric     case PCK_User:
4159e7145dcbSDimitry Andric       break; // We ignore all of these.
4160e7145dcbSDimitry Andric     }
4161e7145dcbSDimitry Andric     break;
4162e7145dcbSDimitry Andric   }
4163e7145dcbSDimitry Andric 
4164e7145dcbSDimitry Andric   case Decl::PragmaDetectMismatch: {
4165e7145dcbSDimitry Andric     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
4166e7145dcbSDimitry Andric     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
4167e7145dcbSDimitry Andric     break;
4168e7145dcbSDimitry Andric   }
4169e7145dcbSDimitry Andric 
4170f22ef01cSRoman Divacky   case Decl::LinkageSpec:
4171f22ef01cSRoman Divacky     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
4172f22ef01cSRoman Divacky     break;
4173f22ef01cSRoman Divacky 
4174f22ef01cSRoman Divacky   case Decl::FileScopeAsm: {
417533956c43SDimitry Andric     // File-scope asm is ignored during device-side CUDA compilation.
417633956c43SDimitry Andric     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
417733956c43SDimitry Andric       break;
4178ea942507SDimitry Andric     // File-scope asm is ignored during device-side OpenMP compilation.
4179ea942507SDimitry Andric     if (LangOpts.OpenMPIsDevice)
4180ea942507SDimitry Andric       break;
418159d1ed5bSDimitry Andric     auto *AD = cast<FileScopeAsmDecl>(D);
418233956c43SDimitry Andric     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
4183f22ef01cSRoman Divacky     break;
4184f22ef01cSRoman Divacky   }
4185f22ef01cSRoman Divacky 
4186139f7f9bSDimitry Andric   case Decl::Import: {
418759d1ed5bSDimitry Andric     auto *Import = cast<ImportDecl>(D);
4188139f7f9bSDimitry Andric 
418944290647SDimitry Andric     // If we've already imported this module, we're done.
419044290647SDimitry Andric     if (!ImportedModules.insert(Import->getImportedModule()))
4191139f7f9bSDimitry Andric       break;
419244290647SDimitry Andric 
419344290647SDimitry Andric     // Emit debug information for direct imports.
419444290647SDimitry Andric     if (!Import->getImportedOwningModule()) {
41953dac3a9bSDimitry Andric       if (CGDebugInfo *DI = getModuleDebugInfo())
41963dac3a9bSDimitry Andric         DI->EmitImportDecl(*Import);
419744290647SDimitry Andric     }
4198139f7f9bSDimitry Andric 
419944290647SDimitry Andric     // Find all of the submodules and emit the module initializers.
420044290647SDimitry Andric     llvm::SmallPtrSet<clang::Module *, 16> Visited;
420144290647SDimitry Andric     SmallVector<clang::Module *, 16> Stack;
420244290647SDimitry Andric     Visited.insert(Import->getImportedModule());
420344290647SDimitry Andric     Stack.push_back(Import->getImportedModule());
420444290647SDimitry Andric 
420544290647SDimitry Andric     while (!Stack.empty()) {
420644290647SDimitry Andric       clang::Module *Mod = Stack.pop_back_val();
420744290647SDimitry Andric       if (!EmittedModuleInitializers.insert(Mod).second)
420844290647SDimitry Andric         continue;
420944290647SDimitry Andric 
421044290647SDimitry Andric       for (auto *D : Context.getModuleInitializers(Mod))
421144290647SDimitry Andric         EmitTopLevelDecl(D);
421244290647SDimitry Andric 
421344290647SDimitry Andric       // Visit the submodules of this module.
421444290647SDimitry Andric       for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
421544290647SDimitry Andric                                              SubEnd = Mod->submodule_end();
421644290647SDimitry Andric            Sub != SubEnd; ++Sub) {
421744290647SDimitry Andric         // Skip explicit children; they need to be explicitly imported to emit
421844290647SDimitry Andric         // the initializers.
421944290647SDimitry Andric         if ((*Sub)->IsExplicit)
422044290647SDimitry Andric           continue;
422144290647SDimitry Andric 
422244290647SDimitry Andric         if (Visited.insert(*Sub).second)
422344290647SDimitry Andric           Stack.push_back(*Sub);
422444290647SDimitry Andric       }
422544290647SDimitry Andric     }
4226139f7f9bSDimitry Andric     break;
4227139f7f9bSDimitry Andric   }
4228139f7f9bSDimitry Andric 
422944290647SDimitry Andric   case Decl::Export:
423044290647SDimitry Andric     EmitDeclContext(cast<ExportDecl>(D));
423144290647SDimitry Andric     break;
423244290647SDimitry Andric 
423339d628a0SDimitry Andric   case Decl::OMPThreadPrivate:
423439d628a0SDimitry Andric     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
423539d628a0SDimitry Andric     break;
423639d628a0SDimitry Andric 
4237e7145dcbSDimitry Andric   case Decl::OMPDeclareReduction:
4238e7145dcbSDimitry Andric     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
4239e7145dcbSDimitry Andric     break;
4240e7145dcbSDimitry Andric 
4241f22ef01cSRoman Divacky   default:
4242f22ef01cSRoman Divacky     // Make sure we handled everything we should, every other kind is a
4243f22ef01cSRoman Divacky     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
4244f22ef01cSRoman Divacky     // function. Need to recode Decl::Kind to do that easily.
4245f22ef01cSRoman Divacky     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
424639d628a0SDimitry Andric     break;
424739d628a0SDimitry Andric   }
424839d628a0SDimitry Andric }
424939d628a0SDimitry Andric 
425039d628a0SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
425139d628a0SDimitry Andric   // Do we need to generate coverage mapping?
425239d628a0SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
425339d628a0SDimitry Andric     return;
425439d628a0SDimitry Andric   switch (D->getKind()) {
425539d628a0SDimitry Andric   case Decl::CXXConversion:
425639d628a0SDimitry Andric   case Decl::CXXMethod:
425739d628a0SDimitry Andric   case Decl::Function:
425839d628a0SDimitry Andric   case Decl::ObjCMethod:
425939d628a0SDimitry Andric   case Decl::CXXConstructor:
426039d628a0SDimitry Andric   case Decl::CXXDestructor: {
42610623d748SDimitry Andric     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
426239d628a0SDimitry Andric       return;
42639a199699SDimitry Andric     SourceManager &SM = getContext().getSourceManager();
42649a199699SDimitry Andric     if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getLocStart()))
42659a199699SDimitry Andric       return;
426639d628a0SDimitry Andric     auto I = DeferredEmptyCoverageMappingDecls.find(D);
426739d628a0SDimitry Andric     if (I == DeferredEmptyCoverageMappingDecls.end())
426839d628a0SDimitry Andric       DeferredEmptyCoverageMappingDecls[D] = true;
426939d628a0SDimitry Andric     break;
427039d628a0SDimitry Andric   }
427139d628a0SDimitry Andric   default:
427239d628a0SDimitry Andric     break;
427339d628a0SDimitry Andric   };
427439d628a0SDimitry Andric }
427539d628a0SDimitry Andric 
427639d628a0SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
427739d628a0SDimitry Andric   // Do we need to generate coverage mapping?
427839d628a0SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
427939d628a0SDimitry Andric     return;
428039d628a0SDimitry Andric   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
428139d628a0SDimitry Andric     if (Fn->isTemplateInstantiation())
428239d628a0SDimitry Andric       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
428339d628a0SDimitry Andric   }
428439d628a0SDimitry Andric   auto I = DeferredEmptyCoverageMappingDecls.find(D);
428539d628a0SDimitry Andric   if (I == DeferredEmptyCoverageMappingDecls.end())
428639d628a0SDimitry Andric     DeferredEmptyCoverageMappingDecls[D] = false;
428739d628a0SDimitry Andric   else
428839d628a0SDimitry Andric     I->second = false;
428939d628a0SDimitry Andric }
429039d628a0SDimitry Andric 
429139d628a0SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
42929a199699SDimitry Andric   for (const auto &Entry : DeferredEmptyCoverageMappingDecls) {
42939a199699SDimitry Andric     if (!Entry.second)
429439d628a0SDimitry Andric       continue;
42959a199699SDimitry Andric     const Decl *D = Entry.first;
429639d628a0SDimitry Andric     switch (D->getKind()) {
429739d628a0SDimitry Andric     case Decl::CXXConversion:
429839d628a0SDimitry Andric     case Decl::CXXMethod:
429939d628a0SDimitry Andric     case Decl::Function:
430039d628a0SDimitry Andric     case Decl::ObjCMethod: {
430139d628a0SDimitry Andric       CodeGenPGO PGO(*this);
430239d628a0SDimitry Andric       GlobalDecl GD(cast<FunctionDecl>(D));
430339d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
430439d628a0SDimitry Andric                                   getFunctionLinkage(GD));
430539d628a0SDimitry Andric       break;
430639d628a0SDimitry Andric     }
430739d628a0SDimitry Andric     case Decl::CXXConstructor: {
430839d628a0SDimitry Andric       CodeGenPGO PGO(*this);
430939d628a0SDimitry Andric       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
431039d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
431139d628a0SDimitry Andric                                   getFunctionLinkage(GD));
431239d628a0SDimitry Andric       break;
431339d628a0SDimitry Andric     }
431439d628a0SDimitry Andric     case Decl::CXXDestructor: {
431539d628a0SDimitry Andric       CodeGenPGO PGO(*this);
431639d628a0SDimitry Andric       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
431739d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
431839d628a0SDimitry Andric                                   getFunctionLinkage(GD));
431939d628a0SDimitry Andric       break;
432039d628a0SDimitry Andric     }
432139d628a0SDimitry Andric     default:
432239d628a0SDimitry Andric       break;
432339d628a0SDimitry Andric     };
4324f22ef01cSRoman Divacky   }
4325f22ef01cSRoman Divacky }
4326ffd1746dSEd Schouten 
4327ffd1746dSEd Schouten /// Turns the given pointer into a constant.
4328ffd1746dSEd Schouten static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4329ffd1746dSEd Schouten                                           const void *Ptr) {
4330ffd1746dSEd Schouten   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
43316122f3e6SDimitry Andric   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
4332ffd1746dSEd Schouten   return llvm::ConstantInt::get(i64, PtrInt);
4333ffd1746dSEd Schouten }
4334ffd1746dSEd Schouten 
4335ffd1746dSEd Schouten static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
4336ffd1746dSEd Schouten                                    llvm::NamedMDNode *&GlobalMetadata,
4337ffd1746dSEd Schouten                                    GlobalDecl D,
4338ffd1746dSEd Schouten                                    llvm::GlobalValue *Addr) {
4339ffd1746dSEd Schouten   if (!GlobalMetadata)
4340ffd1746dSEd Schouten     GlobalMetadata =
4341ffd1746dSEd Schouten       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4342ffd1746dSEd Schouten 
4343ffd1746dSEd Schouten   // TODO: should we report variant information for ctors/dtors?
434439d628a0SDimitry Andric   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
434539d628a0SDimitry Andric                            llvm::ConstantAsMetadata::get(GetPointerConstant(
434639d628a0SDimitry Andric                                CGM.getLLVMContext(), D.getDecl()))};
43473b0f4066SDimitry Andric   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
4348ffd1746dSEd Schouten }
4349ffd1746dSEd Schouten 
4350284c1978SDimitry Andric /// For each function which is declared within an extern "C" region and marked
4351284c1978SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled
4352284c1978SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer
4353284c1978SDimitry Andric /// to such functions with an unmangled name from inline assembly within the
4354284c1978SDimitry Andric /// same translation unit.
4355284c1978SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() {
4356e7145dcbSDimitry Andric   // Don't do anything if we're generating CUDA device code -- the NVPTX
4357e7145dcbSDimitry Andric   // assembly target doesn't support aliases.
4358e7145dcbSDimitry Andric   if (Context.getTargetInfo().getTriple().isNVPTX())
4359e7145dcbSDimitry Andric     return;
43608f0fd8f6SDimitry Andric   for (auto &I : StaticExternCValues) {
43618f0fd8f6SDimitry Andric     IdentifierInfo *Name = I.first;
43628f0fd8f6SDimitry Andric     llvm::GlobalValue *Val = I.second;
4363284c1978SDimitry Andric     if (Val && !getModule().getNamedValue(Name->getName()))
436459d1ed5bSDimitry Andric       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
4365284c1978SDimitry Andric   }
4366284c1978SDimitry Andric }
4367284c1978SDimitry Andric 
436859d1ed5bSDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
436959d1ed5bSDimitry Andric                                              GlobalDecl &Result) const {
437059d1ed5bSDimitry Andric   auto Res = Manglings.find(MangledName);
437159d1ed5bSDimitry Andric   if (Res == Manglings.end())
437259d1ed5bSDimitry Andric     return false;
437359d1ed5bSDimitry Andric   Result = Res->getValue();
437459d1ed5bSDimitry Andric   return true;
437559d1ed5bSDimitry Andric }
437659d1ed5bSDimitry Andric 
4377ffd1746dSEd Schouten /// Emits metadata nodes associating all the global values in the
4378ffd1746dSEd Schouten /// current module with the Decls they came from.  This is useful for
4379ffd1746dSEd Schouten /// projects using IR gen as a subroutine.
4380ffd1746dSEd Schouten ///
4381ffd1746dSEd Schouten /// Since there's currently no way to associate an MDNode directly
4382ffd1746dSEd Schouten /// with an llvm::GlobalValue, we create a global named metadata
4383ffd1746dSEd Schouten /// with the name 'clang.global.decl.ptrs'.
4384ffd1746dSEd Schouten void CodeGenModule::EmitDeclMetadata() {
438559d1ed5bSDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
4386ffd1746dSEd Schouten 
438759d1ed5bSDimitry Andric   for (auto &I : MangledDeclNames) {
438859d1ed5bSDimitry Andric     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
43890623d748SDimitry Andric     // Some mangled names don't necessarily have an associated GlobalValue
43900623d748SDimitry Andric     // in this module, e.g. if we mangled it for DebugInfo.
43910623d748SDimitry Andric     if (Addr)
439259d1ed5bSDimitry Andric       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
4393ffd1746dSEd Schouten   }
4394ffd1746dSEd Schouten }
4395ffd1746dSEd Schouten 
4396ffd1746dSEd Schouten /// Emits metadata nodes for all the local variables in the current
4397ffd1746dSEd Schouten /// function.
4398ffd1746dSEd Schouten void CodeGenFunction::EmitDeclMetadata() {
4399ffd1746dSEd Schouten   if (LocalDeclMap.empty()) return;
4400ffd1746dSEd Schouten 
4401ffd1746dSEd Schouten   llvm::LLVMContext &Context = getLLVMContext();
4402ffd1746dSEd Schouten 
4403ffd1746dSEd Schouten   // Find the unique metadata ID for this name.
4404ffd1746dSEd Schouten   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
4405ffd1746dSEd Schouten 
440659d1ed5bSDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
4407ffd1746dSEd Schouten 
440859d1ed5bSDimitry Andric   for (auto &I : LocalDeclMap) {
440959d1ed5bSDimitry Andric     const Decl *D = I.first;
44100623d748SDimitry Andric     llvm::Value *Addr = I.second.getPointer();
441159d1ed5bSDimitry Andric     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
4412ffd1746dSEd Schouten       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
441339d628a0SDimitry Andric       Alloca->setMetadata(
441439d628a0SDimitry Andric           DeclPtrKind, llvm::MDNode::get(
441539d628a0SDimitry Andric                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
441659d1ed5bSDimitry Andric     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
4417ffd1746dSEd Schouten       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
4418ffd1746dSEd Schouten       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
4419ffd1746dSEd Schouten     }
4420ffd1746dSEd Schouten   }
4421ffd1746dSEd Schouten }
4422e580952dSDimitry Andric 
4423f785676fSDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() {
4424f785676fSDimitry Andric   llvm::NamedMDNode *IdentMetadata =
4425f785676fSDimitry Andric     TheModule.getOrInsertNamedMetadata("llvm.ident");
4426f785676fSDimitry Andric   std::string Version = getClangFullVersion();
4427f785676fSDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
4428f785676fSDimitry Andric 
442939d628a0SDimitry Andric   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
4430f785676fSDimitry Andric   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4431f785676fSDimitry Andric }
4432f785676fSDimitry Andric 
443359d1ed5bSDimitry Andric void CodeGenModule::EmitTargetMetadata() {
443439d628a0SDimitry Andric   // Warning, new MangledDeclNames may be appended within this loop.
443539d628a0SDimitry Andric   // We rely on MapVector insertions adding new elements to the end
443639d628a0SDimitry Andric   // of the container.
443739d628a0SDimitry Andric   // FIXME: Move this loop into the one target that needs it, and only
443839d628a0SDimitry Andric   // loop over those declarations for which we couldn't emit the target
443939d628a0SDimitry Andric   // metadata when we emitted the declaration.
444039d628a0SDimitry Andric   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
444139d628a0SDimitry Andric     auto Val = *(MangledDeclNames.begin() + I);
444239d628a0SDimitry Andric     const Decl *D = Val.first.getDecl()->getMostRecentDecl();
444339d628a0SDimitry Andric     llvm::GlobalValue *GV = GetGlobalValue(Val.second);
444459d1ed5bSDimitry Andric     getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
444559d1ed5bSDimitry Andric   }
444659d1ed5bSDimitry Andric }
444759d1ed5bSDimitry Andric 
4448bd5abe19SDimitry Andric void CodeGenModule::EmitCoverageFile() {
444944290647SDimitry Andric   if (getCodeGenOpts().CoverageDataFile.empty() &&
445044290647SDimitry Andric       getCodeGenOpts().CoverageNotesFile.empty())
445144290647SDimitry Andric     return;
445244290647SDimitry Andric 
445344290647SDimitry Andric   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
445444290647SDimitry Andric   if (!CUNode)
445544290647SDimitry Andric     return;
445644290647SDimitry Andric 
4457bd5abe19SDimitry Andric   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
4458bd5abe19SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
445944290647SDimitry Andric   auto *CoverageDataFile =
446044290647SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
446144290647SDimitry Andric   auto *CoverageNotesFile =
446244290647SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
4463bd5abe19SDimitry Andric   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
4464bd5abe19SDimitry Andric     llvm::MDNode *CU = CUNode->getOperand(i);
446544290647SDimitry Andric     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
446639d628a0SDimitry Andric     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
4467bd5abe19SDimitry Andric   }
4468bd5abe19SDimitry Andric }
44693861d79fSDimitry Andric 
447039d628a0SDimitry Andric llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
44713861d79fSDimitry Andric   // Sema has checked that all uuid strings are of the form
44723861d79fSDimitry Andric   // "12345678-1234-1234-1234-1234567890ab".
44733861d79fSDimitry Andric   assert(Uuid.size() == 36);
4474f785676fSDimitry Andric   for (unsigned i = 0; i < 36; ++i) {
4475f785676fSDimitry Andric     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
4476f785676fSDimitry Andric     else                                         assert(isHexDigit(Uuid[i]));
44773861d79fSDimitry Andric   }
44783861d79fSDimitry Andric 
447939d628a0SDimitry Andric   // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
4480f785676fSDimitry Andric   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
44813861d79fSDimitry Andric 
4482f785676fSDimitry Andric   llvm::Constant *Field3[8];
4483f785676fSDimitry Andric   for (unsigned Idx = 0; Idx < 8; ++Idx)
4484f785676fSDimitry Andric     Field3[Idx] = llvm::ConstantInt::get(
4485f785676fSDimitry Andric         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
44863861d79fSDimitry Andric 
4487f785676fSDimitry Andric   llvm::Constant *Fields[4] = {
4488f785676fSDimitry Andric     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
4489f785676fSDimitry Andric     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
4490f785676fSDimitry Andric     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
4491f785676fSDimitry Andric     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
4492f785676fSDimitry Andric   };
4493f785676fSDimitry Andric 
4494f785676fSDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
44953861d79fSDimitry Andric }
449659d1ed5bSDimitry Andric 
449759d1ed5bSDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
449859d1ed5bSDimitry Andric                                                        bool ForEH) {
449959d1ed5bSDimitry Andric   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
450059d1ed5bSDimitry Andric   // FIXME: should we even be calling this method if RTTI is disabled
450159d1ed5bSDimitry Andric   // and it's not for EH?
450259d1ed5bSDimitry Andric   if (!ForEH && !getLangOpts().RTTI)
450359d1ed5bSDimitry Andric     return llvm::Constant::getNullValue(Int8PtrTy);
450459d1ed5bSDimitry Andric 
450559d1ed5bSDimitry Andric   if (ForEH && Ty->isObjCObjectPointerType() &&
450659d1ed5bSDimitry Andric       LangOpts.ObjCRuntime.isGNUFamily())
450759d1ed5bSDimitry Andric     return ObjCRuntime->GetEHType(Ty);
450859d1ed5bSDimitry Andric 
450959d1ed5bSDimitry Andric   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
451059d1ed5bSDimitry Andric }
451159d1ed5bSDimitry Andric 
451239d628a0SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
451339d628a0SDimitry Andric   for (auto RefExpr : D->varlists()) {
451439d628a0SDimitry Andric     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
451539d628a0SDimitry Andric     bool PerformInit =
451639d628a0SDimitry Andric         VD->getAnyInitializer() &&
451739d628a0SDimitry Andric         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
451839d628a0SDimitry Andric                                                         /*ForRef=*/false);
45190623d748SDimitry Andric 
45200623d748SDimitry Andric     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
452133956c43SDimitry Andric     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
45220623d748SDimitry Andric             VD, Addr, RefExpr->getLocStart(), PerformInit))
452339d628a0SDimitry Andric       CXXGlobalInits.push_back(InitFunction);
452439d628a0SDimitry Andric   }
452539d628a0SDimitry Andric }
45268f0fd8f6SDimitry Andric 
45270623d748SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
45280623d748SDimitry Andric   llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
45290623d748SDimitry Andric   if (InternalId)
45300623d748SDimitry Andric     return InternalId;
45310623d748SDimitry Andric 
45320623d748SDimitry Andric   if (isExternallyVisible(T->getLinkage())) {
45338f0fd8f6SDimitry Andric     std::string OutName;
45348f0fd8f6SDimitry Andric     llvm::raw_string_ostream Out(OutName);
45350623d748SDimitry Andric     getCXXABI().getMangleContext().mangleTypeName(T, Out);
45368f0fd8f6SDimitry Andric 
45370623d748SDimitry Andric     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
45380623d748SDimitry Andric   } else {
45390623d748SDimitry Andric     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
45400623d748SDimitry Andric                                            llvm::ArrayRef<llvm::Metadata *>());
45410623d748SDimitry Andric   }
45420623d748SDimitry Andric 
45430623d748SDimitry Andric   return InternalId;
45440623d748SDimitry Andric }
45450623d748SDimitry Andric 
45469a199699SDimitry Andric // Generalize pointer types to a void pointer with the qualifiers of the
45479a199699SDimitry Andric // originally pointed-to type, e.g. 'const char *' and 'char * const *'
45489a199699SDimitry Andric // generalize to 'const void *' while 'char *' and 'const char **' generalize to
45499a199699SDimitry Andric // 'void *'.
45509a199699SDimitry Andric static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
45519a199699SDimitry Andric   if (!Ty->isPointerType())
45529a199699SDimitry Andric     return Ty;
45539a199699SDimitry Andric 
45549a199699SDimitry Andric   return Ctx.getPointerType(
45559a199699SDimitry Andric       QualType(Ctx.VoidTy).withCVRQualifiers(
45569a199699SDimitry Andric           Ty->getPointeeType().getCVRQualifiers()));
45579a199699SDimitry Andric }
45589a199699SDimitry Andric 
45599a199699SDimitry Andric // Apply type generalization to a FunctionType's return and argument types
45609a199699SDimitry Andric static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
45619a199699SDimitry Andric   if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
45629a199699SDimitry Andric     SmallVector<QualType, 8> GeneralizedParams;
45639a199699SDimitry Andric     for (auto &Param : FnType->param_types())
45649a199699SDimitry Andric       GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
45659a199699SDimitry Andric 
45669a199699SDimitry Andric     return Ctx.getFunctionType(
45679a199699SDimitry Andric         GeneralizeType(Ctx, FnType->getReturnType()),
45689a199699SDimitry Andric         GeneralizedParams, FnType->getExtProtoInfo());
45699a199699SDimitry Andric   }
45709a199699SDimitry Andric 
45719a199699SDimitry Andric   if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
45729a199699SDimitry Andric     return Ctx.getFunctionNoProtoType(
45739a199699SDimitry Andric         GeneralizeType(Ctx, FnType->getReturnType()));
45749a199699SDimitry Andric 
45759a199699SDimitry Andric   llvm_unreachable("Encountered unknown FunctionType");
45769a199699SDimitry Andric }
45779a199699SDimitry Andric 
45789a199699SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
45799a199699SDimitry Andric   T = GeneralizeFunctionType(getContext(), T);
45809a199699SDimitry Andric 
45819a199699SDimitry Andric   llvm::Metadata *&InternalId = GeneralizedMetadataIdMap[T.getCanonicalType()];
45829a199699SDimitry Andric   if (InternalId)
45839a199699SDimitry Andric     return InternalId;
45849a199699SDimitry Andric 
45859a199699SDimitry Andric   if (isExternallyVisible(T->getLinkage())) {
45869a199699SDimitry Andric     std::string OutName;
45879a199699SDimitry Andric     llvm::raw_string_ostream Out(OutName);
45889a199699SDimitry Andric     getCXXABI().getMangleContext().mangleTypeName(T, Out);
45899a199699SDimitry Andric     Out << ".generalized";
45909a199699SDimitry Andric 
45919a199699SDimitry Andric     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
45929a199699SDimitry Andric   } else {
45939a199699SDimitry Andric     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
45949a199699SDimitry Andric                                            llvm::ArrayRef<llvm::Metadata *>());
45959a199699SDimitry Andric   }
45969a199699SDimitry Andric 
45979a199699SDimitry Andric   return InternalId;
45989a199699SDimitry Andric }
45999a199699SDimitry Andric 
4600e7145dcbSDimitry Andric /// Returns whether this module needs the "all-vtables" type identifier.
4601e7145dcbSDimitry Andric bool CodeGenModule::NeedAllVtablesTypeId() const {
4602e7145dcbSDimitry Andric   // Returns true if at least one of vtable-based CFI checkers is enabled and
4603e7145dcbSDimitry Andric   // is not in the trapping mode.
4604e7145dcbSDimitry Andric   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
4605e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
4606e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
4607e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
4608e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
4609e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
4610e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
4611e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
4612e7145dcbSDimitry Andric }
4613e7145dcbSDimitry Andric 
4614e7145dcbSDimitry Andric void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
46150623d748SDimitry Andric                                           CharUnits Offset,
46160623d748SDimitry Andric                                           const CXXRecordDecl *RD) {
46170623d748SDimitry Andric   llvm::Metadata *MD =
46180623d748SDimitry Andric       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
4619e7145dcbSDimitry Andric   VTable->addTypeMetadata(Offset.getQuantity(), MD);
46200623d748SDimitry Andric 
4621e7145dcbSDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
4622e7145dcbSDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
4623e7145dcbSDimitry Andric       VTable->addTypeMetadata(Offset.getQuantity(),
4624e7145dcbSDimitry Andric                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
4625e7145dcbSDimitry Andric 
4626e7145dcbSDimitry Andric   if (NeedAllVtablesTypeId()) {
4627e7145dcbSDimitry Andric     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
4628e7145dcbSDimitry Andric     VTable->addTypeMetadata(Offset.getQuantity(), MD);
46290623d748SDimitry Andric   }
46300623d748SDimitry Andric }
46310623d748SDimitry Andric 
46320623d748SDimitry Andric // Fills in the supplied string map with the set of target features for the
46330623d748SDimitry Andric // passed in function.
46340623d748SDimitry Andric void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
46350623d748SDimitry Andric                                           const FunctionDecl *FD) {
46360623d748SDimitry Andric   StringRef TargetCPU = Target.getTargetOpts().CPU;
46370623d748SDimitry Andric   if (const auto *TD = FD->getAttr<TargetAttr>()) {
46380623d748SDimitry Andric     // If we have a TargetAttr build up the feature map based on that.
46390623d748SDimitry Andric     TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
46400623d748SDimitry Andric 
46419a199699SDimitry Andric     ParsedAttr.Features.erase(
46429a199699SDimitry Andric         llvm::remove_if(ParsedAttr.Features,
46439a199699SDimitry Andric                         [&](const std::string &Feat) {
46449a199699SDimitry Andric                           return !Target.isValidFeatureName(
46459a199699SDimitry Andric                               StringRef{Feat}.substr(1));
46469a199699SDimitry Andric                         }),
46479a199699SDimitry Andric         ParsedAttr.Features.end());
46489a199699SDimitry Andric 
46490623d748SDimitry Andric     // Make a copy of the features as passed on the command line into the
46500623d748SDimitry Andric     // beginning of the additional features from the function to override.
4651b40b48b8SDimitry Andric     ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
46520623d748SDimitry Andric                             Target.getTargetOpts().FeaturesAsWritten.begin(),
46530623d748SDimitry Andric                             Target.getTargetOpts().FeaturesAsWritten.end());
46540623d748SDimitry Andric 
46559a199699SDimitry Andric     if (ParsedAttr.Architecture != "" &&
46569a199699SDimitry Andric         Target.isValidCPUName(ParsedAttr.Architecture))
4657b40b48b8SDimitry Andric       TargetCPU = ParsedAttr.Architecture;
46580623d748SDimitry Andric 
46590623d748SDimitry Andric     // Now populate the feature map, first with the TargetCPU which is either
46600623d748SDimitry Andric     // the default or a new one from the target attribute string. Then we'll use
46610623d748SDimitry Andric     // the passed in features (FeaturesAsWritten) along with the new ones from
46620623d748SDimitry Andric     // the attribute.
4663b40b48b8SDimitry Andric     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
4664b40b48b8SDimitry Andric                           ParsedAttr.Features);
46650623d748SDimitry Andric   } else {
46660623d748SDimitry Andric     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
46670623d748SDimitry Andric                           Target.getTargetOpts().Features);
46680623d748SDimitry Andric   }
46698f0fd8f6SDimitry Andric }
4670e7145dcbSDimitry Andric 
4671e7145dcbSDimitry Andric llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
4672e7145dcbSDimitry Andric   if (!SanStats)
4673e7145dcbSDimitry Andric     SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
4674e7145dcbSDimitry Andric 
4675e7145dcbSDimitry Andric   return *SanStats;
4676e7145dcbSDimitry Andric }
467744290647SDimitry Andric llvm::Value *
467844290647SDimitry Andric CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
467944290647SDimitry Andric                                                   CodeGenFunction &CGF) {
46809a199699SDimitry Andric   llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
46819a199699SDimitry Andric   auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
468244290647SDimitry Andric   auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
468344290647SDimitry Andric   return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
468444290647SDimitry Andric                                 "__translate_sampler_initializer"),
468544290647SDimitry Andric                                 {C});
468644290647SDimitry Andric }
4687