]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/CodeGen/CodeGenModule.cpp
Merge ^/head r319801 through r320041.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / CodeGen / CodeGenModule.cpp
1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This coordinates the per-module state used while generating code.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "CodeGenModule.h"
15 #include "CGBlocks.h"
16 #include "CGCUDARuntime.h"
17 #include "CGCXXABI.h"
18 #include "CGCall.h"
19 #include "CGDebugInfo.h"
20 #include "CGObjCRuntime.h"
21 #include "CGOpenCLRuntime.h"
22 #include "CGOpenMPRuntime.h"
23 #include "CGOpenMPRuntimeNVPTX.h"
24 #include "CodeGenFunction.h"
25 #include "CodeGenPGO.h"
26 #include "CodeGenTBAA.h"
27 #include "CoverageMappingGen.h"
28 #include "TargetInfo.h"
29 #include "clang/AST/ASTContext.h"
30 #include "clang/AST/CharUnits.h"
31 #include "clang/AST/DeclCXX.h"
32 #include "clang/AST/DeclObjC.h"
33 #include "clang/AST/DeclTemplate.h"
34 #include "clang/AST/Mangle.h"
35 #include "clang/AST/RecordLayout.h"
36 #include "clang/AST/RecursiveASTVisitor.h"
37 #include "clang/Basic/Builtins.h"
38 #include "clang/Basic/CharInfo.h"
39 #include "clang/Basic/Diagnostic.h"
40 #include "clang/Basic/Module.h"
41 #include "clang/Basic/SourceManager.h"
42 #include "clang/Basic/TargetInfo.h"
43 #include "clang/Basic/Version.h"
44 #include "clang/CodeGen/ConstantInitBuilder.h"
45 #include "clang/Frontend/CodeGenOptions.h"
46 #include "clang/Sema/SemaDiagnostic.h"
47 #include "llvm/ADT/Triple.h"
48 #include "llvm/Analysis/TargetLibraryInfo.h"
49 #include "llvm/IR/CallSite.h"
50 #include "llvm/IR/CallingConv.h"
51 #include "llvm/IR/DataLayout.h"
52 #include "llvm/IR/Intrinsics.h"
53 #include "llvm/IR/LLVMContext.h"
54 #include "llvm/IR/Module.h"
55 #include "llvm/ProfileData/InstrProfReader.h"
56 #include "llvm/Support/ConvertUTF.h"
57 #include "llvm/Support/ErrorHandling.h"
58 #include "llvm/Support/MD5.h"
59
60 using namespace clang;
61 using namespace CodeGen;
62
63 static const char AnnotationSection[] = "llvm.metadata";
64
65 static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
66   switch (CGM.getTarget().getCXXABI().getKind()) {
67   case TargetCXXABI::GenericAArch64:
68   case TargetCXXABI::GenericARM:
69   case TargetCXXABI::iOS:
70   case TargetCXXABI::iOS64:
71   case TargetCXXABI::WatchOS:
72   case TargetCXXABI::GenericMIPS:
73   case TargetCXXABI::GenericItanium:
74   case TargetCXXABI::WebAssembly:
75     return CreateItaniumCXXABI(CGM);
76   case TargetCXXABI::Microsoft:
77     return CreateMicrosoftCXXABI(CGM);
78   }
79
80   llvm_unreachable("invalid C++ ABI kind");
81 }
82
83 CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
84                              const PreprocessorOptions &PPO,
85                              const CodeGenOptions &CGO, llvm::Module &M,
86                              DiagnosticsEngine &diags,
87                              CoverageSourceInfo *CoverageInfo)
88     : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
89       PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
90       Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
91       VMContext(M.getContext()), Types(*this), VTables(*this),
92       SanitizerMD(new SanitizerMetadata(*this)) {
93
94   // Initialize the type cache.
95   llvm::LLVMContext &LLVMContext = M.getContext();
96   VoidTy = llvm::Type::getVoidTy(LLVMContext);
97   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
98   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
99   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
100   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
101   FloatTy = llvm::Type::getFloatTy(LLVMContext);
102   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
103   PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
104   PointerAlignInBytes =
105     C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
106   SizeSizeInBytes =
107     C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
108   IntAlignInBytes =
109     C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
110   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
111   IntPtrTy = llvm::IntegerType::get(LLVMContext,
112     C.getTargetInfo().getMaxPointerWidth());
113   Int8PtrTy = Int8Ty->getPointerTo(0);
114   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
115   AllocaInt8PtrTy = Int8Ty->getPointerTo(
116       M.getDataLayout().getAllocaAddrSpace());
117   ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
118
119   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
120   BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
121
122   if (LangOpts.ObjC1)
123     createObjCRuntime();
124   if (LangOpts.OpenCL)
125     createOpenCLRuntime();
126   if (LangOpts.OpenMP)
127     createOpenMPRuntime();
128   if (LangOpts.CUDA)
129     createCUDARuntime();
130
131   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
132   if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
133       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
134     TBAA.reset(new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
135                                getCXXABI().getMangleContext()));
136
137   // If debug info or coverage generation is enabled, create the CGDebugInfo
138   // object.
139   if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
140       CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
141     DebugInfo.reset(new CGDebugInfo(*this));
142
143   Block.GlobalUniqueCount = 0;
144
145   if (C.getLangOpts().ObjC1)
146     ObjCData.reset(new ObjCEntrypoints());
147
148   if (CodeGenOpts.hasProfileClangUse()) {
149     auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
150         CodeGenOpts.ProfileInstrumentUsePath);
151     if (auto E = ReaderOrErr.takeError()) {
152       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
153                                               "Could not read profile %0: %1");
154       llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
155         getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
156                                   << EI.message();
157       });
158     } else
159       PGOReader = std::move(ReaderOrErr.get());
160   }
161
162   // If coverage mapping generation is enabled, create the
163   // CoverageMappingModuleGen object.
164   if (CodeGenOpts.CoverageMapping)
165     CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
166 }
167
168 CodeGenModule::~CodeGenModule() {}
169
170 void CodeGenModule::createObjCRuntime() {
171   // This is just isGNUFamily(), but we want to force implementors of
172   // new ABIs to decide how best to do this.
173   switch (LangOpts.ObjCRuntime.getKind()) {
174   case ObjCRuntime::GNUstep:
175   case ObjCRuntime::GCC:
176   case ObjCRuntime::ObjFW:
177     ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
178     return;
179
180   case ObjCRuntime::FragileMacOSX:
181   case ObjCRuntime::MacOSX:
182   case ObjCRuntime::iOS:
183   case ObjCRuntime::WatchOS:
184     ObjCRuntime.reset(CreateMacObjCRuntime(*this));
185     return;
186   }
187   llvm_unreachable("bad runtime kind");
188 }
189
190 void CodeGenModule::createOpenCLRuntime() {
191   OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
192 }
193
194 void CodeGenModule::createOpenMPRuntime() {
195   // Select a specialized code generation class based on the target, if any.
196   // If it does not exist use the default implementation.
197   switch (getTriple().getArch()) {
198   case llvm::Triple::nvptx:
199   case llvm::Triple::nvptx64:
200     assert(getLangOpts().OpenMPIsDevice &&
201            "OpenMP NVPTX is only prepared to deal with device code.");
202     OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
203     break;
204   default:
205     OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
206     break;
207   }
208 }
209
210 void CodeGenModule::createCUDARuntime() {
211   CUDARuntime.reset(CreateNVCUDARuntime(*this));
212 }
213
214 void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
215   Replacements[Name] = C;
216 }
217
218 void CodeGenModule::applyReplacements() {
219   for (auto &I : Replacements) {
220     StringRef MangledName = I.first();
221     llvm::Constant *Replacement = I.second;
222     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
223     if (!Entry)
224       continue;
225     auto *OldF = cast<llvm::Function>(Entry);
226     auto *NewF = dyn_cast<llvm::Function>(Replacement);
227     if (!NewF) {
228       if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
229         NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
230       } else {
231         auto *CE = cast<llvm::ConstantExpr>(Replacement);
232         assert(CE->getOpcode() == llvm::Instruction::BitCast ||
233                CE->getOpcode() == llvm::Instruction::GetElementPtr);
234         NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
235       }
236     }
237
238     // Replace old with new, but keep the old order.
239     OldF->replaceAllUsesWith(Replacement);
240     if (NewF) {
241       NewF->removeFromParent();
242       OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
243                                                        NewF);
244     }
245     OldF->eraseFromParent();
246   }
247 }
248
249 void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
250   GlobalValReplacements.push_back(std::make_pair(GV, C));
251 }
252
253 void CodeGenModule::applyGlobalValReplacements() {
254   for (auto &I : GlobalValReplacements) {
255     llvm::GlobalValue *GV = I.first;
256     llvm::Constant *C = I.second;
257
258     GV->replaceAllUsesWith(C);
259     GV->eraseFromParent();
260   }
261 }
262
263 // This is only used in aliases that we created and we know they have a
264 // linear structure.
265 static const llvm::GlobalObject *getAliasedGlobal(
266     const llvm::GlobalIndirectSymbol &GIS) {
267   llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
268   const llvm::Constant *C = &GIS;
269   for (;;) {
270     C = C->stripPointerCasts();
271     if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
272       return GO;
273     // stripPointerCasts will not walk over weak aliases.
274     auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
275     if (!GIS2)
276       return nullptr;
277     if (!Visited.insert(GIS2).second)
278       return nullptr;
279     C = GIS2->getIndirectSymbol();
280   }
281 }
282
283 void CodeGenModule::checkAliases() {
284   // Check if the constructed aliases are well formed. It is really unfortunate
285   // that we have to do this in CodeGen, but we only construct mangled names
286   // and aliases during codegen.
287   bool Error = false;
288   DiagnosticsEngine &Diags = getDiags();
289   for (const GlobalDecl &GD : Aliases) {
290     const auto *D = cast<ValueDecl>(GD.getDecl());
291     SourceLocation Location;
292     bool IsIFunc = D->hasAttr<IFuncAttr>();
293     if (const Attr *A = D->getDefiningAttr())
294       Location = A->getLocation();
295     else
296       llvm_unreachable("Not an alias or ifunc?");
297     StringRef MangledName = getMangledName(GD);
298     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
299     auto *Alias  = cast<llvm::GlobalIndirectSymbol>(Entry);
300     const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
301     if (!GV) {
302       Error = true;
303       Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
304     } else if (GV->isDeclaration()) {
305       Error = true;
306       Diags.Report(Location, diag::err_alias_to_undefined)
307           << IsIFunc << IsIFunc;
308     } else if (IsIFunc) {
309       // Check resolver function type.
310       llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
311           GV->getType()->getPointerElementType());
312       assert(FTy);
313       if (!FTy->getReturnType()->isPointerTy())
314         Diags.Report(Location, diag::err_ifunc_resolver_return);
315       if (FTy->getNumParams())
316         Diags.Report(Location, diag::err_ifunc_resolver_params);
317     }
318
319     llvm::Constant *Aliasee = Alias->getIndirectSymbol();
320     llvm::GlobalValue *AliaseeGV;
321     if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
322       AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
323     else
324       AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
325
326     if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
327       StringRef AliasSection = SA->getName();
328       if (AliasSection != AliaseeGV->getSection())
329         Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
330             << AliasSection << IsIFunc << IsIFunc;
331     }
332
333     // We have to handle alias to weak aliases in here. LLVM itself disallows
334     // this since the object semantics would not match the IL one. For
335     // compatibility with gcc we implement it by just pointing the alias
336     // to its aliasee's aliasee. We also warn, since the user is probably
337     // expecting the link to be weak.
338     if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
339       if (GA->isInterposable()) {
340         Diags.Report(Location, diag::warn_alias_to_weak_alias)
341             << GV->getName() << GA->getName() << IsIFunc;
342         Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
343             GA->getIndirectSymbol(), Alias->getType());
344         Alias->setIndirectSymbol(Aliasee);
345       }
346     }
347   }
348   if (!Error)
349     return;
350
351   for (const GlobalDecl &GD : Aliases) {
352     StringRef MangledName = getMangledName(GD);
353     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
354     auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
355     Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
356     Alias->eraseFromParent();
357   }
358 }
359
360 void CodeGenModule::clear() {
361   DeferredDeclsToEmit.clear();
362   if (OpenMPRuntime)
363     OpenMPRuntime->clear();
364 }
365
366 void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
367                                        StringRef MainFile) {
368   if (!hasDiagnostics())
369     return;
370   if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
371     if (MainFile.empty())
372       MainFile = "<stdin>";
373     Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
374   } else {
375     if (Mismatched > 0)
376       Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
377
378     if (Missing > 0)
379       Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
380   }
381 }
382
383 void CodeGenModule::Release() {
384   EmitDeferred();
385   EmitVTablesOpportunistically();
386   applyGlobalValReplacements();
387   applyReplacements();
388   checkAliases();
389   EmitCXXGlobalInitFunc();
390   EmitCXXGlobalDtorFunc();
391   EmitCXXThreadLocalInitFunc();
392   if (ObjCRuntime)
393     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
394       AddGlobalCtor(ObjCInitFunction);
395   if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
396       CUDARuntime) {
397     if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
398       AddGlobalCtor(CudaCtorFunction);
399     if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
400       AddGlobalDtor(CudaDtorFunction);
401   }
402   if (OpenMPRuntime)
403     if (llvm::Function *OpenMPRegistrationFunction =
404             OpenMPRuntime->emitRegistrationFunction()) {
405       auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
406         OpenMPRegistrationFunction : nullptr;
407       AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
408     }
409   if (PGOReader) {
410     getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
411     if (PGOStats.hasDiagnostics())
412       PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
413   }
414   EmitCtorList(GlobalCtors, "llvm.global_ctors");
415   EmitCtorList(GlobalDtors, "llvm.global_dtors");
416   EmitGlobalAnnotations();
417   EmitStaticExternCAliases();
418   EmitDeferredUnusedCoverageMappings();
419   if (CoverageMapping)
420     CoverageMapping->emit();
421   if (CodeGenOpts.SanitizeCfiCrossDso) {
422     CodeGenFunction(*this).EmitCfiCheckFail();
423     CodeGenFunction(*this).EmitCfiCheckStub();
424   }
425   emitAtAvailableLinkGuard();
426   emitLLVMUsed();
427   if (SanStats)
428     SanStats->finish();
429
430   if (CodeGenOpts.Autolink &&
431       (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
432     EmitModuleLinkOptions();
433   }
434
435   // Record mregparm value now so it is visible through rest of codegen.
436   if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
437     getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
438                               CodeGenOpts.NumRegisterParameters);
439   
440   if (CodeGenOpts.DwarfVersion) {
441     // We actually want the latest version when there are conflicts.
442     // We can change from Warning to Latest if such mode is supported.
443     getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
444                               CodeGenOpts.DwarfVersion);
445   }
446   if (CodeGenOpts.EmitCodeView) {
447     // Indicate that we want CodeView in the metadata.
448     getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
449   }
450   if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
451     // We don't support LTO with 2 with different StrictVTablePointers
452     // FIXME: we could support it by stripping all the information introduced
453     // by StrictVTablePointers.
454
455     getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
456
457     llvm::Metadata *Ops[2] = {
458               llvm::MDString::get(VMContext, "StrictVTablePointers"),
459               llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
460                   llvm::Type::getInt32Ty(VMContext), 1))};
461
462     getModule().addModuleFlag(llvm::Module::Require,
463                               "StrictVTablePointersRequirement",
464                               llvm::MDNode::get(VMContext, Ops));
465   }
466   if (DebugInfo)
467     // We support a single version in the linked module. The LLVM
468     // parser will drop debug info with a different version number
469     // (and warn about it, too).
470     getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
471                               llvm::DEBUG_METADATA_VERSION);
472
473   // Width of wchar_t in bytes
474   uint64_t WCharWidth =
475       Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
476   assert((LangOpts.ShortWChar ||
477           llvm::TargetLibraryInfoImpl::getTargetWCharSize(Target.getTriple()) ==
478               Target.getWCharWidth() / 8) &&
479          "LLVM wchar_t size out of sync");
480
481   // We need to record the widths of enums and wchar_t, so that we can generate
482   // the correct build attributes in the ARM backend. wchar_size is also used by
483   // TargetLibraryInfo.
484   getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
485
486   llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
487   if (   Arch == llvm::Triple::arm
488       || Arch == llvm::Triple::armeb
489       || Arch == llvm::Triple::thumb
490       || Arch == llvm::Triple::thumbeb) {
491     // The minimum width of an enum in bytes
492     uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
493     getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
494   }
495
496   if (CodeGenOpts.SanitizeCfiCrossDso) {
497     // Indicate that we want cross-DSO control flow integrity checks.
498     getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
499   }
500
501   if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
502     // Indicate whether __nvvm_reflect should be configured to flush denormal
503     // floating point values to 0.  (This corresponds to its "__CUDA_FTZ"
504     // property.)
505     getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
506                               LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
507   }
508
509   if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
510     assert(PLevel < 3 && "Invalid PIC Level");
511     getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
512     if (Context.getLangOpts().PIE)
513       getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
514   }
515
516   SimplifyPersonality();
517
518   if (getCodeGenOpts().EmitDeclMetadata)
519     EmitDeclMetadata();
520
521   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
522     EmitCoverageFile();
523
524   if (DebugInfo)
525     DebugInfo->finalize();
526
527   EmitVersionIdentMetadata();
528
529   EmitTargetMetadata();
530 }
531
532 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
533   // Make sure that this type is translated.
534   Types.UpdateCompletedType(TD);
535 }
536
537 void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
538   // Make sure that this type is translated.
539   Types.RefreshTypeCacheForClass(RD);
540 }
541
542 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
543   if (!TBAA)
544     return nullptr;
545   return TBAA->getTBAAInfo(QTy);
546 }
547
548 llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
549   if (!TBAA)
550     return nullptr;
551   return TBAA->getTBAAInfoForVTablePtr();
552 }
553
554 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
555   if (!TBAA)
556     return nullptr;
557   return TBAA->getTBAAStructInfo(QTy);
558 }
559
560 llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
561                                                   llvm::MDNode *AccessN,
562                                                   uint64_t O) {
563   if (!TBAA)
564     return nullptr;
565   return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
566 }
567
568 /// Decorate the instruction with a TBAA tag. For both scalar TBAA
569 /// and struct-path aware TBAA, the tag has the same format:
570 /// base type, access type and offset.
571 /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
572 void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
573                                                 llvm::MDNode *TBAAInfo,
574                                                 bool ConvertTypeToTag) {
575   if (ConvertTypeToTag && TBAA)
576     Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
577                       TBAA->getTBAAScalarTagInfo(TBAAInfo));
578   else
579     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
580 }
581
582 void CodeGenModule::DecorateInstructionWithInvariantGroup(
583     llvm::Instruction *I, const CXXRecordDecl *RD) {
584   I->setMetadata(llvm::LLVMContext::MD_invariant_group,
585                  llvm::MDNode::get(getLLVMContext(), {}));
586 }
587
588 void CodeGenModule::Error(SourceLocation loc, StringRef message) {
589   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
590   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
591 }
592
593 /// ErrorUnsupported - Print out an error that codegen doesn't support the
594 /// specified stmt yet.
595 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
596   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
597                                                "cannot compile this %0 yet");
598   std::string Msg = Type;
599   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
600     << Msg << S->getSourceRange();
601 }
602
603 /// ErrorUnsupported - Print out an error that codegen doesn't support the
604 /// specified decl yet.
605 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
606   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
607                                                "cannot compile this %0 yet");
608   std::string Msg = Type;
609   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
610 }
611
612 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
613   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
614 }
615
616 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
617                                         const NamedDecl *D) const {
618   // Internal definitions always have default visibility.
619   if (GV->hasLocalLinkage()) {
620     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
621     return;
622   }
623
624   // Set visibility for definitions.
625   LinkageInfo LV = D->getLinkageAndVisibility();
626   if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
627     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
628 }
629
630 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
631   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
632       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
633       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
634       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
635       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
636 }
637
638 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
639     CodeGenOptions::TLSModel M) {
640   switch (M) {
641   case CodeGenOptions::GeneralDynamicTLSModel:
642     return llvm::GlobalVariable::GeneralDynamicTLSModel;
643   case CodeGenOptions::LocalDynamicTLSModel:
644     return llvm::GlobalVariable::LocalDynamicTLSModel;
645   case CodeGenOptions::InitialExecTLSModel:
646     return llvm::GlobalVariable::InitialExecTLSModel;
647   case CodeGenOptions::LocalExecTLSModel:
648     return llvm::GlobalVariable::LocalExecTLSModel;
649   }
650   llvm_unreachable("Invalid TLS model!");
651 }
652
653 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
654   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
655
656   llvm::GlobalValue::ThreadLocalMode TLM;
657   TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
658
659   // Override the TLS model if it is explicitly specified.
660   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
661     TLM = GetLLVMTLSModel(Attr->getModel());
662   }
663
664   GV->setThreadLocalMode(TLM);
665 }
666
667 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
668   GlobalDecl CanonicalGD = GD.getCanonicalDecl();
669
670   // Some ABIs don't have constructor variants.  Make sure that base and
671   // complete constructors get mangled the same.
672   if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
673     if (!getTarget().getCXXABI().hasConstructorVariants()) {
674       CXXCtorType OrigCtorType = GD.getCtorType();
675       assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
676       if (OrigCtorType == Ctor_Base)
677         CanonicalGD = GlobalDecl(CD, Ctor_Complete);
678     }
679   }
680
681   StringRef &FoundStr = MangledDeclNames[CanonicalGD];
682   if (!FoundStr.empty())
683     return FoundStr;
684
685   const auto *ND = cast<NamedDecl>(GD.getDecl());
686   SmallString<256> Buffer;
687   StringRef Str;
688   if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
689     llvm::raw_svector_ostream Out(Buffer);
690     if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
691       getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
692     else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
693       getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
694     else
695       getCXXABI().getMangleContext().mangleName(ND, Out);
696     Str = Out.str();
697   } else {
698     IdentifierInfo *II = ND->getIdentifier();
699     assert(II && "Attempt to mangle unnamed decl.");
700     const auto *FD = dyn_cast<FunctionDecl>(ND);
701
702     if (FD &&
703         FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
704       llvm::raw_svector_ostream Out(Buffer);
705       Out << "__regcall3__" << II->getName();
706       Str = Out.str();
707     } else {
708       Str = II->getName();
709     }
710   }
711
712   // Keep the first result in the case of a mangling collision.
713   auto Result = Manglings.insert(std::make_pair(Str, GD));
714   return FoundStr = Result.first->first();
715 }
716
717 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
718                                              const BlockDecl *BD) {
719   MangleContext &MangleCtx = getCXXABI().getMangleContext();
720   const Decl *D = GD.getDecl();
721
722   SmallString<256> Buffer;
723   llvm::raw_svector_ostream Out(Buffer);
724   if (!D)
725     MangleCtx.mangleGlobalBlock(BD, 
726       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
727   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
728     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
729   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
730     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
731   else
732     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
733
734   auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
735   return Result.first->first();
736 }
737
738 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
739   return getModule().getNamedValue(Name);
740 }
741
742 /// AddGlobalCtor - Add a function to the list that will be called before
743 /// main() runs.
744 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
745                                   llvm::Constant *AssociatedData) {
746   // FIXME: Type coercion of void()* types.
747   GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
748 }
749
750 /// AddGlobalDtor - Add a function to the list that will be called
751 /// when the module is unloaded.
752 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
753   // FIXME: Type coercion of void()* types.
754   GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
755 }
756
757 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
758   if (Fns.empty()) return;
759
760   // Ctor function type is void()*.
761   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
762   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
763
764   // Get the type of a ctor entry, { i32, void ()*, i8* }.
765   llvm::StructType *CtorStructTy = llvm::StructType::get(
766       Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy);
767
768   // Construct the constructor and destructor arrays.
769   ConstantInitBuilder builder(*this);
770   auto ctors = builder.beginArray(CtorStructTy);
771   for (const auto &I : Fns) {
772     auto ctor = ctors.beginStruct(CtorStructTy);
773     ctor.addInt(Int32Ty, I.Priority);
774     ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
775     if (I.AssociatedData)
776       ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
777     else
778       ctor.addNullPointer(VoidPtrTy);
779     ctor.finishAndAddTo(ctors);
780   }
781
782   auto list =
783     ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
784                                 /*constant*/ false,
785                                 llvm::GlobalValue::AppendingLinkage);
786
787   // The LTO linker doesn't seem to like it when we set an alignment
788   // on appending variables.  Take it off as a workaround.
789   list->setAlignment(0);
790
791   Fns.clear();
792 }
793
794 llvm::GlobalValue::LinkageTypes
795 CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
796   const auto *D = cast<FunctionDecl>(GD.getDecl());
797
798   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
799
800   if (isa<CXXDestructorDecl>(D) &&
801       getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
802                                          GD.getDtorType())) {
803     // Destructor variants in the Microsoft C++ ABI are always internal or
804     // linkonce_odr thunks emitted on an as-needed basis.
805     return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
806                                    : llvm::GlobalValue::LinkOnceODRLinkage;
807   }
808
809   if (isa<CXXConstructorDecl>(D) &&
810       cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
811       Context.getTargetInfo().getCXXABI().isMicrosoft()) {
812     // Our approach to inheriting constructors is fundamentally different from
813     // that used by the MS ABI, so keep our inheriting constructor thunks
814     // internal rather than trying to pick an unambiguous mangling for them.
815     return llvm::GlobalValue::InternalLinkage;
816   }
817
818   return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
819 }
820
821 void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
822   const auto *FD = cast<FunctionDecl>(GD.getDecl());
823
824   if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
825     if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
826       // Don't dllexport/import destructor thunks.
827       F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
828       return;
829     }
830   }
831
832   if (FD->hasAttr<DLLImportAttr>())
833     F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
834   else if (FD->hasAttr<DLLExportAttr>())
835     F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
836   else
837     F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
838 }
839
840 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
841   llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
842   if (!MDS) return nullptr;
843
844   return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
845 }
846
847 void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
848                                                     llvm::Function *F) {
849   setNonAliasAttributes(D, F);
850 }
851
852 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
853                                               const CGFunctionInfo &Info,
854                                               llvm::Function *F) {
855   unsigned CallingConv;
856   llvm::AttributeList PAL;
857   ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false);
858   F->setAttributes(PAL);
859   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
860 }
861
862 /// Determines whether the language options require us to model
863 /// unwind exceptions.  We treat -fexceptions as mandating this
864 /// except under the fragile ObjC ABI with only ObjC exceptions
865 /// enabled.  This means, for example, that C with -fexceptions
866 /// enables this.
867 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
868   // If exceptions are completely disabled, obviously this is false.
869   if (!LangOpts.Exceptions) return false;
870
871   // If C++ exceptions are enabled, this is true.
872   if (LangOpts.CXXExceptions) return true;
873
874   // If ObjC exceptions are enabled, this depends on the ABI.
875   if (LangOpts.ObjCExceptions) {
876     return LangOpts.ObjCRuntime.hasUnwindExceptions();
877   }
878
879   return true;
880 }
881
882 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
883                                                            llvm::Function *F) {
884   llvm::AttrBuilder B;
885
886   if (CodeGenOpts.UnwindTables)
887     B.addAttribute(llvm::Attribute::UWTable);
888
889   if (!hasUnwindExceptions(LangOpts))
890     B.addAttribute(llvm::Attribute::NoUnwind);
891
892   if (LangOpts.getStackProtector() == LangOptions::SSPOn)
893     B.addAttribute(llvm::Attribute::StackProtect);
894   else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
895     B.addAttribute(llvm::Attribute::StackProtectStrong);
896   else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
897     B.addAttribute(llvm::Attribute::StackProtectReq);
898
899   if (!D) {
900     // If we don't have a declaration to control inlining, the function isn't
901     // explicitly marked as alwaysinline for semantic reasons, and inlining is
902     // disabled, mark the function as noinline.
903     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
904         CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
905       B.addAttribute(llvm::Attribute::NoInline);
906
907     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
908     return;
909   }
910
911   // Track whether we need to add the optnone LLVM attribute,
912   // starting with the default for this optimization level.
913   bool ShouldAddOptNone =
914       !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
915   // We can't add optnone in the following cases, it won't pass the verifier.
916   ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
917   ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
918   ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
919
920   if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
921     B.addAttribute(llvm::Attribute::OptimizeNone);
922
923     // OptimizeNone implies noinline; we should not be inlining such functions.
924     B.addAttribute(llvm::Attribute::NoInline);
925     assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
926            "OptimizeNone and AlwaysInline on same function!");
927
928     // We still need to handle naked functions even though optnone subsumes
929     // much of their semantics.
930     if (D->hasAttr<NakedAttr>())
931       B.addAttribute(llvm::Attribute::Naked);
932
933     // OptimizeNone wins over OptimizeForSize and MinSize.
934     F->removeFnAttr(llvm::Attribute::OptimizeForSize);
935     F->removeFnAttr(llvm::Attribute::MinSize);
936   } else if (D->hasAttr<NakedAttr>()) {
937     // Naked implies noinline: we should not be inlining such functions.
938     B.addAttribute(llvm::Attribute::Naked);
939     B.addAttribute(llvm::Attribute::NoInline);
940   } else if (D->hasAttr<NoDuplicateAttr>()) {
941     B.addAttribute(llvm::Attribute::NoDuplicate);
942   } else if (D->hasAttr<NoInlineAttr>()) {
943     B.addAttribute(llvm::Attribute::NoInline);
944   } else if (D->hasAttr<AlwaysInlineAttr>() &&
945              !F->hasFnAttribute(llvm::Attribute::NoInline)) {
946     // (noinline wins over always_inline, and we can't specify both in IR)
947     B.addAttribute(llvm::Attribute::AlwaysInline);
948   } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
949     // If we're not inlining, then force everything that isn't always_inline to
950     // carry an explicit noinline attribute.
951     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
952       B.addAttribute(llvm::Attribute::NoInline);
953   } else {
954     // Otherwise, propagate the inline hint attribute and potentially use its
955     // absence to mark things as noinline.
956     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
957       if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
958             return Redecl->isInlineSpecified();
959           })) {
960         B.addAttribute(llvm::Attribute::InlineHint);
961       } else if (CodeGenOpts.getInlining() ==
962                      CodeGenOptions::OnlyHintInlining &&
963                  !FD->isInlined() &&
964                  !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
965         B.addAttribute(llvm::Attribute::NoInline);
966       }
967     }
968   }
969
970   // Add other optimization related attributes if we are optimizing this
971   // function.
972   if (!D->hasAttr<OptimizeNoneAttr>()) {
973     if (D->hasAttr<ColdAttr>()) {
974       if (!ShouldAddOptNone)
975         B.addAttribute(llvm::Attribute::OptimizeForSize);
976       B.addAttribute(llvm::Attribute::Cold);
977     }
978
979     if (D->hasAttr<MinSizeAttr>())
980       B.addAttribute(llvm::Attribute::MinSize);
981   }
982
983   F->addAttributes(llvm::AttributeList::FunctionIndex, B);
984
985   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
986   if (alignment)
987     F->setAlignment(alignment);
988
989   // Some C++ ABIs require 2-byte alignment for member functions, in order to
990   // reserve a bit for differentiating between virtual and non-virtual member
991   // functions. If the current target's C++ ABI requires this and this is a
992   // member function, set its alignment accordingly.
993   if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
994     if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
995       F->setAlignment(2);
996   }
997
998   // In the cross-dso CFI mode, we want !type attributes on definitions only.
999   if (CodeGenOpts.SanitizeCfiCrossDso)
1000     if (auto *FD = dyn_cast<FunctionDecl>(D))
1001       CreateFunctionTypeMetadata(FD, F);
1002 }
1003
1004 void CodeGenModule::SetCommonAttributes(const Decl *D,
1005                                         llvm::GlobalValue *GV) {
1006   if (const auto *ND = dyn_cast_or_null<NamedDecl>(D))
1007     setGlobalVisibility(GV, ND);
1008   else
1009     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1010
1011   if (D && D->hasAttr<UsedAttr>())
1012     addUsedGlobal(GV);
1013 }
1014
1015 void CodeGenModule::setAliasAttributes(const Decl *D,
1016                                        llvm::GlobalValue *GV) {
1017   SetCommonAttributes(D, GV);
1018
1019   // Process the dllexport attribute based on whether the original definition
1020   // (not necessarily the aliasee) was exported.
1021   if (D->hasAttr<DLLExportAttr>())
1022     GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1023 }
1024
1025 void CodeGenModule::setNonAliasAttributes(const Decl *D,
1026                                           llvm::GlobalObject *GO) {
1027   SetCommonAttributes(D, GO);
1028
1029   if (D) {
1030     if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
1031       if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
1032         GV->addAttribute("bss-section", SA->getName());
1033       if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
1034         GV->addAttribute("data-section", SA->getName());
1035       if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
1036         GV->addAttribute("rodata-section", SA->getName());
1037     }
1038
1039     if (auto *F = dyn_cast<llvm::Function>(GO)) {
1040       if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
1041        if (!D->getAttr<SectionAttr>())
1042          F->addFnAttr("implicit-section-name", SA->getName());
1043     }
1044
1045     if (const SectionAttr *SA = D->getAttr<SectionAttr>())
1046       GO->setSection(SA->getName());
1047   }
1048
1049   getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
1050 }
1051
1052 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
1053                                                   llvm::Function *F,
1054                                                   const CGFunctionInfo &FI) {
1055   SetLLVMFunctionAttributes(D, FI, F);
1056   SetLLVMFunctionAttributesForDefinition(D, F);
1057
1058   F->setLinkage(llvm::Function::InternalLinkage);
1059
1060   setNonAliasAttributes(D, F);
1061 }
1062
1063 static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
1064                                          const NamedDecl *ND) {
1065   // Set linkage and visibility in case we never see a definition.
1066   LinkageInfo LV = ND->getLinkageAndVisibility();
1067   if (LV.getLinkage() != ExternalLinkage) {
1068     // Don't set internal linkage on declarations.
1069   } else {
1070     if (ND->hasAttr<DLLImportAttr>()) {
1071       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
1072       GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1073     } else if (ND->hasAttr<DLLExportAttr>()) {
1074       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
1075     } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
1076       // "extern_weak" is overloaded in LLVM; we probably should have
1077       // separate linkage types for this.
1078       GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1079     }
1080
1081     // Set visibility on a declaration only if it's explicit.
1082     if (LV.isVisibilityExplicit())
1083       GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
1084   }
1085 }
1086
1087 void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD,
1088                                                llvm::Function *F) {
1089   // Only if we are checking indirect calls.
1090   if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
1091     return;
1092
1093   // Non-static class methods are handled via vtable pointer checks elsewhere.
1094   if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1095     return;
1096
1097   // Additionally, if building with cross-DSO support...
1098   if (CodeGenOpts.SanitizeCfiCrossDso) {
1099     // Skip available_externally functions. They won't be codegen'ed in the
1100     // current module anyway.
1101     if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
1102       return;
1103   }
1104
1105   llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
1106   F->addTypeMetadata(0, MD);
1107
1108   // Emit a hash-based bit set entry for cross-DSO calls.
1109   if (CodeGenOpts.SanitizeCfiCrossDso)
1110     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1111       F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
1112 }
1113
1114 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1115                                           bool IsIncompleteFunction,
1116                                           bool IsThunk) {
1117   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
1118     // If this is an intrinsic function, set the function's attributes
1119     // to the intrinsic's attributes.
1120     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
1121     return;
1122   }
1123
1124   const auto *FD = cast<FunctionDecl>(GD.getDecl());
1125
1126   if (!IsIncompleteFunction)
1127     SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
1128
1129   // Add the Returned attribute for "this", except for iOS 5 and earlier
1130   // where substantial code, including the libstdc++ dylib, was compiled with
1131   // GCC and does not actually return "this".
1132   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
1133       !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
1134     assert(!F->arg_empty() &&
1135            F->arg_begin()->getType()
1136              ->canLosslesslyBitCastTo(F->getReturnType()) &&
1137            "unexpected this return");
1138     F->addAttribute(1, llvm::Attribute::Returned);
1139   }
1140
1141   // Only a few attributes are set on declarations; these may later be
1142   // overridden by a definition.
1143
1144   setLinkageAndVisibilityForGV(F, FD);
1145
1146   if (FD->getAttr<PragmaClangTextSectionAttr>()) {
1147     F->addFnAttr("implicit-section-name");
1148   }
1149
1150   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
1151     F->setSection(SA->getName());
1152
1153   if (FD->isReplaceableGlobalAllocationFunction()) {
1154     // A replaceable global allocation function does not act like a builtin by
1155     // default, only if it is invoked by a new-expression or delete-expression.
1156     F->addAttribute(llvm::AttributeList::FunctionIndex,
1157                     llvm::Attribute::NoBuiltin);
1158
1159     // A sane operator new returns a non-aliasing pointer.
1160     // FIXME: Also add NonNull attribute to the return value
1161     // for the non-nothrow forms?
1162     auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1163     if (getCodeGenOpts().AssumeSaneOperatorNew &&
1164         (Kind == OO_New || Kind == OO_Array_New))
1165       F->addAttribute(llvm::AttributeList::ReturnIndex,
1166                       llvm::Attribute::NoAlias);
1167   }
1168
1169   if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1170     F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1171   else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1172     if (MD->isVirtual())
1173       F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1174
1175   // Don't emit entries for function declarations in the cross-DSO mode. This
1176   // is handled with better precision by the receiving DSO.
1177   if (!CodeGenOpts.SanitizeCfiCrossDso)
1178     CreateFunctionTypeMetadata(FD, F);
1179 }
1180
1181 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
1182   assert(!GV->isDeclaration() &&
1183          "Only globals with definition can force usage.");
1184   LLVMUsed.emplace_back(GV);
1185 }
1186
1187 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
1188   assert(!GV->isDeclaration() &&
1189          "Only globals with definition can force usage.");
1190   LLVMCompilerUsed.emplace_back(GV);
1191 }
1192
1193 static void emitUsed(CodeGenModule &CGM, StringRef Name,
1194                      std::vector<llvm::WeakTrackingVH> &List) {
1195   // Don't create llvm.used if there is no need.
1196   if (List.empty())
1197     return;
1198
1199   // Convert List to what ConstantArray needs.
1200   SmallVector<llvm::Constant*, 8> UsedArray;
1201   UsedArray.resize(List.size());
1202   for (unsigned i = 0, e = List.size(); i != e; ++i) {
1203     UsedArray[i] =
1204         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1205             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
1206   }
1207
1208   if (UsedArray.empty())
1209     return;
1210   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
1211
1212   auto *GV = new llvm::GlobalVariable(
1213       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
1214       llvm::ConstantArray::get(ATy, UsedArray), Name);
1215
1216   GV->setSection("llvm.metadata");
1217 }
1218
1219 void CodeGenModule::emitLLVMUsed() {
1220   emitUsed(*this, "llvm.used", LLVMUsed);
1221   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
1222 }
1223
1224 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
1225   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
1226   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1227 }
1228
1229 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1230   llvm::SmallString<32> Opt;
1231   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
1232   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1233   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1234 }
1235
1236 void CodeGenModule::AddDependentLib(StringRef Lib) {
1237   llvm::SmallString<24> Opt;
1238   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
1239   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1240   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1241 }
1242
1243 /// \brief Add link options implied by the given module, including modules
1244 /// it depends on, using a postorder walk.
1245 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
1246                                     SmallVectorImpl<llvm::MDNode *> &Metadata,
1247                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
1248   // Import this module's parent.
1249   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
1250     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
1251   }
1252
1253   // Import this module's dependencies.
1254   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
1255     if (Visited.insert(Mod->Imports[I - 1]).second)
1256       addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
1257   }
1258
1259   // Add linker options to link against the libraries/frameworks
1260   // described by this module.
1261   llvm::LLVMContext &Context = CGM.getLLVMContext();
1262   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
1263     // Link against a framework.  Frameworks are currently Darwin only, so we
1264     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
1265     if (Mod->LinkLibraries[I-1].IsFramework) {
1266       llvm::Metadata *Args[2] = {
1267           llvm::MDString::get(Context, "-framework"),
1268           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1269
1270       Metadata.push_back(llvm::MDNode::get(Context, Args));
1271       continue;
1272     }
1273
1274     // Link against a library.
1275     llvm::SmallString<24> Opt;
1276     CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1277       Mod->LinkLibraries[I-1].Library, Opt);
1278     auto *OptString = llvm::MDString::get(Context, Opt);
1279     Metadata.push_back(llvm::MDNode::get(Context, OptString));
1280   }
1281 }
1282
1283 void CodeGenModule::EmitModuleLinkOptions() {
1284   // Collect the set of all of the modules we want to visit to emit link
1285   // options, which is essentially the imported modules and all of their
1286   // non-explicit child modules.
1287   llvm::SetVector<clang::Module *> LinkModules;
1288   llvm::SmallPtrSet<clang::Module *, 16> Visited;
1289   SmallVector<clang::Module *, 16> Stack;
1290
1291   // Seed the stack with imported modules.
1292   for (Module *M : ImportedModules) {
1293     // Do not add any link flags when an implementation TU of a module imports
1294     // a header of that same module.
1295     if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
1296         !getLangOpts().isCompilingModule())
1297       continue;
1298     if (Visited.insert(M).second)
1299       Stack.push_back(M);
1300   }
1301
1302   // Find all of the modules to import, making a little effort to prune
1303   // non-leaf modules.
1304   while (!Stack.empty()) {
1305     clang::Module *Mod = Stack.pop_back_val();
1306
1307     bool AnyChildren = false;
1308
1309     // Visit the submodules of this module.
1310     for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1311                                         SubEnd = Mod->submodule_end();
1312          Sub != SubEnd; ++Sub) {
1313       // Skip explicit children; they need to be explicitly imported to be
1314       // linked against.
1315       if ((*Sub)->IsExplicit)
1316         continue;
1317
1318       if (Visited.insert(*Sub).second) {
1319         Stack.push_back(*Sub);
1320         AnyChildren = true;
1321       }
1322     }
1323
1324     // We didn't find any children, so add this module to the list of
1325     // modules to link against.
1326     if (!AnyChildren) {
1327       LinkModules.insert(Mod);
1328     }
1329   }
1330
1331   // Add link options for all of the imported modules in reverse topological
1332   // order.  We don't do anything to try to order import link flags with respect
1333   // to linker options inserted by things like #pragma comment().
1334   SmallVector<llvm::MDNode *, 16> MetadataArgs;
1335   Visited.clear();
1336   for (Module *M : LinkModules)
1337     if (Visited.insert(M).second)
1338       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
1339   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1340   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1341
1342   // Add the linker options metadata flag.
1343   auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
1344   for (auto *MD : LinkerOptionsMetadata)
1345     NMD->addOperand(MD);
1346 }
1347
1348 void CodeGenModule::EmitDeferred() {
1349   // Emit code for any potentially referenced deferred decls.  Since a
1350   // previously unused static decl may become used during the generation of code
1351   // for a static function, iterate until no changes are made.
1352
1353   if (!DeferredVTables.empty()) {
1354     EmitDeferredVTables();
1355
1356     // Emitting a vtable doesn't directly cause more vtables to
1357     // become deferred, although it can cause functions to be
1358     // emitted that then need those vtables.
1359     assert(DeferredVTables.empty());
1360   }
1361
1362   // Stop if we're out of both deferred vtables and deferred declarations.
1363   if (DeferredDeclsToEmit.empty())
1364     return;
1365
1366   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
1367   // work, it will not interfere with this.
1368   std::vector<GlobalDecl> CurDeclsToEmit;
1369   CurDeclsToEmit.swap(DeferredDeclsToEmit);
1370
1371   for (GlobalDecl &D : CurDeclsToEmit) {
1372     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
1373     // to get GlobalValue with exactly the type we need, not something that
1374     // might had been created for another decl with the same mangled name but
1375     // different type.
1376     llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
1377         GetAddrOfGlobal(D, ForDefinition));
1378
1379     // In case of different address spaces, we may still get a cast, even with
1380     // IsForDefinition equal to true. Query mangled names table to get
1381     // GlobalValue.
1382     if (!GV)
1383       GV = GetGlobalValue(getMangledName(D));
1384
1385     // Make sure GetGlobalValue returned non-null.
1386     assert(GV);
1387
1388     // Check to see if we've already emitted this.  This is necessary
1389     // for a couple of reasons: first, decls can end up in the
1390     // deferred-decls queue multiple times, and second, decls can end
1391     // up with definitions in unusual ways (e.g. by an extern inline
1392     // function acquiring a strong function redefinition).  Just
1393     // ignore these cases.
1394     if (!GV->isDeclaration())
1395       continue;
1396
1397     // Otherwise, emit the definition and move on to the next one.
1398     EmitGlobalDefinition(D, GV);
1399
1400     // If we found out that we need to emit more decls, do that recursively.
1401     // This has the advantage that the decls are emitted in a DFS and related
1402     // ones are close together, which is convenient for testing.
1403     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1404       EmitDeferred();
1405       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1406     }
1407   }
1408 }
1409
1410 void CodeGenModule::EmitVTablesOpportunistically() {
1411   // Try to emit external vtables as available_externally if they have emitted
1412   // all inlined virtual functions.  It runs after EmitDeferred() and therefore
1413   // is not allowed to create new references to things that need to be emitted
1414   // lazily. Note that it also uses fact that we eagerly emitting RTTI.
1415
1416   assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
1417          && "Only emit opportunistic vtables with optimizations");
1418
1419   for (const CXXRecordDecl *RD : OpportunisticVTables) {
1420     assert(getVTables().isVTableExternal(RD) &&
1421            "This queue should only contain external vtables");
1422     if (getCXXABI().canSpeculativelyEmitVTable(RD))
1423       VTables.GenerateClassData(RD);
1424   }
1425   OpportunisticVTables.clear();
1426 }
1427
1428 void CodeGenModule::EmitGlobalAnnotations() {
1429   if (Annotations.empty())
1430     return;
1431
1432   // Create a new global variable for the ConstantStruct in the Module.
1433   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1434     Annotations[0]->getType(), Annotations.size()), Annotations);
1435   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1436                                       llvm::GlobalValue::AppendingLinkage,
1437                                       Array, "llvm.global.annotations");
1438   gv->setSection(AnnotationSection);
1439 }
1440
1441 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1442   llvm::Constant *&AStr = AnnotationStrings[Str];
1443   if (AStr)
1444     return AStr;
1445
1446   // Not found yet, create a new global.
1447   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
1448   auto *gv =
1449       new llvm::GlobalVariable(getModule(), s->getType(), true,
1450                                llvm::GlobalValue::PrivateLinkage, s, ".str");
1451   gv->setSection(AnnotationSection);
1452   gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1453   AStr = gv;
1454   return gv;
1455 }
1456
1457 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1458   SourceManager &SM = getContext().getSourceManager();
1459   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1460   if (PLoc.isValid())
1461     return EmitAnnotationString(PLoc.getFilename());
1462   return EmitAnnotationString(SM.getBufferName(Loc));
1463 }
1464
1465 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1466   SourceManager &SM = getContext().getSourceManager();
1467   PresumedLoc PLoc = SM.getPresumedLoc(L);
1468   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1469     SM.getExpansionLineNumber(L);
1470   return llvm::ConstantInt::get(Int32Ty, LineNo);
1471 }
1472
1473 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1474                                                 const AnnotateAttr *AA,
1475                                                 SourceLocation L) {
1476   // Get the globals for file name, annotation, and the line number.
1477   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1478                  *UnitGV = EmitAnnotationUnit(L),
1479                  *LineNoCst = EmitAnnotationLineNo(L);
1480
1481   // Create the ConstantStruct for the global annotation.
1482   llvm::Constant *Fields[4] = {
1483     llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1484     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1485     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1486     LineNoCst
1487   };
1488   return llvm::ConstantStruct::getAnon(Fields);
1489 }
1490
1491 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1492                                          llvm::GlobalValue *GV) {
1493   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1494   // Get the struct elements for these annotations.
1495   for (const auto *I : D->specific_attrs<AnnotateAttr>())
1496     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
1497 }
1498
1499 bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
1500                                            SourceLocation Loc) const {
1501   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1502   // Blacklist by function name.
1503   if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
1504     return true;
1505   // Blacklist by location.
1506   if (Loc.isValid())
1507     return SanitizerBL.isBlacklistedLocation(Loc);
1508   // If location is unknown, this may be a compiler-generated function. Assume
1509   // it's located in the main file.
1510   auto &SM = Context.getSourceManager();
1511   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1512     return SanitizerBL.isBlacklistedFile(MainFile->getName());
1513   }
1514   return false;
1515 }
1516
1517 bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1518                                            SourceLocation Loc, QualType Ty,
1519                                            StringRef Category) const {
1520   // For now globals can be blacklisted only in ASan and KASan.
1521   if (!LangOpts.Sanitize.hasOneOf(
1522           SanitizerKind::Address | SanitizerKind::KernelAddress))
1523     return false;
1524   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1525   if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
1526     return true;
1527   if (SanitizerBL.isBlacklistedLocation(Loc, Category))
1528     return true;
1529   // Check global type.
1530   if (!Ty.isNull()) {
1531     // Drill down the array types: if global variable of a fixed type is
1532     // blacklisted, we also don't instrument arrays of them.
1533     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1534       Ty = AT->getElementType();
1535     Ty = Ty.getCanonicalType().getUnqualifiedType();
1536     // We allow to blacklist only record types (classes, structs etc.)
1537     if (Ty->isRecordType()) {
1538       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
1539       if (SanitizerBL.isBlacklistedType(TypeStr, Category))
1540         return true;
1541     }
1542   }
1543   return false;
1544 }
1545
1546 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1547                                    StringRef Category) const {
1548   if (!LangOpts.XRayInstrument)
1549     return false;
1550   const auto &XRayFilter = getContext().getXRayFilter();
1551   using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
1552   auto Attr = XRayFunctionFilter::ImbueAttribute::NONE;
1553   if (Loc.isValid())
1554     Attr = XRayFilter.shouldImbueLocation(Loc, Category);
1555   if (Attr == ImbueAttr::NONE)
1556     Attr = XRayFilter.shouldImbueFunction(Fn->getName());
1557   switch (Attr) {
1558   case ImbueAttr::NONE:
1559     return false;
1560   case ImbueAttr::ALWAYS:
1561     Fn->addFnAttr("function-instrument", "xray-always");
1562     break;
1563   case ImbueAttr::ALWAYS_ARG1:
1564     Fn->addFnAttr("function-instrument", "xray-always");
1565     Fn->addFnAttr("xray-log-args", "1");
1566     break;
1567   case ImbueAttr::NEVER:
1568     Fn->addFnAttr("function-instrument", "xray-never");
1569     break;
1570   }
1571   return true;
1572 }
1573
1574 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
1575   // Never defer when EmitAllDecls is specified.
1576   if (LangOpts.EmitAllDecls)
1577     return true;
1578
1579   return getContext().DeclMustBeEmitted(Global);
1580 }
1581
1582 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
1583   if (const auto *FD = dyn_cast<FunctionDecl>(Global))
1584     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1585       // Implicit template instantiations may change linkage if they are later
1586       // explicitly instantiated, so they should not be emitted eagerly.
1587       return false;
1588   if (const auto *VD = dyn_cast<VarDecl>(Global))
1589     if (Context.getInlineVariableDefinitionKind(VD) ==
1590         ASTContext::InlineVariableDefinitionKind::WeakUnknown)
1591       // A definition of an inline constexpr static data member may change
1592       // linkage later if it's redeclared outside the class.
1593       return false;
1594   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
1595   // codegen for global variables, because they may be marked as threadprivate.
1596   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1597       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
1598     return false;
1599
1600   return true;
1601 }
1602
1603 ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
1604     const CXXUuidofExpr* E) {
1605   // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1606   // well-formed.
1607   StringRef Uuid = E->getUuidStr();
1608   std::string Name = "_GUID_" + Uuid.lower();
1609   std::replace(Name.begin(), Name.end(), '-', '_');
1610
1611   // The UUID descriptor should be pointer aligned.
1612   CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
1613
1614   // Look for an existing global.
1615   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1616     return ConstantAddress(GV, Alignment);
1617
1618   llvm::Constant *Init = EmitUuidofInitializer(Uuid);
1619   assert(Init && "failed to initialize as constant");
1620
1621   auto *GV = new llvm::GlobalVariable(
1622       getModule(), Init->getType(),
1623       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
1624   if (supportsCOMDAT())
1625     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
1626   return ConstantAddress(GV, Alignment);
1627 }
1628
1629 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1630   const AliasAttr *AA = VD->getAttr<AliasAttr>();
1631   assert(AA && "No alias?");
1632
1633   CharUnits Alignment = getContext().getDeclAlign(VD);
1634   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1635
1636   // See if there is already something with the target's name in the module.
1637   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
1638   if (Entry) {
1639     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1640     auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1641     return ConstantAddress(Ptr, Alignment);
1642   }
1643
1644   llvm::Constant *Aliasee;
1645   if (isa<llvm::FunctionType>(DeclTy))
1646     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1647                                       GlobalDecl(cast<FunctionDecl>(VD)),
1648                                       /*ForVTable=*/false);
1649   else
1650     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1651                                     llvm::PointerType::getUnqual(DeclTy),
1652                                     nullptr);
1653
1654   auto *F = cast<llvm::GlobalValue>(Aliasee);
1655   F->setLinkage(llvm::Function::ExternalWeakLinkage);
1656   WeakRefReferences.insert(F);
1657
1658   return ConstantAddress(Aliasee, Alignment);
1659 }
1660
1661 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
1662   const auto *Global = cast<ValueDecl>(GD.getDecl());
1663
1664   // Weak references don't produce any output by themselves.
1665   if (Global->hasAttr<WeakRefAttr>())
1666     return;
1667
1668   // If this is an alias definition (which otherwise looks like a declaration)
1669   // emit it now.
1670   if (Global->hasAttr<AliasAttr>())
1671     return EmitAliasDefinition(GD);
1672
1673   // IFunc like an alias whose value is resolved at runtime by calling resolver.
1674   if (Global->hasAttr<IFuncAttr>())
1675     return emitIFuncDefinition(GD);
1676
1677   // If this is CUDA, be selective about which declarations we emit.
1678   if (LangOpts.CUDA) {
1679     if (LangOpts.CUDAIsDevice) {
1680       if (!Global->hasAttr<CUDADeviceAttr>() &&
1681           !Global->hasAttr<CUDAGlobalAttr>() &&
1682           !Global->hasAttr<CUDAConstantAttr>() &&
1683           !Global->hasAttr<CUDASharedAttr>())
1684         return;
1685     } else {
1686       // We need to emit host-side 'shadows' for all global
1687       // device-side variables because the CUDA runtime needs their
1688       // size and host-side address in order to provide access to
1689       // their device-side incarnations.
1690
1691       // So device-only functions are the only things we skip.
1692       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
1693           Global->hasAttr<CUDADeviceAttr>())
1694         return;
1695
1696       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
1697              "Expected Variable or Function");
1698     }
1699   }
1700
1701   if (LangOpts.OpenMP) {
1702     // If this is OpenMP device, check if it is legal to emit this global
1703     // normally.
1704     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
1705       return;
1706     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
1707       if (MustBeEmitted(Global))
1708         EmitOMPDeclareReduction(DRD);
1709       return;
1710     }
1711   }
1712
1713   // Ignore declarations, they will be emitted on their first use.
1714   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1715     // Forward declarations are emitted lazily on first use.
1716     if (!FD->doesThisDeclarationHaveABody()) {
1717       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1718         return;
1719
1720       StringRef MangledName = getMangledName(GD);
1721
1722       // Compute the function info and LLVM type.
1723       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1724       llvm::Type *Ty = getTypes().GetFunctionType(FI);
1725
1726       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
1727                               /*DontDefer=*/false);
1728       return;
1729     }
1730   } else {
1731     const auto *VD = cast<VarDecl>(Global);
1732     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1733     // We need to emit device-side global CUDA variables even if a
1734     // variable does not have a definition -- we still need to define
1735     // host-side shadow for it.
1736     bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
1737                            !VD->hasDefinition() &&
1738                            (VD->hasAttr<CUDAConstantAttr>() ||
1739                             VD->hasAttr<CUDADeviceAttr>());
1740     if (!MustEmitForCuda &&
1741         VD->isThisDeclarationADefinition() != VarDecl::Definition &&
1742         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
1743       // If this declaration may have caused an inline variable definition to
1744       // change linkage, make sure that it's emitted.
1745       if (Context.getInlineVariableDefinitionKind(VD) ==
1746           ASTContext::InlineVariableDefinitionKind::Strong)
1747         GetAddrOfGlobalVar(VD);
1748       return;
1749     }
1750   }
1751
1752   // Defer code generation to first use when possible, e.g. if this is an inline
1753   // function. If the global must always be emitted, do it eagerly if possible
1754   // to benefit from cache locality.
1755   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
1756     // Emit the definition if it can't be deferred.
1757     EmitGlobalDefinition(GD);
1758     return;
1759   }
1760
1761   // If we're deferring emission of a C++ variable with an
1762   // initializer, remember the order in which it appeared in the file.
1763   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1764       cast<VarDecl>(Global)->hasInit()) {
1765     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1766     CXXGlobalInits.push_back(nullptr);
1767   }
1768
1769   StringRef MangledName = getMangledName(GD);
1770   if (GetGlobalValue(MangledName) != nullptr) {
1771     // The value has already been used and should therefore be emitted.
1772     addDeferredDeclToEmit(GD);
1773   } else if (MustBeEmitted(Global)) {
1774     // The value must be emitted, but cannot be emitted eagerly.
1775     assert(!MayBeEmittedEagerly(Global));
1776     addDeferredDeclToEmit(GD);
1777   } else {
1778     // Otherwise, remember that we saw a deferred decl with this name.  The
1779     // first use of the mangled name will cause it to move into
1780     // DeferredDeclsToEmit.
1781     DeferredDecls[MangledName] = GD;
1782   }
1783 }
1784
1785 // Check if T is a class type with a destructor that's not dllimport.
1786 static bool HasNonDllImportDtor(QualType T) {
1787   if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
1788     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1789       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
1790         return true;
1791
1792   return false;
1793 }
1794
1795 namespace {
1796   struct FunctionIsDirectlyRecursive :
1797     public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1798     const StringRef Name;
1799     const Builtin::Context &BI;
1800     bool Result;
1801     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1802       Name(N), BI(C), Result(false) {
1803     }
1804     typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1805
1806     bool TraverseCallExpr(CallExpr *E) {
1807       const FunctionDecl *FD = E->getDirectCallee();
1808       if (!FD)
1809         return true;
1810       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1811       if (Attr && Name == Attr->getLabel()) {
1812         Result = true;
1813         return false;
1814       }
1815       unsigned BuiltinID = FD->getBuiltinID();
1816       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
1817         return true;
1818       StringRef BuiltinName = BI.getName(BuiltinID);
1819       if (BuiltinName.startswith("__builtin_") &&
1820           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1821         Result = true;
1822         return false;
1823       }
1824       return true;
1825     }
1826   };
1827
1828   // Make sure we're not referencing non-imported vars or functions.
1829   struct DLLImportFunctionVisitor
1830       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
1831     bool SafeToInline = true;
1832
1833     bool shouldVisitImplicitCode() const { return true; }
1834
1835     bool VisitVarDecl(VarDecl *VD) {
1836       if (VD->getTLSKind()) {
1837         // A thread-local variable cannot be imported.
1838         SafeToInline = false;
1839         return SafeToInline;
1840       }
1841
1842       // A variable definition might imply a destructor call.
1843       if (VD->isThisDeclarationADefinition())
1844         SafeToInline = !HasNonDllImportDtor(VD->getType());
1845
1846       return SafeToInline;
1847     }
1848
1849     bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
1850       if (const auto *D = E->getTemporary()->getDestructor())
1851         SafeToInline = D->hasAttr<DLLImportAttr>();
1852       return SafeToInline;
1853     }
1854
1855     bool VisitDeclRefExpr(DeclRefExpr *E) {
1856       ValueDecl *VD = E->getDecl();
1857       if (isa<FunctionDecl>(VD))
1858         SafeToInline = VD->hasAttr<DLLImportAttr>();
1859       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
1860         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
1861       return SafeToInline;
1862     }
1863
1864     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
1865       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
1866       return SafeToInline;
1867     }
1868
1869     bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1870       CXXMethodDecl *M = E->getMethodDecl();
1871       if (!M) {
1872         // Call through a pointer to member function. This is safe to inline.
1873         SafeToInline = true;
1874       } else {
1875         SafeToInline = M->hasAttr<DLLImportAttr>();
1876       }
1877       return SafeToInline;
1878     }
1879
1880     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
1881       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
1882       return SafeToInline;
1883     }
1884
1885     bool VisitCXXNewExpr(CXXNewExpr *E) {
1886       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
1887       return SafeToInline;
1888     }
1889   };
1890 }
1891
1892 // isTriviallyRecursive - Check if this function calls another
1893 // decl that, because of the asm attribute or the other decl being a builtin,
1894 // ends up pointing to itself.
1895 bool
1896 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1897   StringRef Name;
1898   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1899     // asm labels are a special kind of mangling we have to support.
1900     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1901     if (!Attr)
1902       return false;
1903     Name = Attr->getLabel();
1904   } else {
1905     Name = FD->getName();
1906   }
1907
1908   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1909   Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1910   return Walker.Result;
1911 }
1912
1913 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1914   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1915     return true;
1916   const auto *F = cast<FunctionDecl>(GD.getDecl());
1917   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1918     return false;
1919
1920   if (F->hasAttr<DLLImportAttr>()) {
1921     // Check whether it would be safe to inline this dllimport function.
1922     DLLImportFunctionVisitor Visitor;
1923     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
1924     if (!Visitor.SafeToInline)
1925       return false;
1926
1927     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
1928       // Implicit destructor invocations aren't captured in the AST, so the
1929       // check above can't see them. Check for them manually here.
1930       for (const Decl *Member : Dtor->getParent()->decls())
1931         if (isa<FieldDecl>(Member))
1932           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
1933             return false;
1934       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
1935         if (HasNonDllImportDtor(B.getType()))
1936           return false;
1937     }
1938   }
1939
1940   // PR9614. Avoid cases where the source code is lying to us. An available
1941   // externally function should have an equivalent function somewhere else,
1942   // but a function that calls itself is clearly not equivalent to the real
1943   // implementation.
1944   // This happens in glibc's btowc and in some configure checks.
1945   return !isTriviallyRecursive(F);
1946 }
1947
1948 bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
1949   return CodeGenOpts.OptimizationLevel > 0;
1950 }
1951
1952 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
1953   const auto *D = cast<ValueDecl>(GD.getDecl());
1954
1955   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 
1956                                  Context.getSourceManager(),
1957                                  "Generating code for declaration");
1958   
1959   if (isa<FunctionDecl>(D)) {
1960     // At -O0, don't generate IR for functions with available_externally 
1961     // linkage.
1962     if (!shouldEmitFunction(GD))
1963       return;
1964
1965     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
1966       // Make sure to emit the definition(s) before we emit the thunks.
1967       // This is necessary for the generation of certain thunks.
1968       if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
1969         ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
1970       else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
1971         ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
1972       else
1973         EmitGlobalFunctionDefinition(GD, GV);
1974
1975       if (Method->isVirtual())
1976         getVTables().EmitThunks(GD);
1977
1978       return;
1979     }
1980
1981     return EmitGlobalFunctionDefinition(GD, GV);
1982   }
1983
1984   if (const auto *VD = dyn_cast<VarDecl>(D))
1985     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
1986   
1987   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1988 }
1989
1990 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1991                                                       llvm::Function *NewFn);
1992
1993 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1994 /// module, create and return an llvm Function with the specified type. If there
1995 /// is something in the module with the specified name, return it potentially
1996 /// bitcasted to the right type.
1997 ///
1998 /// If D is non-null, it specifies a decl that correspond to this.  This is used
1999 /// to set the attributes on the function when it is first created.
2000 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
2001     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
2002     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
2003     ForDefinition_t IsForDefinition) {
2004   const Decl *D = GD.getDecl();
2005
2006   // Lookup the entry, lazily creating it if necessary.
2007   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2008   if (Entry) {
2009     if (WeakRefReferences.erase(Entry)) {
2010       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
2011       if (FD && !FD->hasAttr<WeakAttr>())
2012         Entry->setLinkage(llvm::Function::ExternalLinkage);
2013     }
2014
2015     // Handle dropped DLL attributes.
2016     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2017       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2018
2019     // If there are two attempts to define the same mangled name, issue an
2020     // error.
2021     if (IsForDefinition && !Entry->isDeclaration()) {
2022       GlobalDecl OtherGD;
2023       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
2024       // to make sure that we issue an error only once.
2025       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
2026           (GD.getCanonicalDecl().getDecl() !=
2027            OtherGD.getCanonicalDecl().getDecl()) &&
2028           DiagnosedConflictingDefinitions.insert(GD).second) {
2029         getDiags().Report(D->getLocation(),
2030                           diag::err_duplicate_mangled_name);
2031         getDiags().Report(OtherGD.getDecl()->getLocation(),
2032                           diag::note_previous_definition);
2033       }
2034     }
2035
2036     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
2037         (Entry->getType()->getElementType() == Ty)) {
2038       return Entry;
2039     }
2040
2041     // Make sure the result is of the correct type.
2042     // (If function is requested for a definition, we always need to create a new
2043     // function, not just return a bitcast.)
2044     if (!IsForDefinition)
2045       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
2046   }
2047
2048   // This function doesn't have a complete type (for example, the return
2049   // type is an incomplete struct). Use a fake type instead, and make
2050   // sure not to try to set attributes.
2051   bool IsIncompleteFunction = false;
2052
2053   llvm::FunctionType *FTy;
2054   if (isa<llvm::FunctionType>(Ty)) {
2055     FTy = cast<llvm::FunctionType>(Ty);
2056   } else {
2057     FTy = llvm::FunctionType::get(VoidTy, false);
2058     IsIncompleteFunction = true;
2059   }
2060
2061   llvm::Function *F =
2062       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
2063                              Entry ? StringRef() : MangledName, &getModule());
2064
2065   // If we already created a function with the same mangled name (but different
2066   // type) before, take its name and add it to the list of functions to be
2067   // replaced with F at the end of CodeGen.
2068   //
2069   // This happens if there is a prototype for a function (e.g. "int f()") and
2070   // then a definition of a different type (e.g. "int f(int x)").
2071   if (Entry) {
2072     F->takeName(Entry);
2073
2074     // This might be an implementation of a function without a prototype, in
2075     // which case, try to do special replacement of calls which match the new
2076     // prototype.  The really key thing here is that we also potentially drop
2077     // arguments from the call site so as to make a direct call, which makes the
2078     // inliner happier and suppresses a number of optimizer warnings (!) about
2079     // dropping arguments.
2080     if (!Entry->use_empty()) {
2081       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
2082       Entry->removeDeadConstantUsers();
2083     }
2084
2085     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
2086         F, Entry->getType()->getElementType()->getPointerTo());
2087     addGlobalValReplacement(Entry, BC);
2088   }
2089
2090   assert(F->getName() == MangledName && "name was uniqued!");
2091   if (D)
2092     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
2093   if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
2094     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
2095     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
2096   }
2097
2098   if (!DontDefer) {
2099     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
2100     // each other bottoming out with the base dtor.  Therefore we emit non-base
2101     // dtors on usage, even if there is no dtor definition in the TU.
2102     if (D && isa<CXXDestructorDecl>(D) &&
2103         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
2104                                            GD.getDtorType()))
2105       addDeferredDeclToEmit(GD);
2106
2107     // This is the first use or definition of a mangled name.  If there is a
2108     // deferred decl with this name, remember that we need to emit it at the end
2109     // of the file.
2110     auto DDI = DeferredDecls.find(MangledName);
2111     if (DDI != DeferredDecls.end()) {
2112       // Move the potentially referenced deferred decl to the
2113       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
2114       // don't need it anymore).
2115       addDeferredDeclToEmit(DDI->second);
2116       DeferredDecls.erase(DDI);
2117
2118       // Otherwise, there are cases we have to worry about where we're
2119       // using a declaration for which we must emit a definition but where
2120       // we might not find a top-level definition:
2121       //   - member functions defined inline in their classes
2122       //   - friend functions defined inline in some class
2123       //   - special member functions with implicit definitions
2124       // If we ever change our AST traversal to walk into class methods,
2125       // this will be unnecessary.
2126       //
2127       // We also don't emit a definition for a function if it's going to be an
2128       // entry in a vtable, unless it's already marked as used.
2129     } else if (getLangOpts().CPlusPlus && D) {
2130       // Look for a declaration that's lexically in a record.
2131       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
2132            FD = FD->getPreviousDecl()) {
2133         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
2134           if (FD->doesThisDeclarationHaveABody()) {
2135             addDeferredDeclToEmit(GD.getWithDecl(FD));
2136             break;
2137           }
2138         }
2139       }
2140     }
2141   }
2142
2143   // Make sure the result is of the requested type.
2144   if (!IsIncompleteFunction) {
2145     assert(F->getType()->getElementType() == Ty);
2146     return F;
2147   }
2148
2149   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2150   return llvm::ConstantExpr::getBitCast(F, PTy);
2151 }
2152
2153 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
2154 /// non-null, then this function will use the specified type if it has to
2155 /// create it (this occurs when we see a definition of the function).
2156 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
2157                                                  llvm::Type *Ty,
2158                                                  bool ForVTable,
2159                                                  bool DontDefer,
2160                                               ForDefinition_t IsForDefinition) {
2161   // If there was no specific requested type, just convert it now.
2162   if (!Ty) {
2163     const auto *FD = cast<FunctionDecl>(GD.getDecl());
2164     auto CanonTy = Context.getCanonicalType(FD->getType());
2165     Ty = getTypes().ConvertFunctionType(CanonTy, FD);
2166   }
2167
2168   StringRef MangledName = getMangledName(GD);
2169   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
2170                                  /*IsThunk=*/false, llvm::AttributeList(),
2171                                  IsForDefinition);
2172 }
2173
2174 static const FunctionDecl *
2175 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
2176   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
2177   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2178
2179   IdentifierInfo &CII = C.Idents.get(Name);
2180   for (const auto &Result : DC->lookup(&CII))
2181     if (const auto FD = dyn_cast<FunctionDecl>(Result))
2182       return FD;
2183
2184   if (!C.getLangOpts().CPlusPlus)
2185     return nullptr;
2186
2187   // Demangle the premangled name from getTerminateFn()
2188   IdentifierInfo &CXXII =
2189       (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ")
2190           ? C.Idents.get("terminate")
2191           : C.Idents.get(Name);
2192
2193   for (const auto &N : {"__cxxabiv1", "std"}) {
2194     IdentifierInfo &NS = C.Idents.get(N);
2195     for (const auto &Result : DC->lookup(&NS)) {
2196       NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
2197       if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
2198         for (const auto &Result : LSD->lookup(&NS))
2199           if ((ND = dyn_cast<NamespaceDecl>(Result)))
2200             break;
2201
2202       if (ND)
2203         for (const auto &Result : ND->lookup(&CXXII))
2204           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
2205             return FD;
2206     }
2207   }
2208
2209   return nullptr;
2210 }
2211
2212 /// CreateRuntimeFunction - Create a new runtime function with the specified
2213 /// type and name.
2214 llvm::Constant *
2215 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
2216                                      llvm::AttributeList ExtraAttrs,
2217                                      bool Local) {
2218   llvm::Constant *C =
2219       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2220                               /*DontDefer=*/false, /*IsThunk=*/false,
2221                               ExtraAttrs);
2222
2223   if (auto *F = dyn_cast<llvm::Function>(C)) {
2224     if (F->empty()) {
2225       F->setCallingConv(getRuntimeCC());
2226
2227       if (!Local && getTriple().isOSBinFormatCOFF() &&
2228           !getCodeGenOpts().LTOVisibilityPublicStd) {
2229         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
2230         if (!FD || FD->hasAttr<DLLImportAttr>()) {
2231           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2232           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
2233         }
2234       }
2235     }
2236   }
2237
2238   return C;
2239 }
2240
2241 /// CreateBuiltinFunction - Create a new builtin function with the specified
2242 /// type and name.
2243 llvm::Constant *
2244 CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
2245                                      llvm::AttributeList ExtraAttrs) {
2246   llvm::Constant *C =
2247       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2248                               /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
2249   if (auto *F = dyn_cast<llvm::Function>(C))
2250     if (F->empty())
2251       F->setCallingConv(getBuiltinCC());
2252   return C;
2253 }
2254
2255 /// isTypeConstant - Determine whether an object of this type can be emitted
2256 /// as a constant.
2257 ///
2258 /// If ExcludeCtor is true, the duration when the object's constructor runs
2259 /// will not be considered. The caller will need to verify that the object is
2260 /// not written to during its construction.
2261 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2262   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
2263     return false;
2264
2265   if (Context.getLangOpts().CPlusPlus) {
2266     if (const CXXRecordDecl *Record
2267           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2268       return ExcludeCtor && !Record->hasMutableFields() &&
2269              Record->hasTrivialDestructor();
2270   }
2271
2272   return true;
2273 }
2274
2275 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2276 /// create and return an llvm GlobalVariable with the specified type.  If there
2277 /// is something in the module with the specified name, return it potentially
2278 /// bitcasted to the right type.
2279 ///
2280 /// If D is non-null, it specifies a decl that correspond to this.  This is used
2281 /// to set the attributes on the global when it is first created.
2282 ///
2283 /// If IsForDefinition is true, it is guranteed that an actual global with
2284 /// type Ty will be returned, not conversion of a variable with the same
2285 /// mangled name but some other type.
2286 llvm::Constant *
2287 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
2288                                      llvm::PointerType *Ty,
2289                                      const VarDecl *D,
2290                                      ForDefinition_t IsForDefinition) {
2291   // Lookup the entry, lazily creating it if necessary.
2292   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2293   if (Entry) {
2294     if (WeakRefReferences.erase(Entry)) {
2295       if (D && !D->hasAttr<WeakAttr>())
2296         Entry->setLinkage(llvm::Function::ExternalLinkage);
2297     }
2298
2299     // Handle dropped DLL attributes.
2300     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2301       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2302
2303     if (Entry->getType() == Ty)
2304       return Entry;
2305
2306     // If there are two attempts to define the same mangled name, issue an
2307     // error.
2308     if (IsForDefinition && !Entry->isDeclaration()) {
2309       GlobalDecl OtherGD;
2310       const VarDecl *OtherD;
2311
2312       // Check that D is not yet in DiagnosedConflictingDefinitions is required
2313       // to make sure that we issue an error only once.
2314       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
2315           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2316           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2317           OtherD->hasInit() &&
2318           DiagnosedConflictingDefinitions.insert(D).second) {
2319         getDiags().Report(D->getLocation(),
2320                           diag::err_duplicate_mangled_name);
2321         getDiags().Report(OtherGD.getDecl()->getLocation(),
2322                           diag::note_previous_definition);
2323       }
2324     }
2325
2326     // Make sure the result is of the correct type.
2327     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2328       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2329
2330     // (If global is requested for a definition, we always need to create a new
2331     // global, not just return a bitcast.)
2332     if (!IsForDefinition)
2333       return llvm::ConstantExpr::getBitCast(Entry, Ty);
2334   }
2335
2336   unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
2337   auto *GV = new llvm::GlobalVariable(
2338       getModule(), Ty->getElementType(), false,
2339       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
2340       llvm::GlobalVariable::NotThreadLocal, AddrSpace);
2341
2342   // If we already created a global with the same mangled name (but different
2343   // type) before, take its name and remove it from its parent.
2344   if (Entry) {
2345     GV->takeName(Entry);
2346
2347     if (!Entry->use_empty()) {
2348       llvm::Constant *NewPtrForOldDecl =
2349           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2350       Entry->replaceAllUsesWith(NewPtrForOldDecl);
2351     }
2352
2353     Entry->eraseFromParent();
2354   }
2355
2356   // This is the first use or definition of a mangled name.  If there is a
2357   // deferred decl with this name, remember that we need to emit it at the end
2358   // of the file.
2359   auto DDI = DeferredDecls.find(MangledName);
2360   if (DDI != DeferredDecls.end()) {
2361     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2362     // list, and remove it from DeferredDecls (since we don't need it anymore).
2363     addDeferredDeclToEmit(DDI->second);
2364     DeferredDecls.erase(DDI);
2365   }
2366
2367   // Handle things which are present even on external declarations.
2368   if (D) {
2369     // FIXME: This code is overly simple and should be merged with other global
2370     // handling.
2371     GV->setConstant(isTypeConstant(D->getType(), false));
2372
2373     GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2374
2375     setLinkageAndVisibilityForGV(GV, D);
2376
2377     if (D->getTLSKind()) {
2378       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2379         CXXThreadLocals.push_back(D);
2380       setTLSMode(GV, *D);
2381     }
2382
2383     // If required by the ABI, treat declarations of static data members with
2384     // inline initializers as definitions.
2385     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
2386       EmitGlobalVarDefinition(D);
2387     }
2388
2389     // Handle XCore specific ABI requirements.
2390     if (getTriple().getArch() == llvm::Triple::xcore &&
2391         D->getLanguageLinkage() == CLanguageLinkage &&
2392         D->getType().isConstant(Context) &&
2393         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
2394       GV->setSection(".cp.rodata");
2395   }
2396
2397   if (AddrSpace != Ty->getAddressSpace())
2398     return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
2399
2400   return GV;
2401 }
2402
2403 llvm::Constant *
2404 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
2405                                ForDefinition_t IsForDefinition) {
2406   const Decl *D = GD.getDecl();
2407   if (isa<CXXConstructorDecl>(D))
2408     return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
2409                                 getFromCtorType(GD.getCtorType()),
2410                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2411                                 /*DontDefer=*/false, IsForDefinition);
2412   else if (isa<CXXDestructorDecl>(D))
2413     return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
2414                                 getFromDtorType(GD.getDtorType()),
2415                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2416                                 /*DontDefer=*/false, IsForDefinition);
2417   else if (isa<CXXMethodDecl>(D)) {
2418     auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
2419         cast<CXXMethodDecl>(D));
2420     auto Ty = getTypes().GetFunctionType(*FInfo);
2421     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2422                              IsForDefinition);
2423   } else if (isa<FunctionDecl>(D)) {
2424     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2425     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2426     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2427                              IsForDefinition);
2428   } else
2429     return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
2430                               IsForDefinition);
2431 }
2432
2433 llvm::GlobalVariable *
2434 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name, 
2435                                       llvm::Type *Ty,
2436                                       llvm::GlobalValue::LinkageTypes Linkage) {
2437   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
2438   llvm::GlobalVariable *OldGV = nullptr;
2439
2440   if (GV) {
2441     // Check if the variable has the right type.
2442     if (GV->getType()->getElementType() == Ty)
2443       return GV;
2444
2445     // Because C++ name mangling, the only way we can end up with an already
2446     // existing global with the same name is if it has been declared extern "C".
2447     assert(GV->isDeclaration() && "Declaration has wrong type!");
2448     OldGV = GV;
2449   }
2450   
2451   // Create a new variable.
2452   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
2453                                 Linkage, nullptr, Name);
2454
2455   if (OldGV) {
2456     // Replace occurrences of the old variable if needed.
2457     GV->takeName(OldGV);
2458     
2459     if (!OldGV->use_empty()) {
2460       llvm::Constant *NewPtrForOldDecl =
2461       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2462       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
2463     }
2464     
2465     OldGV->eraseFromParent();
2466   }
2467
2468   if (supportsCOMDAT() && GV->isWeakForLinker() &&
2469       !GV->hasAvailableExternallyLinkage())
2470     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2471
2472   return GV;
2473 }
2474
2475 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
2476 /// given global variable.  If Ty is non-null and if the global doesn't exist,
2477 /// then it will be created with the specified type instead of whatever the
2478 /// normal requested type would be. If IsForDefinition is true, it is guranteed
2479 /// that an actual global with type Ty will be returned, not conversion of a
2480 /// variable with the same mangled name but some other type.
2481 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
2482                                                   llvm::Type *Ty,
2483                                            ForDefinition_t IsForDefinition) {
2484   assert(D->hasGlobalStorage() && "Not a global variable");
2485   QualType ASTTy = D->getType();
2486   if (!Ty)
2487     Ty = getTypes().ConvertTypeForMem(ASTTy);
2488
2489   llvm::PointerType *PTy =
2490     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
2491
2492   StringRef MangledName = getMangledName(D);
2493   return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
2494 }
2495
2496 /// CreateRuntimeVariable - Create a new runtime global variable with the
2497 /// specified type and name.
2498 llvm::Constant *
2499 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
2500                                      StringRef Name) {
2501   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
2502 }
2503
2504 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
2505   assert(!D->getInit() && "Cannot emit definite definitions here!");
2506
2507   StringRef MangledName = getMangledName(D);
2508   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
2509
2510   // We already have a definition, not declaration, with the same mangled name.
2511   // Emitting of declaration is not required (and actually overwrites emitted
2512   // definition).
2513   if (GV && !GV->isDeclaration())
2514     return;
2515
2516   // If we have not seen a reference to this variable yet, place it into the
2517   // deferred declarations table to be emitted if needed later.
2518   if (!MustBeEmitted(D) && !GV) {
2519       DeferredDecls[MangledName] = D;
2520       return;
2521   }
2522
2523   // The tentative definition is the only definition.
2524   EmitGlobalVarDefinition(D);
2525 }
2526
2527 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
2528   return Context.toCharUnitsFromBits(
2529       getDataLayout().getTypeStoreSizeInBits(Ty));
2530 }
2531
2532 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
2533                                                  unsigned AddrSpace) {
2534   if (D && LangOpts.CUDA && LangOpts.CUDAIsDevice) {
2535     if (D->hasAttr<CUDAConstantAttr>())
2536       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
2537     else if (D->hasAttr<CUDASharedAttr>())
2538       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
2539     else
2540       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
2541   }
2542
2543   return AddrSpace;
2544 }
2545
2546 template<typename SomeDecl>
2547 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
2548                                                llvm::GlobalValue *GV) {
2549   if (!getLangOpts().CPlusPlus)
2550     return;
2551
2552   // Must have 'used' attribute, or else inline assembly can't rely on
2553   // the name existing.
2554   if (!D->template hasAttr<UsedAttr>())
2555     return;
2556
2557   // Must have internal linkage and an ordinary name.
2558   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
2559     return;
2560
2561   // Must be in an extern "C" context. Entities declared directly within
2562   // a record are not extern "C" even if the record is in such a context.
2563   const SomeDecl *First = D->getFirstDecl();
2564   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
2565     return;
2566
2567   // OK, this is an internal linkage entity inside an extern "C" linkage
2568   // specification. Make a note of that so we can give it the "expected"
2569   // mangled name if nothing else is using that name.
2570   std::pair<StaticExternCMap::iterator, bool> R =
2571       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
2572
2573   // If we have multiple internal linkage entities with the same name
2574   // in extern "C" regions, none of them gets that name.
2575   if (!R.second)
2576     R.first->second = nullptr;
2577 }
2578
2579 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
2580   if (!CGM.supportsCOMDAT())
2581     return false;
2582
2583   if (D.hasAttr<SelectAnyAttr>())
2584     return true;
2585
2586   GVALinkage Linkage;
2587   if (auto *VD = dyn_cast<VarDecl>(&D))
2588     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
2589   else
2590     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
2591
2592   switch (Linkage) {
2593   case GVA_Internal:
2594   case GVA_AvailableExternally:
2595   case GVA_StrongExternal:
2596     return false;
2597   case GVA_DiscardableODR:
2598   case GVA_StrongODR:
2599     return true;
2600   }
2601   llvm_unreachable("No such linkage");
2602 }
2603
2604 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
2605                                           llvm::GlobalObject &GO) {
2606   if (!shouldBeInCOMDAT(*this, D))
2607     return;
2608   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
2609 }
2610
2611 /// Pass IsTentative as true if you want to create a tentative definition.
2612 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
2613                                             bool IsTentative) {
2614   // OpenCL global variables of sampler type are translated to function calls,
2615   // therefore no need to be translated.
2616   QualType ASTTy = D->getType();
2617   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
2618     return;
2619
2620   llvm::Constant *Init = nullptr;
2621   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2622   bool NeedsGlobalCtor = false;
2623   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
2624
2625   const VarDecl *InitDecl;
2626   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2627
2628   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
2629   // as part of their declaration."  Sema has already checked for
2630   // error cases, so we just need to set Init to UndefValue.
2631   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
2632       D->hasAttr<CUDASharedAttr>())
2633     Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
2634   else if (!InitExpr) {
2635     // This is a tentative definition; tentative definitions are
2636     // implicitly initialized with { 0 }.
2637     //
2638     // Note that tentative definitions are only emitted at the end of
2639     // a translation unit, so they should never have incomplete
2640     // type. In addition, EmitTentativeDefinition makes sure that we
2641     // never attempt to emit a tentative definition if a real one
2642     // exists. A use may still exists, however, so we still may need
2643     // to do a RAUW.
2644     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
2645     Init = EmitNullConstant(D->getType());
2646   } else {
2647     initializedGlobalDecl = GlobalDecl(D);
2648     Init = EmitConstantInit(*InitDecl);
2649
2650     if (!Init) {
2651       QualType T = InitExpr->getType();
2652       if (D->getType()->isReferenceType())
2653         T = D->getType();
2654
2655       if (getLangOpts().CPlusPlus) {
2656         Init = EmitNullConstant(T);
2657         NeedsGlobalCtor = true;
2658       } else {
2659         ErrorUnsupported(D, "static initializer");
2660         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2661       }
2662     } else {
2663       // We don't need an initializer, so remove the entry for the delayed
2664       // initializer position (just in case this entry was delayed) if we
2665       // also don't need to register a destructor.
2666       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
2667         DelayedCXXInitPosition.erase(D);
2668     }
2669   }
2670
2671   llvm::Type* InitType = Init->getType();
2672   llvm::Constant *Entry =
2673       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
2674
2675   // Strip off a bitcast if we got one back.
2676   if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2677     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2678            CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2679            // All zero index gep.
2680            CE->getOpcode() == llvm::Instruction::GetElementPtr);
2681     Entry = CE->getOperand(0);
2682   }
2683
2684   // Entry is now either a Function or GlobalVariable.
2685   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2686
2687   // We have a definition after a declaration with the wrong type.
2688   // We must make a new GlobalVariable* and update everything that used OldGV
2689   // (a declaration or tentative definition) with the new GlobalVariable*
2690   // (which will be a definition).
2691   //
2692   // This happens if there is a prototype for a global (e.g.
2693   // "extern int x[];") and then a definition of a different type (e.g.
2694   // "int x[10];"). This also happens when an initializer has a different type
2695   // from the type of the global (this happens with unions).
2696   if (!GV ||
2697       GV->getType()->getElementType() != InitType ||
2698       GV->getType()->getAddressSpace() !=
2699        GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
2700
2701     // Move the old entry aside so that we'll create a new one.
2702     Entry->setName(StringRef());
2703
2704     // Make a new global with the correct type, this is now guaranteed to work.
2705     GV = cast<llvm::GlobalVariable>(
2706         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
2707
2708     // Replace all uses of the old global with the new global
2709     llvm::Constant *NewPtrForOldDecl =
2710         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2711     Entry->replaceAllUsesWith(NewPtrForOldDecl);
2712
2713     // Erase the old global, since it is no longer used.
2714     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2715   }
2716
2717   MaybeHandleStaticInExternC(D, GV);
2718
2719   if (D->hasAttr<AnnotateAttr>())
2720     AddGlobalAnnotations(D, GV);
2721
2722   // Set the llvm linkage type as appropriate.
2723   llvm::GlobalValue::LinkageTypes Linkage =
2724       getLLVMLinkageVarDefinition(D, GV->isConstant());
2725
2726   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
2727   // the device. [...]"
2728   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
2729   // __device__, declares a variable that: [...]
2730   // Is accessible from all the threads within the grid and from the host
2731   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
2732   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
2733   if (GV && LangOpts.CUDA) {
2734     if (LangOpts.CUDAIsDevice) {
2735       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
2736         GV->setExternallyInitialized(true);
2737     } else {
2738       // Host-side shadows of external declarations of device-side
2739       // global variables become internal definitions. These have to
2740       // be internal in order to prevent name conflicts with global
2741       // host variables with the same name in a different TUs.
2742       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
2743         Linkage = llvm::GlobalValue::InternalLinkage;
2744
2745         // Shadow variables and their properties must be registered
2746         // with CUDA runtime.
2747         unsigned Flags = 0;
2748         if (!D->hasDefinition())
2749           Flags |= CGCUDARuntime::ExternDeviceVar;
2750         if (D->hasAttr<CUDAConstantAttr>())
2751           Flags |= CGCUDARuntime::ConstantDeviceVar;
2752         getCUDARuntime().registerDeviceVar(*GV, Flags);
2753       } else if (D->hasAttr<CUDASharedAttr>())
2754         // __shared__ variables are odd. Shadows do get created, but
2755         // they are not registered with the CUDA runtime, so they
2756         // can't really be used to access their device-side
2757         // counterparts. It's not clear yet whether it's nvcc's bug or
2758         // a feature, but we've got to do the same for compatibility.
2759         Linkage = llvm::GlobalValue::InternalLinkage;
2760     }
2761   }
2762   GV->setInitializer(Init);
2763
2764   // If it is safe to mark the global 'constant', do so now.
2765   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2766                   isTypeConstant(D->getType(), true));
2767
2768   // If it is in a read-only section, mark it 'constant'.
2769   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
2770     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
2771     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
2772       GV->setConstant(true);
2773   }
2774
2775   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2776
2777
2778   // On Darwin, if the normal linkage of a C++ thread_local variable is
2779   // LinkOnce or Weak, we keep the normal linkage to prevent multiple
2780   // copies within a linkage unit; otherwise, the backing variable has
2781   // internal linkage and all accesses should just be calls to the
2782   // Itanium-specified entry point, which has the normal linkage of the
2783   // variable. This is to preserve the ability to change the implementation
2784   // behind the scenes.
2785   if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
2786       Context.getTargetInfo().getTriple().isOSDarwin() &&
2787       !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
2788       !llvm::GlobalVariable::isWeakLinkage(Linkage))
2789     Linkage = llvm::GlobalValue::InternalLinkage;
2790
2791   GV->setLinkage(Linkage);
2792   if (D->hasAttr<DLLImportAttr>())
2793     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2794   else if (D->hasAttr<DLLExportAttr>())
2795     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2796   else
2797     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2798
2799   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
2800     // common vars aren't constant even if declared const.
2801     GV->setConstant(false);
2802     // Tentative definition of global variables may be initialized with
2803     // non-zero null pointers. In this case they should have weak linkage
2804     // since common linkage must have zero initializer and must not have
2805     // explicit section therefore cannot have non-zero initial value.
2806     if (!GV->getInitializer()->isNullValue())
2807       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
2808   }
2809
2810   setNonAliasAttributes(D, GV);
2811
2812   if (D->getTLSKind() && !GV->isThreadLocal()) {
2813     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2814       CXXThreadLocals.push_back(D);
2815     setTLSMode(GV, *D);
2816   }
2817
2818   maybeSetTrivialComdat(*D, *GV);
2819
2820   // Emit the initializer function if necessary.
2821   if (NeedsGlobalCtor || NeedsGlobalDtor)
2822     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
2823
2824   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
2825
2826   // Emit global variable debug information.
2827   if (CGDebugInfo *DI = getModuleDebugInfo())
2828     if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
2829       DI->EmitGlobalVariable(GV, D);
2830 }
2831
2832 static bool isVarDeclStrongDefinition(const ASTContext &Context,
2833                                       CodeGenModule &CGM, const VarDecl *D,
2834                                       bool NoCommon) {
2835   // Don't give variables common linkage if -fno-common was specified unless it
2836   // was overridden by a NoCommon attribute.
2837   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
2838     return true;
2839
2840   // C11 6.9.2/2:
2841   //   A declaration of an identifier for an object that has file scope without
2842   //   an initializer, and without a storage-class specifier or with the
2843   //   storage-class specifier static, constitutes a tentative definition.
2844   if (D->getInit() || D->hasExternalStorage())
2845     return true;
2846
2847   // A variable cannot be both common and exist in a section.
2848   if (D->hasAttr<SectionAttr>())
2849     return true;
2850
2851   // A variable cannot be both common and exist in a section.
2852   // We dont try to determine which is the right section in the front-end.
2853   // If no specialized section name is applicable, it will resort to default.
2854   if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
2855       D->hasAttr<PragmaClangDataSectionAttr>() ||
2856       D->hasAttr<PragmaClangRodataSectionAttr>())
2857     return true;
2858
2859   // Thread local vars aren't considered common linkage.
2860   if (D->getTLSKind())
2861     return true;
2862
2863   // Tentative definitions marked with WeakImportAttr are true definitions.
2864   if (D->hasAttr<WeakImportAttr>())
2865     return true;
2866
2867   // A variable cannot be both common and exist in a comdat.
2868   if (shouldBeInCOMDAT(CGM, *D))
2869     return true;
2870
2871   // Declarations with a required alignment do not have common linkage in MSVC
2872   // mode.
2873   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2874     if (D->hasAttr<AlignedAttr>())
2875       return true;
2876     QualType VarType = D->getType();
2877     if (Context.isAlignmentRequired(VarType))
2878       return true;
2879
2880     if (const auto *RT = VarType->getAs<RecordType>()) {
2881       const RecordDecl *RD = RT->getDecl();
2882       for (const FieldDecl *FD : RD->fields()) {
2883         if (FD->isBitField())
2884           continue;
2885         if (FD->hasAttr<AlignedAttr>())
2886           return true;
2887         if (Context.isAlignmentRequired(FD->getType()))
2888           return true;
2889       }
2890     }
2891   }
2892
2893   return false;
2894 }
2895
2896 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
2897     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
2898   if (Linkage == GVA_Internal)
2899     return llvm::Function::InternalLinkage;
2900
2901   if (D->hasAttr<WeakAttr>()) {
2902     if (IsConstantVariable)
2903       return llvm::GlobalVariable::WeakODRLinkage;
2904     else
2905       return llvm::GlobalVariable::WeakAnyLinkage;
2906   }
2907
2908   // We are guaranteed to have a strong definition somewhere else,
2909   // so we can use available_externally linkage.
2910   if (Linkage == GVA_AvailableExternally)
2911     return llvm::GlobalValue::AvailableExternallyLinkage;
2912
2913   // Note that Apple's kernel linker doesn't support symbol
2914   // coalescing, so we need to avoid linkonce and weak linkages there.
2915   // Normally, this means we just map to internal, but for explicit
2916   // instantiations we'll map to external.
2917
2918   // In C++, the compiler has to emit a definition in every translation unit
2919   // that references the function.  We should use linkonce_odr because
2920   // a) if all references in this translation unit are optimized away, we
2921   // don't need to codegen it.  b) if the function persists, it needs to be
2922   // merged with other definitions. c) C++ has the ODR, so we know the
2923   // definition is dependable.
2924   if (Linkage == GVA_DiscardableODR)
2925     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
2926                                             : llvm::Function::InternalLinkage;
2927
2928   // An explicit instantiation of a template has weak linkage, since
2929   // explicit instantiations can occur in multiple translation units
2930   // and must all be equivalent. However, we are not allowed to
2931   // throw away these explicit instantiations.
2932   //
2933   // We don't currently support CUDA device code spread out across multiple TUs,
2934   // so say that CUDA templates are either external (for kernels) or internal.
2935   // This lets llvm perform aggressive inter-procedural optimizations.
2936   if (Linkage == GVA_StrongODR) {
2937     if (Context.getLangOpts().AppleKext)
2938       return llvm::Function::ExternalLinkage;
2939     if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
2940       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
2941                                           : llvm::Function::InternalLinkage;
2942     return llvm::Function::WeakODRLinkage;
2943   }
2944
2945   // C++ doesn't have tentative definitions and thus cannot have common
2946   // linkage.
2947   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
2948       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
2949                                  CodeGenOpts.NoCommon))
2950     return llvm::GlobalVariable::CommonLinkage;
2951
2952   // selectany symbols are externally visible, so use weak instead of
2953   // linkonce.  MSVC optimizes away references to const selectany globals, so
2954   // all definitions should be the same and ODR linkage should be used.
2955   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
2956   if (D->hasAttr<SelectAnyAttr>())
2957     return llvm::GlobalVariable::WeakODRLinkage;
2958
2959   // Otherwise, we have strong external linkage.
2960   assert(Linkage == GVA_StrongExternal);
2961   return llvm::GlobalVariable::ExternalLinkage;
2962 }
2963
2964 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
2965     const VarDecl *VD, bool IsConstant) {
2966   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
2967   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
2968 }
2969
2970 /// Replace the uses of a function that was declared with a non-proto type.
2971 /// We want to silently drop extra arguments from call sites
2972 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2973                                           llvm::Function *newFn) {
2974   // Fast path.
2975   if (old->use_empty()) return;
2976
2977   llvm::Type *newRetTy = newFn->getReturnType();
2978   SmallVector<llvm::Value*, 4> newArgs;
2979   SmallVector<llvm::OperandBundleDef, 1> newBundles;
2980
2981   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2982          ui != ue; ) {
2983     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
2984     llvm::User *user = use->getUser();
2985
2986     // Recognize and replace uses of bitcasts.  Most calls to
2987     // unprototyped functions will use bitcasts.
2988     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
2989       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2990         replaceUsesOfNonProtoConstant(bitcast, newFn);
2991       continue;
2992     }
2993
2994     // Recognize calls to the function.
2995     llvm::CallSite callSite(user);
2996     if (!callSite) continue;
2997     if (!callSite.isCallee(&*use)) continue;
2998
2999     // If the return types don't match exactly, then we can't
3000     // transform this call unless it's dead.
3001     if (callSite->getType() != newRetTy && !callSite->use_empty())
3002       continue;
3003
3004     // Get the call site's attribute list.
3005     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
3006     llvm::AttributeList oldAttrs = callSite.getAttributes();
3007
3008     // If the function was passed too few arguments, don't transform.
3009     unsigned newNumArgs = newFn->arg_size();
3010     if (callSite.arg_size() < newNumArgs) continue;
3011
3012     // If extra arguments were passed, we silently drop them.
3013     // If any of the types mismatch, we don't transform.
3014     unsigned argNo = 0;
3015     bool dontTransform = false;
3016     for (llvm::Argument &A : newFn->args()) {
3017       if (callSite.getArgument(argNo)->getType() != A.getType()) {
3018         dontTransform = true;
3019         break;
3020       }
3021
3022       // Add any parameter attributes.
3023       newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
3024       argNo++;
3025     }
3026     if (dontTransform)
3027       continue;
3028
3029     // Okay, we can transform this.  Create the new call instruction and copy
3030     // over the required information.
3031     newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
3032
3033     // Copy over any operand bundles.
3034     callSite.getOperandBundlesAsDefs(newBundles);
3035
3036     llvm::CallSite newCall;
3037     if (callSite.isCall()) {
3038       newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
3039                                        callSite.getInstruction());
3040     } else {
3041       auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
3042       newCall = llvm::InvokeInst::Create(newFn,
3043                                          oldInvoke->getNormalDest(),
3044                                          oldInvoke->getUnwindDest(),
3045                                          newArgs, newBundles, "",
3046                                          callSite.getInstruction());
3047     }
3048     newArgs.clear(); // for the next iteration
3049
3050     if (!newCall->getType()->isVoidTy())
3051       newCall->takeName(callSite.getInstruction());
3052     newCall.setAttributes(llvm::AttributeList::get(
3053         newFn->getContext(), oldAttrs.getFnAttributes(),
3054         oldAttrs.getRetAttributes(), newArgAttrs));
3055     newCall.setCallingConv(callSite.getCallingConv());
3056
3057     // Finally, remove the old call, replacing any uses with the new one.
3058     if (!callSite->use_empty())
3059       callSite->replaceAllUsesWith(newCall.getInstruction());
3060
3061     // Copy debug location attached to CI.
3062     if (callSite->getDebugLoc())
3063       newCall->setDebugLoc(callSite->getDebugLoc());
3064
3065     callSite->eraseFromParent();
3066   }
3067 }
3068
3069 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
3070 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
3071 /// existing call uses of the old function in the module, this adjusts them to
3072 /// call the new function directly.
3073 ///
3074 /// This is not just a cleanup: the always_inline pass requires direct calls to
3075 /// functions to be able to inline them.  If there is a bitcast in the way, it
3076 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
3077 /// run at -O0.
3078 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3079                                                       llvm::Function *NewFn) {
3080   // If we're redefining a global as a function, don't transform it.
3081   if (!isa<llvm::Function>(Old)) return;
3082
3083   replaceUsesOfNonProtoConstant(Old, NewFn);
3084 }
3085
3086 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
3087   auto DK = VD->isThisDeclarationADefinition();
3088   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
3089     return;
3090
3091   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
3092   // If we have a definition, this might be a deferred decl. If the
3093   // instantiation is explicit, make sure we emit it at the end.
3094   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
3095     GetAddrOfGlobalVar(VD);
3096
3097   EmitTopLevelDecl(VD);
3098 }
3099
3100 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
3101                                                  llvm::GlobalValue *GV) {
3102   const auto *D = cast<FunctionDecl>(GD.getDecl());
3103
3104   // Compute the function info and LLVM type.
3105   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3106   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3107
3108   // Get or create the prototype for the function.
3109   if (!GV || (GV->getType()->getElementType() != Ty))
3110     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
3111                                                    /*DontDefer=*/true,
3112                                                    ForDefinition));
3113
3114   // Already emitted.
3115   if (!GV->isDeclaration())
3116     return;
3117
3118   // We need to set linkage and visibility on the function before
3119   // generating code for it because various parts of IR generation
3120   // want to propagate this information down (e.g. to local static
3121   // declarations).
3122   auto *Fn = cast<llvm::Function>(GV);
3123   setFunctionLinkage(GD, Fn);
3124   setFunctionDLLStorageClass(GD, Fn);
3125
3126   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
3127   setGlobalVisibility(Fn, D);
3128
3129   MaybeHandleStaticInExternC(D, Fn);
3130
3131   maybeSetTrivialComdat(*D, *Fn);
3132
3133   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
3134
3135   setFunctionDefinitionAttributes(D, Fn);
3136   SetLLVMFunctionAttributesForDefinition(D, Fn);
3137
3138   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
3139     AddGlobalCtor(Fn, CA->getPriority());
3140   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
3141     AddGlobalDtor(Fn, DA->getPriority());
3142   if (D->hasAttr<AnnotateAttr>())
3143     AddGlobalAnnotations(D, Fn);
3144 }
3145
3146 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
3147   const auto *D = cast<ValueDecl>(GD.getDecl());
3148   const AliasAttr *AA = D->getAttr<AliasAttr>();
3149   assert(AA && "Not an alias?");
3150
3151   StringRef MangledName = getMangledName(GD);
3152
3153   if (AA->getAliasee() == MangledName) {
3154     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3155     return;
3156   }
3157
3158   // If there is a definition in the module, then it wins over the alias.
3159   // This is dubious, but allow it to be safe.  Just ignore the alias.
3160   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3161   if (Entry && !Entry->isDeclaration())
3162     return;
3163
3164   Aliases.push_back(GD);
3165
3166   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3167
3168   // Create a reference to the named value.  This ensures that it is emitted
3169   // if a deferred decl.
3170   llvm::Constant *Aliasee;
3171   if (isa<llvm::FunctionType>(DeclTy))
3172     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
3173                                       /*ForVTable=*/false);
3174   else
3175     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
3176                                     llvm::PointerType::getUnqual(DeclTy),
3177                                     /*D=*/nullptr);
3178
3179   // Create the new alias itself, but don't set a name yet.
3180   auto *GA = llvm::GlobalAlias::create(
3181       DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
3182
3183   if (Entry) {
3184     if (GA->getAliasee() == Entry) {
3185       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3186       return;
3187     }
3188
3189     assert(Entry->isDeclaration());
3190
3191     // If there is a declaration in the module, then we had an extern followed
3192     // by the alias, as in:
3193     //   extern int test6();
3194     //   ...
3195     //   int test6() __attribute__((alias("test7")));
3196     //
3197     // Remove it and replace uses of it with the alias.
3198     GA->takeName(Entry);
3199
3200     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
3201                                                           Entry->getType()));
3202     Entry->eraseFromParent();
3203   } else {
3204     GA->setName(MangledName);
3205   }
3206
3207   // Set attributes which are particular to an alias; this is a
3208   // specialization of the attributes which may be set on a global
3209   // variable/function.
3210   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
3211       D->isWeakImported()) {
3212     GA->setLinkage(llvm::Function::WeakAnyLinkage);
3213   }
3214
3215   if (const auto *VD = dyn_cast<VarDecl>(D))
3216     if (VD->getTLSKind())
3217       setTLSMode(GA, *VD);
3218
3219   setAliasAttributes(D, GA);
3220 }
3221
3222 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
3223   const auto *D = cast<ValueDecl>(GD.getDecl());
3224   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
3225   assert(IFA && "Not an ifunc?");
3226
3227   StringRef MangledName = getMangledName(GD);
3228
3229   if (IFA->getResolver() == MangledName) {
3230     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3231     return;
3232   }
3233
3234   // Report an error if some definition overrides ifunc.
3235   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3236   if (Entry && !Entry->isDeclaration()) {
3237     GlobalDecl OtherGD;
3238     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3239         DiagnosedConflictingDefinitions.insert(GD).second) {
3240       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
3241       Diags.Report(OtherGD.getDecl()->getLocation(),
3242                    diag::note_previous_definition);
3243     }
3244     return;
3245   }
3246
3247   Aliases.push_back(GD);
3248
3249   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3250   llvm::Constant *Resolver =
3251       GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3252                               /*ForVTable=*/false);
3253   llvm::GlobalIFunc *GIF =
3254       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
3255                                 "", Resolver, &getModule());
3256   if (Entry) {
3257     if (GIF->getResolver() == Entry) {
3258       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3259       return;
3260     }
3261     assert(Entry->isDeclaration());
3262
3263     // If there is a declaration in the module, then we had an extern followed
3264     // by the ifunc, as in:
3265     //   extern int test();
3266     //   ...
3267     //   int test() __attribute__((ifunc("resolver")));
3268     //
3269     // Remove it and replace uses of it with the ifunc.
3270     GIF->takeName(Entry);
3271
3272     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3273                                                           Entry->getType()));
3274     Entry->eraseFromParent();
3275   } else
3276     GIF->setName(MangledName);
3277
3278   SetCommonAttributes(D, GIF);
3279 }
3280
3281 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
3282                                             ArrayRef<llvm::Type*> Tys) {
3283   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
3284                                          Tys);
3285 }
3286
3287 static llvm::StringMapEntry<llvm::GlobalVariable *> &
3288 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
3289                          const StringLiteral *Literal, bool TargetIsLSB,
3290                          bool &IsUTF16, unsigned &StringLength) {
3291   StringRef String = Literal->getString();
3292   unsigned NumBytes = String.size();
3293
3294   // Check for simple case.
3295   if (!Literal->containsNonAsciiOrNull()) {
3296     StringLength = NumBytes;
3297     return *Map.insert(std::make_pair(String, nullptr)).first;
3298   }
3299
3300   // Otherwise, convert the UTF8 literals into a string of shorts.
3301   IsUTF16 = true;
3302
3303   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
3304   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3305   llvm::UTF16 *ToPtr = &ToBuf[0];
3306
3307   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3308                                  ToPtr + NumBytes, llvm::strictConversion);
3309
3310   // ConvertUTF8toUTF16 returns the length in ToPtr.
3311   StringLength = ToPtr - &ToBuf[0];
3312
3313   // Add an explicit null.
3314   *ToPtr = 0;
3315   return *Map.insert(std::make_pair(
3316                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
3317                                    (StringLength + 1) * 2),
3318                          nullptr)).first;
3319 }
3320
3321 ConstantAddress
3322 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
3323   unsigned StringLength = 0;
3324   bool isUTF16 = false;
3325   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3326       GetConstantCFStringEntry(CFConstantStringMap, Literal,
3327                                getDataLayout().isLittleEndian(), isUTF16,
3328                                StringLength);
3329
3330   if (auto *C = Entry.second)
3331     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
3332
3333   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
3334   llvm::Constant *Zeros[] = { Zero, Zero };
3335
3336   // If we don't already have it, get __CFConstantStringClassReference.
3337   if (!CFConstantStringClassRef) {
3338     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
3339     Ty = llvm::ArrayType::get(Ty, 0);
3340     llvm::Constant *GV =
3341         CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
3342
3343     if (getTriple().isOSBinFormatCOFF()) {
3344       IdentifierInfo &II = getContext().Idents.get(GV->getName());
3345       TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
3346       DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3347       llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
3348
3349       const VarDecl *VD = nullptr;
3350       for (const auto &Result : DC->lookup(&II))
3351         if ((VD = dyn_cast<VarDecl>(Result)))
3352           break;
3353
3354       if (!VD || !VD->hasAttr<DLLExportAttr>()) {
3355         CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3356         CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3357       } else {
3358         CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3359         CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3360       }
3361     }
3362
3363     // Decay array -> ptr
3364     CFConstantStringClassRef =
3365         llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
3366   }
3367
3368   QualType CFTy = getContext().getCFConstantStringType();
3369
3370   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
3371
3372   ConstantInitBuilder Builder(*this);
3373   auto Fields = Builder.beginStruct(STy);
3374
3375   // Class pointer.
3376   Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
3377
3378   // Flags.
3379   Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
3380
3381   // String pointer.
3382   llvm::Constant *C = nullptr;
3383   if (isUTF16) {
3384     auto Arr = llvm::makeArrayRef(
3385         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
3386         Entry.first().size() / 2);
3387     C = llvm::ConstantDataArray::get(VMContext, Arr);
3388   } else {
3389     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
3390   }
3391
3392   // Note: -fwritable-strings doesn't make the backing store strings of
3393   // CFStrings writable. (See <rdar://problem/10657500>)
3394   auto *GV =
3395       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
3396                                llvm::GlobalValue::PrivateLinkage, C, ".str");
3397   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3398   // Don't enforce the target's minimum global alignment, since the only use
3399   // of the string is via this class initializer.
3400   CharUnits Align = isUTF16
3401                         ? getContext().getTypeAlignInChars(getContext().ShortTy)
3402                         : getContext().getTypeAlignInChars(getContext().CharTy);
3403   GV->setAlignment(Align.getQuantity());
3404
3405   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
3406   // Without it LLVM can merge the string with a non unnamed_addr one during
3407   // LTO.  Doing that changes the section it ends in, which surprises ld64.
3408   if (getTriple().isOSBinFormatMachO())
3409     GV->setSection(isUTF16 ? "__TEXT,__ustring"
3410                            : "__TEXT,__cstring,cstring_literals");
3411
3412   // String.
3413   llvm::Constant *Str =
3414       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3415
3416   if (isUTF16)
3417     // Cast the UTF16 string to the correct type.
3418     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
3419   Fields.add(Str);
3420
3421   // String length.
3422   auto Ty = getTypes().ConvertType(getContext().LongTy);
3423   Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
3424
3425   CharUnits Alignment = getPointerAlign();
3426
3427   // The struct.
3428   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
3429                                     /*isConstant=*/false,
3430                                     llvm::GlobalVariable::PrivateLinkage);
3431   switch (getTriple().getObjectFormat()) {
3432   case llvm::Triple::UnknownObjectFormat:
3433     llvm_unreachable("unknown file format");
3434   case llvm::Triple::COFF:
3435   case llvm::Triple::ELF:
3436   case llvm::Triple::Wasm:
3437     GV->setSection("cfstring");
3438     break;
3439   case llvm::Triple::MachO:
3440     GV->setSection("__DATA,__cfstring");
3441     break;
3442   }
3443   Entry.second = GV;
3444
3445   return ConstantAddress(GV, Alignment);
3446 }
3447
3448 QualType CodeGenModule::getObjCFastEnumerationStateType() {
3449   if (ObjCFastEnumerationStateType.isNull()) {
3450     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
3451     D->startDefinition();
3452     
3453     QualType FieldTypes[] = {
3454       Context.UnsignedLongTy,
3455       Context.getPointerType(Context.getObjCIdType()),
3456       Context.getPointerType(Context.UnsignedLongTy),
3457       Context.getConstantArrayType(Context.UnsignedLongTy,
3458                            llvm::APInt(32, 5), ArrayType::Normal, 0)
3459     };
3460     
3461     for (size_t i = 0; i < 4; ++i) {
3462       FieldDecl *Field = FieldDecl::Create(Context,
3463                                            D,
3464                                            SourceLocation(),
3465                                            SourceLocation(), nullptr,
3466                                            FieldTypes[i], /*TInfo=*/nullptr,
3467                                            /*BitWidth=*/nullptr,
3468                                            /*Mutable=*/false,
3469                                            ICIS_NoInit);
3470       Field->setAccess(AS_public);
3471       D->addDecl(Field);
3472     }
3473     
3474     D->completeDefinition();
3475     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
3476   }
3477   
3478   return ObjCFastEnumerationStateType;
3479 }
3480
3481 llvm::Constant *
3482 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
3483   assert(!E->getType()->isPointerType() && "Strings are always arrays");
3484   
3485   // Don't emit it as the address of the string, emit the string data itself
3486   // as an inline array.
3487   if (E->getCharByteWidth() == 1) {
3488     SmallString<64> Str(E->getString());
3489
3490     // Resize the string to the right size, which is indicated by its type.
3491     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
3492     Str.resize(CAT->getSize().getZExtValue());
3493     return llvm::ConstantDataArray::getString(VMContext, Str, false);
3494   }
3495
3496   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
3497   llvm::Type *ElemTy = AType->getElementType();
3498   unsigned NumElements = AType->getNumElements();
3499
3500   // Wide strings have either 2-byte or 4-byte elements.
3501   if (ElemTy->getPrimitiveSizeInBits() == 16) {
3502     SmallVector<uint16_t, 32> Elements;
3503     Elements.reserve(NumElements);
3504
3505     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3506       Elements.push_back(E->getCodeUnit(i));
3507     Elements.resize(NumElements);
3508     return llvm::ConstantDataArray::get(VMContext, Elements);
3509   }
3510   
3511   assert(ElemTy->getPrimitiveSizeInBits() == 32);
3512   SmallVector<uint32_t, 32> Elements;
3513   Elements.reserve(NumElements);
3514   
3515   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3516     Elements.push_back(E->getCodeUnit(i));
3517   Elements.resize(NumElements);
3518   return llvm::ConstantDataArray::get(VMContext, Elements);
3519 }
3520
3521 static llvm::GlobalVariable *
3522 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
3523                       CodeGenModule &CGM, StringRef GlobalName,
3524                       CharUnits Alignment) {
3525   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3526   unsigned AddrSpace = 0;
3527   if (CGM.getLangOpts().OpenCL)
3528     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
3529
3530   llvm::Module &M = CGM.getModule();
3531   // Create a global variable for this string
3532   auto *GV = new llvm::GlobalVariable(
3533       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
3534       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
3535   GV->setAlignment(Alignment.getQuantity());
3536   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3537   if (GV->isWeakForLinker()) {
3538     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
3539     GV->setComdat(M.getOrInsertComdat(GV->getName()));
3540   }
3541
3542   return GV;
3543 }
3544
3545 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
3546 /// constant array for the given string literal.
3547 ConstantAddress
3548 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
3549                                                   StringRef Name) {
3550   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
3551
3552   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
3553   llvm::GlobalVariable **Entry = nullptr;
3554   if (!LangOpts.WritableStrings) {
3555     Entry = &ConstantStringMap[C];
3556     if (auto GV = *Entry) {
3557       if (Alignment.getQuantity() > GV->getAlignment())
3558         GV->setAlignment(Alignment.getQuantity());
3559       return ConstantAddress(GV, Alignment);
3560     }
3561   }
3562
3563   SmallString<256> MangledNameBuffer;
3564   StringRef GlobalVariableName;
3565   llvm::GlobalValue::LinkageTypes LT;
3566
3567   // Mangle the string literal if the ABI allows for it.  However, we cannot
3568   // do this if  we are compiling with ASan or -fwritable-strings because they
3569   // rely on strings having normal linkage.
3570   if (!LangOpts.WritableStrings &&
3571       !LangOpts.Sanitize.has(SanitizerKind::Address) &&
3572       getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
3573     llvm::raw_svector_ostream Out(MangledNameBuffer);
3574     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
3575
3576     LT = llvm::GlobalValue::LinkOnceODRLinkage;
3577     GlobalVariableName = MangledNameBuffer;
3578   } else {
3579     LT = llvm::GlobalValue::PrivateLinkage;
3580     GlobalVariableName = Name;
3581   }
3582
3583   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
3584   if (Entry)
3585     *Entry = GV;
3586
3587   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
3588                                   QualType());
3589   return ConstantAddress(GV, Alignment);
3590 }
3591
3592 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
3593 /// array for the given ObjCEncodeExpr node.
3594 ConstantAddress
3595 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
3596   std::string Str;
3597   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
3598
3599   return GetAddrOfConstantCString(Str);
3600 }
3601
3602 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
3603 /// the literal and a terminating '\0' character.
3604 /// The result has pointer to array type.
3605 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
3606     const std::string &Str, const char *GlobalName) {
3607   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
3608   CharUnits Alignment =
3609     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
3610
3611   llvm::Constant *C =
3612       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
3613
3614   // Don't share any string literals if strings aren't constant.
3615   llvm::GlobalVariable **Entry = nullptr;
3616   if (!LangOpts.WritableStrings) {
3617     Entry = &ConstantStringMap[C];
3618     if (auto GV = *Entry) {
3619       if (Alignment.getQuantity() > GV->getAlignment())
3620         GV->setAlignment(Alignment.getQuantity());
3621       return ConstantAddress(GV, Alignment);
3622     }
3623   }
3624
3625   // Get the default prefix if a name wasn't specified.
3626   if (!GlobalName)
3627     GlobalName = ".str";
3628   // Create a global variable for this.
3629   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
3630                                   GlobalName, Alignment);
3631   if (Entry)
3632     *Entry = GV;
3633   return ConstantAddress(GV, Alignment);
3634 }
3635
3636 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
3637     const MaterializeTemporaryExpr *E, const Expr *Init) {
3638   assert((E->getStorageDuration() == SD_Static ||
3639           E->getStorageDuration() == SD_Thread) && "not a global temporary");
3640   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
3641
3642   // If we're not materializing a subobject of the temporary, keep the
3643   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
3644   QualType MaterializedType = Init->getType();
3645   if (Init == E->GetTemporaryExpr())
3646     MaterializedType = E->getType();
3647
3648   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
3649
3650   if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
3651     return ConstantAddress(Slot, Align);
3652
3653   // FIXME: If an externally-visible declaration extends multiple temporaries,
3654   // we need to give each temporary the same name in every translation unit (and
3655   // we also need to make the temporaries externally-visible).
3656   SmallString<256> Name;
3657   llvm::raw_svector_ostream Out(Name);
3658   getCXXABI().getMangleContext().mangleReferenceTemporary(
3659       VD, E->getManglingNumber(), Out);
3660
3661   APValue *Value = nullptr;
3662   if (E->getStorageDuration() == SD_Static) {
3663     // We might have a cached constant initializer for this temporary. Note
3664     // that this might have a different value from the value computed by
3665     // evaluating the initializer if the surrounding constant expression
3666     // modifies the temporary.
3667     Value = getContext().getMaterializedTemporaryValue(E, false);
3668     if (Value && Value->isUninit())
3669       Value = nullptr;
3670   }
3671
3672   // Try evaluating it now, it might have a constant initializer.
3673   Expr::EvalResult EvalResult;
3674   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3675       !EvalResult.hasSideEffects())
3676     Value = &EvalResult.Val;
3677
3678   llvm::Constant *InitialValue = nullptr;
3679   bool Constant = false;
3680   llvm::Type *Type;
3681   if (Value) {
3682     // The temporary has a constant initializer, use it.
3683     InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
3684     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3685     Type = InitialValue->getType();
3686   } else {
3687     // No initializer, the initialization will be provided when we
3688     // initialize the declaration which performed lifetime extension.
3689     Type = getTypes().ConvertTypeForMem(MaterializedType);
3690   }
3691
3692   // Create a global variable for this lifetime-extended temporary.
3693   llvm::GlobalValue::LinkageTypes Linkage =
3694       getLLVMLinkageVarDefinition(VD, Constant);
3695   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
3696     const VarDecl *InitVD;
3697     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
3698         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
3699       // Temporaries defined inside a class get linkonce_odr linkage because the
3700       // class can be defined in multipe translation units.
3701       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
3702     } else {
3703       // There is no need for this temporary to have external linkage if the
3704       // VarDecl has external linkage.
3705       Linkage = llvm::GlobalVariable::InternalLinkage;
3706     }
3707   }
3708   unsigned AddrSpace = GetGlobalVarAddressSpace(
3709       VD, getContext().getTargetAddressSpace(MaterializedType));
3710   auto *GV = new llvm::GlobalVariable(
3711       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
3712       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3713       AddrSpace);
3714   setGlobalVisibility(GV, VD);
3715   GV->setAlignment(Align.getQuantity());
3716   if (supportsCOMDAT() && GV->isWeakForLinker())
3717     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3718   if (VD->getTLSKind())
3719     setTLSMode(GV, *VD);
3720   MaterializedGlobalTemporaryMap[E] = GV;
3721   return ConstantAddress(GV, Align);
3722 }
3723
3724 /// EmitObjCPropertyImplementations - Emit information for synthesized
3725 /// properties for an implementation.
3726 void CodeGenModule::EmitObjCPropertyImplementations(const
3727                                                     ObjCImplementationDecl *D) {
3728   for (const auto *PID : D->property_impls()) {
3729     // Dynamic is just for type-checking.
3730     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3731       ObjCPropertyDecl *PD = PID->getPropertyDecl();
3732
3733       // Determine which methods need to be implemented, some may have
3734       // been overridden. Note that ::isPropertyAccessor is not the method
3735       // we want, that just indicates if the decl came from a
3736       // property. What we want to know is if the method is defined in
3737       // this implementation.
3738       if (!D->getInstanceMethod(PD->getGetterName()))
3739         CodeGenFunction(*this).GenerateObjCGetter(
3740                                  const_cast<ObjCImplementationDecl *>(D), PID);
3741       if (!PD->isReadOnly() &&
3742           !D->getInstanceMethod(PD->getSetterName()))
3743         CodeGenFunction(*this).GenerateObjCSetter(
3744                                  const_cast<ObjCImplementationDecl *>(D), PID);
3745     }
3746   }
3747 }
3748
3749 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
3750   const ObjCInterfaceDecl *iface = impl->getClassInterface();
3751   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
3752        ivar; ivar = ivar->getNextIvar())
3753     if (ivar->getType().isDestructedType())
3754       return true;
3755
3756   return false;
3757 }
3758
3759 static bool AllTrivialInitializers(CodeGenModule &CGM,
3760                                    ObjCImplementationDecl *D) {
3761   CodeGenFunction CGF(CGM);
3762   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
3763        E = D->init_end(); B != E; ++B) {
3764     CXXCtorInitializer *CtorInitExp = *B;
3765     Expr *Init = CtorInitExp->getInit();
3766     if (!CGF.isTrivialInitializer(Init))
3767       return false;
3768   }
3769   return true;
3770 }
3771
3772 /// EmitObjCIvarInitializations - Emit information for ivar initialization
3773 /// for an implementation.
3774 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
3775   // We might need a .cxx_destruct even if we don't have any ivar initializers.
3776   if (needsDestructMethod(D)) {
3777     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3778     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3779     ObjCMethodDecl *DTORMethod =
3780       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
3781                              cxxSelector, getContext().VoidTy, nullptr, D,
3782                              /*isInstance=*/true, /*isVariadic=*/false,
3783                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
3784                              /*isDefined=*/false, ObjCMethodDecl::Required);
3785     D->addInstanceMethod(DTORMethod);
3786     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
3787     D->setHasDestructors(true);
3788   }
3789
3790   // If the implementation doesn't have any ivar initializers, we don't need
3791   // a .cxx_construct.
3792   if (D->getNumIvarInitializers() == 0 ||
3793       AllTrivialInitializers(*this, D))
3794     return;
3795   
3796   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
3797   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3798   // The constructor returns 'self'.
3799   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 
3800                                                 D->getLocation(),
3801                                                 D->getLocation(),
3802                                                 cxxSelector,
3803                                                 getContext().getObjCIdType(),
3804                                                 nullptr, D, /*isInstance=*/true,
3805                                                 /*isVariadic=*/false,
3806                                                 /*isPropertyAccessor=*/true,
3807                                                 /*isImplicitlyDeclared=*/true,
3808                                                 /*isDefined=*/false,
3809                                                 ObjCMethodDecl::Required);
3810   D->addInstanceMethod(CTORMethod);
3811   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
3812   D->setHasNonZeroConstructors(true);
3813 }
3814
3815 // EmitLinkageSpec - Emit all declarations in a linkage spec.
3816 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
3817   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3818       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
3819     ErrorUnsupported(LSD, "linkage spec");
3820     return;
3821   }
3822
3823   EmitDeclContext(LSD);
3824 }
3825
3826 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
3827   for (auto *I : DC->decls()) {
3828     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
3829     // are themselves considered "top-level", so EmitTopLevelDecl on an
3830     // ObjCImplDecl does not recursively visit them. We need to do that in
3831     // case they're nested inside another construct (LinkageSpecDecl /
3832     // ExportDecl) that does stop them from being considered "top-level".
3833     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
3834       for (auto *M : OID->methods())
3835         EmitTopLevelDecl(M);
3836     }
3837
3838     EmitTopLevelDecl(I);
3839   }
3840 }
3841
3842 /// EmitTopLevelDecl - Emit code for a single top level declaration.
3843 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
3844   // Ignore dependent declarations.
3845   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3846     return;
3847
3848   switch (D->getKind()) {
3849   case Decl::CXXConversion:
3850   case Decl::CXXMethod:
3851   case Decl::Function:
3852     // Skip function templates
3853     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3854         cast<FunctionDecl>(D)->isLateTemplateParsed())
3855       return;
3856
3857     EmitGlobal(cast<FunctionDecl>(D));
3858     // Always provide some coverage mapping
3859     // even for the functions that aren't emitted.
3860     AddDeferredUnusedCoverageMapping(D);
3861     break;
3862
3863   case Decl::CXXDeductionGuide:
3864     // Function-like, but does not result in code emission.
3865     break;
3866
3867   case Decl::Var:
3868   case Decl::Decomposition:
3869     // Skip variable templates
3870     if (cast<VarDecl>(D)->getDescribedVarTemplate())
3871       return;
3872     LLVM_FALLTHROUGH;
3873   case Decl::VarTemplateSpecialization:
3874     EmitGlobal(cast<VarDecl>(D));
3875     if (auto *DD = dyn_cast<DecompositionDecl>(D))
3876       for (auto *B : DD->bindings())
3877         if (auto *HD = B->getHoldingVar())
3878           EmitGlobal(HD);
3879     break;
3880
3881   // Indirect fields from global anonymous structs and unions can be
3882   // ignored; only the actual variable requires IR gen support.
3883   case Decl::IndirectField:
3884     break;
3885
3886   // C++ Decls
3887   case Decl::Namespace:
3888     EmitDeclContext(cast<NamespaceDecl>(D));
3889     break;
3890   case Decl::CXXRecord:
3891     if (DebugInfo) {
3892       if (auto *ES = D->getASTContext().getExternalSource())
3893         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
3894           DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
3895     }
3896     // Emit any static data members, they may be definitions.
3897     for (auto *I : cast<CXXRecordDecl>(D)->decls())
3898       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
3899         EmitTopLevelDecl(I);
3900     break;
3901     // No code generation needed.
3902   case Decl::UsingShadow:
3903   case Decl::ClassTemplate:
3904   case Decl::VarTemplate:
3905   case Decl::VarTemplatePartialSpecialization:
3906   case Decl::FunctionTemplate:
3907   case Decl::TypeAliasTemplate:
3908   case Decl::Block:
3909   case Decl::Empty:
3910     break;
3911   case Decl::Using:          // using X; [C++]
3912     if (CGDebugInfo *DI = getModuleDebugInfo())
3913         DI->EmitUsingDecl(cast<UsingDecl>(*D));
3914     return;
3915   case Decl::NamespaceAlias:
3916     if (CGDebugInfo *DI = getModuleDebugInfo())
3917         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3918     return;
3919   case Decl::UsingDirective: // using namespace X; [C++]
3920     if (CGDebugInfo *DI = getModuleDebugInfo())
3921       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3922     return;
3923   case Decl::CXXConstructor:
3924     // Skip function templates
3925     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3926         cast<FunctionDecl>(D)->isLateTemplateParsed())
3927       return;
3928       
3929     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
3930     break;
3931   case Decl::CXXDestructor:
3932     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3933       return;
3934     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
3935     break;
3936
3937   case Decl::StaticAssert:
3938     // Nothing to do.
3939     break;
3940
3941   // Objective-C Decls
3942
3943   // Forward declarations, no (immediate) code generation.
3944   case Decl::ObjCInterface:
3945   case Decl::ObjCCategory:
3946     break;
3947
3948   case Decl::ObjCProtocol: {
3949     auto *Proto = cast<ObjCProtocolDecl>(D);
3950     if (Proto->isThisDeclarationADefinition())
3951       ObjCRuntime->GenerateProtocol(Proto);
3952     break;
3953   }
3954       
3955   case Decl::ObjCCategoryImpl:
3956     // Categories have properties but don't support synthesize so we
3957     // can ignore them here.
3958     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
3959     break;
3960
3961   case Decl::ObjCImplementation: {
3962     auto *OMD = cast<ObjCImplementationDecl>(D);
3963     EmitObjCPropertyImplementations(OMD);
3964     EmitObjCIvarInitializations(OMD);
3965     ObjCRuntime->GenerateClass(OMD);
3966     // Emit global variable debug information.
3967     if (CGDebugInfo *DI = getModuleDebugInfo())
3968       if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
3969         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3970             OMD->getClassInterface()), OMD->getLocation());
3971     break;
3972   }
3973   case Decl::ObjCMethod: {
3974     auto *OMD = cast<ObjCMethodDecl>(D);
3975     // If this is not a prototype, emit the body.
3976     if (OMD->getBody())
3977       CodeGenFunction(*this).GenerateObjCMethod(OMD);
3978     break;
3979   }
3980   case Decl::ObjCCompatibleAlias:
3981     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3982     break;
3983
3984   case Decl::PragmaComment: {
3985     const auto *PCD = cast<PragmaCommentDecl>(D);
3986     switch (PCD->getCommentKind()) {
3987     case PCK_Unknown:
3988       llvm_unreachable("unexpected pragma comment kind");
3989     case PCK_Linker:
3990       AppendLinkerOptions(PCD->getArg());
3991       break;
3992     case PCK_Lib:
3993       AddDependentLib(PCD->getArg());
3994       break;
3995     case PCK_Compiler:
3996     case PCK_ExeStr:
3997     case PCK_User:
3998       break; // We ignore all of these.
3999     }
4000     break;
4001   }
4002
4003   case Decl::PragmaDetectMismatch: {
4004     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
4005     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
4006     break;
4007   }
4008
4009   case Decl::LinkageSpec:
4010     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
4011     break;
4012
4013   case Decl::FileScopeAsm: {
4014     // File-scope asm is ignored during device-side CUDA compilation.
4015     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
4016       break;
4017     // File-scope asm is ignored during device-side OpenMP compilation.
4018     if (LangOpts.OpenMPIsDevice)
4019       break;
4020     auto *AD = cast<FileScopeAsmDecl>(D);
4021     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
4022     break;
4023   }
4024
4025   case Decl::Import: {
4026     auto *Import = cast<ImportDecl>(D);
4027
4028     // If we've already imported this module, we're done.
4029     if (!ImportedModules.insert(Import->getImportedModule()))
4030       break;
4031
4032     // Emit debug information for direct imports.
4033     if (!Import->getImportedOwningModule()) {
4034       if (CGDebugInfo *DI = getModuleDebugInfo())
4035         DI->EmitImportDecl(*Import);
4036     }
4037
4038     // Find all of the submodules and emit the module initializers.
4039     llvm::SmallPtrSet<clang::Module *, 16> Visited;
4040     SmallVector<clang::Module *, 16> Stack;
4041     Visited.insert(Import->getImportedModule());
4042     Stack.push_back(Import->getImportedModule());
4043
4044     while (!Stack.empty()) {
4045       clang::Module *Mod = Stack.pop_back_val();
4046       if (!EmittedModuleInitializers.insert(Mod).second)
4047         continue;
4048
4049       for (auto *D : Context.getModuleInitializers(Mod))
4050         EmitTopLevelDecl(D);
4051
4052       // Visit the submodules of this module.
4053       for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
4054                                              SubEnd = Mod->submodule_end();
4055            Sub != SubEnd; ++Sub) {
4056         // Skip explicit children; they need to be explicitly imported to emit
4057         // the initializers.
4058         if ((*Sub)->IsExplicit)
4059           continue;
4060
4061         if (Visited.insert(*Sub).second)
4062           Stack.push_back(*Sub);
4063       }
4064     }
4065     break;
4066   }
4067
4068   case Decl::Export:
4069     EmitDeclContext(cast<ExportDecl>(D));
4070     break;
4071
4072   case Decl::OMPThreadPrivate:
4073     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
4074     break;
4075
4076   case Decl::ClassTemplateSpecialization: {
4077     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
4078     if (DebugInfo &&
4079         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
4080         Spec->hasDefinition())
4081       DebugInfo->completeTemplateDefinition(*Spec);
4082     break;
4083   }
4084
4085   case Decl::OMPDeclareReduction:
4086     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
4087     break;
4088
4089   default:
4090     // Make sure we handled everything we should, every other kind is a
4091     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
4092     // function. Need to recode Decl::Kind to do that easily.
4093     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
4094     break;
4095   }
4096 }
4097
4098 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
4099   // Do we need to generate coverage mapping?
4100   if (!CodeGenOpts.CoverageMapping)
4101     return;
4102   switch (D->getKind()) {
4103   case Decl::CXXConversion:
4104   case Decl::CXXMethod:
4105   case Decl::Function:
4106   case Decl::ObjCMethod:
4107   case Decl::CXXConstructor:
4108   case Decl::CXXDestructor: {
4109     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
4110       return;
4111     auto I = DeferredEmptyCoverageMappingDecls.find(D);
4112     if (I == DeferredEmptyCoverageMappingDecls.end())
4113       DeferredEmptyCoverageMappingDecls[D] = true;
4114     break;
4115   }
4116   default:
4117     break;
4118   };
4119 }
4120
4121 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
4122   // Do we need to generate coverage mapping?
4123   if (!CodeGenOpts.CoverageMapping)
4124     return;
4125   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
4126     if (Fn->isTemplateInstantiation())
4127       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
4128   }
4129   auto I = DeferredEmptyCoverageMappingDecls.find(D);
4130   if (I == DeferredEmptyCoverageMappingDecls.end())
4131     DeferredEmptyCoverageMappingDecls[D] = false;
4132   else
4133     I->second = false;
4134 }
4135
4136 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
4137   std::vector<const Decl *> DeferredDecls;
4138   for (const auto &I : DeferredEmptyCoverageMappingDecls) {
4139     if (!I.second)
4140       continue;
4141     DeferredDecls.push_back(I.first);
4142   }
4143   // Sort the declarations by their location to make sure that the tests get a
4144   // predictable order for the coverage mapping for the unused declarations.
4145   if (CodeGenOpts.DumpCoverageMapping)
4146     std::sort(DeferredDecls.begin(), DeferredDecls.end(),
4147               [] (const Decl *LHS, const Decl *RHS) {
4148       return LHS->getLocStart() < RHS->getLocStart();
4149     });
4150   for (const auto *D : DeferredDecls) {
4151     switch (D->getKind()) {
4152     case Decl::CXXConversion:
4153     case Decl::CXXMethod:
4154     case Decl::Function:
4155     case Decl::ObjCMethod: {
4156       CodeGenPGO PGO(*this);
4157       GlobalDecl GD(cast<FunctionDecl>(D));
4158       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4159                                   getFunctionLinkage(GD));
4160       break;
4161     }
4162     case Decl::CXXConstructor: {
4163       CodeGenPGO PGO(*this);
4164       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
4165       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4166                                   getFunctionLinkage(GD));
4167       break;
4168     }
4169     case Decl::CXXDestructor: {
4170       CodeGenPGO PGO(*this);
4171       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
4172       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4173                                   getFunctionLinkage(GD));
4174       break;
4175     }
4176     default:
4177       break;
4178     };
4179   }
4180 }
4181
4182 /// Turns the given pointer into a constant.
4183 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4184                                           const void *Ptr) {
4185   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
4186   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
4187   return llvm::ConstantInt::get(i64, PtrInt);
4188 }
4189
4190 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
4191                                    llvm::NamedMDNode *&GlobalMetadata,
4192                                    GlobalDecl D,
4193                                    llvm::GlobalValue *Addr) {
4194   if (!GlobalMetadata)
4195     GlobalMetadata =
4196       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4197
4198   // TODO: should we report variant information for ctors/dtors?
4199   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
4200                            llvm::ConstantAsMetadata::get(GetPointerConstant(
4201                                CGM.getLLVMContext(), D.getDecl()))};
4202   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
4203 }
4204
4205 /// For each function which is declared within an extern "C" region and marked
4206 /// as 'used', but has internal linkage, create an alias from the unmangled
4207 /// name to the mangled name if possible. People expect to be able to refer
4208 /// to such functions with an unmangled name from inline assembly within the
4209 /// same translation unit.
4210 void CodeGenModule::EmitStaticExternCAliases() {
4211   // Don't do anything if we're generating CUDA device code -- the NVPTX
4212   // assembly target doesn't support aliases.
4213   if (Context.getTargetInfo().getTriple().isNVPTX())
4214     return;
4215   for (auto &I : StaticExternCValues) {
4216     IdentifierInfo *Name = I.first;
4217     llvm::GlobalValue *Val = I.second;
4218     if (Val && !getModule().getNamedValue(Name->getName()))
4219       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
4220   }
4221 }
4222
4223 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
4224                                              GlobalDecl &Result) const {
4225   auto Res = Manglings.find(MangledName);
4226   if (Res == Manglings.end())
4227     return false;
4228   Result = Res->getValue();
4229   return true;
4230 }
4231
4232 /// Emits metadata nodes associating all the global values in the
4233 /// current module with the Decls they came from.  This is useful for
4234 /// projects using IR gen as a subroutine.
4235 ///
4236 /// Since there's currently no way to associate an MDNode directly
4237 /// with an llvm::GlobalValue, we create a global named metadata
4238 /// with the name 'clang.global.decl.ptrs'.
4239 void CodeGenModule::EmitDeclMetadata() {
4240   llvm::NamedMDNode *GlobalMetadata = nullptr;
4241
4242   for (auto &I : MangledDeclNames) {
4243     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
4244     // Some mangled names don't necessarily have an associated GlobalValue
4245     // in this module, e.g. if we mangled it for DebugInfo.
4246     if (Addr)
4247       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
4248   }
4249 }
4250
4251 /// Emits metadata nodes for all the local variables in the current
4252 /// function.
4253 void CodeGenFunction::EmitDeclMetadata() {
4254   if (LocalDeclMap.empty()) return;
4255
4256   llvm::LLVMContext &Context = getLLVMContext();
4257
4258   // Find the unique metadata ID for this name.
4259   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
4260
4261   llvm::NamedMDNode *GlobalMetadata = nullptr;
4262
4263   for (auto &I : LocalDeclMap) {
4264     const Decl *D = I.first;
4265     llvm::Value *Addr = I.second.getPointer();
4266     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
4267       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
4268       Alloca->setMetadata(
4269           DeclPtrKind, llvm::MDNode::get(
4270                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
4271     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
4272       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
4273       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
4274     }
4275   }
4276 }
4277
4278 void CodeGenModule::EmitVersionIdentMetadata() {
4279   llvm::NamedMDNode *IdentMetadata =
4280     TheModule.getOrInsertNamedMetadata("llvm.ident");
4281   std::string Version = getClangFullVersion();
4282   llvm::LLVMContext &Ctx = TheModule.getContext();
4283
4284   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
4285   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4286 }
4287
4288 void CodeGenModule::EmitTargetMetadata() {
4289   // Warning, new MangledDeclNames may be appended within this loop.
4290   // We rely on MapVector insertions adding new elements to the end
4291   // of the container.
4292   // FIXME: Move this loop into the one target that needs it, and only
4293   // loop over those declarations for which we couldn't emit the target
4294   // metadata when we emitted the declaration.
4295   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
4296     auto Val = *(MangledDeclNames.begin() + I);
4297     const Decl *D = Val.first.getDecl()->getMostRecentDecl();
4298     llvm::GlobalValue *GV = GetGlobalValue(Val.second);
4299     getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
4300   }
4301 }
4302
4303 void CodeGenModule::EmitCoverageFile() {
4304   if (getCodeGenOpts().CoverageDataFile.empty() &&
4305       getCodeGenOpts().CoverageNotesFile.empty())
4306     return;
4307
4308   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
4309   if (!CUNode)
4310     return;
4311
4312   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
4313   llvm::LLVMContext &Ctx = TheModule.getContext();
4314   auto *CoverageDataFile =
4315       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
4316   auto *CoverageNotesFile =
4317       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
4318   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
4319     llvm::MDNode *CU = CUNode->getOperand(i);
4320     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
4321     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
4322   }
4323 }
4324
4325 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
4326   // Sema has checked that all uuid strings are of the form
4327   // "12345678-1234-1234-1234-1234567890ab".
4328   assert(Uuid.size() == 36);
4329   for (unsigned i = 0; i < 36; ++i) {
4330     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
4331     else                                         assert(isHexDigit(Uuid[i]));
4332   }
4333
4334   // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
4335   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
4336
4337   llvm::Constant *Field3[8];
4338   for (unsigned Idx = 0; Idx < 8; ++Idx)
4339     Field3[Idx] = llvm::ConstantInt::get(
4340         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
4341
4342   llvm::Constant *Fields[4] = {
4343     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
4344     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
4345     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
4346     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
4347   };
4348
4349   return llvm::ConstantStruct::getAnon(Fields);
4350 }
4351
4352 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
4353                                                        bool ForEH) {
4354   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
4355   // FIXME: should we even be calling this method if RTTI is disabled
4356   // and it's not for EH?
4357   if (!ForEH && !getLangOpts().RTTI)
4358     return llvm::Constant::getNullValue(Int8PtrTy);
4359   
4360   if (ForEH && Ty->isObjCObjectPointerType() &&
4361       LangOpts.ObjCRuntime.isGNUFamily())
4362     return ObjCRuntime->GetEHType(Ty);
4363
4364   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
4365 }
4366
4367 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
4368   for (auto RefExpr : D->varlists()) {
4369     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
4370     bool PerformInit =
4371         VD->getAnyInitializer() &&
4372         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
4373                                                         /*ForRef=*/false);
4374
4375     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
4376     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
4377             VD, Addr, RefExpr->getLocStart(), PerformInit))
4378       CXXGlobalInits.push_back(InitFunction);
4379   }
4380 }
4381
4382 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
4383   llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
4384   if (InternalId)
4385     return InternalId;
4386
4387   if (isExternallyVisible(T->getLinkage())) {
4388     std::string OutName;
4389     llvm::raw_string_ostream Out(OutName);
4390     getCXXABI().getMangleContext().mangleTypeName(T, Out);
4391
4392     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
4393   } else {
4394     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
4395                                            llvm::ArrayRef<llvm::Metadata *>());
4396   }
4397
4398   return InternalId;
4399 }
4400
4401 /// Returns whether this module needs the "all-vtables" type identifier.
4402 bool CodeGenModule::NeedAllVtablesTypeId() const {
4403   // Returns true if at least one of vtable-based CFI checkers is enabled and
4404   // is not in the trapping mode.
4405   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
4406            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
4407           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
4408            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
4409           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
4410            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
4411           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
4412            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
4413 }
4414
4415 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
4416                                           CharUnits Offset,
4417                                           const CXXRecordDecl *RD) {
4418   llvm::Metadata *MD =
4419       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
4420   VTable->addTypeMetadata(Offset.getQuantity(), MD);
4421
4422   if (CodeGenOpts.SanitizeCfiCrossDso)
4423     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
4424       VTable->addTypeMetadata(Offset.getQuantity(),
4425                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
4426
4427   if (NeedAllVtablesTypeId()) {
4428     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
4429     VTable->addTypeMetadata(Offset.getQuantity(), MD);
4430   }
4431 }
4432
4433 // Fills in the supplied string map with the set of target features for the
4434 // passed in function.
4435 void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
4436                                           const FunctionDecl *FD) {
4437   StringRef TargetCPU = Target.getTargetOpts().CPU;
4438   if (const auto *TD = FD->getAttr<TargetAttr>()) {
4439     // If we have a TargetAttr build up the feature map based on that.
4440     TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
4441
4442     // Make a copy of the features as passed on the command line into the
4443     // beginning of the additional features from the function to override.
4444     ParsedAttr.first.insert(ParsedAttr.first.begin(),
4445                             Target.getTargetOpts().FeaturesAsWritten.begin(),
4446                             Target.getTargetOpts().FeaturesAsWritten.end());
4447
4448     if (ParsedAttr.second != "")
4449       TargetCPU = ParsedAttr.second;
4450
4451     // Now populate the feature map, first with the TargetCPU which is either
4452     // the default or a new one from the target attribute string. Then we'll use
4453     // the passed in features (FeaturesAsWritten) along with the new ones from
4454     // the attribute.
4455     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first);
4456   } else {
4457     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
4458                           Target.getTargetOpts().Features);
4459   }
4460 }
4461
4462 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
4463   if (!SanStats)
4464     SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
4465
4466   return *SanStats;
4467 }
4468 llvm::Value *
4469 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
4470                                                   CodeGenFunction &CGF) {
4471   llvm::Constant *C = EmitConstantExpr(E, E->getType(), &CGF);
4472   auto SamplerT = getOpenCLRuntime().getSamplerType();
4473   auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
4474   return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
4475                                 "__translate_sampler_initializer"),
4476                                 {C});
4477 }