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