xref: /freebsd/contrib/llvm-project/llvm/lib/Target/TargetMachine.cpp (revision 1db9f3b21e39176dd5b67cf8ac378633b172463e)
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 
13 #include "llvm/Target/TargetMachine.h"
14 #include "llvm/Analysis/TargetTransformInfo.h"
15 #include "llvm/IR/Function.h"
16 #include "llvm/IR/GlobalValue.h"
17 #include "llvm/IR/GlobalVariable.h"
18 #include "llvm/IR/Mangler.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCInstrInfo.h"
22 #include "llvm/MC/MCRegisterInfo.h"
23 #include "llvm/MC/MCSubtargetInfo.h"
24 #include "llvm/Support/CodeGen.h"
25 #include "llvm/Target/TargetLoweringObjectFile.h"
26 using namespace llvm;
27 
28 //---------------------------------------------------------------------------
29 // TargetMachine Class
30 //
31 
32 TargetMachine::TargetMachine(const Target &T, StringRef DataLayoutString,
33                              const Triple &TT, StringRef CPU, StringRef FS,
34                              const TargetOptions &Options)
35     : TheTarget(T), DL(DataLayoutString), TargetTriple(TT),
36       TargetCPU(std::string(CPU)), TargetFS(std::string(FS)), AsmInfo(nullptr),
37       MRI(nullptr), MII(nullptr), STI(nullptr), RequireStructuredCFG(false),
38       O0WantsFastISel(false), Options(Options) {}
39 
40 TargetMachine::~TargetMachine() = default;
41 
42 bool TargetMachine::isLargeGlobalValue(const GlobalValue *GVal) const {
43   if (getTargetTriple().getArch() != Triple::x86_64)
44     return false;
45 
46   auto *GO = GVal->getAliaseeObject();
47 
48   // Be conservative if we can't find an underlying GlobalObject.
49   if (!GO)
50     return true;
51 
52   auto *GV = dyn_cast<GlobalVariable>(GO);
53 
54   // Functions/GlobalIFuncs are only large under the large code model.
55   if (!GV)
56     return getCodeModel() == CodeModel::Large;
57 
58   if (GV->isThreadLocal())
59     return false;
60 
61   // We should properly mark well-known section name prefixes as small/large,
62   // because otherwise the output section may have the wrong section flags and
63   // the linker will lay it out in an unexpected way.
64   StringRef Name = GV->getSection();
65   if (!Name.empty()) {
66     auto IsPrefix = [&](StringRef Prefix) {
67       StringRef S = Name;
68       return S.consume_front(Prefix) && (S.empty() || S[0] == '.');
69     };
70     if (IsPrefix(".bss") || IsPrefix(".data") || IsPrefix(".rodata"))
71       return false;
72     if (IsPrefix(".lbss") || IsPrefix(".ldata") || IsPrefix(".lrodata"))
73       return true;
74   }
75 
76   // For x86-64, we treat an explicit GlobalVariable small code model to mean
77   // that the global should be placed in a small section, and ditto for large.
78   // Well-known section names above take precedence for correctness.
79   if (auto CM = GV->getCodeModel()) {
80     if (*CM == CodeModel::Small)
81       return false;
82     if (*CM == CodeModel::Large)
83       return true;
84   }
85 
86   if (getCodeModel() == CodeModel::Medium ||
87       getCodeModel() == CodeModel::Large) {
88     if (!GV->getValueType()->isSized())
89       return true;
90     const DataLayout &DL = GV->getParent()->getDataLayout();
91     uint64_t Size = DL.getTypeSizeInBits(GV->getValueType()) / 8;
92     return Size == 0 || Size > LargeDataThreshold;
93   }
94 
95   return false;
96 }
97 
98 bool TargetMachine::isPositionIndependent() const {
99   return getRelocationModel() == Reloc::PIC_;
100 }
101 
102 /// Reset the target options based on the function's attributes.
103 /// setFunctionAttributes should have made the raw attribute value consistent
104 /// with the command line flag if used.
105 //
106 // FIXME: This function needs to go away for a number of reasons:
107 // a) global state on the TargetMachine is terrible in general,
108 // b) these target options should be passed only on the function
109 //    and not on the TargetMachine (via TargetOptions) at all.
110 void TargetMachine::resetTargetOptions(const Function &F) const {
111 #define RESET_OPTION(X, Y)                                              \
112   do {                                                                  \
113     Options.X = F.getFnAttribute(Y).getValueAsBool();     \
114   } while (0)
115 
116   RESET_OPTION(UnsafeFPMath, "unsafe-fp-math");
117   RESET_OPTION(NoInfsFPMath, "no-infs-fp-math");
118   RESET_OPTION(NoNaNsFPMath, "no-nans-fp-math");
119   RESET_OPTION(NoSignedZerosFPMath, "no-signed-zeros-fp-math");
120   RESET_OPTION(ApproxFuncFPMath, "approx-func-fp-math");
121 }
122 
123 /// Returns the code generation relocation model. The choices are static, PIC,
124 /// and dynamic-no-pic.
125 Reloc::Model TargetMachine::getRelocationModel() const { return RM; }
126 
127 uint64_t TargetMachine::getMaxCodeSize() const {
128   switch (getCodeModel()) {
129   case CodeModel::Tiny:
130     return llvm::maxUIntN(10);
131   case CodeModel::Small:
132   case CodeModel::Kernel:
133   case CodeModel::Medium:
134     return llvm::maxUIntN(31);
135   case CodeModel::Large:
136     return llvm::maxUIntN(64);
137   }
138   llvm_unreachable("Unhandled CodeModel enum");
139 }
140 
141 /// Get the IR-specified TLS model for Var.
142 static TLSModel::Model getSelectedTLSModel(const GlobalValue *GV) {
143   switch (GV->getThreadLocalMode()) {
144   case GlobalVariable::NotThreadLocal:
145     llvm_unreachable("getSelectedTLSModel for non-TLS variable");
146     break;
147   case GlobalVariable::GeneralDynamicTLSModel:
148     return TLSModel::GeneralDynamic;
149   case GlobalVariable::LocalDynamicTLSModel:
150     return TLSModel::LocalDynamic;
151   case GlobalVariable::InitialExecTLSModel:
152     return TLSModel::InitialExec;
153   case GlobalVariable::LocalExecTLSModel:
154     return TLSModel::LocalExec;
155   }
156   llvm_unreachable("invalid TLS model");
157 }
158 
159 bool TargetMachine::shouldAssumeDSOLocal(const Module &M,
160                                          const GlobalValue *GV) const {
161   const Triple &TT = getTargetTriple();
162   Reloc::Model RM = getRelocationModel();
163 
164   // According to the llvm language reference, we should be able to
165   // just return false in here if we have a GV, as we know it is
166   // dso_preemptable.  At this point in time, the various IR producers
167   // have not been transitioned to always produce a dso_local when it
168   // is possible to do so.
169   //
170   // As a result we still have some logic in here to improve the quality of the
171   // generated code.
172   if (!GV)
173     return false;
174 
175   // If the IR producer requested that this GV be treated as dso local, obey.
176   if (GV->isDSOLocal())
177     return true;
178 
179   if (TT.isOSBinFormatCOFF()) {
180     // DLLImport explicitly marks the GV as external.
181     if (GV->hasDLLImportStorageClass())
182       return false;
183 
184     // On MinGW, variables that haven't been declared with DLLImport may still
185     // end up automatically imported by the linker. To make this feasible,
186     // don't assume the variables to be DSO local unless we actually know
187     // that for sure. This only has to be done for variables; for functions
188     // the linker can insert thunks for calling functions from another DLL.
189     if (TT.isWindowsGNUEnvironment() && GV->isDeclarationForLinker() &&
190         isa<GlobalVariable>(GV))
191       return false;
192 
193     // Don't mark 'extern_weak' symbols as DSO local. If these symbols remain
194     // unresolved in the link, they can be resolved to zero, which is outside
195     // the current DSO.
196     if (GV->hasExternalWeakLinkage())
197       return false;
198 
199     // Every other GV is local on COFF.
200     return true;
201   }
202 
203   if (TT.isOSBinFormatGOFF())
204     return true;
205 
206   if (TT.isOSBinFormatMachO()) {
207     if (RM == Reloc::Static)
208       return true;
209     return GV->isStrongDefinitionForLinker();
210   }
211 
212   assert(TT.isOSBinFormatELF() || TT.isOSBinFormatWasm() ||
213          TT.isOSBinFormatXCOFF());
214   return false;
215 }
216 
217 bool TargetMachine::useEmulatedTLS() const { return Options.EmulatedTLS; }
218 
219 TLSModel::Model TargetMachine::getTLSModel(const GlobalValue *GV) const {
220   bool IsPIE = GV->getParent()->getPIELevel() != PIELevel::Default;
221   Reloc::Model RM = getRelocationModel();
222   bool IsSharedLibrary = RM == Reloc::PIC_ && !IsPIE;
223   bool IsLocal = shouldAssumeDSOLocal(*GV->getParent(), GV);
224 
225   TLSModel::Model Model;
226   if (IsSharedLibrary) {
227     if (IsLocal)
228       Model = TLSModel::LocalDynamic;
229     else
230       Model = TLSModel::GeneralDynamic;
231   } else {
232     if (IsLocal)
233       Model = TLSModel::LocalExec;
234     else
235       Model = TLSModel::InitialExec;
236   }
237 
238   // If the user specified a more specific model, use that.
239   TLSModel::Model SelectedModel = getSelectedTLSModel(GV);
240   if (SelectedModel > Model)
241     return SelectedModel;
242 
243   return Model;
244 }
245 
246 /// Returns the optimization level: None, Less, Default, or Aggressive.
247 CodeGenOptLevel TargetMachine::getOptLevel() const { return OptLevel; }
248 
249 void TargetMachine::setOptLevel(CodeGenOptLevel Level) { OptLevel = Level; }
250 
251 TargetTransformInfo
252 TargetMachine::getTargetTransformInfo(const Function &F) const {
253   return TargetTransformInfo(F.getParent()->getDataLayout());
254 }
255 
256 void TargetMachine::getNameWithPrefix(SmallVectorImpl<char> &Name,
257                                       const GlobalValue *GV, Mangler &Mang,
258                                       bool MayAlwaysUsePrivate) const {
259   if (MayAlwaysUsePrivate || !GV->hasPrivateLinkage()) {
260     // Simple case: If GV is not private, it is not important to find out if
261     // private labels are legal in this case or not.
262     Mang.getNameWithPrefix(Name, GV, false);
263     return;
264   }
265   const TargetLoweringObjectFile *TLOF = getObjFileLowering();
266   TLOF->getNameWithPrefix(Name, GV, *this);
267 }
268 
269 MCSymbol *TargetMachine::getSymbol(const GlobalValue *GV) const {
270   const TargetLoweringObjectFile *TLOF = getObjFileLowering();
271   // XCOFF symbols could have special naming convention.
272   if (MCSymbol *TargetSymbol = TLOF->getTargetSymbol(GV, *this))
273     return TargetSymbol;
274 
275   SmallString<128> NameStr;
276   getNameWithPrefix(NameStr, GV, TLOF->getMangler());
277   return TLOF->getContext().getOrCreateSymbol(NameStr);
278 }
279 
280 TargetIRAnalysis TargetMachine::getTargetIRAnalysis() const {
281   // Since Analysis can't depend on Target, use a std::function to invert the
282   // dependency.
283   return TargetIRAnalysis(
284       [this](const Function &F) { return this->getTargetTransformInfo(F); });
285 }
286 
287 std::pair<int, int> TargetMachine::parseBinutilsVersion(StringRef Version) {
288   if (Version == "none")
289     return {INT_MAX, INT_MAX}; // Make binutilsIsAtLeast() return true.
290   std::pair<int, int> Ret;
291   if (!Version.consumeInteger(10, Ret.first) && Version.consume_front("."))
292     Version.consumeInteger(10, Ret.second);
293   return Ret;
294 }
295