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