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