clang  7.0.0
CodeGenModule.cpp
Go to the documentation of this file.
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 "ConstantEmitter.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"
37 #include "clang/Basic/Builtins.h"
38 #include "clang/Basic/CharInfo.h"
39 #include "clang/Basic/Diagnostic.h"
40 #include "clang/Basic/Module.h"
42 #include "clang/Basic/TargetInfo.h"
43 #include "clang/Basic/Version.h"
47 #include "llvm/ADT/Triple.h"
48 #include "llvm/Analysis/TargetLibraryInfo.h"
49 #include "llvm/IR/CallSite.h"
50 #include "llvm/IR/CallingConv.h"
51 #include "llvm/IR/DataLayout.h"
52 #include "llvm/IR/Intrinsics.h"
53 #include "llvm/IR/LLVMContext.h"
54 #include "llvm/IR/Module.h"
55 #include "llvm/ProfileData/InstrProfReader.h"
56 #include "llvm/Support/ConvertUTF.h"
57 #include "llvm/Support/ErrorHandling.h"
58 #include "llvm/Support/MD5.h"
59 
60 using namespace clang;
61 using namespace CodeGen;
62 
63 static llvm::cl::opt<bool> LimitedCoverage(
64  "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
65  llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
66  llvm::cl::init(false));
67 
68 static const char AnnotationSection[] = "llvm.metadata";
69 
71  switch (CGM.getTarget().getCXXABI().getKind()) {
74  case TargetCXXABI::iOS:
80  return CreateItaniumCXXABI(CGM);
82  return CreateMicrosoftCXXABI(CGM);
83  }
84 
85  llvm_unreachable("invalid C++ ABI kind");
86 }
87 
88 CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
89  const PreprocessorOptions &PPO,
90  const CodeGenOptions &CGO, llvm::Module &M,
91  DiagnosticsEngine &diags,
92  CoverageSourceInfo *CoverageInfo)
93  : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
94  PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
95  Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
96  VMContext(M.getContext()), Types(*this), VTables(*this),
97  SanitizerMD(new SanitizerMetadata(*this)) {
98 
99  // Initialize the type cache.
100  llvm::LLVMContext &LLVMContext = M.getContext();
101  VoidTy = llvm::Type::getVoidTy(LLVMContext);
102  Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
103  Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
104  Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
105  Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
106  HalfTy = llvm::Type::getHalfTy(LLVMContext);
107  FloatTy = llvm::Type::getFloatTy(LLVMContext);
108  DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
111  C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
115  C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
116  IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
117  IntPtrTy = llvm::IntegerType::get(LLVMContext,
119  Int8PtrTy = Int8Ty->getPointerTo(0);
120  Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
121  AllocaInt8PtrTy = Int8Ty->getPointerTo(
122  M.getDataLayout().getAllocaAddrSpace());
124 
126 
127  if (LangOpts.ObjC1)
128  createObjCRuntime();
129  if (LangOpts.OpenCL)
130  createOpenCLRuntime();
131  if (LangOpts.OpenMP)
132  createOpenMPRuntime();
133  if (LangOpts.CUDA)
134  createCUDARuntime();
135 
136  // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
137  if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
138  (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
139  TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
140  getCXXABI().getMangleContext()));
141 
142  // If debug info or coverage generation is enabled, create the CGDebugInfo
143  // object.
144  if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
145  CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
146  DebugInfo.reset(new CGDebugInfo(*this));
147 
148  Block.GlobalUniqueCount = 0;
149 
150  if (C.getLangOpts().ObjC1)
151  ObjCData.reset(new ObjCEntrypoints());
152 
153  if (CodeGenOpts.hasProfileClangUse()) {
154  auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
155  CodeGenOpts.ProfileInstrumentUsePath);
156  if (auto E = ReaderOrErr.takeError()) {
157  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
158  "Could not read profile %0: %1");
159  llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
160  getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
161  << EI.message();
162  });
163  } else
164  PGOReader = std::move(ReaderOrErr.get());
165  }
166 
167  // If coverage mapping generation is enabled, create the
168  // CoverageMappingModuleGen object.
169  if (CodeGenOpts.CoverageMapping)
170  CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
171 }
172 
174 
175 void CodeGenModule::createObjCRuntime() {
176  // This is just isGNUFamily(), but we want to force implementors of
177  // new ABIs to decide how best to do this.
178  switch (LangOpts.ObjCRuntime.getKind()) {
180  case ObjCRuntime::GCC:
181  case ObjCRuntime::ObjFW:
182  ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
183  return;
184 
186  case ObjCRuntime::MacOSX:
187  case ObjCRuntime::iOS:
189  ObjCRuntime.reset(CreateMacObjCRuntime(*this));
190  return;
191  }
192  llvm_unreachable("bad runtime kind");
193 }
194 
195 void CodeGenModule::createOpenCLRuntime() {
196  OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
197 }
198 
199 void CodeGenModule::createOpenMPRuntime() {
200  // Select a specialized code generation class based on the target, if any.
201  // If it does not exist use the default implementation.
202  switch (getTriple().getArch()) {
203  case llvm::Triple::nvptx:
204  case llvm::Triple::nvptx64:
205  assert(getLangOpts().OpenMPIsDevice &&
206  "OpenMP NVPTX is only prepared to deal with device code.");
207  OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
208  break;
209  default:
210  if (LangOpts.OpenMPSimd)
211  OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
212  else
213  OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
214  break;
215  }
216 }
217 
218 void CodeGenModule::createCUDARuntime() {
219  CUDARuntime.reset(CreateNVCUDARuntime(*this));
220 }
221 
222 void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
223  Replacements[Name] = C;
224 }
225 
226 void CodeGenModule::applyReplacements() {
227  for (auto &I : Replacements) {
228  StringRef MangledName = I.first();
229  llvm::Constant *Replacement = I.second;
230  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
231  if (!Entry)
232  continue;
233  auto *OldF = cast<llvm::Function>(Entry);
234  auto *NewF = dyn_cast<llvm::Function>(Replacement);
235  if (!NewF) {
236  if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
237  NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
238  } else {
239  auto *CE = cast<llvm::ConstantExpr>(Replacement);
240  assert(CE->getOpcode() == llvm::Instruction::BitCast ||
241  CE->getOpcode() == llvm::Instruction::GetElementPtr);
242  NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
243  }
244  }
245 
246  // Replace old with new, but keep the old order.
247  OldF->replaceAllUsesWith(Replacement);
248  if (NewF) {
249  NewF->removeFromParent();
250  OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
251  NewF);
252  }
253  OldF->eraseFromParent();
254  }
255 }
256 
257 void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
258  GlobalValReplacements.push_back(std::make_pair(GV, C));
259 }
260 
261 void CodeGenModule::applyGlobalValReplacements() {
262  for (auto &I : GlobalValReplacements) {
263  llvm::GlobalValue *GV = I.first;
264  llvm::Constant *C = I.second;
265 
266  GV->replaceAllUsesWith(C);
267  GV->eraseFromParent();
268  }
269 }
270 
271 // This is only used in aliases that we created and we know they have a
272 // linear structure.
273 static const llvm::GlobalObject *getAliasedGlobal(
274  const llvm::GlobalIndirectSymbol &GIS) {
275  llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
276  const llvm::Constant *C = &GIS;
277  for (;;) {
278  C = C->stripPointerCasts();
279  if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
280  return GO;
281  // stripPointerCasts will not walk over weak aliases.
282  auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
283  if (!GIS2)
284  return nullptr;
285  if (!Visited.insert(GIS2).second)
286  return nullptr;
287  C = GIS2->getIndirectSymbol();
288  }
289 }
290 
291 void CodeGenModule::checkAliases() {
292  // Check if the constructed aliases are well formed. It is really unfortunate
293  // that we have to do this in CodeGen, but we only construct mangled names
294  // and aliases during codegen.
295  bool Error = false;
296  DiagnosticsEngine &Diags = getDiags();
297  for (const GlobalDecl &GD : Aliases) {
298  const auto *D = cast<ValueDecl>(GD.getDecl());
299  SourceLocation Location;
300  bool IsIFunc = D->hasAttr<IFuncAttr>();
301  if (const Attr *A = D->getDefiningAttr())
302  Location = A->getLocation();
303  else
304  llvm_unreachable("Not an alias or ifunc?");
305  StringRef MangledName = getMangledName(GD);
306  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
307  auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
308  const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
309  if (!GV) {
310  Error = true;
311  Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
312  } else if (GV->isDeclaration()) {
313  Error = true;
314  Diags.Report(Location, diag::err_alias_to_undefined)
315  << IsIFunc << IsIFunc;
316  } else if (IsIFunc) {
317  // Check resolver function type.
318  llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
319  GV->getType()->getPointerElementType());
320  assert(FTy);
321  if (!FTy->getReturnType()->isPointerTy())
322  Diags.Report(Location, diag::err_ifunc_resolver_return);
323  if (FTy->getNumParams())
324  Diags.Report(Location, diag::err_ifunc_resolver_params);
325  }
326 
327  llvm::Constant *Aliasee = Alias->getIndirectSymbol();
328  llvm::GlobalValue *AliaseeGV;
329  if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
330  AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
331  else
332  AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
333 
334  if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
335  StringRef AliasSection = SA->getName();
336  if (AliasSection != AliaseeGV->getSection())
337  Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
338  << AliasSection << IsIFunc << IsIFunc;
339  }
340 
341  // We have to handle alias to weak aliases in here. LLVM itself disallows
342  // this since the object semantics would not match the IL one. For
343  // compatibility with gcc we implement it by just pointing the alias
344  // to its aliasee's aliasee. We also warn, since the user is probably
345  // expecting the link to be weak.
346  if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
347  if (GA->isInterposable()) {
348  Diags.Report(Location, diag::warn_alias_to_weak_alias)
349  << GV->getName() << GA->getName() << IsIFunc;
350  Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
351  GA->getIndirectSymbol(), Alias->getType());
352  Alias->setIndirectSymbol(Aliasee);
353  }
354  }
355  }
356  if (!Error)
357  return;
358 
359  for (const GlobalDecl &GD : Aliases) {
360  StringRef MangledName = getMangledName(GD);
361  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
362  auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
363  Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
364  Alias->eraseFromParent();
365  }
366 }
367 
369  DeferredDeclsToEmit.clear();
370  if (OpenMPRuntime)
371  OpenMPRuntime->clear();
372 }
373 
375  StringRef MainFile) {
376  if (!hasDiagnostics())
377  return;
378  if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
379  if (MainFile.empty())
380  MainFile = "<stdin>";
381  Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
382  } else {
383  if (Mismatched > 0)
384  Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
385 
386  if (Missing > 0)
387  Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
388  }
389 }
390 
392  EmitDeferred();
393  EmitVTablesOpportunistically();
394  applyGlobalValReplacements();
395  applyReplacements();
396  checkAliases();
397  emitMultiVersionFunctions();
398  EmitCXXGlobalInitFunc();
399  EmitCXXGlobalDtorFunc();
400  registerGlobalDtorsWithAtExit();
401  EmitCXXThreadLocalInitFunc();
402  if (ObjCRuntime)
403  if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
404  AddGlobalCtor(ObjCInitFunction);
405  if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
406  CUDARuntime) {
407  if (llvm::Function *CudaCtorFunction =
408  CUDARuntime->makeModuleCtorFunction())
409  AddGlobalCtor(CudaCtorFunction);
410  }
411  if (OpenMPRuntime) {
412  if (llvm::Function *OpenMPRegistrationFunction =
413  OpenMPRuntime->emitRegistrationFunction()) {
414  auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
415  OpenMPRegistrationFunction : nullptr;
416  AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
417  }
418  OpenMPRuntime->clear();
419  }
420  if (PGOReader) {
421  getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
422  if (PGOStats.hasDiagnostics())
423  PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
424  }
425  EmitCtorList(GlobalCtors, "llvm.global_ctors");
426  EmitCtorList(GlobalDtors, "llvm.global_dtors");
428  EmitStaticExternCAliases();
430  if (CoverageMapping)
431  CoverageMapping->emit();
432  if (CodeGenOpts.SanitizeCfiCrossDso) {
435  }
436  emitAtAvailableLinkGuard();
437  emitLLVMUsed();
438  if (SanStats)
439  SanStats->finish();
440 
441  if (CodeGenOpts.Autolink &&
442  (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
443  EmitModuleLinkOptions();
444  }
445 
446  // Record mregparm value now so it is visible through rest of codegen.
447  if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
448  getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
449  CodeGenOpts.NumRegisterParameters);
450 
451  if (CodeGenOpts.DwarfVersion) {
452  // We actually want the latest version when there are conflicts.
453  // We can change from Warning to Latest if such mode is supported.
454  getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
455  CodeGenOpts.DwarfVersion);
456  }
457  if (CodeGenOpts.EmitCodeView) {
458  // Indicate that we want CodeView in the metadata.
459  getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
460  }
461  if (CodeGenOpts.ControlFlowGuard) {
462  // We want function ID tables for Control Flow Guard.
463  getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
464  }
465  if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
466  // We don't support LTO with 2 with different StrictVTablePointers
467  // FIXME: we could support it by stripping all the information introduced
468  // by StrictVTablePointers.
469 
470  getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
471 
472  llvm::Metadata *Ops[2] = {
473  llvm::MDString::get(VMContext, "StrictVTablePointers"),
474  llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
475  llvm::Type::getInt32Ty(VMContext), 1))};
476 
477  getModule().addModuleFlag(llvm::Module::Require,
478  "StrictVTablePointersRequirement",
479  llvm::MDNode::get(VMContext, Ops));
480  }
481  if (DebugInfo)
482  // We support a single version in the linked module. The LLVM
483  // parser will drop debug info with a different version number
484  // (and warn about it, too).
485  getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
486  llvm::DEBUG_METADATA_VERSION);
487 
488  // We need to record the widths of enums and wchar_t, so that we can generate
489  // the correct build attributes in the ARM backend. wchar_size is also used by
490  // TargetLibraryInfo.
491  uint64_t WCharWidth =
492  Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
493  getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
494 
495  llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
496  if ( Arch == llvm::Triple::arm
497  || Arch == llvm::Triple::armeb
498  || Arch == llvm::Triple::thumb
499  || Arch == llvm::Triple::thumbeb) {
500  // The minimum width of an enum in bytes
501  uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
502  getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
503  }
504 
505  if (CodeGenOpts.SanitizeCfiCrossDso) {
506  // Indicate that we want cross-DSO control flow integrity checks.
507  getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
508  }
509 
510  if (CodeGenOpts.CFProtectionReturn &&
512  // Indicate that we want to instrument return control flow protection.
513  getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
514  1);
515  }
516 
517  if (CodeGenOpts.CFProtectionBranch &&
519  // Indicate that we want to instrument branch control flow protection.
520  getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
521  1);
522  }
523 
524  if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
525  // Indicate whether __nvvm_reflect should be configured to flush denormal
526  // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
527  // property.)
528  getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
529  CodeGenOpts.FlushDenorm ? 1 : 0);
530  }
531 
532  // Emit OpenCL specific module metadata: OpenCL/SPIR version.
533  if (LangOpts.OpenCL) {
534  EmitOpenCLMetadata();
535  // Emit SPIR version.
536  if (getTriple().getArch() == llvm::Triple::spir ||
537  getTriple().getArch() == llvm::Triple::spir64) {
538  // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
539  // opencl.spir.version named metadata.
540  llvm::Metadata *SPIRVerElts[] = {
541  llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
542  Int32Ty, LangOpts.OpenCLVersion / 100)),
543  llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
544  Int32Ty, (LangOpts.OpenCLVersion / 100 > 1) ? 0 : 2))};
545  llvm::NamedMDNode *SPIRVerMD =
546  TheModule.getOrInsertNamedMetadata("opencl.spir.version");
547  llvm::LLVMContext &Ctx = TheModule.getContext();
548  SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
549  }
550  }
551 
552  if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
553  assert(PLevel < 3 && "Invalid PIC Level");
554  getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
555  if (Context.getLangOpts().PIE)
556  getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
557  }
558 
559  if (CodeGenOpts.NoPLT)
560  getModule().setRtLibUseGOT();
561 
562  SimplifyPersonality();
563 
564  if (getCodeGenOpts().EmitDeclMetadata)
565  EmitDeclMetadata();
566 
567  if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
568  EmitCoverageFile();
569 
570  if (DebugInfo)
571  DebugInfo->finalize();
572 
573  if (getCodeGenOpts().EmitVersionIdentMetadata)
574  EmitVersionIdentMetadata();
575 
576  EmitTargetMetadata();
577 }
578 
579 void CodeGenModule::EmitOpenCLMetadata() {
580  // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
581  // opencl.ocl.version named metadata node.
582  llvm::Metadata *OCLVerElts[] = {
583  llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
584  Int32Ty, LangOpts.OpenCLVersion / 100)),
585  llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
586  Int32Ty, (LangOpts.OpenCLVersion % 100) / 10))};
587  llvm::NamedMDNode *OCLVerMD =
588  TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
589  llvm::LLVMContext &Ctx = TheModule.getContext();
590  OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
591 }
592 
594  // Make sure that this type is translated.
595  Types.UpdateCompletedType(TD);
596 }
597 
599  // Make sure that this type is translated.
600  Types.RefreshTypeCacheForClass(RD);
601 }
602 
604  if (!TBAA)
605  return nullptr;
606  return TBAA->getTypeInfo(QTy);
607 }
608 
610  if (!TBAA)
611  return TBAAAccessInfo();
612  return TBAA->getAccessInfo(AccessType);
613 }
614 
617  if (!TBAA)
618  return TBAAAccessInfo();
619  return TBAA->getVTablePtrAccessInfo(VTablePtrType);
620 }
621 
623  if (!TBAA)
624  return nullptr;
625  return TBAA->getTBAAStructInfo(QTy);
626 }
627 
629  if (!TBAA)
630  return nullptr;
631  return TBAA->getBaseTypeInfo(QTy);
632 }
633 
635  if (!TBAA)
636  return nullptr;
637  return TBAA->getAccessTagInfo(Info);
638 }
639 
642  if (!TBAA)
643  return TBAAAccessInfo();
644  return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
645 }
646 
649  TBAAAccessInfo InfoB) {
650  if (!TBAA)
651  return TBAAAccessInfo();
652  return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
653 }
654 
657  TBAAAccessInfo SrcInfo) {
658  if (!TBAA)
659  return TBAAAccessInfo();
660  return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
661 }
662 
663 void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
664  TBAAAccessInfo TBAAInfo) {
665  if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
666  Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
667 }
668 
670  llvm::Instruction *I, const CXXRecordDecl *RD) {
671  I->setMetadata(llvm::LLVMContext::MD_invariant_group,
672  llvm::MDNode::get(getLLVMContext(), {}));
673 }
674 
675 void CodeGenModule::Error(SourceLocation loc, StringRef message) {
676  unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
677  getDiags().Report(Context.getFullLoc(loc), diagID) << message;
678 }
679 
680 /// ErrorUnsupported - Print out an error that codegen doesn't support the
681 /// specified stmt yet.
682 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
684  "cannot compile this %0 yet");
685  std::string Msg = Type;
686  getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
687  << Msg << S->getSourceRange();
688 }
689 
690 /// ErrorUnsupported - Print out an error that codegen doesn't support the
691 /// specified decl yet.
692 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
694  "cannot compile this %0 yet");
695  std::string Msg = Type;
696  getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
697 }
698 
699 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
700  return llvm::ConstantInt::get(SizeTy, size.getQuantity());
701 }
702 
703 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
704  const NamedDecl *D) const {
705  if (GV->hasDLLImportStorageClass())
706  return;
707  // Internal definitions always have default visibility.
708  if (GV->hasLocalLinkage()) {
709  GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
710  return;
711  }
712  if (!D)
713  return;
714  // Set visibility for definitions.
716  if (LV.isVisibilityExplicit() || !GV->isDeclarationForLinker())
717  GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
718 }
719 
720 static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
721  llvm::GlobalValue *GV) {
722  if (GV->hasLocalLinkage())
723  return true;
724 
725  if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
726  return true;
727 
728  // DLLImport explicitly marks the GV as external.
729  if (GV->hasDLLImportStorageClass())
730  return false;
731 
732  const llvm::Triple &TT = CGM.getTriple();
733  // Every other GV is local on COFF.
734  // Make an exception for windows OS in the triple: Some firmware builds use
735  // *-win32-macho triples. This (accidentally?) produced windows relocations
736  // without GOT tables in older clang versions; Keep this behaviour.
737  // FIXME: even thread local variables?
738  if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
739  return true;
740 
741  // Only handle COFF and ELF for now.
742  if (!TT.isOSBinFormatELF())
743  return false;
744 
745  // If this is not an executable, don't assume anything is local.
746  const auto &CGOpts = CGM.getCodeGenOpts();
747  llvm::Reloc::Model RM = CGOpts.RelocationModel;
748  const auto &LOpts = CGM.getLangOpts();
749  if (RM != llvm::Reloc::Static && !LOpts.PIE)
750  return false;
751 
752  // A definition cannot be preempted from an executable.
753  if (!GV->isDeclarationForLinker())
754  return true;
755 
756  // Most PIC code sequences that assume that a symbol is local cannot produce a
757  // 0 if it turns out the symbol is undefined. While this is ABI and relocation
758  // depended, it seems worth it to handle it here.
759  if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
760  return false;
761 
762  // PPC has no copy relocations and cannot use a plt entry as a symbol address.
763  llvm::Triple::ArchType Arch = TT.getArch();
764  if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
765  Arch == llvm::Triple::ppc64le)
766  return false;
767 
768  // If we can use copy relocations we can assume it is local.
769  if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
770  if (!Var->isThreadLocal() &&
771  (RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations))
772  return true;
773 
774  // If we can use a plt entry as the symbol address we can assume it
775  // is local.
776  // FIXME: This should work for PIE, but the gold linker doesn't support it.
777  if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
778  return true;
779 
780  // Otherwise don't assue it is local.
781  return false;
782 }
783 
784 void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
785  GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
786 }
787 
788 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
789  GlobalDecl GD) const {
790  const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
791  // C++ destructors have a few C++ ABI specific special cases.
792  if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
794  return;
795  }
796  setDLLImportDLLExport(GV, D);
797 }
798 
799 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
800  const NamedDecl *D) const {
801  if (D && D->isExternallyVisible()) {
802  if (D->hasAttr<DLLImportAttr>())
803  GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
804  else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
805  GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
806  }
807 }
808 
809 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
810  GlobalDecl GD) const {
811  setDLLImportDLLExport(GV, GD);
812  setGlobalVisibilityAndLocal(GV, dyn_cast<NamedDecl>(GD.getDecl()));
813 }
814 
815 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
816  const NamedDecl *D) const {
817  setDLLImportDLLExport(GV, D);
819 }
820 
822  const NamedDecl *D) const {
823  setGlobalVisibility(GV, D);
824  setDSOLocal(GV);
825 }
826 
827 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
828  return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
829  .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
830  .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
831  .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
832  .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
833 }
834 
835 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
837  switch (M) {
839  return llvm::GlobalVariable::GeneralDynamicTLSModel;
841  return llvm::GlobalVariable::LocalDynamicTLSModel;
843  return llvm::GlobalVariable::InitialExecTLSModel;
845  return llvm::GlobalVariable::LocalExecTLSModel;
846  }
847  llvm_unreachable("Invalid TLS model!");
848 }
849 
850 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
851  assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
852 
853  llvm::GlobalValue::ThreadLocalMode TLM;
854  TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
855 
856  // Override the TLS model if it is explicitly specified.
857  if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
858  TLM = GetLLVMTLSModel(Attr->getModel());
859  }
860 
861  GV->setThreadLocalMode(TLM);
862 }
863 
864 static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
865  StringRef Name) {
866  const TargetInfo &Target = CGM.getTarget();
867  return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
868 }
869 
871  const CPUSpecificAttr *Attr,
872  raw_ostream &Out) {
873  // cpu_specific gets the current name, dispatch gets the resolver.
874  if (Attr)
875  Out << getCPUSpecificMangling(CGM, Attr->getCurCPUName()->getName());
876  else
877  Out << ".resolver";
878 }
879 
880 static void AppendTargetMangling(const CodeGenModule &CGM,
881  const TargetAttr *Attr, raw_ostream &Out) {
882  if (Attr->isDefaultVersion())
883  return;
884 
885  Out << '.';
886  const TargetInfo &Target = CGM.getTarget();
887  TargetAttr::ParsedTargetAttr Info =
888  Attr->parse([&Target](StringRef LHS, StringRef RHS) {
889  // Multiversioning doesn't allow "no-${feature}", so we can
890  // only have "+" prefixes here.
891  assert(LHS.startswith("+") && RHS.startswith("+") &&
892  "Features should always have a prefix.");
893  return Target.multiVersionSortPriority(LHS.substr(1)) >
894  Target.multiVersionSortPriority(RHS.substr(1));
895  });
896 
897  bool IsFirst = true;
898 
899  if (!Info.Architecture.empty()) {
900  IsFirst = false;
901  Out << "arch_" << Info.Architecture;
902  }
903 
904  for (StringRef Feat : Info.Features) {
905  if (!IsFirst)
906  Out << '_';
907  IsFirst = false;
908  Out << Feat.substr(1);
909  }
910 }
911 
912 static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD,
913  const NamedDecl *ND,
914  bool OmitMultiVersionMangling = false) {
915  SmallString<256> Buffer;
916  llvm::raw_svector_ostream Out(Buffer);
918  if (MC.shouldMangleDeclName(ND)) {
919  llvm::raw_svector_ostream Out(Buffer);
920  if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
921  MC.mangleCXXCtor(D, GD.getCtorType(), Out);
922  else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
923  MC.mangleCXXDtor(D, GD.getDtorType(), Out);
924  else
925  MC.mangleName(ND, Out);
926  } else {
927  IdentifierInfo *II = ND->getIdentifier();
928  assert(II && "Attempt to mangle unnamed decl.");
929  const auto *FD = dyn_cast<FunctionDecl>(ND);
930 
931  if (FD &&
932  FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
933  llvm::raw_svector_ostream Out(Buffer);
934  Out << "__regcall3__" << II->getName();
935  } else {
936  Out << II->getName();
937  }
938  }
939 
940  if (const auto *FD = dyn_cast<FunctionDecl>(ND))
941  if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
942  if (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion())
944  CGM, FD->getAttr<CPUSpecificAttr>(), Out);
945  else
946  AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
947  }
948 
949  return Out.str();
950 }
951 
952 void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
953  const FunctionDecl *FD) {
954  if (!FD->isMultiVersion())
955  return;
956 
957  // Get the name of what this would be without the 'target' attribute. This
958  // allows us to lookup the version that was emitted when this wasn't a
959  // multiversion function.
960  std::string NonTargetName =
961  getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
962  GlobalDecl OtherGD;
963  if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
964  assert(OtherGD.getCanonicalDecl()
965  .getDecl()
966  ->getAsFunction()
967  ->isMultiVersion() &&
968  "Other GD should now be a multiversioned function");
969  // OtherFD is the version of this function that was mangled BEFORE
970  // becoming a MultiVersion function. It potentially needs to be updated.
971  const FunctionDecl *OtherFD =
972  OtherGD.getCanonicalDecl().getDecl()->getAsFunction();
973  std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
974  // This is so that if the initial version was already the 'default'
975  // version, we don't try to update it.
976  if (OtherName != NonTargetName) {
977  // Remove instead of erase, since others may have stored the StringRef
978  // to this.
979  const auto ExistingRecord = Manglings.find(NonTargetName);
980  if (ExistingRecord != std::end(Manglings))
981  Manglings.remove(&(*ExistingRecord));
982  auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
983  MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
984  if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
985  Entry->setName(OtherName);
986  }
987  }
988 }
989 
991  GlobalDecl CanonicalGD = GD.getCanonicalDecl();
992 
993  // Some ABIs don't have constructor variants. Make sure that base and
994  // complete constructors get mangled the same.
995  if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
997  CXXCtorType OrigCtorType = GD.getCtorType();
998  assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
999  if (OrigCtorType == Ctor_Base)
1000  CanonicalGD = GlobalDecl(CD, Ctor_Complete);
1001  }
1002  }
1003 
1004  const auto *FD = dyn_cast<FunctionDecl>(GD.getDecl());
1005  // Since CPUSpecific can require multiple emits per decl, store the manglings
1006  // separately.
1007  if (FD &&
1009  const auto *SD = FD->getAttr<CPUSpecificAttr>();
1010 
1011  std::pair<GlobalDecl, unsigned> SpecCanonicalGD{
1012  CanonicalGD,
1013  SD ? SD->ActiveArgIndex : std::numeric_limits<unsigned>::max()};
1014 
1015  auto FoundName = CPUSpecificMangledDeclNames.find(SpecCanonicalGD);
1016  if (FoundName != CPUSpecificMangledDeclNames.end())
1017  return FoundName->second;
1018 
1019  auto Result = CPUSpecificManglings.insert(
1020  std::make_pair(getMangledNameImpl(*this, GD, FD), SpecCanonicalGD));
1021  return CPUSpecificMangledDeclNames[SpecCanonicalGD] = Result.first->first();
1022  }
1023 
1024  auto FoundName = MangledDeclNames.find(CanonicalGD);
1025  if (FoundName != MangledDeclNames.end())
1026  return FoundName->second;
1027 
1028  // Keep the first result in the case of a mangling collision.
1029  const auto *ND = cast<NamedDecl>(GD.getDecl());
1030  auto Result =
1031  Manglings.insert(std::make_pair(getMangledNameImpl(*this, GD, ND), GD));
1032  return MangledDeclNames[CanonicalGD] = Result.first->first();
1033 }
1034 
1036  const BlockDecl *BD) {
1037  MangleContext &MangleCtx = getCXXABI().getMangleContext();
1038  const Decl *D = GD.getDecl();
1039 
1040  SmallString<256> Buffer;
1041  llvm::raw_svector_ostream Out(Buffer);
1042  if (!D)
1043  MangleCtx.mangleGlobalBlock(BD,
1044  dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
1045  else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
1046  MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
1047  else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
1048  MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
1049  else
1050  MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
1051 
1052  auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
1053  return Result.first->first();
1054 }
1055 
1056 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
1057  return getModule().getNamedValue(Name);
1058 }
1059 
1060 /// AddGlobalCtor - Add a function to the list that will be called before
1061 /// main() runs.
1062 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
1063  llvm::Constant *AssociatedData) {
1064  // FIXME: Type coercion of void()* types.
1065  GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
1066 }
1067 
1068 /// AddGlobalDtor - Add a function to the list that will be called
1069 /// when the module is unloaded.
1070 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
1071  if (CodeGenOpts.RegisterGlobalDtorsWithAtExit) {
1072  DtorsUsingAtExit[Priority].push_back(Dtor);
1073  return;
1074  }
1075 
1076  // FIXME: Type coercion of void()* types.
1077  GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
1078 }
1079 
1080 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
1081  if (Fns.empty()) return;
1082 
1083  // Ctor function type is void()*.
1084  llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
1085  llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
1086 
1087  // Get the type of a ctor entry, { i32, void ()*, i8* }.
1088  llvm::StructType *CtorStructTy = llvm::StructType::get(
1089  Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy);
1090 
1091  // Construct the constructor and destructor arrays.
1092  ConstantInitBuilder builder(*this);
1093  auto ctors = builder.beginArray(CtorStructTy);
1094  for (const auto &I : Fns) {
1095  auto ctor = ctors.beginStruct(CtorStructTy);
1096  ctor.addInt(Int32Ty, I.Priority);
1097  ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
1098  if (I.AssociatedData)
1099  ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
1100  else
1101  ctor.addNullPointer(VoidPtrTy);
1102  ctor.finishAndAddTo(ctors);
1103  }
1104 
1105  auto list =
1106  ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
1107  /*constant*/ false,
1108  llvm::GlobalValue::AppendingLinkage);
1109 
1110  // The LTO linker doesn't seem to like it when we set an alignment
1111  // on appending variables. Take it off as a workaround.
1112  list->setAlignment(0);
1113 
1114  Fns.clear();
1115 }
1116 
1117 llvm::GlobalValue::LinkageTypes
1119  const auto *D = cast<FunctionDecl>(GD.getDecl());
1120 
1122 
1123  if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
1124  return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
1125 
1126  if (isa<CXXConstructorDecl>(D) &&
1127  cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
1128  Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1129  // Our approach to inheriting constructors is fundamentally different from
1130  // that used by the MS ABI, so keep our inheriting constructor thunks
1131  // internal rather than trying to pick an unambiguous mangling for them.
1133  }
1134 
1135  return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
1136 }
1137 
1138 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
1139  llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
1140  if (!MDS) return nullptr;
1141 
1142  return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
1143 }
1144 
1146  const CGFunctionInfo &Info,
1147  llvm::Function *F) {
1148  unsigned CallingConv;
1149  llvm::AttributeList PAL;
1150  ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false);
1151  F->setAttributes(PAL);
1152  F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
1153 }
1154 
1155 /// Determines whether the language options require us to model
1156 /// unwind exceptions. We treat -fexceptions as mandating this
1157 /// except under the fragile ObjC ABI with only ObjC exceptions
1158 /// enabled. This means, for example, that C with -fexceptions
1159 /// enables this.
1160 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
1161  // If exceptions are completely disabled, obviously this is false.
1162  if (!LangOpts.Exceptions) return false;
1163 
1164  // If C++ exceptions are enabled, this is true.
1165  if (LangOpts.CXXExceptions) return true;
1166 
1167  // If ObjC exceptions are enabled, this depends on the ABI.
1168  if (LangOpts.ObjCExceptions) {
1169  return LangOpts.ObjCRuntime.hasUnwindExceptions();
1170  }
1171 
1172  return true;
1173 }
1174 
1176  const CXXMethodDecl *MD) {
1177  // Check that the type metadata can ever actually be used by a call.
1178  if (!CGM.getCodeGenOpts().LTOUnit ||
1179  !CGM.HasHiddenLTOVisibility(MD->getParent()))
1180  return false;
1181 
1182  // Only functions whose address can be taken with a member function pointer
1183  // need this sort of type metadata.
1184  return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
1185  !isa<CXXDestructorDecl>(MD);
1186 }
1187 
1188 std::vector<const CXXRecordDecl *>
1190  llvm::SetVector<const CXXRecordDecl *> MostBases;
1191 
1192  std::function<void (const CXXRecordDecl *)> CollectMostBases;
1193  CollectMostBases = [&](const CXXRecordDecl *RD) {
1194  if (RD->getNumBases() == 0)
1195  MostBases.insert(RD);
1196  for (const CXXBaseSpecifier &B : RD->bases())
1197  CollectMostBases(B.getType()->getAsCXXRecordDecl());
1198  };
1199  CollectMostBases(RD);
1200  return MostBases.takeVector();
1201 }
1202 
1204  llvm::Function *F) {
1205  llvm::AttrBuilder B;
1206 
1207  if (CodeGenOpts.UnwindTables)
1208  B.addAttribute(llvm::Attribute::UWTable);
1209 
1210  if (!hasUnwindExceptions(LangOpts))
1211  B.addAttribute(llvm::Attribute::NoUnwind);
1212 
1213  if (!D || !D->hasAttr<NoStackProtectorAttr>()) {
1214  if (LangOpts.getStackProtector() == LangOptions::SSPOn)
1215  B.addAttribute(llvm::Attribute::StackProtect);
1216  else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
1217  B.addAttribute(llvm::Attribute::StackProtectStrong);
1218  else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
1219  B.addAttribute(llvm::Attribute::StackProtectReq);
1220  }
1221 
1222  if (!D) {
1223  // If we don't have a declaration to control inlining, the function isn't
1224  // explicitly marked as alwaysinline for semantic reasons, and inlining is
1225  // disabled, mark the function as noinline.
1226  if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1227  CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
1228  B.addAttribute(llvm::Attribute::NoInline);
1229 
1230  F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1231  return;
1232  }
1233 
1234  // Track whether we need to add the optnone LLVM attribute,
1235  // starting with the default for this optimization level.
1236  bool ShouldAddOptNone =
1237  !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
1238  // We can't add optnone in the following cases, it won't pass the verifier.
1239  ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
1240  ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
1241  ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
1242 
1243  if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
1244  B.addAttribute(llvm::Attribute::OptimizeNone);
1245 
1246  // OptimizeNone implies noinline; we should not be inlining such functions.
1247  B.addAttribute(llvm::Attribute::NoInline);
1248  assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1249  "OptimizeNone and AlwaysInline on same function!");
1250 
1251  // We still need to handle naked functions even though optnone subsumes
1252  // much of their semantics.
1253  if (D->hasAttr<NakedAttr>())
1254  B.addAttribute(llvm::Attribute::Naked);
1255 
1256  // OptimizeNone wins over OptimizeForSize and MinSize.
1257  F->removeFnAttr(llvm::Attribute::OptimizeForSize);
1258  F->removeFnAttr(llvm::Attribute::MinSize);
1259  } else if (D->hasAttr<NakedAttr>()) {
1260  // Naked implies noinline: we should not be inlining such functions.
1261  B.addAttribute(llvm::Attribute::Naked);
1262  B.addAttribute(llvm::Attribute::NoInline);
1263  } else if (D->hasAttr<NoDuplicateAttr>()) {
1264  B.addAttribute(llvm::Attribute::NoDuplicate);
1265  } else if (D->hasAttr<NoInlineAttr>()) {
1266  B.addAttribute(llvm::Attribute::NoInline);
1267  } else if (D->hasAttr<AlwaysInlineAttr>() &&
1268  !F->hasFnAttribute(llvm::Attribute::NoInline)) {
1269  // (noinline wins over always_inline, and we can't specify both in IR)
1270  B.addAttribute(llvm::Attribute::AlwaysInline);
1271  } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
1272  // If we're not inlining, then force everything that isn't always_inline to
1273  // carry an explicit noinline attribute.
1274  if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
1275  B.addAttribute(llvm::Attribute::NoInline);
1276  } else {
1277  // Otherwise, propagate the inline hint attribute and potentially use its
1278  // absence to mark things as noinline.
1279  if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1280  if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
1281  return Redecl->isInlineSpecified();
1282  })) {
1283  B.addAttribute(llvm::Attribute::InlineHint);
1284  } else if (CodeGenOpts.getInlining() ==
1286  !FD->isInlined() &&
1287  !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1288  B.addAttribute(llvm::Attribute::NoInline);
1289  }
1290  }
1291  }
1292 
1293  // Add other optimization related attributes if we are optimizing this
1294  // function.
1295  if (!D->hasAttr<OptimizeNoneAttr>()) {
1296  if (D->hasAttr<ColdAttr>()) {
1297  if (!ShouldAddOptNone)
1298  B.addAttribute(llvm::Attribute::OptimizeForSize);
1299  B.addAttribute(llvm::Attribute::Cold);
1300  }
1301 
1302  if (D->hasAttr<MinSizeAttr>())
1303  B.addAttribute(llvm::Attribute::MinSize);
1304  }
1305 
1306  F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1307 
1308  unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
1309  if (alignment)
1310  F->setAlignment(alignment);
1311 
1312  if (!D->hasAttr<AlignedAttr>())
1313  if (LangOpts.FunctionAlignment)
1314  F->setAlignment(1 << LangOpts.FunctionAlignment);
1315 
1316  // Some C++ ABIs require 2-byte alignment for member functions, in order to
1317  // reserve a bit for differentiating between virtual and non-virtual member
1318  // functions. If the current target's C++ ABI requires this and this is a
1319  // member function, set its alignment accordingly.
1320  if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
1321  if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1322  F->setAlignment(2);
1323  }
1324 
1325  // In the cross-dso CFI mode, we want !type attributes on definitions only.
1326  if (CodeGenOpts.SanitizeCfiCrossDso)
1327  if (auto *FD = dyn_cast<FunctionDecl>(D))
1329 
1330  // Emit type metadata on member functions for member function pointer checks.
1331  // These are only ever necessary on definitions; we're guaranteed that the
1332  // definition will be present in the LTO unit as a result of LTO visibility.
1333  auto *MD = dyn_cast<CXXMethodDecl>(D);
1334  if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
1335  for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
1336  llvm::Metadata *Id =
1338  MD->getType(), Context.getRecordType(Base).getTypePtr()));
1339  F->addTypeMetadata(0, Id);
1340  }
1341  }
1342 }
1343 
1344 void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
1345  const Decl *D = GD.getDecl();
1346  if (dyn_cast_or_null<NamedDecl>(D))
1347  setGVProperties(GV, GD);
1348  else
1349  GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1350 
1351  if (D && D->hasAttr<UsedAttr>())
1352  addUsedGlobal(GV);
1353 }
1354 
1355 bool CodeGenModule::GetCPUAndFeaturesAttributes(const Decl *D,
1356  llvm::AttrBuilder &Attrs) {
1357  // Add target-cpu and target-features attributes to functions. If
1358  // we have a decl for the function and it has a target attribute then
1359  // parse that and add it to the feature set.
1360  StringRef TargetCPU = getTarget().getTargetOpts().CPU;
1361  std::vector<std::string> Features;
1362  const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
1363  FD = FD ? FD->getMostRecentDecl() : FD;
1364  const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
1365  const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
1366  bool AddedAttr = false;
1367  if (TD || SD) {
1368  llvm::StringMap<bool> FeatureMap;
1369  getFunctionFeatureMap(FeatureMap, FD);
1370 
1371  // Produce the canonical string for this set of features.
1372  for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
1373  Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
1374 
1375  // Now add the target-cpu and target-features to the function.
1376  // While we populated the feature map above, we still need to
1377  // get and parse the target attribute so we can get the cpu for
1378  // the function.
1379  if (TD) {
1380  TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
1381  if (ParsedAttr.Architecture != "" &&
1382  getTarget().isValidCPUName(ParsedAttr.Architecture))
1383  TargetCPU = ParsedAttr.Architecture;
1384  }
1385  } else {
1386  // Otherwise just add the existing target cpu and target features to the
1387  // function.
1388  Features = getTarget().getTargetOpts().Features;
1389  }
1390 
1391  if (TargetCPU != "") {
1392  Attrs.addAttribute("target-cpu", TargetCPU);
1393  AddedAttr = true;
1394  }
1395  if (!Features.empty()) {
1396  llvm::sort(Features.begin(), Features.end());
1397  Attrs.addAttribute("target-features", llvm::join(Features, ","));
1398  AddedAttr = true;
1399  }
1400 
1401  return AddedAttr;
1402 }
1403 
1404 void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
1405  llvm::GlobalObject *GO) {
1406  const Decl *D = GD.getDecl();
1407  SetCommonAttributes(GD, GO);
1408 
1409  if (D) {
1410  if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
1411  if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
1412  GV->addAttribute("bss-section", SA->getName());
1413  if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
1414  GV->addAttribute("data-section", SA->getName());
1415  if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
1416  GV->addAttribute("rodata-section", SA->getName());
1417  }
1418 
1419  if (auto *F = dyn_cast<llvm::Function>(GO)) {
1420  if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
1421  if (!D->getAttr<SectionAttr>())
1422  F->addFnAttr("implicit-section-name", SA->getName());
1423 
1424  llvm::AttrBuilder Attrs;
1425  if (GetCPUAndFeaturesAttributes(D, Attrs)) {
1426  // We know that GetCPUAndFeaturesAttributes will always have the
1427  // newest set, since it has the newest possible FunctionDecl, so the
1428  // new ones should replace the old.
1429  F->removeFnAttr("target-cpu");
1430  F->removeFnAttr("target-features");
1431  F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
1432  }
1433  }
1434 
1435  if (const auto *CSA = D->getAttr<CodeSegAttr>())
1436  GO->setSection(CSA->getName());
1437  else if (const auto *SA = D->getAttr<SectionAttr>())
1438  GO->setSection(SA->getName());
1439  }
1440 
1441  getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
1442 }
1443 
1445  llvm::Function *F,
1446  const CGFunctionInfo &FI) {
1447  const Decl *D = GD.getDecl();
1448  SetLLVMFunctionAttributes(D, FI, F);
1450 
1451  F->setLinkage(llvm::Function::InternalLinkage);
1452 
1453  setNonAliasAttributes(GD, F);
1454 }
1455 
1456 static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
1457  // Set linkage and visibility in case we never see a definition.
1459  // Don't set internal linkage on declarations.
1460  // "extern_weak" is overloaded in LLVM; we probably should have
1461  // separate linkage types for this.
1462  if (isExternallyVisible(LV.getLinkage()) &&
1463  (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
1464  GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1465 }
1466 
1468  llvm::Function *F) {
1469  // Only if we are checking indirect calls.
1470  if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
1471  return;
1472 
1473  // Non-static class methods are handled via vtable or member function pointer
1474  // checks elsewhere.
1475  if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1476  return;
1477 
1478  // Additionally, if building with cross-DSO support...
1479  if (CodeGenOpts.SanitizeCfiCrossDso) {
1480  // Skip available_externally functions. They won't be codegen'ed in the
1481  // current module anyway.
1483  return;
1484  }
1485 
1486  llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
1487  F->addTypeMetadata(0, MD);
1488  F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
1489 
1490  // Emit a hash-based bit set entry for cross-DSO calls.
1491  if (CodeGenOpts.SanitizeCfiCrossDso)
1492  if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1493  F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
1494 }
1495 
1496 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1497  bool IsIncompleteFunction,
1498  bool IsThunk) {
1499 
1500  if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
1501  // If this is an intrinsic function, set the function's attributes
1502  // to the intrinsic's attributes.
1503  F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
1504  return;
1505  }
1506 
1507  const auto *FD = cast<FunctionDecl>(GD.getDecl());
1508 
1509  if (!IsIncompleteFunction) {
1510  SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
1511  // Setup target-specific attributes.
1512  if (F->isDeclaration())
1513  getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
1514  }
1515 
1516  // Add the Returned attribute for "this", except for iOS 5 and earlier
1517  // where substantial code, including the libstdc++ dylib, was compiled with
1518  // GCC and does not actually return "this".
1519  if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
1520  !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
1521  assert(!F->arg_empty() &&
1522  F->arg_begin()->getType()
1523  ->canLosslesslyBitCastTo(F->getReturnType()) &&
1524  "unexpected this return");
1525  F->addAttribute(1, llvm::Attribute::Returned);
1526  }
1527 
1528  // Only a few attributes are set on declarations; these may later be
1529  // overridden by a definition.
1530 
1531  setLinkageForGV(F, FD);
1532  setGVProperties(F, FD);
1533 
1534  if (const auto *CSA = FD->getAttr<CodeSegAttr>())
1535  F->setSection(CSA->getName());
1536  else if (const auto *SA = FD->getAttr<SectionAttr>())
1537  F->setSection(SA->getName());
1538 
1540  // A replaceable global allocation function does not act like a builtin by
1541  // default, only if it is invoked by a new-expression or delete-expression.
1542  F->addAttribute(llvm::AttributeList::FunctionIndex,
1543  llvm::Attribute::NoBuiltin);
1544 
1545  // A sane operator new returns a non-aliasing pointer.
1546  // FIXME: Also add NonNull attribute to the return value
1547  // for the non-nothrow forms?
1548  auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1549  if (getCodeGenOpts().AssumeSaneOperatorNew &&
1550  (Kind == OO_New || Kind == OO_Array_New))
1551  F->addAttribute(llvm::AttributeList::ReturnIndex,
1552  llvm::Attribute::NoAlias);
1553  }
1554 
1555  if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1556  F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1557  else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1558  if (MD->isVirtual())
1559  F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1560 
1561  // Don't emit entries for function declarations in the cross-DSO mode. This
1562  // is handled with better precision by the receiving DSO.
1563  if (!CodeGenOpts.SanitizeCfiCrossDso)
1565 
1566  if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
1567  getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
1568 }
1569 
1570 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
1571  assert(!GV->isDeclaration() &&
1572  "Only globals with definition can force usage.");
1573  LLVMUsed.emplace_back(GV);
1574 }
1575 
1576 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
1577  assert(!GV->isDeclaration() &&
1578  "Only globals with definition can force usage.");
1579  LLVMCompilerUsed.emplace_back(GV);
1580 }
1581 
1582 static void emitUsed(CodeGenModule &CGM, StringRef Name,
1583  std::vector<llvm::WeakTrackingVH> &List) {
1584  // Don't create llvm.used if there is no need.
1585  if (List.empty())
1586  return;
1587 
1588  // Convert List to what ConstantArray needs.
1590  UsedArray.resize(List.size());
1591  for (unsigned i = 0, e = List.size(); i != e; ++i) {
1592  UsedArray[i] =
1593  llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1594  cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
1595  }
1596 
1597  if (UsedArray.empty())
1598  return;
1599  llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
1600 
1601  auto *GV = new llvm::GlobalVariable(
1602  CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
1603  llvm::ConstantArray::get(ATy, UsedArray), Name);
1604 
1605  GV->setSection("llvm.metadata");
1606 }
1607 
1608 void CodeGenModule::emitLLVMUsed() {
1609  emitUsed(*this, "llvm.used", LLVMUsed);
1610  emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
1611 }
1612 
1614  auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
1615  LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1616 }
1617 
1618 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1620  getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
1621  auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1622  LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1623 }
1624 
1626  auto &C = getLLVMContext();
1627  LinkerOptionsMetadata.push_back(llvm::MDNode::get(
1628  C, {llvm::MDString::get(C, "lib"), llvm::MDString::get(C, Lib)}));
1629 }
1630 
1631 void CodeGenModule::AddDependentLib(StringRef Lib) {
1634  auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1635  LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1636 }
1637 
1638 /// Add link options implied by the given module, including modules
1639 /// it depends on, using a postorder walk.
1642  llvm::SmallPtrSet<Module *, 16> &Visited) {
1643  // Import this module's parent.
1644  if (Mod->Parent && Visited.insert(Mod->Parent).second) {
1645  addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
1646  }
1647 
1648  // Import this module's dependencies.
1649  for (unsigned I = Mod->Imports.size(); I > 0; --I) {
1650  if (Visited.insert(Mod->Imports[I - 1]).second)
1651  addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
1652  }
1653 
1654  // Add linker options to link against the libraries/frameworks
1655  // described by this module.
1656  llvm::LLVMContext &Context = CGM.getLLVMContext();
1657 
1658  // For modules that use export_as for linking, use that module
1659  // name instead.
1660  if (Mod->UseExportAsModuleLinkName)
1661  return;
1662 
1663  for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
1664  // Link against a framework. Frameworks are currently Darwin only, so we
1665  // don't to ask TargetCodeGenInfo for the spelling of the linker option.
1666  if (Mod->LinkLibraries[I-1].IsFramework) {
1667  llvm::Metadata *Args[2] = {
1668  llvm::MDString::get(Context, "-framework"),
1669  llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1670 
1671  Metadata.push_back(llvm::MDNode::get(Context, Args));
1672  continue;
1673  }
1674 
1675  // Link against a library.
1678  Mod->LinkLibraries[I-1].Library, Opt);
1679  auto *OptString = llvm::MDString::get(Context, Opt);
1680  Metadata.push_back(llvm::MDNode::get(Context, OptString));
1681  }
1682 }
1683 
1684 void CodeGenModule::EmitModuleLinkOptions() {
1685  // Collect the set of all of the modules we want to visit to emit link
1686  // options, which is essentially the imported modules and all of their
1687  // non-explicit child modules.
1688  llvm::SetVector<clang::Module *> LinkModules;
1689  llvm::SmallPtrSet<clang::Module *, 16> Visited;
1691 
1692  // Seed the stack with imported modules.
1693  for (Module *M : ImportedModules) {
1694  // Do not add any link flags when an implementation TU of a module imports
1695  // a header of that same module.
1696  if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
1698  continue;
1699  if (Visited.insert(M).second)
1700  Stack.push_back(M);
1701  }
1702 
1703  // Find all of the modules to import, making a little effort to prune
1704  // non-leaf modules.
1705  while (!Stack.empty()) {
1706  clang::Module *Mod = Stack.pop_back_val();
1707 
1708  bool AnyChildren = false;
1709 
1710  // Visit the submodules of this module.
1712  SubEnd = Mod->submodule_end();
1713  Sub != SubEnd; ++Sub) {
1714  // Skip explicit children; they need to be explicitly imported to be
1715  // linked against.
1716  if ((*Sub)->IsExplicit)
1717  continue;
1718 
1719  if (Visited.insert(*Sub).second) {
1720  Stack.push_back(*Sub);
1721  AnyChildren = true;
1722  }
1723  }
1724 
1725  // We didn't find any children, so add this module to the list of
1726  // modules to link against.
1727  if (!AnyChildren) {
1728  LinkModules.insert(Mod);
1729  }
1730  }
1731 
1732  // Add link options for all of the imported modules in reverse topological
1733  // order. We don't do anything to try to order import link flags with respect
1734  // to linker options inserted by things like #pragma comment().
1735  SmallVector<llvm::MDNode *, 16> MetadataArgs;
1736  Visited.clear();
1737  for (Module *M : LinkModules)
1738  if (Visited.insert(M).second)
1739  addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
1740  std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1741  LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1742 
1743  // Add the linker options metadata flag.
1744  auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
1745  for (auto *MD : LinkerOptionsMetadata)
1746  NMD->addOperand(MD);
1747 }
1748 
1749 void CodeGenModule::EmitDeferred() {
1750  // Emit code for any potentially referenced deferred decls. Since a
1751  // previously unused static decl may become used during the generation of code
1752  // for a static function, iterate until no changes are made.
1753 
1754  if (!DeferredVTables.empty()) {
1755  EmitDeferredVTables();
1756 
1757  // Emitting a vtable doesn't directly cause more vtables to
1758  // become deferred, although it can cause functions to be
1759  // emitted that then need those vtables.
1760  assert(DeferredVTables.empty());
1761  }
1762 
1763  // Stop if we're out of both deferred vtables and deferred declarations.
1764  if (DeferredDeclsToEmit.empty())
1765  return;
1766 
1767  // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
1768  // work, it will not interfere with this.
1769  std::vector<GlobalDecl> CurDeclsToEmit;
1770  CurDeclsToEmit.swap(DeferredDeclsToEmit);
1771 
1772  for (GlobalDecl &D : CurDeclsToEmit) {
1773  // We should call GetAddrOfGlobal with IsForDefinition set to true in order
1774  // to get GlobalValue with exactly the type we need, not something that
1775  // might had been created for another decl with the same mangled name but
1776  // different type.
1777  llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
1779 
1780  // In case of different address spaces, we may still get a cast, even with
1781  // IsForDefinition equal to true. Query mangled names table to get
1782  // GlobalValue.
1783  if (!GV)
1784  GV = GetGlobalValue(getMangledName(D));
1785 
1786  // Make sure GetGlobalValue returned non-null.
1787  assert(GV);
1788 
1789  // Check to see if we've already emitted this. This is necessary
1790  // for a couple of reasons: first, decls can end up in the
1791  // deferred-decls queue multiple times, and second, decls can end
1792  // up with definitions in unusual ways (e.g. by an extern inline
1793  // function acquiring a strong function redefinition). Just
1794  // ignore these cases.
1795  if (!GV->isDeclaration())
1796  continue;
1797 
1798  // Otherwise, emit the definition and move on to the next one.
1799  EmitGlobalDefinition(D, GV);
1800 
1801  // If we found out that we need to emit more decls, do that recursively.
1802  // This has the advantage that the decls are emitted in a DFS and related
1803  // ones are close together, which is convenient for testing.
1804  if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1805  EmitDeferred();
1806  assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1807  }
1808  }
1809 }
1810 
1811 void CodeGenModule::EmitVTablesOpportunistically() {
1812  // Try to emit external vtables as available_externally if they have emitted
1813  // all inlined virtual functions. It runs after EmitDeferred() and therefore
1814  // is not allowed to create new references to things that need to be emitted
1815  // lazily. Note that it also uses fact that we eagerly emitting RTTI.
1816 
1817  assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
1818  && "Only emit opportunistic vtables with optimizations");
1819 
1820  for (const CXXRecordDecl *RD : OpportunisticVTables) {
1821  assert(getVTables().isVTableExternal(RD) &&
1822  "This queue should only contain external vtables");
1823  if (getCXXABI().canSpeculativelyEmitVTable(RD))
1824  VTables.GenerateClassData(RD);
1825  }
1826  OpportunisticVTables.clear();
1827 }
1828 
1830  if (Annotations.empty())
1831  return;
1832 
1833  // Create a new global variable for the ConstantStruct in the Module.
1834  llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1835  Annotations[0]->getType(), Annotations.size()), Annotations);
1836  auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1837  llvm::GlobalValue::AppendingLinkage,
1838  Array, "llvm.global.annotations");
1839  gv->setSection(AnnotationSection);
1840 }
1841 
1842 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1843  llvm::Constant *&AStr = AnnotationStrings[Str];
1844  if (AStr)
1845  return AStr;
1846 
1847  // Not found yet, create a new global.
1848  llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
1849  auto *gv =
1850  new llvm::GlobalVariable(getModule(), s->getType(), true,
1851  llvm::GlobalValue::PrivateLinkage, s, ".str");
1852  gv->setSection(AnnotationSection);
1853  gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1854  AStr = gv;
1855  return gv;
1856 }
1857 
1860  PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1861  if (PLoc.isValid())
1862  return EmitAnnotationString(PLoc.getFilename());
1863  return EmitAnnotationString(SM.getBufferName(Loc));
1864 }
1865 
1868  PresumedLoc PLoc = SM.getPresumedLoc(L);
1869  unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1870  SM.getExpansionLineNumber(L);
1871  return llvm::ConstantInt::get(Int32Ty, LineNo);
1872 }
1873 
1874 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1875  const AnnotateAttr *AA,
1876  SourceLocation L) {
1877  // Get the globals for file name, annotation, and the line number.
1878  llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1879  *UnitGV = EmitAnnotationUnit(L),
1880  *LineNoCst = EmitAnnotationLineNo(L);
1881 
1882  // Create the ConstantStruct for the global annotation.
1883  llvm::Constant *Fields[4] = {
1884  llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1885  llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1886  llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1887  LineNoCst
1888  };
1889  return llvm::ConstantStruct::getAnon(Fields);
1890 }
1891 
1893  llvm::GlobalValue *GV) {
1894  assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1895  // Get the struct elements for these annotations.
1896  for (const auto *I : D->specific_attrs<AnnotateAttr>())
1897  Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
1898 }
1899 
1901  llvm::Function *Fn,
1902  SourceLocation Loc) const {
1903  const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1904  // Blacklist by function name.
1905  if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
1906  return true;
1907  // Blacklist by location.
1908  if (Loc.isValid())
1909  return SanitizerBL.isBlacklistedLocation(Kind, Loc);
1910  // If location is unknown, this may be a compiler-generated function. Assume
1911  // it's located in the main file.
1912  auto &SM = Context.getSourceManager();
1913  if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1914  return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
1915  }
1916  return false;
1917 }
1918 
1919 bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1920  SourceLocation Loc, QualType Ty,
1921  StringRef Category) const {
1922  // For now globals can be blacklisted only in ASan and KASan.
1923  const SanitizerMask EnabledAsanMask = LangOpts.Sanitize.Mask &
1924  (SanitizerKind::Address | SanitizerKind::KernelAddress |
1925  SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress);
1926  if (!EnabledAsanMask)
1927  return false;
1928  const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1929  if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
1930  return true;
1931  if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
1932  return true;
1933  // Check global type.
1934  if (!Ty.isNull()) {
1935  // Drill down the array types: if global variable of a fixed type is
1936  // blacklisted, we also don't instrument arrays of them.
1937  while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1938  Ty = AT->getElementType();
1940  // We allow to blacklist only record types (classes, structs etc.)
1941  if (Ty->isRecordType()) {
1942  std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
1943  if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
1944  return true;
1945  }
1946  }
1947  return false;
1948 }
1949 
1950 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1951  StringRef Category) const {
1952  if (!LangOpts.XRayInstrument)
1953  return false;
1954 
1955  const auto &XRayFilter = getContext().getXRayFilter();
1956  using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
1957  auto Attr = ImbueAttr::NONE;
1958  if (Loc.isValid())
1959  Attr = XRayFilter.shouldImbueLocation(Loc, Category);
1960  if (Attr == ImbueAttr::NONE)
1961  Attr = XRayFilter.shouldImbueFunction(Fn->getName());
1962  switch (Attr) {
1963  case ImbueAttr::NONE:
1964  return false;
1965  case ImbueAttr::ALWAYS:
1966  Fn->addFnAttr("function-instrument", "xray-always");
1967  break;
1968  case ImbueAttr::ALWAYS_ARG1:
1969  Fn->addFnAttr("function-instrument", "xray-always");
1970  Fn->addFnAttr("xray-log-args", "1");
1971  break;
1972  case ImbueAttr::NEVER:
1973  Fn->addFnAttr("function-instrument", "xray-never");
1974  break;
1975  }
1976  return true;
1977 }
1978 
1979 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
1980  // Never defer when EmitAllDecls is specified.
1981  if (LangOpts.EmitAllDecls)
1982  return true;
1983 
1984  return getContext().DeclMustBeEmitted(Global);
1985 }
1986 
1987 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
1988  if (const auto *FD = dyn_cast<FunctionDecl>(Global))
1990  // Implicit template instantiations may change linkage if they are later
1991  // explicitly instantiated, so they should not be emitted eagerly.
1992  return false;
1993  if (const auto *VD = dyn_cast<VarDecl>(Global))
1994  if (Context.getInlineVariableDefinitionKind(VD) ==
1996  // A definition of an inline constexpr static data member may change
1997  // linkage later if it's redeclared outside the class.
1998  return false;
1999  // If OpenMP is enabled and threadprivates must be generated like TLS, delay
2000  // codegen for global variables, because they may be marked as threadprivate.
2001  if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
2002  getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
2003  !isTypeConstant(Global->getType(), false))
2004  return false;
2005 
2006  return true;
2007 }
2008 
2010  const CXXUuidofExpr* E) {
2011  // Sema has verified that IIDSource has a __declspec(uuid()), and that its
2012  // well-formed.
2013  StringRef Uuid = E->getUuidStr();
2014  std::string Name = "_GUID_" + Uuid.lower();
2015  std::replace(Name.begin(), Name.end(), '-', '_');
2016 
2017  // The UUID descriptor should be pointer aligned.
2019 
2020  // Look for an existing global.
2021  if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
2022  return ConstantAddress(GV, Alignment);
2023 
2024  llvm::Constant *Init = EmitUuidofInitializer(Uuid);
2025  assert(Init && "failed to initialize as constant");
2026 
2027  auto *GV = new llvm::GlobalVariable(
2028  getModule(), Init->getType(),
2029  /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
2030  if (supportsCOMDAT())
2031  GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2032  setDSOLocal(GV);
2033  return ConstantAddress(GV, Alignment);
2034 }
2035 
2037  const AliasAttr *AA = VD->getAttr<AliasAttr>();
2038  assert(AA && "No alias?");
2039 
2040  CharUnits Alignment = getContext().getDeclAlign(VD);
2041  llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
2042 
2043  // See if there is already something with the target's name in the module.
2044  llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
2045  if (Entry) {
2046  unsigned AS = getContext().getTargetAddressSpace(VD->getType());
2047  auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
2048  return ConstantAddress(Ptr, Alignment);
2049  }
2050 
2051  llvm::Constant *Aliasee;
2052  if (isa<llvm::FunctionType>(DeclTy))
2053  Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
2054  GlobalDecl(cast<FunctionDecl>(VD)),
2055  /*ForVTable=*/false);
2056  else
2057  Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2058  llvm::PointerType::getUnqual(DeclTy),
2059  nullptr);
2060 
2061  auto *F = cast<llvm::GlobalValue>(Aliasee);
2062  F->setLinkage(llvm::Function::ExternalWeakLinkage);
2063  WeakRefReferences.insert(F);
2064 
2065  return ConstantAddress(Aliasee, Alignment);
2066 }
2067 
2069  const auto *Global = cast<ValueDecl>(GD.getDecl());
2070 
2071  // Weak references don't produce any output by themselves.
2072  if (Global->hasAttr<WeakRefAttr>())
2073  return;
2074 
2075  // If this is an alias definition (which otherwise looks like a declaration)
2076  // emit it now.
2077  if (Global->hasAttr<AliasAttr>())
2078  return EmitAliasDefinition(GD);
2079 
2080  // IFunc like an alias whose value is resolved at runtime by calling resolver.
2081  if (Global->hasAttr<IFuncAttr>())
2082  return emitIFuncDefinition(GD);
2083 
2084  // If this is a cpu_dispatch multiversion function, emit the resolver.
2085  if (Global->hasAttr<CPUDispatchAttr>())
2086  return emitCPUDispatchDefinition(GD);
2087 
2088  // If this is CUDA, be selective about which declarations we emit.
2089  if (LangOpts.CUDA) {
2090  if (LangOpts.CUDAIsDevice) {
2091  if (!Global->hasAttr<CUDADeviceAttr>() &&
2092  !Global->hasAttr<CUDAGlobalAttr>() &&
2093  !Global->hasAttr<CUDAConstantAttr>() &&
2094  !Global->hasAttr<CUDASharedAttr>())
2095  return;
2096  } else {
2097  // We need to emit host-side 'shadows' for all global
2098  // device-side variables because the CUDA runtime needs their
2099  // size and host-side address in order to provide access to
2100  // their device-side incarnations.
2101 
2102  // So device-only functions are the only things we skip.
2103  if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
2104  Global->hasAttr<CUDADeviceAttr>())
2105  return;
2106 
2107  assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
2108  "Expected Variable or Function");
2109  }
2110  }
2111 
2112  if (LangOpts.OpenMP) {
2113  // If this is OpenMP device, check if it is legal to emit this global
2114  // normally.
2115  if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
2116  return;
2117  if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
2118  if (MustBeEmitted(Global))
2120  return;
2121  }
2122  }
2123 
2124  // Ignore declarations, they will be emitted on their first use.
2125  if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
2126  // Forward declarations are emitted lazily on first use.
2127  if (!FD->doesThisDeclarationHaveABody()) {
2129  return;
2130 
2131  StringRef MangledName = getMangledName(GD);
2132 
2133  // Compute the function info and LLVM type.
2135  llvm::Type *Ty = getTypes().GetFunctionType(FI);
2136 
2137  GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
2138  /*DontDefer=*/false);
2139  return;
2140  }
2141  } else {
2142  const auto *VD = cast<VarDecl>(Global);
2143  assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
2144  // We need to emit device-side global CUDA variables even if a
2145  // variable does not have a definition -- we still need to define
2146  // host-side shadow for it.
2147  bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
2148  !VD->hasDefinition() &&
2149  (VD->hasAttr<CUDAConstantAttr>() ||
2150  VD->hasAttr<CUDADeviceAttr>());
2151  if (!MustEmitForCuda &&
2152  VD->isThisDeclarationADefinition() != VarDecl::Definition &&
2153  !Context.isMSStaticDataMemberInlineDefinition(VD)) {
2154  // If this declaration may have caused an inline variable definition to
2155  // change linkage, make sure that it's emitted.
2156  if (Context.getInlineVariableDefinitionKind(VD) ==
2158  GetAddrOfGlobalVar(VD);
2159  return;
2160  }
2161  }
2162 
2163  // Defer code generation to first use when possible, e.g. if this is an inline
2164  // function. If the global must always be emitted, do it eagerly if possible
2165  // to benefit from cache locality.
2166  if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
2167  // Emit the definition if it can't be deferred.
2168  EmitGlobalDefinition(GD);
2169  return;
2170  }
2171 
2172  // If we're deferring emission of a C++ variable with an
2173  // initializer, remember the order in which it appeared in the file.
2174  if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
2175  cast<VarDecl>(Global)->hasInit()) {
2176  DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
2177  CXXGlobalInits.push_back(nullptr);
2178  }
2179 
2180  StringRef MangledName = getMangledName(GD);
2181  if (GetGlobalValue(MangledName) != nullptr) {
2182  // The value has already been used and should therefore be emitted.
2183  addDeferredDeclToEmit(GD);
2184  } else if (MustBeEmitted(Global)) {
2185  // The value must be emitted, but cannot be emitted eagerly.
2186  assert(!MayBeEmittedEagerly(Global));
2187  addDeferredDeclToEmit(GD);
2188  } else {
2189  // Otherwise, remember that we saw a deferred decl with this name. The
2190  // first use of the mangled name will cause it to move into
2191  // DeferredDeclsToEmit.
2192  DeferredDecls[MangledName] = GD;
2193  }
2194 }
2195 
2196 // Check if T is a class type with a destructor that's not dllimport.
2198  if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
2199  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2200  if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
2201  return true;
2202 
2203  return false;
2204 }
2205 
2206 namespace {
2207  struct FunctionIsDirectlyRecursive :
2208  public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
2209  const StringRef Name;
2210  const Builtin::Context &BI;
2211  bool Result;
2212  FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
2213  Name(N), BI(C), Result(false) {
2214  }
2216 
2217  bool TraverseCallExpr(CallExpr *E) {
2218  const FunctionDecl *FD = E->getDirectCallee();
2219  if (!FD)
2220  return true;
2221  AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2222  if (Attr && Name == Attr->getLabel()) {
2223  Result = true;
2224  return false;
2225  }
2226  unsigned BuiltinID = FD->getBuiltinID();
2227  if (!BuiltinID || !BI.isLibFunction(BuiltinID))
2228  return true;
2229  StringRef BuiltinName = BI.getName(BuiltinID);
2230  if (BuiltinName.startswith("__builtin_") &&
2231  Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
2232  Result = true;
2233  return false;
2234  }
2235  return true;
2236  }
2237  };
2238 
2239  // Make sure we're not referencing non-imported vars or functions.
2240  struct DLLImportFunctionVisitor
2241  : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
2242  bool SafeToInline = true;
2243 
2244  bool shouldVisitImplicitCode() const { return true; }
2245 
2246  bool VisitVarDecl(VarDecl *VD) {
2247  if (VD->getTLSKind()) {
2248  // A thread-local variable cannot be imported.
2249  SafeToInline = false;
2250  return SafeToInline;
2251  }
2252 
2253  // A variable definition might imply a destructor call.
2254  if (VD->isThisDeclarationADefinition())
2255  SafeToInline = !HasNonDllImportDtor(VD->getType());
2256 
2257  return SafeToInline;
2258  }
2259 
2260  bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
2261  if (const auto *D = E->getTemporary()->getDestructor())
2262  SafeToInline = D->hasAttr<DLLImportAttr>();
2263  return SafeToInline;
2264  }
2265 
2266  bool VisitDeclRefExpr(DeclRefExpr *E) {
2267  ValueDecl *VD = E->getDecl();
2268  if (isa<FunctionDecl>(VD))
2269  SafeToInline = VD->hasAttr<DLLImportAttr>();
2270  else if (VarDecl *V = dyn_cast<VarDecl>(VD))
2271  SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
2272  return SafeToInline;
2273  }
2274 
2275  bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2276  SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
2277  return SafeToInline;
2278  }
2279 
2280  bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2281  CXXMethodDecl *M = E->getMethodDecl();
2282  if (!M) {
2283  // Call through a pointer to member function. This is safe to inline.
2284  SafeToInline = true;
2285  } else {
2286  SafeToInline = M->hasAttr<DLLImportAttr>();
2287  }
2288  return SafeToInline;
2289  }
2290 
2291  bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
2292  SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
2293  return SafeToInline;
2294  }
2295 
2296  bool VisitCXXNewExpr(CXXNewExpr *E) {
2297  SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
2298  return SafeToInline;
2299  }
2300  };
2301 }
2302 
2303 // isTriviallyRecursive - Check if this function calls another
2304 // decl that, because of the asm attribute or the other decl being a builtin,
2305 // ends up pointing to itself.
2306 bool
2307 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
2308  StringRef Name;
2309  if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
2310  // asm labels are a special kind of mangling we have to support.
2311  AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2312  if (!Attr)
2313  return false;
2314  Name = Attr->getLabel();
2315  } else {
2316  Name = FD->getName();
2317  }
2318 
2319  FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
2320  Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
2321  return Walker.Result;
2322 }
2323 
2324 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
2325  if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
2326  return true;
2327  const auto *F = cast<FunctionDecl>(GD.getDecl());
2328  if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
2329  return false;
2330 
2331  if (F->hasAttr<DLLImportAttr>()) {
2332  // Check whether it would be safe to inline this dllimport function.
2333  DLLImportFunctionVisitor Visitor;
2334  Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
2335  if (!Visitor.SafeToInline)
2336  return false;
2337 
2338  if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
2339  // Implicit destructor invocations aren't captured in the AST, so the
2340  // check above can't see them. Check for them manually here.
2341  for (const Decl *Member : Dtor->getParent()->decls())
2342  if (isa<FieldDecl>(Member))
2343  if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
2344  return false;
2345  for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
2346  if (HasNonDllImportDtor(B.getType()))
2347  return false;
2348  }
2349  }
2350 
2351  // PR9614. Avoid cases where the source code is lying to us. An available
2352  // externally function should have an equivalent function somewhere else,
2353  // but a function that calls itself is clearly not equivalent to the real
2354  // implementation.
2355  // This happens in glibc's btowc and in some configure checks.
2356  return !isTriviallyRecursive(F);
2357 }
2358 
2359 bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
2360  return CodeGenOpts.OptimizationLevel > 0;
2361 }
2362 
2363 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
2364  const auto *D = cast<ValueDecl>(GD.getDecl());
2365 
2366  PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
2367  Context.getSourceManager(),
2368  "Generating code for declaration");
2369 
2370  if (isa<FunctionDecl>(D)) {
2371  // At -O0, don't generate IR for functions with available_externally
2372  // linkage.
2373  if (!shouldEmitFunction(GD))
2374  return;
2375 
2376  if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
2377  // Make sure to emit the definition(s) before we emit the thunks.
2378  // This is necessary for the generation of certain thunks.
2379  if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
2380  ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
2381  else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
2382  ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
2383  else
2384  EmitGlobalFunctionDefinition(GD, GV);
2385 
2386  if (Method->isVirtual())
2387  getVTables().EmitThunks(GD);
2388 
2389  return;
2390  }
2391 
2392  return EmitGlobalFunctionDefinition(GD, GV);
2393  }
2394 
2395  if (const auto *VD = dyn_cast<VarDecl>(D))
2396  return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
2397 
2398  llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
2399 }
2400 
2401 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2402  llvm::Function *NewFn);
2403 
2404 void CodeGenModule::emitMultiVersionFunctions() {
2405  for (GlobalDecl GD : MultiVersionFuncs) {
2407  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2409  FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
2410  GlobalDecl CurGD{
2411  (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
2412  StringRef MangledName = getMangledName(CurGD);
2413  llvm::Constant *Func = GetGlobalValue(MangledName);
2414  if (!Func) {
2415  if (CurFD->isDefined()) {
2416  EmitGlobalFunctionDefinition(CurGD, nullptr);
2417  Func = GetGlobalValue(MangledName);
2418  } else {
2419  const CGFunctionInfo &FI =
2421  llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2422  Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
2423  /*DontDefer=*/false, ForDefinition);
2424  }
2425  assert(Func && "This should have just been created");
2426  }
2427  Options.emplace_back(getTarget(), cast<llvm::Function>(Func),
2428  CurFD->getAttr<TargetAttr>()->parse());
2429  });
2430 
2431  llvm::Function *ResolverFunc = cast<llvm::Function>(
2432  GetGlobalValue((getMangledName(GD) + ".resolver").str()));
2433  if (supportsCOMDAT())
2434  ResolverFunc->setComdat(
2435  getModule().getOrInsertComdat(ResolverFunc->getName()));
2436  std::stable_sort(
2437  Options.begin(), Options.end(),
2438  std::greater<CodeGenFunction::TargetMultiVersionResolverOption>());
2439  CodeGenFunction CGF(*this);
2440  CGF.EmitTargetMultiVersionResolver(ResolverFunc, Options);
2441  }
2442 }
2443 
2444 void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
2445  const auto *FD = cast<FunctionDecl>(GD.getDecl());
2446  assert(FD && "Not a FunctionDecl?");
2447  const auto *DD = FD->getAttr<CPUDispatchAttr>();
2448  assert(DD && "Not a cpu_dispatch Function?");
2449  llvm::Type *DeclTy = getTypes().ConvertTypeForMem(FD->getType());
2450 
2451  StringRef ResolverName = getMangledName(GD);
2452  llvm::Type *ResolverType = llvm::FunctionType::get(
2453  llvm::PointerType::get(DeclTy,
2454  Context.getTargetAddressSpace(FD->getType())),
2455  false);
2456  auto *ResolverFunc = cast<llvm::Function>(
2457  GetOrCreateLLVMFunction(ResolverName, ResolverType, GlobalDecl{},
2458  /*ForVTable=*/false));
2459 
2461  Options;
2462  const TargetInfo &Target = getTarget();
2463  for (const IdentifierInfo *II : DD->cpus()) {
2464  // Get the name of the target function so we can look it up/create it.
2465  std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
2466  getCPUSpecificMangling(*this, II->getName());
2467  llvm::Constant *Func = GetOrCreateLLVMFunction(
2468  MangledName, DeclTy, GD, /*ForVTable=*/false, /*DontDefer=*/false,
2469  /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
2471  Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
2472  llvm::transform(Features, Features.begin(),
2473  [](StringRef Str) { return Str.substr(1); });
2474  Features.erase(std::remove_if(
2475  Features.begin(), Features.end(), [&Target](StringRef Feat) {
2476  return !Target.validateCpuSupports(Feat);
2477  }), Features.end());
2478  Options.emplace_back(cast<llvm::Function>(Func),
2480  }
2481 
2482  llvm::sort(
2483  Options.begin(), Options.end(),
2484  std::greater<CodeGenFunction::CPUDispatchMultiVersionResolverOption>());
2485  CodeGenFunction CGF(*this);
2486  CGF.EmitCPUDispatchMultiVersionResolver(ResolverFunc, Options);
2487 }
2488 
2489 /// If an ifunc for the specified mangled name is not in the module, create and
2490 /// return an llvm IFunc Function with the specified type.
2491 llvm::Constant *
2492 CodeGenModule::GetOrCreateMultiVersionIFunc(GlobalDecl GD, llvm::Type *DeclTy,
2493  const FunctionDecl *FD) {
2494  std::string MangledName =
2495  getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
2496  std::string IFuncName = MangledName + ".ifunc";
2497  if (llvm::GlobalValue *IFuncGV = GetGlobalValue(IFuncName))
2498  return IFuncGV;
2499 
2500  // Since this is the first time we've created this IFunc, make sure
2501  // that we put this multiversioned function into the list to be
2502  // replaced later if necessary (target multiversioning only).
2504  MultiVersionFuncs.push_back(GD);
2505 
2506  std::string ResolverName = MangledName + ".resolver";
2507  llvm::Type *ResolverType = llvm::FunctionType::get(
2508  llvm::PointerType::get(DeclTy,
2509  Context.getTargetAddressSpace(FD->getType())),
2510  false);
2511  llvm::Constant *Resolver =
2512  GetOrCreateLLVMFunction(ResolverName, ResolverType, GlobalDecl{},
2513  /*ForVTable=*/false);
2514  llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
2515  DeclTy, 0, llvm::Function::ExternalLinkage, "", Resolver, &getModule());
2516  GIF->setName(IFuncName);
2517  SetCommonAttributes(FD, GIF);
2518 
2519  return GIF;
2520 }
2521 
2522 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
2523 /// module, create and return an llvm Function with the specified type. If there
2524 /// is something in the module with the specified name, return it potentially
2525 /// bitcasted to the right type.
2526 ///
2527 /// If D is non-null, it specifies a decl that correspond to this. This is used
2528 /// to set the attributes on the function when it is first created.
2529 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
2530  StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
2531  bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
2532  ForDefinition_t IsForDefinition) {
2533  const Decl *D = GD.getDecl();
2534 
2535  // Any attempts to use a MultiVersion function should result in retrieving
2536  // the iFunc instead. Name Mangling will handle the rest of the changes.
2537  if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
2538  // For the device mark the function as one that should be emitted.
2539  if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
2540  !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
2541  !DontDefer && !IsForDefinition) {
2542  if (const FunctionDecl *FDDef = FD->getDefinition())
2543  if (getContext().DeclMustBeEmitted(FDDef)) {
2544  GlobalDecl GDDef;
2545  if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
2546  GDDef = GlobalDecl(CD, GD.getCtorType());
2547  else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
2548  GDDef = GlobalDecl(DD, GD.getDtorType());
2549  else
2550  GDDef = GlobalDecl(FDDef);
2551  addDeferredDeclToEmit(GDDef);
2552  }
2553  }
2554 
2555  if (FD->isMultiVersion()) {
2556  const auto *TA = FD->getAttr<TargetAttr>();
2557  if (TA && TA->isDefaultVersion())
2558  UpdateMultiVersionNames(GD, FD);
2559  if (!IsForDefinition)
2560  return GetOrCreateMultiVersionIFunc(GD, Ty, FD);
2561  }
2562  }
2563 
2564  // Lookup the entry, lazily creating it if necessary.
2565  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2566  if (Entry) {
2567  if (WeakRefReferences.erase(Entry)) {
2568  const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
2569  if (FD && !FD->hasAttr<WeakAttr>())
2570  Entry->setLinkage(llvm::Function::ExternalLinkage);
2571  }
2572 
2573  // Handle dropped DLL attributes.
2574  if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
2575  Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2576  setDSOLocal(Entry);
2577  }
2578 
2579  // If there are two attempts to define the same mangled name, issue an
2580  // error.
2581  if (IsForDefinition && !Entry->isDeclaration()) {
2582  GlobalDecl OtherGD;
2583  // Check that GD is not yet in DiagnosedConflictingDefinitions is required
2584  // to make sure that we issue an error only once.
2585  if (lookupRepresentativeDecl(MangledName, OtherGD) &&
2586  (GD.getCanonicalDecl().getDecl() !=
2587  OtherGD.getCanonicalDecl().getDecl()) &&
2588  DiagnosedConflictingDefinitions.insert(GD).second) {
2589  getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
2590  << MangledName;
2591  getDiags().Report(OtherGD.getDecl()->getLocation(),
2592  diag::note_previous_definition);
2593  }
2594  }
2595 
2596  if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
2597  (Entry->getType()->getElementType() == Ty)) {
2598  return Entry;
2599  }
2600 
2601  // Make sure the result is of the correct type.
2602  // (If function is requested for a definition, we always need to create a new
2603  // function, not just return a bitcast.)
2604  if (!IsForDefinition)
2605  return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
2606  }
2607 
2608  // This function doesn't have a complete type (for example, the return
2609  // type is an incomplete struct). Use a fake type instead, and make
2610  // sure not to try to set attributes.
2611  bool IsIncompleteFunction = false;
2612 
2613  llvm::FunctionType *FTy;
2614  if (isa<llvm::FunctionType>(Ty)) {
2615  FTy = cast<llvm::FunctionType>(Ty);
2616  } else {
2617  FTy = llvm::FunctionType::get(VoidTy, false);
2618  IsIncompleteFunction = true;
2619  }
2620 
2621  llvm::Function *F =
2623  Entry ? StringRef() : MangledName, &getModule());
2624 
2625  // If we already created a function with the same mangled name (but different
2626  // type) before, take its name and add it to the list of functions to be
2627  // replaced with F at the end of CodeGen.
2628  //
2629  // This happens if there is a prototype for a function (e.g. "int f()") and
2630  // then a definition of a different type (e.g. "int f(int x)").
2631  if (Entry) {
2632  F->takeName(Entry);
2633 
2634  // This might be an implementation of a function without a prototype, in
2635  // which case, try to do special replacement of calls which match the new
2636  // prototype. The really key thing here is that we also potentially drop
2637  // arguments from the call site so as to make a direct call, which makes the
2638  // inliner happier and suppresses a number of optimizer warnings (!) about
2639  // dropping arguments.
2640  if (!Entry->use_empty()) {
2642  Entry->removeDeadConstantUsers();
2643  }
2644 
2645  llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
2646  F, Entry->getType()->getElementType()->getPointerTo());
2647  addGlobalValReplacement(Entry, BC);
2648  }
2649 
2650  assert(F->getName() == MangledName && "name was uniqued!");
2651  if (D)
2652  SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
2653  if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
2654  llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
2655  F->addAttributes(llvm::AttributeList::FunctionIndex, B);
2656  }
2657 
2658  if (!DontDefer) {
2659  // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
2660  // each other bottoming out with the base dtor. Therefore we emit non-base
2661  // dtors on usage, even if there is no dtor definition in the TU.
2662  if (D && isa<CXXDestructorDecl>(D) &&
2663  getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
2664  GD.getDtorType()))
2665  addDeferredDeclToEmit(GD);
2666 
2667  // This is the first use or definition of a mangled name. If there is a
2668  // deferred decl with this name, remember that we need to emit it at the end
2669  // of the file.
2670  auto DDI = DeferredDecls.find(MangledName);
2671  if (DDI != DeferredDecls.end()) {
2672  // Move the potentially referenced deferred decl to the
2673  // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
2674  // don't need it anymore).
2675  addDeferredDeclToEmit(DDI->second);
2676  DeferredDecls.erase(DDI);
2677 
2678  // Otherwise, there are cases we have to worry about where we're
2679  // using a declaration for which we must emit a definition but where
2680  // we might not find a top-level definition:
2681  // - member functions defined inline in their classes
2682  // - friend functions defined inline in some class
2683  // - special member functions with implicit definitions
2684  // If we ever change our AST traversal to walk into class methods,
2685  // this will be unnecessary.
2686  //
2687  // We also don't emit a definition for a function if it's going to be an
2688  // entry in a vtable, unless it's already marked as used.
2689  } else if (getLangOpts().CPlusPlus && D) {
2690  // Look for a declaration that's lexically in a record.
2691  for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
2692  FD = FD->getPreviousDecl()) {
2693  if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
2694  if (FD->doesThisDeclarationHaveABody()) {
2695  addDeferredDeclToEmit(GD.getWithDecl(FD));
2696  break;
2697  }
2698  }
2699  }
2700  }
2701  }
2702 
2703  // Make sure the result is of the requested type.
2704  if (!IsIncompleteFunction) {
2705  assert(F->getType()->getElementType() == Ty);
2706  return F;
2707  }
2708 
2709  llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2710  return llvm::ConstantExpr::getBitCast(F, PTy);
2711 }
2712 
2713 /// GetAddrOfFunction - Return the address of the given function. If Ty is
2714 /// non-null, then this function will use the specified type if it has to
2715 /// create it (this occurs when we see a definition of the function).
2717  llvm::Type *Ty,
2718  bool ForVTable,
2719  bool DontDefer,
2720  ForDefinition_t IsForDefinition) {
2721  // If there was no specific requested type, just convert it now.
2722  if (!Ty) {
2723  const auto *FD = cast<FunctionDecl>(GD.getDecl());
2724  auto CanonTy = Context.getCanonicalType(FD->getType());
2725  Ty = getTypes().ConvertFunctionType(CanonTy, FD);
2726  }
2727 
2728  // Devirtualized destructor calls may come through here instead of via
2729  // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
2730  // of the complete destructor when necessary.
2731  if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
2732  if (getTarget().getCXXABI().isMicrosoft() &&
2733  GD.getDtorType() == Dtor_Complete &&
2734  DD->getParent()->getNumVBases() == 0)
2735  GD = GlobalDecl(DD, Dtor_Base);
2736  }
2737 
2738  StringRef MangledName = getMangledName(GD);
2739  return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
2740  /*IsThunk=*/false, llvm::AttributeList(),
2741  IsForDefinition);
2742 }
2743 
2744 static const FunctionDecl *
2745 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
2748 
2749  IdentifierInfo &CII = C.Idents.get(Name);
2750  for (const auto &Result : DC->lookup(&CII))
2751  if (const auto FD = dyn_cast<FunctionDecl>(Result))
2752  return FD;
2753 
2754  if (!C.getLangOpts().CPlusPlus)
2755  return nullptr;
2756 
2757  // Demangle the premangled name from getTerminateFn()
2758  IdentifierInfo &CXXII =
2759  (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
2760  ? C.Idents.get("terminate")
2761  : C.Idents.get(Name);
2762 
2763  for (const auto &N : {"__cxxabiv1", "std"}) {
2764  IdentifierInfo &NS = C.Idents.get(N);
2765  for (const auto &Result : DC->lookup(&NS)) {
2766  NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
2767  if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
2768  for (const auto &Result : LSD->lookup(&NS))
2769  if ((ND = dyn_cast<NamespaceDecl>(Result)))
2770  break;
2771 
2772  if (ND)
2773  for (const auto &Result : ND->lookup(&CXXII))
2774  if (const auto *FD = dyn_cast<FunctionDecl>(Result))
2775  return FD;
2776  }
2777  }
2778 
2779  return nullptr;
2780 }
2781 
2782 /// CreateRuntimeFunction - Create a new runtime function with the specified
2783 /// type and name.
2784 llvm::Constant *
2785 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
2786  llvm::AttributeList ExtraAttrs,
2787  bool Local) {
2788  llvm::Constant *C =
2789  GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2790  /*DontDefer=*/false, /*IsThunk=*/false,
2791  ExtraAttrs);
2792 
2793  if (auto *F = dyn_cast<llvm::Function>(C)) {
2794  if (F->empty()) {
2795  F->setCallingConv(getRuntimeCC());
2796 
2797  if (!Local && getTriple().isOSBinFormatCOFF() &&
2798  !getCodeGenOpts().LTOVisibilityPublicStd &&
2799  !getTriple().isWindowsGNUEnvironment()) {
2800  const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
2801  if (!FD || FD->hasAttr<DLLImportAttr>()) {
2802  F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2803  F->setLinkage(llvm::GlobalValue::ExternalLinkage);
2804  }
2805  }
2806  setDSOLocal(F);
2807  }
2808  }
2809 
2810  return C;
2811 }
2812 
2813 /// CreateBuiltinFunction - Create a new builtin function with the specified
2814 /// type and name.
2815 llvm::Constant *
2816 CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
2817  llvm::AttributeList ExtraAttrs) {
2818  return CreateRuntimeFunction(FTy, Name, ExtraAttrs, true);
2819 }
2820 
2821 /// isTypeConstant - Determine whether an object of this type can be emitted
2822 /// as a constant.
2823 ///
2824 /// If ExcludeCtor is true, the duration when the object's constructor runs
2825 /// will not be considered. The caller will need to verify that the object is
2826 /// not written to during its construction.
2827 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2828  if (!Ty.isConstant(Context) && !Ty->isReferenceType())
2829  return false;
2830 
2831  if (Context.getLangOpts().CPlusPlus) {
2832  if (const CXXRecordDecl *Record
2833  = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2834  return ExcludeCtor && !Record->hasMutableFields() &&
2835  Record->hasTrivialDestructor();
2836  }
2837 
2838  return true;
2839 }
2840 
2841 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2842 /// create and return an llvm GlobalVariable with the specified type. If there
2843 /// is something in the module with the specified name, return it potentially
2844 /// bitcasted to the right type.
2845 ///
2846 /// If D is non-null, it specifies a decl that correspond to this. This is used
2847 /// to set the attributes on the global when it is first created.
2848 ///
2849 /// If IsForDefinition is true, it is guaranteed that an actual global with
2850 /// type Ty will be returned, not conversion of a variable with the same
2851 /// mangled name but some other type.
2852 llvm::Constant *
2853 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
2854  llvm::PointerType *Ty,
2855  const VarDecl *D,
2856  ForDefinition_t IsForDefinition) {
2857  // Lookup the entry, lazily creating it if necessary.
2858  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2859  if (Entry) {
2860  if (WeakRefReferences.erase(Entry)) {
2861  if (D && !D->hasAttr<WeakAttr>())
2862  Entry->setLinkage(llvm::Function::ExternalLinkage);
2863  }
2864 
2865  // Handle dropped DLL attributes.
2866  if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2867  Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2868 
2869  if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
2870  getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
2871 
2872  if (Entry->getType() == Ty)
2873  return Entry;
2874 
2875  // If there are two attempts to define the same mangled name, issue an
2876  // error.
2877  if (IsForDefinition && !Entry->isDeclaration()) {
2878  GlobalDecl OtherGD;
2879  const VarDecl *OtherD;
2880 
2881  // Check that D is not yet in DiagnosedConflictingDefinitions is required
2882  // to make sure that we issue an error only once.
2883  if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
2884  (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2885  (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2886  OtherD->hasInit() &&
2887  DiagnosedConflictingDefinitions.insert(D).second) {
2888  getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
2889  << MangledName;
2890  getDiags().Report(OtherGD.getDecl()->getLocation(),
2891  diag::note_previous_definition);
2892  }
2893  }
2894 
2895  // Make sure the result is of the correct type.
2896  if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2897  return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2898 
2899  // (If global is requested for a definition, we always need to create a new
2900  // global, not just return a bitcast.)
2901  if (!IsForDefinition)
2902  return llvm::ConstantExpr::getBitCast(Entry, Ty);
2903  }
2904 
2905  auto AddrSpace = GetGlobalVarAddressSpace(D);
2906  auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
2907 
2908  auto *GV = new llvm::GlobalVariable(
2909  getModule(), Ty->getElementType(), false,
2910  llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
2911  llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
2912 
2913  // If we already created a global with the same mangled name (but different
2914  // type) before, take its name and remove it from its parent.
2915  if (Entry) {
2916  GV->takeName(Entry);
2917 
2918  if (!Entry->use_empty()) {
2919  llvm::Constant *NewPtrForOldDecl =
2920  llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2921  Entry->replaceAllUsesWith(NewPtrForOldDecl);
2922  }
2923 
2924  Entry->eraseFromParent();
2925  }
2926 
2927  // This is the first use or definition of a mangled name. If there is a
2928  // deferred decl with this name, remember that we need to emit it at the end
2929  // of the file.
2930  auto DDI = DeferredDecls.find(MangledName);
2931  if (DDI != DeferredDecls.end()) {
2932  // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2933  // list, and remove it from DeferredDecls (since we don't need it anymore).
2934  addDeferredDeclToEmit(DDI->second);
2935  DeferredDecls.erase(DDI);
2936  }
2937 
2938  // Handle things which are present even on external declarations.
2939  if (D) {
2940  if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
2941  getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
2942 
2943  // FIXME: This code is overly simple and should be merged with other global
2944  // handling.
2945  GV->setConstant(isTypeConstant(D->getType(), false));
2946 
2947  GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2948 
2949  setLinkageForGV(GV, D);
2950 
2951  if (D->getTLSKind()) {
2952  if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2953  CXXThreadLocals.push_back(D);
2954  setTLSMode(GV, *D);
2955  }
2956 
2957  setGVProperties(GV, D);
2958 
2959  // If required by the ABI, treat declarations of static data members with
2960  // inline initializers as definitions.
2961  if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
2962  EmitGlobalVarDefinition(D);
2963  }
2964 
2965  // Emit section information for extern variables.
2966  if (D->hasExternalStorage()) {
2967  if (const SectionAttr *SA = D->getAttr<SectionAttr>())
2968  GV->setSection(SA->getName());
2969  }
2970 
2971  // Handle XCore specific ABI requirements.
2972  if (getTriple().getArch() == llvm::Triple::xcore &&
2974  D->getType().isConstant(Context) &&
2976  GV->setSection(".cp.rodata");
2977 
2978  // Check if we a have a const declaration with an initializer, we may be
2979  // able to emit it as available_externally to expose it's value to the
2980  // optimizer.
2981  if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
2982  D->getType().isConstQualified() && !GV->hasInitializer() &&
2983  !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
2984  const auto *Record =
2985  Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
2986  bool HasMutableFields = Record && Record->hasMutableFields();
2987  if (!HasMutableFields) {
2988  const VarDecl *InitDecl;
2989  const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2990  if (InitExpr) {
2991  ConstantEmitter emitter(*this);
2992  llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
2993  if (Init) {
2994  auto *InitType = Init->getType();
2995  if (GV->getType()->getElementType() != InitType) {
2996  // The type of the initializer does not match the definition.
2997  // This happens when an initializer has a different type from
2998  // the type of the global (because of padding at the end of a
2999  // structure for instance).
3000  GV->setName(StringRef());
3001  // Make a new global with the correct type, this is now guaranteed
3002  // to work.
3003  auto *NewGV = cast<llvm::GlobalVariable>(
3004  GetAddrOfGlobalVar(D, InitType, IsForDefinition));
3005 
3006  // Erase the old global, since it is no longer used.
3007  GV->eraseFromParent();
3008  GV = NewGV;
3009  } else {
3010  GV->setInitializer(Init);
3011  GV->setConstant(true);
3012  GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
3013  }
3014  emitter.finalize(GV);
3015  }
3016  }
3017  }
3018  }
3019  }
3020 
3021  LangAS ExpectedAS =
3022  D ? D->getType().getAddressSpace()
3023  : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
3024  assert(getContext().getTargetAddressSpace(ExpectedAS) ==
3025  Ty->getPointerAddressSpace());
3026  if (AddrSpace != ExpectedAS)
3027  return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
3028  ExpectedAS, Ty);
3029 
3030  return GV;
3031 }
3032 
3033 llvm::Constant *
3035  ForDefinition_t IsForDefinition) {
3036  const Decl *D = GD.getDecl();
3037  if (isa<CXXConstructorDecl>(D))
3038  return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
3040  /*FnInfo=*/nullptr, /*FnType=*/nullptr,
3041  /*DontDefer=*/false, IsForDefinition);
3042  else if (isa<CXXDestructorDecl>(D))
3043  return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
3045  /*FnInfo=*/nullptr, /*FnType=*/nullptr,
3046  /*DontDefer=*/false, IsForDefinition);
3047  else if (isa<CXXMethodDecl>(D)) {
3048  auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
3049  cast<CXXMethodDecl>(D));
3050  auto Ty = getTypes().GetFunctionType(*FInfo);
3051  return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3052  IsForDefinition);
3053  } else if (isa<FunctionDecl>(D)) {
3055  llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3056  return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3057  IsForDefinition);
3058  } else
3059  return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
3060  IsForDefinition);
3061 }
3062 
3063 llvm::GlobalVariable *
3065  llvm::Type *Ty,
3066  llvm::GlobalValue::LinkageTypes Linkage) {
3067  llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
3068  llvm::GlobalVariable *OldGV = nullptr;
3069 
3070  if (GV) {
3071  // Check if the variable has the right type.
3072  if (GV->getType()->getElementType() == Ty)
3073  return GV;
3074 
3075  // Because C++ name mangling, the only way we can end up with an already
3076  // existing global with the same name is if it has been declared extern "C".
3077  assert(GV->isDeclaration() && "Declaration has wrong type!");
3078  OldGV = GV;
3079  }
3080 
3081  // Create a new variable.
3082  GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
3083  Linkage, nullptr, Name);
3084 
3085  if (OldGV) {
3086  // Replace occurrences of the old variable if needed.
3087  GV->takeName(OldGV);
3088 
3089  if (!OldGV->use_empty()) {
3090  llvm::Constant *NewPtrForOldDecl =
3091  llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3092  OldGV->replaceAllUsesWith(NewPtrForOldDecl);
3093  }
3094 
3095  OldGV->eraseFromParent();
3096  }
3097 
3098  if (supportsCOMDAT() && GV->isWeakForLinker() &&
3099  !GV->hasAvailableExternallyLinkage())
3100  GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3101 
3102  return GV;
3103 }
3104 
3105 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
3106 /// given global variable. If Ty is non-null and if the global doesn't exist,
3107 /// then it will be created with the specified type instead of whatever the
3108 /// normal requested type would be. If IsForDefinition is true, it is guaranteed
3109 /// that an actual global with type Ty will be returned, not conversion of a
3110 /// variable with the same mangled name but some other type.
3112  llvm::Type *Ty,
3113  ForDefinition_t IsForDefinition) {
3114  assert(D->hasGlobalStorage() && "Not a global variable");
3115  QualType ASTTy = D->getType();
3116  if (!Ty)
3117  Ty = getTypes().ConvertTypeForMem(ASTTy);
3118 
3119  llvm::PointerType *PTy =
3120  llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
3121 
3122  StringRef MangledName = getMangledName(D);
3123  return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
3124 }
3125 
3126 /// CreateRuntimeVariable - Create a new runtime global variable with the
3127 /// specified type and name.
3128 llvm::Constant *
3130  StringRef Name) {
3131  auto *Ret =
3132  GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
3133  setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
3134  return Ret;
3135 }
3136 
3138  assert(!D->getInit() && "Cannot emit definite definitions here!");
3139 
3140  StringRef MangledName = getMangledName(D);
3141  llvm::GlobalValue *GV = GetGlobalValue(MangledName);
3142 
3143  // We already have a definition, not declaration, with the same mangled name.
3144  // Emitting of declaration is not required (and actually overwrites emitted
3145  // definition).
3146  if (GV && !GV->isDeclaration())
3147  return;
3148 
3149  // If we have not seen a reference to this variable yet, place it into the
3150  // deferred declarations table to be emitted if needed later.
3151  if (!MustBeEmitted(D) && !GV) {
3152  DeferredDecls[MangledName] = D;
3153  return;
3154  }
3155 
3156  // The tentative definition is the only definition.
3157  EmitGlobalVarDefinition(D);
3158 }
3159 
3161  return Context.toCharUnitsFromBits(
3162  getDataLayout().getTypeStoreSizeInBits(Ty));
3163 }
3164 
3166  LangAS AddrSpace = LangAS::Default;
3167  if (LangOpts.OpenCL) {
3168  AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
3169  assert(AddrSpace == LangAS::opencl_global ||
3170  AddrSpace == LangAS::opencl_constant ||
3171  AddrSpace == LangAS::opencl_local ||
3172  AddrSpace >= LangAS::FirstTargetAddressSpace);
3173  return AddrSpace;
3174  }
3175 
3176  if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
3177  if (D && D->hasAttr<CUDAConstantAttr>())
3178  return LangAS::cuda_constant;
3179  else if (D && D->hasAttr<CUDASharedAttr>())
3180  return LangAS::cuda_shared;
3181  else if (D && D->hasAttr<CUDADeviceAttr>())
3182  return LangAS::cuda_device;
3183  else if (D && D->getType().isConstQualified())
3184  return LangAS::cuda_constant;
3185  else
3186  return LangAS::cuda_device;
3187  }
3188 
3190 }
3191 
3193  // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3194  if (LangOpts.OpenCL)
3195  return LangAS::opencl_constant;
3196  if (auto AS = getTarget().getConstantAddressSpace())
3197  return AS.getValue();
3198  return LangAS::Default;
3199 }
3200 
3201 // In address space agnostic languages, string literals are in default address
3202 // space in AST. However, certain targets (e.g. amdgcn) request them to be
3203 // emitted in constant address space in LLVM IR. To be consistent with other
3204 // parts of AST, string literal global variables in constant address space
3205 // need to be casted to default address space before being put into address
3206 // map and referenced by other part of CodeGen.
3207 // In OpenCL, string literals are in constant address space in AST, therefore
3208 // they should not be casted to default address space.
3209 static llvm::Constant *
3211  llvm::GlobalVariable *GV) {
3212  llvm::Constant *Cast = GV;
3213  if (!CGM.getLangOpts().OpenCL) {
3214  if (auto AS = CGM.getTarget().getConstantAddressSpace()) {
3215  if (AS != LangAS::Default)
3217  CGM, GV, AS.getValue(), LangAS::Default,
3218  GV->getValueType()->getPointerTo(
3220  }
3221  }
3222  return Cast;
3223 }
3224 
3225 template<typename SomeDecl>
3227  llvm::GlobalValue *GV) {
3228  if (!getLangOpts().CPlusPlus)
3229  return;
3230 
3231  // Must have 'used' attribute, or else inline assembly can't rely on
3232  // the name existing.
3233  if (!D->template hasAttr<UsedAttr>())
3234  return;
3235 
3236  // Must have internal linkage and an ordinary name.
3237  if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
3238  return;
3239 
3240  // Must be in an extern "C" context. Entities declared directly within
3241  // a record are not extern "C" even if the record is in such a context.
3242  const SomeDecl *First = D->getFirstDecl();
3243  if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
3244  return;
3245 
3246  // OK, this is an internal linkage entity inside an extern "C" linkage
3247  // specification. Make a note of that so we can give it the "expected"
3248  // mangled name if nothing else is using that name.
3249  std::pair<StaticExternCMap::iterator, bool> R =
3250  StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
3251 
3252  // If we have multiple internal linkage entities with the same name
3253  // in extern "C" regions, none of them gets that name.
3254  if (!R.second)
3255  R.first->second = nullptr;
3256 }
3257 
3258 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
3259  if (!CGM.supportsCOMDAT())
3260  return false;
3261 
3262  if (D.hasAttr<SelectAnyAttr>())
3263  return true;
3264 
3266  if (auto *VD = dyn_cast<VarDecl>(&D))
3267  Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
3268  else
3269  Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
3270 
3271  switch (Linkage) {
3272  case GVA_Internal:
3274  case GVA_StrongExternal:
3275  return false;
3276  case GVA_DiscardableODR:
3277  case GVA_StrongODR:
3278  return true;
3279  }
3280  llvm_unreachable("No such linkage");
3281 }
3282 
3284  llvm::GlobalObject &GO) {
3285  if (!shouldBeInCOMDAT(*this, D))
3286  return;
3287  GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
3288 }
3289 
3290 /// Pass IsTentative as true if you want to create a tentative definition.
3291 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
3292  bool IsTentative) {
3293  // OpenCL global variables of sampler type are translated to function calls,
3294  // therefore no need to be translated.
3295  QualType ASTTy = D->getType();
3296  if (getLangOpts().OpenCL && ASTTy->isSamplerT())
3297  return;
3298 
3299  // If this is OpenMP device, check if it is legal to emit this global
3300  // normally.
3301  if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
3302  OpenMPRuntime->emitTargetGlobalVariable(D))
3303  return;
3304 
3305  llvm::Constant *Init = nullptr;
3307  bool NeedsGlobalCtor = false;
3308  bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
3309 
3310  const VarDecl *InitDecl;
3311  const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3312 
3313  Optional<ConstantEmitter> emitter;
3314 
3315  // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
3316  // as part of their declaration." Sema has already checked for
3317  // error cases, so we just need to set Init to UndefValue.
3318  if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
3319  D->hasAttr<CUDASharedAttr>())
3320  Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
3321  else if (!InitExpr) {
3322  // This is a tentative definition; tentative definitions are
3323  // implicitly initialized with { 0 }.
3324  //
3325  // Note that tentative definitions are only emitted at the end of
3326  // a translation unit, so they should never have incomplete
3327  // type. In addition, EmitTentativeDefinition makes sure that we
3328  // never attempt to emit a tentative definition if a real one
3329  // exists. A use may still exists, however, so we still may need
3330  // to do a RAUW.
3331  assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
3332  Init = EmitNullConstant(D->getType());
3333  } else {
3334  initializedGlobalDecl = GlobalDecl(D);
3335  emitter.emplace(*this);
3336  Init = emitter->tryEmitForInitializer(*InitDecl);
3337 
3338  if (!Init) {
3339  QualType T = InitExpr->getType();
3340  if (D->getType()->isReferenceType())
3341  T = D->getType();
3342 
3343  if (getLangOpts().CPlusPlus) {
3344  Init = EmitNullConstant(T);
3345  NeedsGlobalCtor = true;
3346  } else {
3347  ErrorUnsupported(D, "static initializer");
3348  Init = llvm::UndefValue::get(getTypes().ConvertType(T));
3349  }
3350  } else {
3351  // We don't need an initializer, so remove the entry for the delayed
3352  // initializer position (just in case this entry was delayed) if we
3353  // also don't need to register a destructor.
3354  if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
3355  DelayedCXXInitPosition.erase(D);
3356  }
3357  }
3358 
3359  llvm::Type* InitType = Init->getType();
3360  llvm::Constant *Entry =
3361  GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
3362 
3363  // Strip off a bitcast if we got one back.
3364  if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
3365  assert(CE->getOpcode() == llvm::Instruction::BitCast ||
3366  CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
3367  // All zero index gep.
3368  CE->getOpcode() == llvm::Instruction::GetElementPtr);
3369  Entry = CE->getOperand(0);
3370  }
3371 
3372  // Entry is now either a Function or GlobalVariable.
3373  auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
3374 
3375  // We have a definition after a declaration with the wrong type.
3376  // We must make a new GlobalVariable* and update everything that used OldGV
3377  // (a declaration or tentative definition) with the new GlobalVariable*
3378  // (which will be a definition).
3379  //
3380  // This happens if there is a prototype for a global (e.g.
3381  // "extern int x[];") and then a definition of a different type (e.g.
3382  // "int x[10];"). This also happens when an initializer has a different type
3383  // from the type of the global (this happens with unions).
3384  if (!GV || GV->getType()->getElementType() != InitType ||
3385  GV->getType()->getAddressSpace() !=
3387 
3388  // Move the old entry aside so that we'll create a new one.
3389  Entry->setName(StringRef());
3390 
3391  // Make a new global with the correct type, this is now guaranteed to work.
3392  GV = cast<llvm::GlobalVariable>(
3393  GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
3394 
3395  // Replace all uses of the old global with the new global
3396  llvm::Constant *NewPtrForOldDecl =
3397  llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3398  Entry->replaceAllUsesWith(NewPtrForOldDecl);
3399 
3400  // Erase the old global, since it is no longer used.
3401  cast<llvm::GlobalValue>(Entry)->eraseFromParent();
3402  }
3403 
3405 
3406  if (D->hasAttr<AnnotateAttr>())
3407  AddGlobalAnnotations(D, GV);
3408 
3409  // Set the llvm linkage type as appropriate.
3410  llvm::GlobalValue::LinkageTypes Linkage =
3411  getLLVMLinkageVarDefinition(D, GV->isConstant());
3412 
3413  // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
3414  // the device. [...]"
3415  // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
3416  // __device__, declares a variable that: [...]
3417  // Is accessible from all the threads within the grid and from the host
3418  // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
3419  // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
3420  if (GV && LangOpts.CUDA) {
3421  if (LangOpts.CUDAIsDevice) {
3422  if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
3423  GV->setExternallyInitialized(true);
3424  } else {
3425  // Host-side shadows of external declarations of device-side
3426  // global variables become internal definitions. These have to
3427  // be internal in order to prevent name conflicts with global
3428  // host variables with the same name in a different TUs.
3429  if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
3431 
3432  // Shadow variables and their properties must be registered
3433  // with CUDA runtime.
3434  unsigned Flags = 0;
3435  if (!D->hasDefinition())
3437  if (D->hasAttr<CUDAConstantAttr>())
3439  getCUDARuntime().registerDeviceVar(*GV, Flags);
3440  } else if (D->hasAttr<CUDASharedAttr>())
3441  // __shared__ variables are odd. Shadows do get created, but
3442  // they are not registered with the CUDA runtime, so they
3443  // can't really be used to access their device-side
3444  // counterparts. It's not clear yet whether it's nvcc's bug or
3445  // a feature, but we've got to do the same for compatibility.
3447  }
3448  }
3449 
3450  GV->setInitializer(Init);
3451  if (emitter) emitter->finalize(GV);
3452 
3453  // If it is safe to mark the global 'constant', do so now.
3454  GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
3455  isTypeConstant(D->getType(), true));
3456 
3457  // If it is in a read-only section, mark it 'constant'.
3458  if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
3459  const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
3460  if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
3461  GV->setConstant(true);
3462  }
3463 
3464  GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
3465 
3466 
3467  // On Darwin, if the normal linkage of a C++ thread_local variable is
3468  // LinkOnce or Weak, we keep the normal linkage to prevent multiple
3469  // copies within a linkage unit; otherwise, the backing variable has
3470  // internal linkage and all accesses should just be calls to the
3471  // Itanium-specified entry point, which has the normal linkage of the
3472  // variable. This is to preserve the ability to change the implementation
3473  // behind the scenes.
3474  if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
3475  Context.getTargetInfo().getTriple().isOSDarwin() &&
3476  !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
3477  !llvm::GlobalVariable::isWeakLinkage(Linkage))
3479 
3480  GV->setLinkage(Linkage);
3481  if (D->hasAttr<DLLImportAttr>())
3482  GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
3483  else if (D->hasAttr<DLLExportAttr>())
3484  GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
3485  else
3486  GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
3487 
3488  if (Linkage == llvm::GlobalVariable::CommonLinkage) {
3489  // common vars aren't constant even if declared const.
3490  GV->setConstant(false);
3491  // Tentative definition of global variables may be initialized with
3492  // non-zero null pointers. In this case they should have weak linkage
3493  // since common linkage must have zero initializer and must not have
3494  // explicit section therefore cannot have non-zero initial value.
3495  if (!GV->getInitializer()->isNullValue())
3496  GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
3497  }
3498 
3499  setNonAliasAttributes(D, GV);
3500 
3501  if (D->getTLSKind() && !GV->isThreadLocal()) {
3502  if (D->getTLSKind() == VarDecl::TLS_Dynamic)
3503  CXXThreadLocals.push_back(D);
3504  setTLSMode(GV, *D);
3505  }
3506 
3507  maybeSetTrivialComdat(*D, *GV);
3508 
3509  // Emit the initializer function if necessary.
3510  if (NeedsGlobalCtor || NeedsGlobalDtor)
3511  EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
3512 
3513  SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
3514 
3515  // Emit global variable debug information.
3516  if (CGDebugInfo *DI = getModuleDebugInfo())
3517  if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
3518  DI->EmitGlobalVariable(GV, D);
3519 }
3520 
3521 static bool isVarDeclStrongDefinition(const ASTContext &Context,
3522  CodeGenModule &CGM, const VarDecl *D,
3523  bool NoCommon) {
3524  // Don't give variables common linkage if -fno-common was specified unless it
3525  // was overridden by a NoCommon attribute.
3526  if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
3527  return true;
3528 
3529  // C11 6.9.2/2:
3530  // A declaration of an identifier for an object that has file scope without
3531  // an initializer, and without a storage-class specifier or with the
3532  // storage-class specifier static, constitutes a tentative definition.
3533  if (D->getInit() || D->hasExternalStorage())
3534  return true;
3535 
3536  // A variable cannot be both common and exist in a section.
3537  if (D->hasAttr<SectionAttr>())
3538  return true;
3539 
3540  // A variable cannot be both common and exist in a section.
3541  // We don't try to determine which is the right section in the front-end.
3542  // If no specialized section name is applicable, it will resort to default.
3543  if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
3544  D->hasAttr<PragmaClangDataSectionAttr>() ||
3545  D->hasAttr<PragmaClangRodataSectionAttr>())
3546  return true;
3547 
3548  // Thread local vars aren't considered common linkage.
3549  if (D->getTLSKind())
3550  return true;
3551 
3552  // Tentative definitions marked with WeakImportAttr are true definitions.
3553  if (D->hasAttr<WeakImportAttr>())
3554  return true;
3555 
3556  // A variable cannot be both common and exist in a comdat.
3557  if (shouldBeInCOMDAT(CGM, *D))
3558  return true;
3559 
3560  // Declarations with a required alignment do not have common linkage in MSVC
3561  // mode.
3562  if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3563  if (D->hasAttr<AlignedAttr>())
3564  return true;
3565  QualType VarType = D->getType();
3566  if (Context.isAlignmentRequired(VarType))
3567  return true;
3568 
3569  if (const auto *RT = VarType->getAs<RecordType>()) {
3570  const RecordDecl *RD = RT->getDecl();
3571  for (const FieldDecl *FD : RD->fields()) {
3572  if (FD->isBitField())
3573  continue;
3574  if (FD->hasAttr<AlignedAttr>())
3575  return true;
3576  if (Context.isAlignmentRequired(FD->getType()))
3577  return true;
3578  }
3579  }
3580  }
3581 
3582  return false;
3583 }
3584 
3585 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
3586  const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
3587  if (Linkage == GVA_Internal)
3589 
3590  if (D->hasAttr<WeakAttr>()) {
3591  if (IsConstantVariable)
3592  return llvm::GlobalVariable::WeakODRLinkage;
3593  else
3594  return llvm::GlobalVariable::WeakAnyLinkage;
3595  }
3596 
3597  // We are guaranteed to have a strong definition somewhere else,
3598  // so we can use available_externally linkage.
3599  if (Linkage == GVA_AvailableExternally)
3600  return llvm::GlobalValue::AvailableExternallyLinkage;
3601 
3602  // Note that Apple's kernel linker doesn't support symbol
3603  // coalescing, so we need to avoid linkonce and weak linkages there.
3604  // Normally, this means we just map to internal, but for explicit
3605  // instantiations we'll map to external.
3606 
3607  // In C++, the compiler has to emit a definition in every translation unit
3608  // that references the function. We should use linkonce_odr because
3609  // a) if all references in this translation unit are optimized away, we
3610  // don't need to codegen it. b) if the function persists, it needs to be
3611  // merged with other definitions. c) C++ has the ODR, so we know the
3612  // definition is dependable.
3613  if (Linkage == GVA_DiscardableODR)
3614  return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
3616 
3617  // An explicit instantiation of a template has weak linkage, since
3618  // explicit instantiations can occur in multiple translation units
3619  // and must all be equivalent. However, we are not allowed to
3620  // throw away these explicit instantiations.
3621  //
3622  // We don't currently support CUDA device code spread out across multiple TUs,
3623  // so say that CUDA templates are either external (for kernels) or internal.
3624  // This lets llvm perform aggressive inter-procedural optimizations.
3625  if (Linkage == GVA_StrongODR) {
3626  if (Context.getLangOpts().AppleKext)
3628  if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
3629  return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
3631  return llvm::Function::WeakODRLinkage;
3632  }
3633 
3634  // C++ doesn't have tentative definitions and thus cannot have common
3635  // linkage.
3636  if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
3637  !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
3638  CodeGenOpts.NoCommon))
3639  return llvm::GlobalVariable::CommonLinkage;
3640 
3641  // selectany symbols are externally visible, so use weak instead of
3642  // linkonce. MSVC optimizes away references to const selectany globals, so
3643  // all definitions should be the same and ODR linkage should be used.
3644  // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
3645  if (D->hasAttr<SelectAnyAttr>())
3646  return llvm::GlobalVariable::WeakODRLinkage;
3647 
3648  // Otherwise, we have strong external linkage.
3649  assert(Linkage == GVA_StrongExternal);
3651 }
3652 
3653 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
3654  const VarDecl *VD, bool IsConstant) {
3656  return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
3657 }
3658 
3659 /// Replace the uses of a function that was declared with a non-proto type.
3660 /// We want to silently drop extra arguments from call sites
3661 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
3662  llvm::Function *newFn) {
3663  // Fast path.
3664  if (old->use_empty()) return;
3665 
3666  llvm::Type *newRetTy = newFn->getReturnType();
3669 
3670  for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
3671  ui != ue; ) {
3672  llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
3673  llvm::User *user = use->getUser();
3674 
3675  // Recognize and replace uses of bitcasts. Most calls to
3676  // unprototyped functions will use bitcasts.
3677  if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
3678  if (bitcast->getOpcode() == llvm::Instruction::BitCast)
3679  replaceUsesOfNonProtoConstant(bitcast, newFn);
3680  continue;
3681  }
3682 
3683  // Recognize calls to the function.
3684  llvm::CallSite callSite(user);
3685  if (!callSite) continue;
3686  if (!callSite.isCallee(&*use)) continue;
3687 
3688  // If the return types don't match exactly, then we can't
3689  // transform this call unless it's dead.
3690  if (callSite->getType() != newRetTy && !callSite->use_empty())
3691  continue;
3692 
3693  // Get the call site's attribute list.
3695  llvm::AttributeList oldAttrs = callSite.getAttributes();
3696 
3697  // If the function was passed too few arguments, don't transform.
3698  unsigned newNumArgs = newFn->arg_size();
3699  if (callSite.arg_size() < newNumArgs) continue;
3700 
3701  // If extra arguments were passed, we silently drop them.
3702  // If any of the types mismatch, we don't transform.
3703  unsigned argNo = 0;
3704  bool dontTransform = false;
3705  for (llvm::Argument &A : newFn->args()) {
3706  if (callSite.getArgument(argNo)->getType() != A.getType()) {
3707  dontTransform = true;
3708  break;
3709  }
3710 
3711  // Add any parameter attributes.
3712  newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
3713  argNo++;
3714  }
3715  if (dontTransform)
3716  continue;
3717 
3718  // Okay, we can transform this. Create the new call instruction and copy
3719  // over the required information.
3720  newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
3721 
3722  // Copy over any operand bundles.
3723  callSite.getOperandBundlesAsDefs(newBundles);
3724 
3725  llvm::CallSite newCall;
3726  if (callSite.isCall()) {
3727  newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
3728  callSite.getInstruction());
3729  } else {
3730  auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
3731  newCall = llvm::InvokeInst::Create(newFn,
3732  oldInvoke->getNormalDest(),
3733  oldInvoke->getUnwindDest(),
3734  newArgs, newBundles, "",
3735  callSite.getInstruction());
3736  }
3737  newArgs.clear(); // for the next iteration
3738 
3739  if (!newCall->getType()->isVoidTy())
3740  newCall->takeName(callSite.getInstruction());
3741  newCall.setAttributes(llvm::AttributeList::get(
3742  newFn->getContext(), oldAttrs.getFnAttributes(),
3743  oldAttrs.getRetAttributes(), newArgAttrs));
3744  newCall.setCallingConv(callSite.getCallingConv());
3745 
3746  // Finally, remove the old call, replacing any uses with the new one.
3747  if (!callSite->use_empty())
3748  callSite->replaceAllUsesWith(newCall.getInstruction());
3749 
3750  // Copy debug location attached to CI.
3751  if (callSite->getDebugLoc())
3752  newCall->setDebugLoc(callSite->getDebugLoc());
3753 
3754  callSite->eraseFromParent();
3755  }
3756 }
3757 
3758 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
3759 /// implement a function with no prototype, e.g. "int foo() {}". If there are
3760 /// existing call uses of the old function in the module, this adjusts them to
3761 /// call the new function directly.
3762 ///
3763 /// This is not just a cleanup: the always_inline pass requires direct calls to
3764 /// functions to be able to inline them. If there is a bitcast in the way, it
3765 /// won't inline them. Instcombine normally deletes these calls, but it isn't
3766 /// run at -O0.
3767 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3768  llvm::Function *NewFn) {
3769  // If we're redefining a global as a function, don't transform it.
3770  if (!isa<llvm::Function>(Old)) return;
3771 
3772  replaceUsesOfNonProtoConstant(Old, NewFn);
3773 }
3774 
3776  auto DK = VD->isThisDeclarationADefinition();
3777  if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
3778  return;
3779 
3781  // If we have a definition, this might be a deferred decl. If the
3782  // instantiation is explicit, make sure we emit it at the end.
3784  GetAddrOfGlobalVar(VD);
3785 
3786  EmitTopLevelDecl(VD);
3787 }
3788 
3789 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
3790  llvm::GlobalValue *GV) {
3791  const auto *D = cast<FunctionDecl>(GD.getDecl());
3792 
3793  // Compute the function info and LLVM type.
3795  llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3796 
3797  // Get or create the prototype for the function.
3798  if (!GV || (GV->getType()->getElementType() != Ty))
3799  GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
3800  /*DontDefer=*/true,
3801  ForDefinition));
3802 
3803  // Already emitted.
3804  if (!GV->isDeclaration())
3805  return;
3806 
3807  // We need to set linkage and visibility on the function before
3808  // generating code for it because various parts of IR generation
3809  // want to propagate this information down (e.g. to local static
3810  // declarations).
3811  auto *Fn = cast<llvm::Function>(GV);
3812  setFunctionLinkage(GD, Fn);
3813 
3814  // FIXME: this is redundant with part of setFunctionDefinitionAttributes
3815  setGVProperties(Fn, GD);
3816 
3818 
3819 
3820  maybeSetTrivialComdat(*D, *Fn);
3821 
3822  CodeGenFunction(*this).GenerateCode(D, Fn, FI);
3823 
3824  setNonAliasAttributes(GD, Fn);
3826 
3827  if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
3828  AddGlobalCtor(Fn, CA->getPriority());
3829  if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
3830  AddGlobalDtor(Fn, DA->getPriority());
3831  if (D->hasAttr<AnnotateAttr>())
3832  AddGlobalAnnotations(D, Fn);
3833 
3834  if (D->isCPUSpecificMultiVersion()) {
3835  auto *Spec = D->getAttr<CPUSpecificAttr>();
3836  // If there is another specific version we need to emit, do so here.
3837  if (Spec->ActiveArgIndex + 1 < Spec->cpus_size()) {
3838  ++Spec->ActiveArgIndex;
3839  EmitGlobalFunctionDefinition(GD, nullptr);
3840  }
3841  }
3842 }
3843 
3844 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
3845  const auto *D = cast<ValueDecl>(GD.getDecl());
3846  const AliasAttr *AA = D->getAttr<AliasAttr>();
3847  assert(AA && "Not an alias?");
3848 
3849  StringRef MangledName = getMangledName(GD);
3850 
3851  if (AA->getAliasee() == MangledName) {
3852  Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3853  return;
3854  }
3855 
3856  // If there is a definition in the module, then it wins over the alias.
3857  // This is dubious, but allow it to be safe. Just ignore the alias.
3858  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3859  if (Entry && !Entry->isDeclaration())
3860  return;
3861 
3862  Aliases.push_back(GD);
3863 
3864  llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3865 
3866  // Create a reference to the named value. This ensures that it is emitted
3867  // if a deferred decl.
3868  llvm::Constant *Aliasee;
3869  if (isa<llvm::FunctionType>(DeclTy))
3870  Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
3871  /*ForVTable=*/false);
3872  else
3873  Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
3874  llvm::PointerType::getUnqual(DeclTy),
3875  /*D=*/nullptr);
3876 
3877  // Create the new alias itself, but don't set a name yet.
3878  auto *GA = llvm::GlobalAlias::create(
3879  DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
3880 
3881  if (Entry) {
3882  if (GA->getAliasee() == Entry) {
3883  Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3884  return;
3885  }
3886 
3887  assert(Entry->isDeclaration());
3888 
3889  // If there is a declaration in the module, then we had an extern followed
3890  // by the alias, as in:
3891  // extern int test6();
3892  // ...
3893  // int test6() __attribute__((alias("test7")));
3894  //
3895  // Remove it and replace uses of it with the alias.
3896  GA->takeName(Entry);
3897 
3898  Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
3899  Entry->getType()));
3900  Entry->eraseFromParent();
3901  } else {
3902  GA->setName(MangledName);
3903  }
3904 
3905  // Set attributes which are particular to an alias; this is a
3906  // specialization of the attributes which may be set on a global
3907  // variable/function.
3908  if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
3909  D->isWeakImported()) {
3910  GA->setLinkage(llvm::Function::WeakAnyLinkage);
3911  }
3912 
3913  if (const auto *VD = dyn_cast<VarDecl>(D))
3914  if (VD->getTLSKind())
3915  setTLSMode(GA, *VD);
3916 
3917  SetCommonAttributes(GD, GA);
3918 }
3919 
3920 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
3921  const auto *D = cast<ValueDecl>(GD.getDecl());
3922  const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
3923  assert(IFA && "Not an ifunc?");
3924 
3925  StringRef MangledName = getMangledName(GD);
3926 
3927  if (IFA->getResolver() == MangledName) {
3928  Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3929  return;
3930  }
3931 
3932  // Report an error if some definition overrides ifunc.
3933  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3934  if (Entry && !Entry->isDeclaration()) {
3935  GlobalDecl OtherGD;
3936  if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3937  DiagnosedConflictingDefinitions.insert(GD).second) {
3938  Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
3939  << MangledName;
3940  Diags.Report(OtherGD.getDecl()->getLocation(),
3941  diag::note_previous_definition);
3942  }
3943  return;
3944  }
3945 
3946  Aliases.push_back(GD);
3947 
3948  llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3949  llvm::Constant *Resolver =
3950  GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3951  /*ForVTable=*/false);
3952  llvm::GlobalIFunc *GIF =
3954  "", Resolver, &getModule());
3955  if (Entry) {
3956  if (GIF->getResolver() == Entry) {
3957  Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3958  return;
3959  }
3960  assert(Entry->isDeclaration());
3961 
3962  // If there is a declaration in the module, then we had an extern followed
3963  // by the ifunc, as in:
3964  // extern int test();
3965  // ...
3966  // int test() __attribute__((ifunc("resolver")));
3967  //
3968  // Remove it and replace uses of it with the ifunc.
3969  GIF->takeName(Entry);
3970 
3971  Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3972  Entry->getType()));
3973  Entry->eraseFromParent();
3974  } else
3975  GIF->setName(MangledName);
3976 
3977  SetCommonAttributes(GD, GIF);
3978 }
3979 
3980 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
3981  ArrayRef<llvm::Type*> Tys) {
3982  return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
3983  Tys);
3984 }
3985 
3986 static llvm::StringMapEntry<llvm::GlobalVariable *> &
3987 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
3988  const StringLiteral *Literal, bool TargetIsLSB,
3989  bool &IsUTF16, unsigned &StringLength) {
3990  StringRef String = Literal->getString();
3991  unsigned NumBytes = String.size();
3992 
3993  // Check for simple case.
3994  if (!Literal->containsNonAsciiOrNull()) {
3995  StringLength = NumBytes;
3996  return *Map.insert(std::make_pair(String, nullptr)).first;
3997  }
3998 
3999  // Otherwise, convert the UTF8 literals into a string of shorts.
4000  IsUTF16 = true;
4001 
4002  SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
4003  const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
4004  llvm::UTF16 *ToPtr = &ToBuf[0];
4005 
4006  (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4007  ToPtr + NumBytes, llvm::strictConversion);
4008 
4009  // ConvertUTF8toUTF16 returns the length in ToPtr.
4010  StringLength = ToPtr - &ToBuf[0];
4011 
4012  // Add an explicit null.
4013  *ToPtr = 0;
4014  return *Map.insert(std::make_pair(
4015  StringRef(reinterpret_cast<const char *>(ToBuf.data()),
4016  (StringLength + 1) * 2),
4017  nullptr)).first;
4018 }
4019 
4022  unsigned StringLength = 0;
4023  bool isUTF16 = false;
4024  llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
4025  GetConstantCFStringEntry(CFConstantStringMap, Literal,
4026  getDataLayout().isLittleEndian(), isUTF16,
4027  StringLength);
4028 
4029  if (auto *C = Entry.second)
4030  return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
4031 
4032  llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
4033  llvm::Constant *Zeros[] = { Zero, Zero };
4034 
4035  // If we don't already have it, get __CFConstantStringClassReference.
4036  if (!CFConstantStringClassRef) {
4038  Ty = llvm::ArrayType::get(Ty, 0);
4039  llvm::GlobalValue *GV = cast<llvm::GlobalValue>(
4040  CreateRuntimeVariable(Ty, "__CFConstantStringClassReference"));
4041 
4042  if (getTriple().isOSBinFormatCOFF()) {
4043  IdentifierInfo &II = getContext().Idents.get(GV->getName());
4046 
4047  const VarDecl *VD = nullptr;
4048  for (const auto &Result : DC->lookup(&II))
4049  if ((VD = dyn_cast<VarDecl>(Result)))
4050  break;
4051 
4052  if (!VD || !VD->hasAttr<DLLExportAttr>()) {
4053  GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
4054  GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4055  } else {
4056  GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
4057  GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4058  }
4059  }
4060  setDSOLocal(GV);
4061 
4062  // Decay array -> ptr
4063  CFConstantStringClassRef =
4064  llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
4065  }
4066 
4068 
4069  auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
4070 
4071  ConstantInitBuilder Builder(*this);
4072  auto Fields = Builder.beginStruct(STy);
4073 
4074  // Class pointer.
4075  Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
4076 
4077  // Flags.
4078  Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
4079 
4080  // String pointer.
4081  llvm::Constant *C = nullptr;
4082  if (isUTF16) {
4083  auto Arr = llvm::makeArrayRef(
4084  reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
4085  Entry.first().size() / 2);
4086  C = llvm::ConstantDataArray::get(VMContext, Arr);
4087  } else {
4088  C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
4089  }
4090 
4091  // Note: -fwritable-strings doesn't make the backing store strings of
4092  // CFStrings writable. (See <rdar://problem/10657500>)
4093  auto *GV =
4094  new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
4095  llvm::GlobalValue::PrivateLinkage, C, ".str");
4096  GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4097  // Don't enforce the target's minimum global alignment, since the only use
4098  // of the string is via this class initializer.
4099  CharUnits Align = isUTF16
4102  GV->setAlignment(Align.getQuantity());
4103 
4104  // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
4105  // Without it LLVM can merge the string with a non unnamed_addr one during
4106  // LTO. Doing that changes the section it ends in, which surprises ld64.
4107  if (getTriple().isOSBinFormatMachO())
4108  GV->setSection(isUTF16 ? "__TEXT,__ustring"
4109  : "__TEXT,__cstring,cstring_literals");
4110 
4111  // String.
4112  llvm::Constant *Str =
4113  llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
4114 
4115  if (isUTF16)
4116  // Cast the UTF16 string to the correct type.
4117  Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
4118  Fields.add(Str);
4119 
4120  // String length.
4121  auto Ty = getTypes().ConvertType(getContext().LongTy);
4122  Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
4123 
4124  CharUnits Alignment = getPointerAlign();
4125 
4126  // The struct.
4127  GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
4128  /*isConstant=*/false,
4129  llvm::GlobalVariable::PrivateLinkage);
4130  switch (getTriple().getObjectFormat()) {
4131  case llvm::Triple::UnknownObjectFormat:
4132  llvm_unreachable("unknown file format");
4133  case llvm::Triple::COFF:
4134  case llvm::Triple::ELF:
4135  case llvm::Triple::Wasm:
4136  GV->setSection("cfstring");
4137  break;
4138  case llvm::Triple::MachO:
4139  GV->setSection("__DATA,__cfstring");
4140  break;
4141  }
4142  Entry.second = GV;
4143 
4144  return ConstantAddress(GV, Alignment);
4145 }
4146 
4148  return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
4149 }
4150 
4152  if (ObjCFastEnumerationStateType.isNull()) {
4153  RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
4154  D->startDefinition();
4155 
4156  QualType FieldTypes[] = {
4157  Context.UnsignedLongTy,
4158  Context.getPointerType(Context.getObjCIdType()),
4159  Context.getPointerType(Context.UnsignedLongTy),
4160  Context.getConstantArrayType(Context.UnsignedLongTy,
4161  llvm::APInt(32, 5), ArrayType::Normal, 0)
4162  };
4163 
4164  for (size_t i = 0; i < 4; ++i) {
4165  FieldDecl *Field = FieldDecl::Create(Context,
4166  D,
4167  SourceLocation(),
4168  SourceLocation(), nullptr,
4169  FieldTypes[i], /*TInfo=*/nullptr,
4170  /*BitWidth=*/nullptr,
4171  /*Mutable=*/false,
4172  ICIS_NoInit);
4173  Field->setAccess(AS_public);
4174  D->addDecl(Field);
4175  }
4176 
4177  D->completeDefinition();
4178  ObjCFastEnumerationStateType = Context.getTagDeclType(D);
4179  }
4180 
4181  return ObjCFastEnumerationStateType;
4182 }
4183 
4184 llvm::Constant *
4186  assert(!E->getType()->isPointerType() && "Strings are always arrays");
4187 
4188  // Don't emit it as the address of the string, emit the string data itself
4189  // as an inline array.
4190  if (E->getCharByteWidth() == 1) {
4191  SmallString<64> Str(E->getString());
4192 
4193  // Resize the string to the right size, which is indicated by its type.
4194  const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
4195  Str.resize(CAT->getSize().getZExtValue());
4196  return llvm::ConstantDataArray::getString(VMContext, Str, false);
4197  }
4198 
4199  auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
4200  llvm::Type *ElemTy = AType->getElementType();
4201  unsigned NumElements = AType->getNumElements();
4202 
4203  // Wide strings have either 2-byte or 4-byte elements.
4204  if (ElemTy->getPrimitiveSizeInBits() == 16) {
4205  SmallVector<uint16_t, 32> Elements;
4206  Elements.reserve(NumElements);
4207 
4208  for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4209  Elements.push_back(E->getCodeUnit(i));
4210  Elements.resize(NumElements);
4211  return llvm::ConstantDataArray::get(VMContext, Elements);
4212  }
4213 
4214  assert(ElemTy->getPrimitiveSizeInBits() == 32);
4215  SmallVector<uint32_t, 32> Elements;
4216  Elements.reserve(NumElements);
4217 
4218  for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4219  Elements.push_back(E->getCodeUnit(i));
4220  Elements.resize(NumElements);
4221  return llvm::ConstantDataArray::get(VMContext, Elements);
4222 }
4223 
4224 static llvm::GlobalVariable *
4225 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
4226  CodeGenModule &CGM, StringRef GlobalName,
4227  CharUnits Alignment) {
4228  unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
4230 
4231  llvm::Module &M = CGM.getModule();
4232  // Create a global variable for this string
4233  auto *GV = new llvm::GlobalVariable(
4234  M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
4235  nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
4236  GV->setAlignment(Alignment.getQuantity());
4237  GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4238  if (GV->isWeakForLinker()) {
4239  assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
4240  GV->setComdat(M.getOrInsertComdat(GV->getName()));
4241  }
4242  CGM.setDSOLocal(GV);
4243 
4244  return GV;
4245 }
4246 
4247 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
4248 /// constant array for the given string literal.
4251  StringRef Name) {
4253 
4254  llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
4255  llvm::GlobalVariable **Entry = nullptr;
4256  if (!LangOpts.WritableStrings) {
4257  Entry = &ConstantStringMap[C];
4258  if (auto GV = *Entry) {
4259  if (Alignment.getQuantity() > GV->getAlignment())
4260  GV->setAlignment(Alignment.getQuantity());
4261  return ConstantAddress(GV, Alignment);
4262  }
4263  }
4264 
4265  SmallString<256> MangledNameBuffer;
4266  StringRef GlobalVariableName;
4267  llvm::GlobalValue::LinkageTypes LT;
4268 
4269  // Mangle the string literal if the ABI allows for it. However, we cannot
4270  // do this if we are compiling with ASan or -fwritable-strings because they
4271  // rely on strings having normal linkage.
4272  if (!LangOpts.WritableStrings &&
4273  !LangOpts.Sanitize.has(SanitizerKind::Address) &&
4275  llvm::raw_svector_ostream Out(MangledNameBuffer);
4277 
4278  LT = llvm::GlobalValue::LinkOnceODRLinkage;
4279  GlobalVariableName = MangledNameBuffer;
4280  } else {
4281  LT = llvm::GlobalValue::PrivateLinkage;
4282  GlobalVariableName = Name;
4283  }
4284 
4285  auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
4286  if (Entry)
4287  *Entry = GV;
4288 
4289  SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
4290  QualType());
4291 
4293  Alignment);
4294 }
4295 
4296 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
4297 /// array for the given ObjCEncodeExpr node.
4300  std::string Str;
4302 
4303  return GetAddrOfConstantCString(Str);
4304 }
4305 
4306 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
4307 /// the literal and a terminating '\0' character.
4308 /// The result has pointer to array type.
4310  const std::string &Str, const char *GlobalName) {
4311  StringRef StrWithNull(Str.c_str(), Str.size() + 1);
4312  CharUnits Alignment =
4314 
4315  llvm::Constant *C =
4316  llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
4317 
4318  // Don't share any string literals if strings aren't constant.
4319  llvm::GlobalVariable **Entry = nullptr;
4320  if (!LangOpts.WritableStrings) {
4321  Entry = &ConstantStringMap[C];
4322  if (auto GV = *Entry) {
4323  if (Alignment.getQuantity() > GV->getAlignment())
4324  GV->setAlignment(Alignment.getQuantity());
4325  return ConstantAddress(GV, Alignment);
4326  }
4327  }
4328 
4329  // Get the default prefix if a name wasn't specified.
4330  if (!GlobalName)
4331  GlobalName = ".str";
4332  // Create a global variable for this.
4333  auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
4334  GlobalName, Alignment);
4335  if (Entry)
4336  *Entry = GV;
4337 
4339  Alignment);
4340 }
4341 
4343  const MaterializeTemporaryExpr *E, const Expr *Init) {
4344  assert((E->getStorageDuration() == SD_Static ||
4345  E->getStorageDuration() == SD_Thread) && "not a global temporary");
4346  const auto *VD = cast<VarDecl>(E->getExtendingDecl());
4347 
4348  // If we're not materializing a subobject of the temporary, keep the
4349  // cv-qualifiers from the type of the MaterializeTemporaryExpr.
4350  QualType MaterializedType = Init->getType();
4351  if (Init == E->GetTemporaryExpr())
4352  MaterializedType = E->getType();
4353 
4354  CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
4355 
4356  if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
4357  return ConstantAddress(Slot, Align);
4358 
4359  // FIXME: If an externally-visible declaration extends multiple temporaries,
4360  // we need to give each temporary the same name in every translation unit (and
4361  // we also need to make the temporaries externally-visible).
4362  SmallString<256> Name;
4363  llvm::raw_svector_ostream Out(Name);
4365  VD, E->getManglingNumber(), Out);
4366 
4367  APValue *Value = nullptr;
4368  if (E->getStorageDuration() == SD_Static) {
4369  // We might have a cached constant initializer for this temporary. Note
4370  // that this might have a different value from the value computed by
4371  // evaluating the initializer if the surrounding constant expression
4372  // modifies the temporary.
4373  Value = getContext().getMaterializedTemporaryValue(E, false);
4374  if (Value && Value->isUninit())
4375  Value = nullptr;
4376  }
4377 
4378  // Try evaluating it now, it might have a constant initializer.
4379  Expr::EvalResult EvalResult;
4380  if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
4381  !EvalResult.hasSideEffects())
4382  Value = &EvalResult.Val;
4383 
4384  LangAS AddrSpace =
4385  VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
4386 
4387  Optional<ConstantEmitter> emitter;
4388  llvm::Constant *InitialValue = nullptr;
4389  bool Constant = false;
4390  llvm::Type *Type;
4391  if (Value) {
4392  // The temporary has a constant initializer, use it.
4393  emitter.emplace(*this);
4394  InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
4395  MaterializedType);
4396  Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
4397  Type = InitialValue->getType();
4398  } else {
4399  // No initializer, the initialization will be provided when we
4400  // initialize the declaration which performed lifetime extension.
4401  Type = getTypes().ConvertTypeForMem(MaterializedType);
4402  }
4403 
4404  // Create a global variable for this lifetime-extended temporary.
4405  llvm::GlobalValue::LinkageTypes Linkage =
4406  getLLVMLinkageVarDefinition(VD, Constant);
4407  if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
4408  const VarDecl *InitVD;
4409  if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
4410  isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
4411  // Temporaries defined inside a class get linkonce_odr linkage because the
4412  // class can be defined in multiple translation units.
4413  Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
4414  } else {
4415  // There is no need for this temporary to have external linkage if the
4416  // VarDecl has external linkage.
4418  }
4419  }
4420  auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
4421  auto *GV = new llvm::GlobalVariable(
4422  getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
4423  /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
4424  if (emitter) emitter->finalize(GV);
4425  setGVProperties(GV, VD);
4426  GV->setAlignment(Align.getQuantity());
4427  if (supportsCOMDAT() && GV->isWeakForLinker())
4428  GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4429  if (VD->getTLSKind())
4430  setTLSMode(GV, *VD);
4431  llvm::Constant *CV = GV;
4432  if (AddrSpace != LangAS::Default)
4434  *this, GV, AddrSpace, LangAS::Default,
4435  Type->getPointerTo(
4436  getContext().getTargetAddressSpace(LangAS::Default)));
4437  MaterializedGlobalTemporaryMap[E] = CV;
4438  return ConstantAddress(CV, Align);
4439 }
4440 
4441 /// EmitObjCPropertyImplementations - Emit information for synthesized
4442 /// properties for an implementation.
4443 void CodeGenModule::EmitObjCPropertyImplementations(const
4445  for (const auto *PID : D->property_impls()) {
4446  // Dynamic is just for type-checking.
4447  if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
4448  ObjCPropertyDecl *PD = PID->getPropertyDecl();
4449 
4450  // Determine which methods need to be implemented, some may have
4451  // been overridden. Note that ::isPropertyAccessor is not the method
4452  // we want, that just indicates if the decl came from a
4453  // property. What we want to know is if the method is defined in
4454  // this implementation.
4455  if (!D->getInstanceMethod(PD->getGetterName()))
4457  const_cast<ObjCImplementationDecl *>(D), PID);
4458  if (!PD->isReadOnly() &&
4459  !D->getInstanceMethod(PD->getSetterName()))
4461  const_cast<ObjCImplementationDecl *>(D), PID);
4462  }
4463  }
4464 }
4465 
4467  const ObjCInterfaceDecl *iface = impl->getClassInterface();
4468  for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
4469  ivar; ivar = ivar->getNextIvar())
4470  if (ivar->getType().isDestructedType())
4471  return true;
4472 
4473  return false;
4474 }
4475 
4478  CodeGenFunction CGF(CGM);
4480  E = D->init_end(); B != E; ++B) {
4481  CXXCtorInitializer *CtorInitExp = *B;
4482  Expr *Init = CtorInitExp->getInit();
4483  if (!CGF.isTrivialInitializer(Init))
4484  return false;
4485  }
4486  return true;
4487 }
4488 
4489 /// EmitObjCIvarInitializations - Emit information for ivar initialization
4490 /// for an implementation.
4491 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
4492  // We might need a .cxx_destruct even if we don't have any ivar initializers.
4493  if (needsDestructMethod(D)) {
4494  IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
4495  Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
4496  ObjCMethodDecl *DTORMethod =
4498  cxxSelector, getContext().VoidTy, nullptr, D,
4499  /*isInstance=*/true, /*isVariadic=*/false,
4500  /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
4501  /*isDefined=*/false, ObjCMethodDecl::Required);
4502  D->addInstanceMethod(DTORMethod);
4503  CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
4504  D->setHasDestructors(true);
4505  }
4506 
4507  // If the implementation doesn't have any ivar initializers, we don't need
4508  // a .cxx_construct.
4509  if (D->getNumIvarInitializers() == 0 ||
4510  AllTrivialInitializers(*this, D))
4511  return;
4512 
4513  IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
4514  Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
4515  // The constructor returns 'self'.
4517  D->getLocation(),
4518  D->getLocation(),
4519  cxxSelector,
4521  nullptr, D, /*isInstance=*/true,
4522  /*isVariadic=*/false,
4523  /*isPropertyAccessor=*/true,
4524  /*isImplicitlyDeclared=*/true,
4525  /*isDefined=*/false,
4527  D->addInstanceMethod(CTORMethod);
4528  CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
4529  D->setHasNonZeroConstructors(true);
4530 }
4531 
4532 // EmitLinkageSpec - Emit all declarations in a linkage spec.
4533 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
4534  if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
4536  ErrorUnsupported(LSD, "linkage spec");
4537  return;
4538  }
4539 
4540  EmitDeclContext(LSD);
4541 }
4542 
4543 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
4544  for (auto *I : DC->decls()) {
4545  // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
4546  // are themselves considered "top-level", so EmitTopLevelDecl on an
4547  // ObjCImplDecl does not recursively visit them. We need to do that in
4548  // case they're nested inside another construct (LinkageSpecDecl /
4549  // ExportDecl) that does stop them from being considered "top-level".
4550  if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
4551  for (auto *M : OID->methods())
4552  EmitTopLevelDecl(M);
4553  }
4554 
4555  EmitTopLevelDecl(I);
4556  }
4557 }
4558 
4559 /// EmitTopLevelDecl - Emit code for a single top level declaration.
4561  // Ignore dependent declarations.
4562  if (D->isTemplated())
4563  return;
4564 
4565  switch (D->getKind()) {
4566  case Decl::CXXConversion:
4567  case Decl::CXXMethod:
4568  case Decl::Function:
4569  EmitGlobal(cast<FunctionDecl>(D));
4570  // Always provide some coverage mapping
4571  // even for the functions that aren't emitted.
4573  break;
4574 
4575  case Decl::CXXDeductionGuide:
4576  // Function-like, but does not result in code emission.
4577  break;
4578 
4579  case Decl::Var:
4580  case Decl::Decomposition:
4581  case Decl::VarTemplateSpecialization:
4582  EmitGlobal(cast<VarDecl>(D));
4583  if (auto *DD = dyn_cast<DecompositionDecl>(D))
4584  for (auto *B : DD->bindings())
4585  if (auto *HD = B->getHoldingVar())
4586  EmitGlobal(HD);
4587  break;
4588 
4589  // Indirect fields from global anonymous structs and unions can be
4590  // ignored; only the actual variable requires IR gen support.
4591  case Decl::IndirectField:
4592  break;
4593 
4594  // C++ Decls
4595  case Decl::Namespace:
4596  EmitDeclContext(cast<NamespaceDecl>(D));
4597  break;
4598  case Decl::ClassTemplateSpecialization: {
4599  const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
4600  if (DebugInfo &&
4601  Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
4602  Spec->hasDefinition())
4603  DebugInfo->completeTemplateDefinition(*Spec);
4604  } LLVM_FALLTHROUGH;
4605  case Decl::CXXRecord:
4606  if (DebugInfo) {
4607  if (auto *ES = D->getASTContext().getExternalSource())
4608  if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
4609  DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
4610  }
4611  // Emit any static data members, they may be definitions.
4612  for (auto *I : cast<CXXRecordDecl>(D)->decls())
4613  if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
4614  EmitTopLevelDecl(I);
4615  break;
4616  // No code generation needed.
4617  case Decl::UsingShadow:
4618  case Decl::ClassTemplate:
4619  case Decl::VarTemplate:
4620  case Decl::VarTemplatePartialSpecialization:
4621  case Decl::FunctionTemplate:
4622  case Decl::TypeAliasTemplate:
4623  case Decl::Block:
4624  case Decl::Empty:
4625  break;
4626  case Decl::Using: // using X; [C++]
4627  if (CGDebugInfo *DI = getModuleDebugInfo())
4628  DI->EmitUsingDecl(cast<UsingDecl>(*D));
4629  return;
4630  case Decl::NamespaceAlias:
4631  if (CGDebugInfo *DI = getModuleDebugInfo())
4632  DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
4633  return;
4634  case Decl::UsingDirective: // using namespace X; [C++]
4635  if (CGDebugInfo *DI = getModuleDebugInfo())
4636  DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
4637  return;
4638  case Decl::CXXConstructor:
4639  getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
4640  break;
4641  case Decl::CXXDestructor:
4642  getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
4643  break;
4644 
4645  case Decl::StaticAssert:
4646  // Nothing to do.
4647  break;
4648 
4649  // Objective-C Decls
4650 
4651  // Forward declarations, no (immediate) code generation.
4652  case Decl::ObjCInterface:
4653  case Decl::ObjCCategory:
4654  break;
4655 
4656  case Decl::ObjCProtocol: {
4657  auto *Proto = cast<ObjCProtocolDecl>(D);
4658  if (Proto->isThisDeclarationADefinition())
4659  ObjCRuntime->GenerateProtocol(Proto);
4660  break;
4661  }
4662 
4663  case Decl::ObjCCategoryImpl:
4664  // Categories have properties but don't support synthesize so we
4665  // can ignore them here.
4666  ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
4667  break;
4668 
4669  case Decl::ObjCImplementation: {
4670  auto *OMD = cast<ObjCImplementationDecl>(D);
4671  EmitObjCPropertyImplementations(OMD);
4672  EmitObjCIvarInitializations(OMD);
4673  ObjCRuntime->GenerateClass(OMD);
4674  // Emit global variable debug information.
4675  if (CGDebugInfo *DI = getModuleDebugInfo())
4676  if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
4677  DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
4678  OMD->getClassInterface()), OMD->getLocation());
4679  break;
4680  }
4681  case Decl::ObjCMethod: {
4682  auto *OMD = cast<ObjCMethodDecl>(D);
4683  // If this is not a prototype, emit the body.
4684  if (OMD->getBody())
4685  CodeGenFunction(*this).GenerateObjCMethod(OMD);
4686  break;
4687  }
4688  case Decl::ObjCCompatibleAlias:
4689  ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
4690  break;
4691 
4692  case Decl::PragmaComment: {
4693  const auto *PCD = cast<PragmaCommentDecl>(D);
4694  switch (PCD->getCommentKind()) {
4695  case PCK_Unknown:
4696  llvm_unreachable("unexpected pragma comment kind");
4697  case PCK_Linker:
4698  AppendLinkerOptions(PCD->getArg());
4699  break;
4700  case PCK_Lib:
4701  if (getTarget().getTriple().isOSBinFormatELF() &&
4702  !getTarget().getTriple().isPS4())
4703  AddELFLibDirective(PCD->getArg());
4704  else
4705  AddDependentLib(PCD->getArg());
4706  break;
4707  case PCK_Compiler:
4708  case PCK_ExeStr:
4709  case PCK_User:
4710  break; // We ignore all of these.
4711  }
4712  break;
4713  }
4714 
4715  case Decl::PragmaDetectMismatch: {
4716  const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
4717  AddDetectMismatch(PDMD->getName(), PDMD->getValue());
4718  break;
4719  }
4720 
4721  case Decl::LinkageSpec:
4722  EmitLinkageSpec(cast<LinkageSpecDecl>(D));
4723  break;
4724 
4725  case Decl::FileScopeAsm: {
4726  // File-scope asm is ignored during device-side CUDA compilation.
4727  if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
4728  break;
4729  // File-scope asm is ignored during device-side OpenMP compilation.
4730  if (LangOpts.OpenMPIsDevice)
4731  break;
4732  auto *AD = cast<FileScopeAsmDecl>(D);
4733  getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
4734  break;
4735  }
4736 
4737  case Decl::Import: {
4738  auto *Import = cast<ImportDecl>(D);
4739 
4740  // If we've already imported this module, we're done.
4741  if (!ImportedModules.insert(Import->getImportedModule()))
4742  break;
4743 
4744  // Emit debug information for direct imports.
4745  if (!Import->getImportedOwningModule()) {
4746  if (CGDebugInfo *DI = getModuleDebugInfo())
4747  DI->EmitImportDecl(*Import);
4748  }
4749 
4750  // Find all of the submodules and emit the module initializers.
4751  llvm::SmallPtrSet<clang::Module *, 16> Visited;
4753  Visited.insert(Import->getImportedModule());
4754  Stack.push_back(Import->getImportedModule());
4755 
4756  while (!Stack.empty()) {
4757  clang::Module *Mod = Stack.pop_back_val();
4758  if (!EmittedModuleInitializers.insert(Mod).second)
4759  continue;
4760 
4761  for (auto *D : Context.getModuleInitializers(Mod))
4762  EmitTopLevelDecl(D);
4763 
4764  // Visit the submodules of this module.
4766  SubEnd = Mod->submodule_end();
4767  Sub != SubEnd; ++Sub) {
4768  // Skip explicit children; they need to be explicitly imported to emit
4769  // the initializers.
4770  if ((*Sub)->IsExplicit)
4771  continue;
4772 
4773  if (Visited.insert(*Sub).second)
4774  Stack.push_back(*Sub);
4775  }
4776  }
4777  break;
4778  }
4779 
4780  case Decl::Export:
4781  EmitDeclContext(cast<ExportDecl>(D));
4782  break;
4783 
4784  case Decl::OMPThreadPrivate:
4785  EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
4786  break;
4787 
4788  case Decl::OMPDeclareReduction:
4789  EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
4790  break;
4791 
4792  default:
4793  // Make sure we handled everything we should, every other kind is a
4794  // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
4795  // function. Need to recode Decl::Kind to do that easily.
4796  assert(isa<TypeDecl>(D) && "Unsupported decl kind");
4797  break;
4798  }
4799 }
4800 
4802  // Do we need to generate coverage mapping?
4803  if (!CodeGenOpts.CoverageMapping)
4804  return;
4805  switch (D->getKind()) {
4806  case Decl::CXXConversion:
4807  case Decl::CXXMethod:
4808  case Decl::Function:
4809  case Decl::ObjCMethod:
4810  case Decl::CXXConstructor:
4811  case Decl::CXXDestructor: {
4812  if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
4813  return;
4815  if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getLocStart()))
4816  return;
4817  auto I = DeferredEmptyCoverageMappingDecls.find(D);
4818  if (I == DeferredEmptyCoverageMappingDecls.end())
4819  DeferredEmptyCoverageMappingDecls[D] = true;
4820  break;
4821  }
4822  default:
4823  break;
4824  };
4825 }
4826 
4828  // Do we need to generate coverage mapping?
4829  if (!CodeGenOpts.CoverageMapping)
4830  return;
4831  if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
4832  if (Fn->isTemplateInstantiation())
4833  ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
4834  }
4835  auto I = DeferredEmptyCoverageMappingDecls.find(D);
4836  if (I == DeferredEmptyCoverageMappingDecls.end())
4837  DeferredEmptyCoverageMappingDecls[D] = false;
4838  else
4839  I->second = false;
4840 }
4841 
4843  // We call takeVector() here to avoid use-after-free.
4844  // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
4845  // we deserialize function bodies to emit coverage info for them, and that
4846  // deserializes more declarations. How should we handle that case?
4847  for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
4848  if (!Entry.second)
4849  continue;
4850  const Decl *D = Entry.first;
4851  switch (D->getKind()) {
4852  case Decl::CXXConversion:
4853  case Decl::CXXMethod:
4854  case Decl::Function:
4855  case Decl::ObjCMethod: {
4856  CodeGenPGO PGO(*this);
4857  GlobalDecl GD(cast<FunctionDecl>(D));
4859  getFunctionLinkage(GD));
4860  break;
4861  }
4862  case Decl::CXXConstructor: {
4863  CodeGenPGO PGO(*this);
4864  GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
4866  getFunctionLinkage(GD));
4867  break;
4868  }
4869  case Decl::CXXDestructor: {
4870  CodeGenPGO PGO(*this);
4871  GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
4873  getFunctionLinkage(GD));
4874  break;
4875  }
4876  default:
4877  break;
4878  };
4879  }
4880 }
4881 
4882 /// Turns the given pointer into a constant.
4883 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4884  const void *Ptr) {
4885  uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
4886  llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
4887  return llvm::ConstantInt::get(i64, PtrInt);
4888 }
4889 
4891  llvm::NamedMDNode *&GlobalMetadata,
4892  GlobalDecl D,
4893  llvm::GlobalValue *Addr) {
4894  if (!GlobalMetadata)
4895  GlobalMetadata =
4896  CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4897 
4898  // TODO: should we report variant information for ctors/dtors?
4899  llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
4900  llvm::ConstantAsMetadata::get(GetPointerConstant(
4901  CGM.getLLVMContext(), D.getDecl()))};
4902  GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
4903 }
4904 
4905 /// For each function which is declared within an extern "C" region and marked
4906 /// as 'used', but has internal linkage, create an alias from the unmangled
4907 /// name to the mangled name if possible. People expect to be able to refer
4908 /// to such functions with an unmangled name from inline assembly within the
4909 /// same translation unit.
4910 void CodeGenModule::EmitStaticExternCAliases() {
4911  if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
4912  return;
4913  for (auto &I : StaticExternCValues) {
4914  IdentifierInfo *Name = I.first;
4915  llvm::GlobalValue *Val = I.second;
4916  if (Val && !getModule().getNamedValue(Name->getName()))
4918  }
4919 }
4920 
4921 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
4922  GlobalDecl &Result) const {
4923  auto Res = Manglings.find(MangledName);
4924  if (Res == Manglings.end())
4925  return false;
4926  Result = Res->getValue();
4927  return true;
4928 }
4929 
4930 /// Emits metadata nodes associating all the global values in the
4931 /// current module with the Decls they came from. This is useful for
4932 /// projects using IR gen as a subroutine.
4933 ///
4934 /// Since there's currently no way to associate an MDNode directly
4935 /// with an llvm::GlobalValue, we create a global named metadata
4936 /// with the name 'clang.global.decl.ptrs'.
4937 void CodeGenModule::EmitDeclMetadata() {
4938  llvm::NamedMDNode *GlobalMetadata = nullptr;
4939 
4940  for (auto &I : MangledDeclNames) {
4941  llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
4942  // Some mangled names don't necessarily have an associated GlobalValue
4943  // in this module, e.g. if we mangled it for DebugInfo.
4944  if (Addr)
4945  EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
4946  }
4947 }
4948 
4949 /// Emits metadata nodes for all the local variables in the current
4950 /// function.
4951 void CodeGenFunction::EmitDeclMetadata() {
4952  if (LocalDeclMap.empty()) return;
4953 
4954  llvm::LLVMContext &Context = getLLVMContext();
4955 
4956  // Find the unique metadata ID for this name.
4957  unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
4958 
4959  llvm::NamedMDNode *GlobalMetadata = nullptr;
4960 
4961  for (auto &I : LocalDeclMap) {
4962  const Decl *D = I.first;
4963  llvm::Value *Addr = I.second.getPointer();
4964  if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
4966  Alloca->setMetadata(
4967  DeclPtrKind, llvm::MDNode::get(
4968  Context, llvm::ValueAsMetadata::getConstant(DAddr)));
4969  } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
4970  GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
4971  EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
4972  }
4973  }
4974 }
4975 
4976 void CodeGenModule::EmitVersionIdentMetadata() {
4977  llvm::NamedMDNode *IdentMetadata =
4978  TheModule.getOrInsertNamedMetadata("llvm.ident");
4979  std::string Version = getClangFullVersion();
4980  llvm::LLVMContext &Ctx = TheModule.getContext();
4981 
4982  llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
4983  IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4984 }
4985 
4986 void CodeGenModule::EmitTargetMetadata() {
4987  // Warning, new MangledDeclNames may be appended within this loop.
4988  // We rely on MapVector insertions adding new elements to the end
4989  // of the container.
4990  // FIXME: Move this loop into the one target that needs it, and only
4991  // loop over those declarations for which we couldn't emit the target
4992  // metadata when we emitted the declaration.
4993  for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
4994  auto Val = *(MangledDeclNames.begin() + I);
4995  const Decl *D = Val.first.getDecl()->getMostRecentDecl();
4996  llvm::GlobalValue *GV = GetGlobalValue(Val.second);
4997  getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
4998  }
4999 }
5000 
5001 void CodeGenModule::EmitCoverageFile() {
5002  if (getCodeGenOpts().CoverageDataFile.empty() &&
5004  return;
5005 
5006  llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
5007  if (!CUNode)
5008  return;
5009 
5010  llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
5011  llvm::LLVMContext &Ctx = TheModule.getContext();
5012  auto *CoverageDataFile =
5013  llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
5014  auto *CoverageNotesFile =
5015  llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
5016  for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
5017  llvm::MDNode *CU = CUNode->getOperand(i);
5018  llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
5019  GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
5020  }
5021 }
5022 
5023 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
5024  // Sema has checked that all uuid strings are of the form
5025  // "12345678-1234-1234-1234-1234567890ab".
5026  assert(Uuid.size() == 36);
5027  for (unsigned i = 0; i < 36; ++i) {
5028  if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
5029  else assert(isHexDigit(Uuid[i]));
5030  }
5031 
5032  // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
5033  const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
5034 
5035  llvm::Constant *Field3[8];
5036  for (unsigned Idx = 0; Idx < 8; ++Idx)
5037  Field3[Idx] = llvm::ConstantInt::get(
5038  Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
5039 
5040  llvm::Constant *Fields[4] = {
5041  llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
5042  llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
5043  llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
5044  llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
5045  };
5046 
5047  return llvm::ConstantStruct::getAnon(Fields);
5048 }
5049 
5051  bool ForEH) {
5052  // Return a bogus pointer if RTTI is disabled, unless it's for EH.
5053  // FIXME: should we even be calling this method if RTTI is disabled
5054  // and it's not for EH?
5055  if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice)
5056  return llvm::Constant::getNullValue(Int8PtrTy);
5057 
5058  if (ForEH && Ty->isObjCObjectPointerType() &&
5059  LangOpts.ObjCRuntime.isGNUFamily())
5060  return ObjCRuntime->GetEHType(Ty);
5061 
5062  return getCXXABI().getAddrOfRTTIDescriptor(Ty);
5063 }
5064 
5066  // Do not emit threadprivates in simd-only mode.
5067  if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
5068  return;
5069  for (auto RefExpr : D->varlists()) {
5070  auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
5071  bool PerformInit =
5072  VD->getAnyInitializer() &&
5073  !VD->getAnyInitializer()->isConstantInitializer(getContext(),
5074  /*ForRef=*/false);
5075 
5077  if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
5078  VD, Addr, RefExpr->getLocStart(), PerformInit))
5079  CXXGlobalInits.push_back(InitFunction);
5080  }
5081 }
5082 
5083 llvm::Metadata *
5084 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
5085  StringRef Suffix) {
5086  llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
5087  if (InternalId)
5088  return InternalId;
5089 
5090  if (isExternallyVisible(T->getLinkage())) {
5091  std::string OutName;
5092  llvm::raw_string_ostream Out(OutName);
5094  Out << Suffix;
5095 
5096  InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
5097  } else {
5098  InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
5100  }
5101 
5102  return InternalId;
5103 }
5104 
5106  return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
5107 }
5108 
5109 llvm::Metadata *
5111  return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
5112 }
5113 
5114 // Generalize pointer types to a void pointer with the qualifiers of the
5115 // originally pointed-to type, e.g. 'const char *' and 'char * const *'
5116 // generalize to 'const void *' while 'char *' and 'const char **' generalize to
5117 // 'void *'.
5119  if (!Ty->isPointerType())
5120  return Ty;
5121 
5122  return Ctx.getPointerType(
5124  Ty->getPointeeType().getCVRQualifiers()));
5125 }
5126 
5127 // Apply type generalization to a FunctionType's return and argument types
5129  if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
5130  SmallVector<QualType, 8> GeneralizedParams;
5131  for (auto &Param : FnType->param_types())
5132  GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
5133 
5134  return Ctx.getFunctionType(
5135  GeneralizeType(Ctx, FnType->getReturnType()),
5136  GeneralizedParams, FnType->getExtProtoInfo());
5137  }
5138 
5139  if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
5140  return Ctx.getFunctionNoProtoType(
5141  GeneralizeType(Ctx, FnType->getReturnType()));
5142 
5143  llvm_unreachable("Encountered unknown FunctionType");
5144 }
5145 
5147  return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
5148  GeneralizedMetadataIdMap, ".generalized");
5149 }
5150 
5151 /// Returns whether this module needs the "all-vtables" type identifier.
5153  // Returns true if at least one of vtable-based CFI checkers is enabled and
5154  // is not in the trapping mode.
5155  return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
5156  !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
5157  (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
5158  !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
5159  (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
5160  !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
5161  (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
5162  !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
5163 }
5164 
5165 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
5166  CharUnits Offset,
5167  const CXXRecordDecl *RD) {
5168  llvm::Metadata *MD =
5170  VTable->addTypeMetadata(Offset.getQuantity(), MD);
5171 
5172  if (CodeGenOpts.SanitizeCfiCrossDso)
5173  if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
5174  VTable->addTypeMetadata(Offset.getQuantity(),
5175  llvm::ConstantAsMetadata::get(CrossDsoTypeId));
5176 
5177  if (NeedAllVtablesTypeId()) {
5178  llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
5179  VTable->addTypeMetadata(Offset.getQuantity(), MD);
5180  }
5181 }
5182 
5183 TargetAttr::ParsedTargetAttr CodeGenModule::filterFunctionTargetAttrs(const TargetAttr *TD) {
5184  assert(TD != nullptr);
5185  TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
5186 
5187  ParsedAttr.Features.erase(
5188  llvm::remove_if(ParsedAttr.Features,
5189  [&](const std::string &Feat) {
5190  return !Target.isValidFeatureName(
5191  StringRef{Feat}.substr(1));
5192  }),
5193  ParsedAttr.Features.end());
5194  return ParsedAttr;
5195 }
5196 
5197 
5198 // Fills in the supplied string map with the set of target features for the
5199 // passed in function.
5200 void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
5201  const FunctionDecl *FD) {
5202  StringRef TargetCPU = Target.getTargetOpts().CPU;
5203  if (const auto *TD = FD->getAttr<TargetAttr>()) {
5204  TargetAttr::ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
5205 
5206  // Make a copy of the features as passed on the command line into the
5207  // beginning of the additional features from the function to override.
5208  ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
5209  Target.getTargetOpts().FeaturesAsWritten.begin(),
5210  Target.getTargetOpts().FeaturesAsWritten.end());
5211 
5212  if (ParsedAttr.Architecture != "" &&
5213  Target.isValidCPUName(ParsedAttr.Architecture))
5214  TargetCPU = ParsedAttr.Architecture;
5215 
5216  // Now populate the feature map, first with the TargetCPU which is either
5217  // the default or a new one from the target attribute string. Then we'll use
5218  // the passed in features (FeaturesAsWritten) along with the new ones from
5219  // the attribute.
5220  Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
5221  ParsedAttr.Features);
5222  } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
5224  Target.getCPUSpecificCPUDispatchFeatures(SD->getCurCPUName()->getName(),
5225  FeaturesTmp);
5226  std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
5227  Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, Features);
5228  } else {
5229  Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
5230  Target.getTargetOpts().Features);
5231  }
5232 }
5233 
5234 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
5235  if (!SanStats)
5236  SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
5237 
5238  return *SanStats;
5239 }
5240 llvm::Value *
5242  CodeGenFunction &CGF) {
5243  llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
5244  auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
5245  auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
5246  return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
5247  "__translate_sampler_initializer"),
5248  {C});
5249 }
void setLinkage(Linkage L)
Definition: Visibility.h:88
std::string CoverageNotesFile
The filename with path we use for coverage notes files.
RecordDecl * buildImplicitRecord(StringRef Name, RecordDecl::TagKind TK=TTK_Struct) const
Create a new implicit TU-level CXXRecordDecl or RecordDecl declaration.
const llvm::DataLayout & getDataLayout() const
virtual bool checkCFProtectionReturnSupported(DiagnosticsEngine &Diags) const
Check if the target supports CFProtection branch.
Definition: TargetInfo.cpp:144
std::string ProfileInstrumentUsePath
Name of the profile file to use as input for -fprofile-instr-use.
CGOpenCLRuntime & getOpenCLRuntime()
Return a reference to the configured OpenCL runtime.
Defines the clang::ASTContext interface.
The generic AArch64 ABI is also a modified version of the Itanium ABI, but it has fewer divergences t...
Definition: TargetCXXABI.h:84
llvm::Metadata * CreateMetadataIdentifierForVirtualMemPtrType(QualType T)
Create a metadata identifier that is intended to be used to check virtual calls via a member function...
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition: Decl.h:1991
TargetOptions & getTargetOpts() const
Retrieve the target options.
Definition: TargetInfo.h:151
const CXXDestructorDecl * getDestructor() const
Definition: ExprCXX.h:1224
Represents a function declaration or definition.
Definition: Decl.h:1716
llvm::IntegerType * IntTy
int
void CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD, llvm::Function *F)
Create and attach type metadata to the given function.
Expr * getInit() const
Get the initializer.
Definition: DeclCXX.h:2447
External linkage, which indicates that the entity can be referred to from other translation units...
Definition: Linkage.h:60
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition: Decl.cpp:1990
void EmitDeferredUnusedCoverageMappings()
Emit all the deferred coverage mappings for the uninstrumented functions.
std::vector< const CXXRecordDecl * > getMostBaseClasses(const CXXRecordDecl *RD)
Return a vector of most-base classes for RD.
Smart pointer class that efficiently represents Objective-C method names.
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:1834
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
void DecorateInstructionWithInvariantGroup(llvm::Instruction *I, const CXXRecordDecl *RD)
Adds !invariant.barrier !tag to instruction.
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition: Builtins.h:68
Complete object ctor.
Definition: ABI.h:26
void EmitTargetMultiVersionResolver(llvm::Function *Resolver, ArrayRef< TargetMultiVersionResolverOption > Options)
A (possibly-)qualified type.
Definition: Type.h:655
The iOS 64-bit ABI is follows ARM&#39;s published 64-bit ABI more closely, but we don&#39;t guarantee to foll...
Definition: TargetCXXABI.h:71
Static storage duration.
Definition: Specifiers.h:280
static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty)
base_class_range bases()
Definition: DeclCXX.h:825
std::vector< Module * >::iterator submodule_iterator
Definition: Module.h:553
const CodeGenOptions & getCodeGenOpts() const
GlobalDecl getWithDecl(const Decl *D)
Definition: GlobalDecl.h:88
static llvm::cl::opt< bool > LimitedCoverage("limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden, llvm::cl::desc("Emit limited coverage mapping information (experimental)"), llvm::cl::init(false))
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:819
void UpdateCompletedType(const TagDecl *TD)
UpdateCompletedType - When we find the full definition for a TagDecl, replace the &#39;opaque&#39; type we pr...
llvm::LLVMContext & getLLVMContext()
std::string getClangFullVersion()
Retrieves a string representing the complete clang version, which includes the clang version number...
Definition: Version.cpp:118
CXXDtorType getDtorType() const
Definition: GlobalDecl.h:71
ConstantAddress GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *)
Return a pointer to a constant array for the given ObjCEncodeExpr node.
submodule_iterator submodule_begin()
Definition: Module.h:556
bool containsNonAsciiOrNull() const
Definition: Expr.h:1691
The standard implementation of ConstantInitBuilder used in Clang.
Stmt - This represents one statement.
Definition: Stmt.h:66
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3211
SanitizerSet Sanitize
Set of enabled sanitizers.
Definition: LangOptions.h:142
virtual void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type, raw_ostream &)=0
llvm::Constant * tryEmitForInitializer(const VarDecl &D)
Try to emit the initiaizer of the given declaration as an abstract constant.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:497
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:941
StringRef getBufferName(SourceLocation Loc, bool *Invalid=nullptr) const
Return the filename or buffer identifier of the buffer the location is in.
Defines the SourceManager interface.
CharUnits getAlignOfGlobalVarInChars(QualType T) const
Return the alignment in characters that should be given to a global variable with type T...
virtual void setCXXDestructorDLLStorage(llvm::GlobalValue *GV, const CXXDestructorDecl *Dtor, CXXDtorType DT) const
Definition: CGCXXABI.cpp:290
bool isRecordType() const
Definition: Type.h:6186
virtual void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type, raw_ostream &)=0
Defines the clang::Module class, which describes a module in the source code.
const Type * getTypeForDecl() const
Definition: Decl.h:2853
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
llvm::MDNode * getTBAAStructInfo(QualType QTy)
bool isVirtual() const
Definition: DeclCXX.h:2090
FunctionDecl * getOperatorNew() const
Definition: ExprCXX.h:2015
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2112
LangAS GetGlobalVarAddressSpace(const VarDecl *D)
Return the AST address space of the underlying global variable for D, as determined by its declaratio...
Defines the C++ template declaration subclasses.
Kind getKind() const
Definition: TargetCXXABI.h:132
GlobalDecl getCanonicalDecl() const
Definition: GlobalDecl.h:56
bool isUninit() const
Definition: APValue.h:233
The base class of the type hierarchy.
Definition: Type.h:1428
void setFunctionLinkage(GlobalDecl GD, llvm::Function *F)
Stores additional source code information like skipped ranges which is required by the coverage mappi...
void GenerateObjCSetter(ObjCImplementationDecl *IMP, const ObjCPropertyImplDecl *PID)
GenerateObjCSetter - Synthesize an Objective-C property setter function for the given property...
Definition: CGObjC.cpp:1343
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1294
const ABIInfo & getABIInfo() const
getABIInfo() - Returns ABI info helper for the target.
Definition: TargetInfo.h:55
void GenerateCode(GlobalDecl GD, llvm::Function *Fn, const CGFunctionInfo &FnInfo)
bool isCompilingModule() const
Are we compiling a module interface (.cppm or module map)?
Definition: LangOptions.h:219
bool isBlacklistedLocation(SanitizerMask Mask, SourceLocation Loc, StringRef Category=StringRef()) const
Represent a C++ namespace.
Definition: Decl.h:514
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1292
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:4049
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:679
void EmitCfiCheckFail()
Emit a cross-DSO CFI failure handling function.
Definition: CGExpr.cpp:3058
bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, StringRef Category=StringRef()) const
Imbue XRay attributes to a function, applying the always/never attribute lists in the process...
constexpr XRayInstrMask Function
Definition: XRayInstr.h:39
static const llvm::GlobalObject * getAliasedGlobal(const llvm::GlobalIndirectSymbol &GIS)
bool HasHiddenLTOVisibility(const CXXRecordDecl *RD)
Returns whether the given record has hidden LTO visibility and therefore may participate in (single-m...
Definition: CGVTables.cpp:973
Linkage getLinkage() const
Determine the linkage of this type.
Definition: Type.cpp:3605
bool isDefined(const FunctionDecl *&Definition) const
Returns true if the function has a definition that does not need to be instantiated.
Definition: Decl.cpp:2651
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to...
Definition: Decl.h:1209
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
Represents a prvalue temporary that is written into memory so that a reference can bind to it...
Definition: ExprCXX.h:4150
static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V)
static llvm::Constant * castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM, llvm::GlobalVariable *GV)
&#39;gcc&#39; is the Objective-C runtime shipped with GCC, implementing a fragile Objective-C ABI ...
Definition: ObjCRuntime.h:53
void HandleCXXStaticMemberVarInstantiation(VarDecl *VD)
Tell the consumer that this variable has been instantiated.
Represents a variable declaration or definition.
Definition: Decl.h:814
QualType getCFConstantStringType() const
Return the C structure type used to represent constant CFStrings.
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6526
Visibility getVisibility() const
Definition: Visibility.h:85
CGDebugInfo * getModuleDebugInfo()
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:1588
LangAS
Defines the address space values used by the address space qualifier of QualType. ...
Definition: AddressSpaces.h:26
Class supports emissionof SIMD-only code.
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition: CGDebugInfo.h:54
static llvm::GlobalVariable * GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, CodeGenModule &CGM, StringRef GlobalName, CharUnits Alignment)
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:139
DiagnosticsEngine & getDiags() const
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const
Set the visibility for the given LLVM GlobalValue.
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
bool isStatic() const
Definition: DeclCXX.cpp:1838
virtual void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, llvm::SmallString< 32 > &Opt) const
Gets the linker options necessary to detect object file mismatches on this platform.
Definition: TargetInfo.h:219
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have...
Definition: Linkage.h:24
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:269
Represents a struct/union/class.
Definition: Decl.h:3570
LanguageIDs getLanguage() const
Return the language specified by this linkage specification.
Definition: DeclCXX.h:2869
uint64_t getPointerWidth(unsigned AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:340
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:297
static const FunctionDecl * GetRuntimeFunctionDecl(ASTContext &C, StringRef Name)
TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, TBAAAccessInfo TargetInfo)
mergeTBAAInfoForCast - Get merged TBAA information for the purposes of type casts.
One of these records is kept for each identifier that is lexed.
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1010
&#39;macosx-fragile&#39; is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
Definition: ObjCRuntime.h:40
Expr * GetTemporaryExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue...
Definition: ExprCXX.h:4191
unsigned getIntAlign() const
Definition: TargetInfo.h:376
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:150
field_range fields() const
Definition: Decl.h:3786
llvm::Constant * getAddrOfCXXStructor(const CXXMethodDecl *MD, StructorType Type, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the constructor/destructor of the given type.
Definition: CGCXX.cpp:231
The generic Mips ABI is a modified version of the Itanium ABI.
Definition: TargetCXXABI.h:90
Represents a member of a struct/union/class.
Definition: Decl.h:2534
static CGCXXABI * createCXXABI(CodeGenModule &CGM)
StructorType getFromDtorType(CXXDtorType T)
Definition: CodeGenTypes.h:104
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:3791
bool isReferenceType() const
Definition: Type.h:6125
SanitizerMask Mask
Bitmask of enabled sanitizers.
Definition: Sanitizers.h:73
int Category
Definition: Format.cpp:1608
This declaration is definitely a definition.
Definition: Decl.h:1152
void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, ObjCMethodDecl *MD, bool ctor)
Definition: CGObjC.cpp:1424
static std::string getCPUSpecificMangling(const CodeGenModule &CGM, StringRef Name)
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:50
unsigned getCharByteWidth() const
Definition: Expr.h:1667
Describes a module or submodule.
Definition: Module.h:65
IdentifierTable & Idents
Definition: ASTContext.h:545
bool shouldMangleDeclName(const NamedDecl *D)
Definition: Mangle.cpp:99
CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const
Return the store size, in character units, of the given LLVM type.
Objects with "default" visibility are seen by the dynamic linker and act like normal objects...
Definition: Visibility.h:46
llvm::Constant * GetConstantArrayFromStringLiteral(const StringLiteral *E)
Return a constant array for the given string.
bool isReplaceableGlobalAllocationFunction(bool *IsAligned=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition: Decl.cpp:2749
static void EmitGlobalDeclMetadata(CodeGenModule &CGM, llvm::NamedMDNode *&GlobalMetadata, GlobalDecl D, llvm::GlobalValue *Addr)
static void AppendTargetMangling(const CodeGenModule &CGM, const TargetAttr *Attr, raw_ostream &Out)
CGCUDARuntime & getCUDARuntime()
Return a reference to the configured CUDA runtime.
unsigned getLength() const
Definition: Expr.h:1666
bool isLibFunction(unsigned ID) const
Return true if this is a builtin for a libc/libm function, with a "__builtin_" prefix (e...
Definition: Builtins.h:134
FunctionDecl * getOperatorDelete() const
Definition: ExprCXX.h:2197
Base object ctor.
Definition: ABI.h:27
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:573
uint32_t Offset
Definition: CacheTokens.cpp:43
void setDSOLocal(llvm::GlobalValue *GV) const
The Microsoft ABI is the ABI used by Microsoft Visual Studio (and compatible compilers).
Definition: TargetCXXABI.h:113
bool hasConstructorVariants() const
Does this ABI have different entrypoints for complete-object and base-subobject constructors?
Definition: TargetCXXABI.h:215
void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D, CodeGenFunction *CGF=nullptr)
Emit a code for declare reduction construct.
Definition: CGDecl.cpp:2221
virtual void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber, raw_ostream &)=0
TBAAAccessInfo getTBAAAccessInfo(QualType AccessType)
getTBAAAccessInfo - Get TBAA information that describes an access to an object of the given type...
unsigned char PointerWidthInBits
The width of a pointer into the generic address space.
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:149
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2406
CGObjCRuntime * CreateMacObjCRuntime(CodeGenModule &CGM)
CXXCtorType getCtorType() const
Definition: GlobalDecl.h:66
void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info, CGCalleeInfo CalleeInfo, llvm::AttributeList &Attrs, unsigned &CallingConv, bool AttrOnCallSite)
Get the LLVM attributes and calling convention to use for a particular function type.
Definition: CGCall.cpp:1816
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
Module * Parent
The parent of this module.
Definition: Module.h:91
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
Definition: DeclObjC.h:882
Defines the Diagnostic-related interfaces.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:5889
void AddELFLibDirective(StringRef Lib)
submodule_iterator submodule_end()
Definition: Module.h:558
void addCompilerUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.compiler.used metadata.
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition: Decl.cpp:2880
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1245
llvm::Constant * CreateRuntimeVariable(llvm::Type *Ty, StringRef Name)
Create a new runtime global variable with the specified type and name.
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC)...
Definition: DeclBase.h:828
CXXTemporary * getTemporary()
Definition: ExprCXX.h:1264
const CGFunctionInfo & arrangeCXXMethodDeclaration(const CXXMethodDecl *MD)
C++ methods have some special rules and also have implicit parameters.
Definition: CGCall.cpp:273
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1482
void EmitTentativeDefinition(const VarDecl *D)
void addInstanceMethod(ObjCMethodDecl *method)
Definition: DeclObjC.h:2465
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
llvm::SanitizerStatReport & getSanStats()
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
Represents an ObjC class declaration.
Definition: DeclObjC.h:1193
Represents a linkage specification.
Definition: DeclCXX.h:2823
The iOS ABI is a partial implementation of the ARM ABI.
Definition: TargetCXXABI.h:63
virtual llvm::GlobalValue::LinkageTypes getCXXDestructorLinkage(GVALinkage Linkage, const CXXDestructorDecl *Dtor, CXXDtorType DT) const
Definition: CGCXXABI.cpp:297
const CGFunctionInfo & arrangeGlobalDeclaration(GlobalDecl GD)
Definition: CGCall.cpp:510
void mangleName(const NamedDecl *D, raw_ostream &)
Definition: Mangle.cpp:123
virtual llvm::Value * performAddrSpaceCast(CodeGen::CodeGenFunction &CGF, llvm::Value *V, LangAS SrcAddr, LangAS DestAddr, llvm::Type *DestTy, bool IsNonNull=false) const
Perform address space cast of an expression of pointer type.
Definition: TargetInfo.cpp:447
llvm::Constant * CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false)
Create a new runtime function with the specified type and name.
bool lookupRepresentativeDecl(StringRef MangledName, GlobalDecl &Result) const
bool hasProfileClangUse() const
Check if Clang profile use is on.
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1545
bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor)
isTypeConstant - Determine whether an object of this type can be emitted as a constant.
llvm::PointerType * getSamplerType(const Type *T)
Represents a K&R-style &#39;int foo()&#39; function, which has no information available about its arguments...
Definition: Type.h:3397
llvm::MDNode * getTBAAAccessTagInfo(TBAAAccessInfo Info)
getTBAAAccessTagInfo - Get TBAA tag for a given memory access.
const XRayFunctionFilter & getXRayFilter() const
Definition: ASTContext.h:702
&#39;watchos&#39; is a variant of iOS for Apple&#39;s watchOS.
Definition: ObjCRuntime.h:49
bool hasAttr() const
Definition: DeclBase.h:538
llvm::StringMap< SectionInfo > SectionInfos
Definition: ASTContext.h:2928
llvm::Type * HalfTy
float, double
const ValueDecl * getExtendingDecl() const
Get the declaration which triggered the lifetime-extension of this temporary, if any.
Definition: ExprCXX.h:4213
StringRef getString() const
Definition: Expr.h:1633
static bool hasUnwindExceptions(const LangOptions &LangOpts)
Determines whether the language options require us to model unwind exceptions.
virtual bool checkCFProtectionBranchSupported(DiagnosticsEngine &Diags) const
Check if the target supports CFProtection branch.
Definition: TargetInfo.cpp:138
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1627
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3432
static bool AllTrivialInitializers(CodeGenModule &CGM, ObjCImplementationDecl *D)
The generic ARM ABI is a modified version of the Itanium ABI proposed by ARM for use on ARM-based pla...
Definition: TargetCXXABI.h:52
std::string CurrentModule
The name of the current module, of which the main source file is a part.
Definition: LangOptions.h:183
void setHasDestructors(bool val)
Definition: DeclObjC.h:2681
const TargetCodeGenInfo & getTargetCodeGenInfo()
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1355
void AddDetectMismatch(StringRef Name, StringRef Value)
Appends a detect mismatch command to the linker options.
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:689
llvm::SmallSetVector< Module *, 2 > Imports
The set of modules imported by this module, and on which this module depends.
Definition: Module.h:282
virtual void getDependentLibraryOption(llvm::StringRef Lib, llvm::SmallString< 24 > &Opt) const
Gets the linker options necessary to link a dependent library on this platform.
Definition: TargetInfo.cpp:411
OverloadedOperatorKind getCXXOverloadedOperator() const
getCXXOverloadedOperator - If this name is the name of an overloadable operator in C++ (e...
static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND)
bool isInSanitizerBlacklist(SanitizerMask Kind, llvm::Function *Fn, SourceLocation Loc) const
const char * getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.h:86
StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD)
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:179
llvm::CallingConv::ID getRuntimeCC() const
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *FD)
Exposes information about the current target.
Definition: TargetInfo.h:54
void SetLLVMFunctionAttributes(const Decl *D, const CGFunctionInfo &Info, llvm::Function *F)
Set the LLVM function attributes (sext, zext, etc).
llvm::Constant * EmitAnnotationUnit(SourceLocation Loc)
Emit the annotation&#39;s translation unit.
bool isValid() const
static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, SmallVectorImpl< llvm::MDNode *> &Metadata, llvm::SmallPtrSet< Module *, 16 > &Visited)
Add link options implied by the given module, including modules it depends on, using a postorder walk...
virtual void EmitCXXConstructors(const CXXConstructorDecl *D)=0
Emit constructor variants required by this ABI.
Pepresents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:3860
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2206
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:637
Expr - This represents one expression.
Definition: Expr.h:106
static ObjCMethodDecl * Create(ASTContext &C, SourceLocation beginLoc, SourceLocation endLoc, Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo, DeclContext *contextDecl, bool isInstance=true, bool isVariadic=false, bool isPropertyAccessor=false, bool isImplicitlyDeclared=false, bool isDefined=false, ImplementationControl impControl=None, bool HasRelatedResultType=false)
Definition: DeclObjC.cpp:772
Emit only debug info necessary for generating line number tables (-gline-tables-only).
Selector getSetterName() const
Definition: DeclObjC.h:933
&#39;macosx&#39; is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the non-fragile AB...
Definition: ObjCRuntime.h:35
virtual void EmitCXXDestructors(const CXXDestructorDecl *D)=0
Emit destructor variants required by this ABI.
int Id
Definition: ASTDiff.cpp:191
void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV)
Add global annotations that are set on D, for the global GV.
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
unsigned getIntWidth() const
getIntWidth/Align - Return the size of &#39;signed int&#39; and &#39;unsigned int&#39; for this target, in bits.
Definition: TargetInfo.h:375
void GenerateObjCMethod(const ObjCMethodDecl *OMD)
Generate an Objective-C method.
Definition: CGObjC.cpp:572
llvm::Constant * GetAddrOfGlobalVar(const VarDecl *D, llvm::Type *Ty=nullptr, ForDefinition_t IsForDefinition=NotForDefinition)
Return the llvm::Constant for the address of the given global variable.
unsigned getLine() const
Return the presumed line number of this location.
Organizes the cross-function state that is used while generating code coverage mapping data...
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2700
bool UseExportAsModuleLinkName
Autolinking uses the framework name for linking purposes when this is false and the export_as name ot...
Definition: Module.h:340
void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile)
Report potential problems we&#39;ve found to Diags.
Defines version macros and version-related utility functions for Clang.
static QualType GeneralizeType(ASTContext &Ctx, QualType Ty)
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl...
Linkage getLinkage() const
Definition: Visibility.h:84
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
uint32_t getCodeUnit(size_t i) const
Definition: Expr.h:1655
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition: Decl.cpp:2876
TLSKind getTLSKind() const
Definition: Decl.cpp:1916
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
CGOpenMPRuntime(CodeGenModule &CGM)
llvm::SmallVector< LinkLibrary, 2 > LinkLibraries
The set of libraries or frameworks to link against when an entity from this module is used...
Definition: Module.h:336
static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM, const CXXMethodDecl *MD)
Base object dtor.
Definition: ABI.h:37
QualType getType() const
Definition: Expr.h:128
llvm::GlobalValue::LinkageTypes getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant)
Returns LLVM linkage for a declarator.
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition: Decl.cpp:2121
virtual bool validateCpuSupports(StringRef Name) const
Definition: TargetInfo.h:1083
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:165
propimpl_range property_impls() const
Definition: DeclObjC.h:2488
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type...
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl, 0 if there are none.
Definition: DeclBase.cpp:384
llvm::Constant * EmitAnnotationString(StringRef Str)
Emit an annotation string.
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition: ExprCXX.h:4194
QualType getEncodedType() const
Definition: ExprObjC.h:417
llvm::PointerType * AllocaInt8PtrTy
bool isExternallyVisible(Linkage L)
Definition: Linkage.h:86
ConstantAddress GetAddrOfUuidDescriptor(const CXXUuidofExpr *E)
Get the address of a uuid descriptor .
llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD)
QualType getRecordType(const RecordDecl *Decl) const
Represents an unpacked "presumed" location which can be presented to the user.
static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM, const CPUSpecificAttr *Attr, raw_ostream &Out)
CXXMethodDecl * getMethodDecl() const
Retrieves the declaration of the called method.
Definition: ExprCXX.cpp:517
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1365
virtual void getCPUSpecificCPUDispatchFeatures(StringRef Name, llvm::SmallVectorImpl< StringRef > &Features) const
Definition: TargetInfo.h:1110
static bool isVarDeclStrongDefinition(const ASTContext &Context, CodeGenModule &CGM, const VarDecl *D, bool NoCommon)
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:6484
const TargetInfo & getTarget() const
ValueDecl * getDecl()
Definition: Expr.h:1059
void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV)
Set attributes which are common to any form of a global definition (alias, Objective-C method...
static bool shouldAssumeDSOLocal(const CodeGenModule &CGM, llvm::GlobalValue *GV)
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:152
&#39;gnustep&#39; is the modern non-fragile GNUstep runtime.
Definition: ObjCRuntime.h:56
unsigned getExpansionLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
const LangOptions & getLangOpts() const
ASTContext & getContext() const
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:720
void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset, const CXXRecordDecl *RD)
Create and attach type metadata for the given vtable.
const SourceManager & SM
Definition: Format.cpp:1475
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
Definition: opencl-c.h:82
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:236
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2006
const SanitizerBlacklist & getSanitizerBlacklist() const
Definition: ASTContext.h:698
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:35
TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, TBAAAccessInfo InfoB)
mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the purposes of conditional ope...
llvm::GlobalVariable * CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage)
Will return a global variable of the given type.
llvm::Constant * EmitAnnotateAttr(llvm::GlobalValue *GV, const AnnotateAttr *AA, SourceLocation L)
Generate the llvm::ConstantStruct which contains the annotation information for a given GlobalValue...
init_iterator init_begin()
init_begin() - Retrieve an iterator to the first initializer.
Definition: DeclObjC.h:2642
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:5922
ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E, const Expr *Inner)
Returns a pointer to a global variable representing a temporary with static or thread storage duratio...
WatchOS is a modernisation of the iOS ABI, which roughly means it&#39;s the iOS64 ABI ported to 32-bits...
Definition: TargetCXXABI.h:76
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:5948
std::string CPU
If given, the name of the target CPU to generate code for.
Definition: TargetOptions.h:36
The l-value was considered opaque, so the alignment was determined from a type.
const char * getFilename() const
Return the presumed filename of this location.
Thread storage duration.
Definition: Specifiers.h:279
SourceLocation getLocStart() const LLVM_READONLY
Definition: DeclBase.h:409
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:1550
static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD, const NamedDecl *ND, bool OmitMultiVersionMangling=false)
static void emitUsed(CodeGenModule &CGM, StringRef Name, std::vector< llvm::WeakTrackingVH > &List)
SelectorTable & Selectors
Definition: ASTContext.h:546
Kind
void RefreshTypeCacheForClass(const CXXRecordDecl *Class)
QualType getCanonicalType() const
Definition: Type.h:5928
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:204
void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV)
If the declaration has internal linkage but is inside an extern "C" linkage specification, prepare to emit an alias for it to the expected name.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:218
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:295
Encodes a location in the source.
virtual bool shouldMangleStringLiteral(const StringLiteral *SL)=0
static DeclContext * castToDeclContext(const TranslationUnitDecl *D)
Definition: Decl.h:129
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:6005
void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const
Set the TLS mode for the given LLVM GlobalValue for the thread-local variable declaration D...
&#39;objfw&#39; is the Objective-C runtime included in ObjFW
Definition: ObjCRuntime.h:59
ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal)
Return a pointer to a constant CFString object for the given string.
TBAAAccessInfo getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType)
getTBAAVTablePtrAccessInfo - Get the TBAA information that describes an access to a virtual table poi...
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)"...
Definition: ExprCXX.h:1915
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3020
void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const
Set visibility, dllimport/dllexport and dso_local.
Represents a call to a member function that may be written either with member call syntax (e...
Definition: ExprCXX.h:166
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:376
llvm::Metadata * CreateMetadataIdentifierForType(QualType T)
Create a metadata identifier for the given type.
SourceLocation getLocStart() const LLVM_READONLY
Definition: Stmt.h:401
Kind getKind() const
Definition: ObjCRuntime.h:77
bool hasUnwindExceptions() const
Does this runtime use zero-cost exceptions?
Definition: ObjCRuntime.h:286
const Decl * getDecl() const
Definition: GlobalDecl.h:64
void mangleDtorBlock(const CXXDestructorDecl *CD, CXXDtorType DT, const BlockDecl *BD, raw_ostream &Out)
Definition: Mangle.cpp:220
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:105
LangAS getStringLiteralAddressSpace() const
Return the AST address space of string literal, which is used to emit the string literal as global va...
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
TargetAttr::ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD)
Parses the target attributes passed in, and returns only the ones that are valid feature names...
virtual llvm::Function * emitThreadPrivateVarDefinition(const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit, CodeGenFunction *CGF=nullptr)
Emit a code for initialization of threadprivate variable.
Per-function PGO state.
Definition: CodeGenPGO.h:29
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2045
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition: Mangle.h:43
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2395
SourceLocation getStrTokenLoc(unsigned TokNum) const
Definition: Expr.h:1703
ConstantAddress GetAddrOfConstantStringFromLiteral(const StringLiteral *S, StringRef Name=".str")
Return a pointer to a constant array for the given string literal.
Weak for now, might become strong later in this TU.
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1077
llvm::Metadata * CreateMetadataIdentifierGeneralized(QualType T)
Create a metadata identifier for the generalization of the given type.
llvm::Constant * CreateBuiltinFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList())
Create a new compiler builtin function with the specified type and name.
llvm::Constant * GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH=false)
Get the address of the RTTI descriptor for the given type.
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings startin...
Definition: TargetOptions.h:55
bool doesDeclarationForceExternallyVisibleDefinition() const
For a function declaration in C or C++, determine whether this declaration causes the definition to b...
Definition: Decl.cpp:3058
bool isTrivialInitializer(const Expr *Init)
Determine whether the given initializer is trivial in the sense that it requires no code to be genera...
Definition: CGDecl.cpp:1418
CanQualType VoidTy
Definition: ASTContext.h:1004
llvm::Constant * emitAbstract(const Expr *E, QualType T)
Emit the result of the given expression as an abstract constant, asserting that it succeeded...
void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C)
bool isObjCObjectPointerType() const
Definition: Type.h:6210
llvm::MDNode * getTBAATypeInfo(QualType QTy)
getTBAATypeInfo - Get metadata used to describe accesses to objects of the given type.
ConstantAddress GetWeakRefReference(const ValueDecl *VD)
Get a reference to the target of VD.
An aligned address.
Definition: Address.h:25
init_iterator init_end()
init_end() - Retrieve an iterator past the last initializer.
Definition: DeclObjC.h:2651
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:748
void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F)
Set the LLVM function attributes which only apply to a function definition.
The generic Itanium ABI is the standard ABI of most open-source and Unix-like platforms.
Definition: TargetCXXABI.h:34
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:775
void EmitTopLevelDecl(Decl *D)
Emit code for a single top level declaration.
MangleContext & getMangleContext()
Gets the mangle context.
Definition: CGCXXABI.h:97
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:164
Complete object dtor.
Definition: ABI.h:36
CGCXXABI * CreateMicrosoftCXXABI(CodeGenModule &CGM)
Creates a Microsoft-family ABI.
llvm::Constant * EmitAnnotationLineNo(SourceLocation L)
Emit the annotation line number.
void Error(SourceLocation loc, StringRef error)
Emit a general error that something can&#39;t be done.
llvm::CallingConv::ID getRuntimeCC() const
Return the calling convention to use for system runtime functions.
Definition: ABIInfo.h:73
std::vector< Structor > CtorList
TBAAAccessInfo mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, TBAAAccessInfo SrcInfo)
mergeTBAAInfoForMemoryTransfer - Get merged TBAA information for the purposes of memory transfer call...
bool isWeakImported() const
Determine whether this is a weak-imported symbol.
Definition: DeclBase.cpp:685
virtual void mangleTypeName(QualType T, raw_ostream &)=0
Generates a unique string for an externally visible type for use with TBAA or type uniquing...
CXXCtorType
C++ constructor types.
Definition: ABI.h:25
The WebAssembly ABI is a modified version of the Itanium ABI.
Definition: TargetCXXABI.h:105
void addReplacement(StringRef Name, llvm::Constant *C)
ConstantAddress GetAddrOfConstantCString(const std::string &Str, const char *GlobalName=nullptr)
Returns a pointer to a character array containing the literal and a terminating &#39;\0&#39; character...
llvm::Constant * GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition=NotForDefinition)
ArrayRef< Decl * > getModuleInitializers(Module *M)
Get the initializations to perform when importing a module, if any.
StringRef getName() const
Return the actual identifier string.
void addUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.used metadata.
ObjCIvarDecl * getNextIvar()
Definition: DeclObjC.h:1999
TLS with a dynamic initializer.
Definition: Decl.h:837
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn&#39;t support the specified stmt yet.
CGFunctionInfo - Class to encapsulate the information about a function definition.
This class organizes the cross-function state that is used while generating LLVM code.
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
const ObjCInterfaceDecl * getClassInterface() const
Definition: DeclObjC.h:2461
llvm::GlobalValue * GetGlobalValue(StringRef Ref)
void mangleGlobalBlock(const BlockDecl *BD, const NamedDecl *ID, raw_ostream &Out)
Definition: Mangle.cpp:194
void mangleBlock(const DeclContext *DC, const BlockDecl *BD, raw_ostream &Out)
Definition: Mangle.cpp:229
Dataflow Directional Tag Classes.
bool isValid() const
Return true if this is a valid SourceLocation object.
bool hasSideEffects() const
Definition: Expr.h:565
virtual LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, const VarDecl *D) const
Get target favored AST address space of a global variable for languages other than OpenCL and CUDA...
Definition: TargetInfo.cpp:439
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1264
virtual char CPUSpecificManglingCharacter(StringRef Name) const
Definition: TargetInfo.h:1102
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:571
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
Represents a delete expression for memory deallocation and destructor calls, e.g. ...
Definition: ExprCXX.h:2145
void GenerateObjCGetter(ObjCImplementationDecl *IMP, const ObjCPropertyImplDecl *PID)
GenerateObjCGetter - Synthesize an Objective-C property getter function.
Definition: CGObjC.cpp:810
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return 0.
Definition: Expr.cpp:1251
bool isVisibilityExplicit() const
Definition: Visibility.h:86
The basic abstraction for the target Objective-C runtime.
Definition: ObjCRuntime.h:28
llvm::MDNode * getTBAABaseTypeInfo(QualType QTy)
getTBAABaseTypeInfo - Get metadata that describes the given base access type.
bool NeedAllVtablesTypeId() const
Returns whether this module needs the "all-vtables" type identifier.
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:3488
void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D)
Emit a code for threadprivate directive.
const Expr * getInit() const
Definition: Decl.h:1219
FileID getMainFileID() const
Returns the FileID of the main source file.
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const
Returns true if this is an inline-initialized static data member which is treated as a definition for...
llvm::Reloc::Model RelocationModel
The name of the relocation model to use.
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:988
const CXXRecordDecl * getParent() const
Returns the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:2165
Kind getKind() const
Definition: DeclBase.h:422
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like &#39;int()&#39;.
llvm::Constant * EmitNullConstant(QualType T)
Return the result of value-initializing the given type, i.e.
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.
void UpdateCompletedType(const TagDecl *TD)
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type *> Tys=None)
static bool needsDestructMethod(ObjCImplementationDecl *impl)
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:146
static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S)
llvm::Module & getModule() const
void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO)
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any...
Definition: ASTContext.h:1068
void EmitThunks(GlobalDecl GD)
EmitThunks - Emit the associated thunks for the given global decl.
Definition: CGVTables.cpp:572
const Expr * Replacement
Definition: ParsedAttr.h:67
virtual void registerDeviceVar(llvm::GlobalVariable &Var, unsigned Flags)=0
void AddDeferredUnusedCoverageMapping(Decl *D)
Stored a deferred empty coverage mapping for an unused and thus uninstrumented top level declaration...
LLVM_READONLY bool isHexDigit(unsigned char c)
Return true if this character is an ASCII hex digit: [0-9a-fA-F].
Definition: CharInfo.h:124
GVALinkage GetGVALinkageForVariable(const VarDecl *VD)
&#39;ios&#39; is the Apple-provided NeXT-derived runtime on iOS or the iOS simulator; it is always non-fragil...
Definition: ObjCRuntime.h:45
void emitEmptyCounterMapping(const Decl *D, StringRef FuncName, llvm::GlobalValue::LinkageTypes Linkage)
Emit a coverage mapping range with a counter zero for an unused declaration.
Definition: CodeGenPGO.cpp:842
uint64_t SanitizerMask
Definition: Sanitizers.h:26
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2573
virtual void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const
setTargetAttributes - Provides a convenient hook to handle extra target-specific attributes for the g...
Definition: TargetInfo.h:59
virtual llvm::Optional< LangAS > getConstantAddressSpace() const
Return an AST address space which can be used opportunistically for constant global memory...
Definition: TargetInfo.h:1175
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4135
StructorType getFromCtorType(CXXCtorType T)
Definition: CodeGenTypes.h:77
LinkageInfo getLinkageAndVisibility() const
Determines the linkage and visibility of this entity.
Definition: Decl.cpp:1070
void AppendLinkerOptions(StringRef Opts)
Appends Opts to the "llvm.linker.options" metadata value.
void DecorateInstructionWithTBAA(llvm::Instruction *Inst, TBAAAccessInfo TBAAInfo)
DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag.
void setHasNonZeroConstructors(bool val)
Definition: DeclObjC.h:2676
llvm::Type * ConvertFunctionType(QualType FT, const FunctionDecl *FD=nullptr)
Converts the GlobalDecl into an llvm::Type.
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2252
virtual llvm::Constant * getAddrOfRTTIDescriptor(QualType Ty)=0
CanQualType UnsignedLongTy
Definition: ASTContext.h:1014
Implements C++ ABI-specific code generation functions.
Definition: CGCXXABI.h:44
ObjCEncodeExpr, used for @encode in Objective-C.
Definition: ExprObjC.h:396
T * getAttr() const
Definition: DeclBase.h:534
static llvm::StringMapEntry< llvm::GlobalVariable * > & GetConstantCFStringEntry(llvm::StringMap< llvm::GlobalVariable *> &Map, const StringLiteral *Literal, bool TargetIsLSB, bool &IsUTF16, unsigned &StringLength)
Selector getSelector(unsigned NumArgs, IdentifierInfo **IIV)
Can create any sort of selector.
virtual unsigned multiVersionSortPriority(StringRef Name) const
Definition: TargetInfo.h:1087
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2056
bool hasDiagnostics()
Whether or not the stats we&#39;ve gathered indicate any potential problems.
virtual void emitTargetMD(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const
emitTargetMD - Provides a convenient hook to handle extra target-specific metadata for the given glob...
Definition: TargetInfo.h:64
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1059
void GenerateClassData(const CXXRecordDecl *RD)
GenerateClassData - Generate all the class data required to be generated upon definition of a KeyFunc...
Definition: CGVTables.cpp:888
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, llvm::Function *NewFn)
ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we implement a function with...
virtual uint64_t getMaxPointerWidth() const
Return the maximum width of pointers on this target.
Definition: TargetInfo.h:348
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the given function.
void EmitCPUDispatchMultiVersionResolver(llvm::Function *Resolver, ArrayRef< CPUDispatchMultiVersionResolverOption > Options)
void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F, const CGFunctionInfo &FI)
Set the attributes on the LLVM function for the given decl and function info.
StringRef getMangledName(GlobalDecl GD)
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition: Linkage.h:32
llvm::Value * createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF)
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1460
CGCUDARuntime * CreateNVCUDARuntime(CodeGenModule &CGM)
Creates an instance of a CUDA runtime class.
Definition: CGCUDANV.cpp:617
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
Definition: APValue.h:38
CodeGenTBAA - This class organizes the cross-module state that is used while lowering AST types to LL...
Definition: CodeGenTBAA.h:118
Represents a base class of a C++ class.
Definition: DeclCXX.h:192
static const char AnnotationSection[]
SourceManager & getSourceManager()
Definition: ASTContext.h:651
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
Definition: Type.cpp:2034
llvm::ConstantInt * getSize(CharUnits numChars)
Emit the given number of characters as a value of type size_t.
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2321
QualType withCVRQualifiers(unsigned CVR) const
Definition: Type.h:847
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2235
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:520
ArrayBuilder beginArray(llvm::Type *eltTy=nullptr)
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
StringRef getUuidStr() const
Definition: ExprCXX.h:952
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:997
virtual LangAS getASTAllocaAddressSpace() const
Get the AST address space for alloca.
Definition: TargetInfo.h:242
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:5969
Represents a C++ struct/union/class.
Definition: DeclCXX.h:302
CGCXXABI * CreateItaniumCXXABI(CodeGenModule &CGM)
Creates an Itanium-family ABI.
unsigned getBuiltinID() const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:2910
bool isTLSSupported() const
Whether the target supports thread-local storage.
Definition: TargetInfo.h:1123
A specialization of Address that requires the address to be an LLVM Constant.
Definition: Address.h:75
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1966
static bool HasNonDllImportDtor(QualType T)
void Release()
Finalize LLVM code generation.
static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D)
void ClearUnusedCoverageMapping(const Decl *D)
Remove the deferred empty coverage mapping as this declaration is actually instrumented.
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:547
bool isSamplerT() const
Definition: Type.h:6267
virtual void mangleStringLiteral(const StringLiteral *SL, raw_ostream &)=0
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
void EmitGlobalAnnotations()
Emit all the global annotations.
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:1068
llvm::ConstantInt * CreateCrossDsoCfiTypeId(llvm::Metadata *MD)
Generate a cross-DSO type identifier for MD.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:266
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition: Sanitizers.h:52
uint64_t getPointerAlign(unsigned AddrSpace) const
Definition: TargetInfo.h:343
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1585
Defines the clang::TargetInfo interface.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2316
void finalize(llvm::GlobalVariable *global)
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:154
bool getExpressionLocationsEnabled() const
Return true if we should emit location information for expressions.
void RefreshTypeCacheForClass(const CXXRecordDecl *RD)
Remove stale types from the type cache when an inheritance model gets assigned to a class...
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition: Decl.h:2025
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:275
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
CGCXXABI & getCXXABI() const
__DEVICE__ int max(int __a, int __b)
QualType getObjCFastEnumerationStateType()
Retrieve the record type that describes the state of an Objective-C fast enumeration loop (for...
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:226
The top declaration context.
Definition: Decl.h:107
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:974
NamedDecl * getMostRecentDecl()
Definition: Decl.h:445
static uint32_t GetX86CpuSupportsMask(ArrayRef< StringRef > FeatureStrs)
Definition: CGBuiltin.cpp:8915
GVALinkage
A more specific kind of linkage than enum Linkage.
Definition: Linkage.h:74
bool isPointerType() const
Definition: Type.h:6113
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition: Decl.cpp:2009
varlist_range varlists()
Definition: DeclOpenMP.h:77
static llvm::Constant * GetPointerConstant(llvm::LLVMContext &Context, const void *Ptr)
Turns the given pointer into a constant.
QualType getType() const
Definition: Decl.h:648
CodeGenVTables & getVTables()
This represents a decl that may have a name.
Definition: Decl.h:248
ObjCIvarDecl * all_declared_ivar_begin()
all_declared_ivar_begin - return first ivar declared in this class, its extensions and its implementa...
Definition: DeclObjC.cpp:1546
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:458
static void replaceUsesOfNonProtoConstant(llvm::Constant *old, llvm::Function *newFn)
Replace the uses of a function that was declared with a non-proto type.
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen&#39;ed or deserialized from PCH lazily, only when used; this is onl...
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition: ExprCXX.h:895
ObjCMethodDecl * getInstanceMethod(Selector Sel, bool AllowHidden=false) const
Definition: DeclObjC.h:1107
bool isConstant(const ASTContext &Ctx) const
Definition: Type.h:790
unsigned getTargetAddressSpace(QualType T) const
Definition: ASTContext.h:2481
void EmitCfiCheckStub()
Emit a stub for the cross-DSO CFI check function.
Definition: CGExpr.cpp:3034
Selector getGetterName() const
Definition: DeclObjC.h:925
void mangleCtorBlock(const CXXConstructorDecl *CD, CXXCtorType CT, const BlockDecl *BD, raw_ostream &Out)
Definition: Mangle.cpp:211
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition: Decl.cpp:3692
void setGlobalVisibilityAndLocal(llvm::GlobalValue *GV, const NamedDecl *D) const
bool hasInit() const
Definition: Decl.cpp:2144
const LangOptions & getLangOpts() const
Definition: ASTContext.h:696
unsigned getNumIvarInitializers() const
getNumArgs - Number of ivars which must be initialized.
Definition: DeclObjC.h:2661
FullSourceLoc getFullLoc(SourceLocation Loc) const
Definition: ASTContext.h:708
This represents &#39;#pragma omp threadprivate ...&#39; directive.
Definition: DeclOpenMP.h:39
No in-class initializer.
Definition: Specifiers.h:230
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition: DeclBase.cpp:243
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2728
This class handles loading and caching of source files into memory.
void EmitGlobal(GlobalDecl D)
Emit code for a single global function or var decl.
Defines enum values for all the target-independent builtin functions.
void AddDependentLib(StringRef Lib)
Appends a dependent lib to the "llvm.linker.options" metadata value.
llvm::GlobalValue::LinkageTypes getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable)
Returns LLVM linkage for a declarator.
Attr - This represents one attribute.
Definition: Attr.h:43
InlineVariableDefinitionKind getInlineVariableDefinitionKind(const VarDecl *VD) const
Determine whether a definition of this inline variable should be treated as a weak or strong definiti...
SourceLocation getLocation() const
Definition: DeclBase.h:419
bool isExternallyVisible() const
Definition: Decl.h:379
APValue * getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E, bool MayCreate)
Get the storage for the constant value of a materialized temporary of static storage duration...
static OMPLinearClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind Modifier, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef< Expr *> VL, ArrayRef< Expr *> PL, ArrayRef< Expr *> IL, Expr *Step, Expr *CalcStep, Stmt *PreInit, Expr *PostUpdate)
Creates clause with a list of variables VL and a linear step Step.
PrettyStackTraceDecl - If a crash occurs, indicate that it happened when doing something to a specifi...
Definition: DeclBase.h:1173
void setDLLImportDLLExport(llvm::GlobalValue *GV, GlobalDecl D) const
static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, ASTContext &Context)
A helper function to get the alignment of a Decl referred to by DeclRefExpr or MemberExpr.
CGObjCRuntime * CreateGNUObjCRuntime(CodeGenModule &CGM)
Creates an instance of an Objective-C runtime class.
Definition: CGObjCGNU.cpp:3983
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition: CGCall.cpp:1544
const llvm::Triple & getTriple() const