TargetMachine.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. //===-- TargetMachine.cpp - General Target Information ---------------------==//
  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 file describes the general parts of a Target machine.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Target/TargetMachine.h"
  13. #include "llvm/Analysis/TargetTransformInfo.h"
  14. #include "llvm/IR/Function.h"
  15. #include "llvm/IR/GlobalAlias.h"
  16. #include "llvm/IR/GlobalValue.h"
  17. #include "llvm/IR/GlobalVariable.h"
  18. #include "llvm/IR/LegacyPassManager.h"
  19. #include "llvm/IR/Mangler.h"
  20. #include "llvm/MC/MCAsmInfo.h"
  21. #include "llvm/MC/MCContext.h"
  22. #include "llvm/MC/MCInstrInfo.h"
  23. #include "llvm/MC/MCSectionMachO.h"
  24. #include "llvm/MC/MCTargetOptions.h"
  25. #include "llvm/MC/SectionKind.h"
  26. #include "llvm/Target/TargetLoweringObjectFile.h"
  27. using namespace llvm;
  28. //---------------------------------------------------------------------------
  29. // TargetMachine Class
  30. //
  31. TargetMachine::TargetMachine(const Target &T, StringRef DataLayoutString,
  32. const Triple &TT, StringRef CPU, StringRef FS,
  33. const TargetOptions &Options)
  34. : TheTarget(T), DL(DataLayoutString), TargetTriple(TT),
  35. TargetCPU(std::string(CPU)), TargetFS(std::string(FS)), AsmInfo(nullptr),
  36. MRI(nullptr), MII(nullptr), STI(nullptr), RequireStructuredCFG(false),
  37. O0WantsFastISel(false), DefaultOptions(Options), Options(Options) {}
  38. TargetMachine::~TargetMachine() = default;
  39. bool TargetMachine::isPositionIndependent() const {
  40. return getRelocationModel() == Reloc::PIC_;
  41. }
  42. /// Reset the target options based on the function's attributes.
  43. /// setFunctionAttributes should have made the raw attribute value consistent
  44. /// with the command line flag if used.
  45. //
  46. // FIXME: This function needs to go away for a number of reasons:
  47. // a) global state on the TargetMachine is terrible in general,
  48. // b) these target options should be passed only on the function
  49. // and not on the TargetMachine (via TargetOptions) at all.
  50. void TargetMachine::resetTargetOptions(const Function &F) const {
  51. #define RESET_OPTION(X, Y) \
  52. do { \
  53. Options.X = (F.getFnAttribute(Y).getValueAsString() == "true"); \
  54. } while (0)
  55. RESET_OPTION(UnsafeFPMath, "unsafe-fp-math");
  56. RESET_OPTION(NoInfsFPMath, "no-infs-fp-math");
  57. RESET_OPTION(NoNaNsFPMath, "no-nans-fp-math");
  58. RESET_OPTION(NoSignedZerosFPMath, "no-signed-zeros-fp-math");
  59. }
  60. /// Returns the code generation relocation model. The choices are static, PIC,
  61. /// and dynamic-no-pic.
  62. Reloc::Model TargetMachine::getRelocationModel() const { return RM; }
  63. /// Returns the code model. The choices are small, kernel, medium, large, and
  64. /// target default.
  65. CodeModel::Model TargetMachine::getCodeModel() const { return CMModel; }
  66. /// Get the IR-specified TLS model for Var.
  67. static TLSModel::Model getSelectedTLSModel(const GlobalValue *GV) {
  68. switch (GV->getThreadLocalMode()) {
  69. case GlobalVariable::NotThreadLocal:
  70. llvm_unreachable("getSelectedTLSModel for non-TLS variable");
  71. break;
  72. case GlobalVariable::GeneralDynamicTLSModel:
  73. return TLSModel::GeneralDynamic;
  74. case GlobalVariable::LocalDynamicTLSModel:
  75. return TLSModel::LocalDynamic;
  76. case GlobalVariable::InitialExecTLSModel:
  77. return TLSModel::InitialExec;
  78. case GlobalVariable::LocalExecTLSModel:
  79. return TLSModel::LocalExec;
  80. }
  81. llvm_unreachable("invalid TLS model");
  82. }
  83. bool TargetMachine::shouldAssumeDSOLocal(const Module &M,
  84. const GlobalValue *GV) const {
  85. const Triple &TT = getTargetTriple();
  86. Reloc::Model RM = getRelocationModel();
  87. // According to the llvm language reference, we should be able to
  88. // just return false in here if we have a GV, as we know it is
  89. // dso_preemptable. At this point in time, the various IR producers
  90. // have not been transitioned to always produce a dso_local when it
  91. // is possible to do so.
  92. // In the case of ExternalSymbolSDNode, GV is null and we should just return
  93. // false. However, COFF currently relies on this to be true
  94. //
  95. // As a result we still have some logic in here to improve the quality of the
  96. // generated code.
  97. // FIXME: Add a module level metadata for whether intrinsics should be assumed
  98. // local.
  99. if (!GV)
  100. return TT.isOSBinFormatCOFF();
  101. // If the IR producer requested that this GV be treated as dso local, obey.
  102. if (GV->isDSOLocal())
  103. return true;
  104. // DLLImport explicitly marks the GV as external.
  105. if (GV->hasDLLImportStorageClass())
  106. return false;
  107. // On MinGW, variables that haven't been declared with DLLImport may still
  108. // end up automatically imported by the linker. To make this feasible,
  109. // don't assume the variables to be DSO local unless we actually know
  110. // that for sure. This only has to be done for variables; for functions
  111. // the linker can insert thunks for calling functions from another DLL.
  112. if (TT.isWindowsGNUEnvironment() && TT.isOSBinFormatCOFF() &&
  113. GV->isDeclarationForLinker() && isa<GlobalVariable>(GV))
  114. return false;
  115. // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
  116. // remain unresolved in the link, they can be resolved to zero, which is
  117. // outside the current DSO.
  118. if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
  119. return false;
  120. // Every other GV is local on COFF.
  121. // Make an exception for windows OS in the triple: Some firmware builds use
  122. // *-win32-macho triples. This (accidentally?) produced windows relocations
  123. // without GOT tables in older clang versions; Keep this behaviour.
  124. // Some JIT users use *-win32-elf triples; these shouldn't use GOT tables
  125. // either.
  126. if (TT.isOSBinFormatCOFF() || TT.isOSWindows())
  127. return true;
  128. if (TT.isOSBinFormatMachO()) {
  129. if (RM == Reloc::Static)
  130. return true;
  131. return GV->isStrongDefinitionForLinker();
  132. }
  133. // Due to the AIX linkage model, any global with default visibility is
  134. // considered non-local.
  135. if (TT.isOSBinFormatXCOFF())
  136. return false;
  137. assert(TT.isOSBinFormatELF() || TT.isOSBinFormatWasm());
  138. assert(RM != Reloc::DynamicNoPIC);
  139. return false;
  140. }
  141. bool TargetMachine::useEmulatedTLS() const {
  142. // Returns Options.EmulatedTLS if the -emulated-tls or -no-emulated-tls
  143. // was specified explicitly; otherwise uses target triple to decide default.
  144. if (Options.ExplicitEmulatedTLS)
  145. return Options.EmulatedTLS;
  146. return getTargetTriple().hasDefaultEmulatedTLS();
  147. }
  148. TLSModel::Model TargetMachine::getTLSModel(const GlobalValue *GV) const {
  149. bool IsPIE = GV->getParent()->getPIELevel() != PIELevel::Default;
  150. Reloc::Model RM = getRelocationModel();
  151. bool IsSharedLibrary = RM == Reloc::PIC_ && !IsPIE;
  152. bool IsLocal = shouldAssumeDSOLocal(*GV->getParent(), GV);
  153. TLSModel::Model Model;
  154. if (IsSharedLibrary) {
  155. if (IsLocal)
  156. Model = TLSModel::LocalDynamic;
  157. else
  158. Model = TLSModel::GeneralDynamic;
  159. } else {
  160. if (IsLocal)
  161. Model = TLSModel::LocalExec;
  162. else
  163. Model = TLSModel::InitialExec;
  164. }
  165. // If the user specified a more specific model, use that.
  166. TLSModel::Model SelectedModel = getSelectedTLSModel(GV);
  167. if (SelectedModel > Model)
  168. return SelectedModel;
  169. return Model;
  170. }
  171. /// Returns the optimization level: None, Less, Default, or Aggressive.
  172. CodeGenOpt::Level TargetMachine::getOptLevel() const { return OptLevel; }
  173. void TargetMachine::setOptLevel(CodeGenOpt::Level Level) { OptLevel = Level; }
  174. TargetTransformInfo TargetMachine::getTargetTransformInfo(const Function &F) {
  175. return TargetTransformInfo(F.getParent()->getDataLayout());
  176. }
  177. void TargetMachine::getNameWithPrefix(SmallVectorImpl<char> &Name,
  178. const GlobalValue *GV, Mangler &Mang,
  179. bool MayAlwaysUsePrivate) const {
  180. if (MayAlwaysUsePrivate || !GV->hasPrivateLinkage()) {
  181. // Simple case: If GV is not private, it is not important to find out if
  182. // private labels are legal in this case or not.
  183. Mang.getNameWithPrefix(Name, GV, false);
  184. return;
  185. }
  186. const TargetLoweringObjectFile *TLOF = getObjFileLowering();
  187. TLOF->getNameWithPrefix(Name, GV, *this);
  188. }
  189. MCSymbol *TargetMachine::getSymbol(const GlobalValue *GV) const {
  190. const TargetLoweringObjectFile *TLOF = getObjFileLowering();
  191. // XCOFF symbols could have special naming convention.
  192. if (MCSymbol *TargetSymbol = TLOF->getTargetSymbol(GV, *this))
  193. return TargetSymbol;
  194. SmallString<128> NameStr;
  195. getNameWithPrefix(NameStr, GV, TLOF->getMangler());
  196. return TLOF->getContext().getOrCreateSymbol(NameStr);
  197. }
  198. TargetIRAnalysis TargetMachine::getTargetIRAnalysis() {
  199. // Since Analysis can't depend on Target, use a std::function to invert the
  200. // dependency.
  201. return TargetIRAnalysis(
  202. [this](const Function &F) { return this->getTargetTransformInfo(F); });
  203. }
  204. std::pair<int, int> TargetMachine::parseBinutilsVersion(StringRef Version) {
  205. if (Version == "none")
  206. return {INT_MAX, INT_MAX}; // Make binutilsIsAtLeast() return true.
  207. std::pair<int, int> Ret;
  208. if (!Version.consumeInteger(10, Ret.first) && Version.consume_front("."))
  209. Version.consumeInteger(10, Ret.second);
  210. return Ret;
  211. }