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 
TargetMachine(const Target & T,StringRef DataLayoutString,const Triple & TT,StringRef CPU,StringRef FS,const TargetOptions & Options)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 
isLargeGlobalValue(const GlobalValue * GVal) const42 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   // For x86-64, we treat an explicit GlobalVariable small code model to mean
62   // that the global should be placed in a small section, and ditto for large.
63   if (auto CM = GV->getCodeModel()) {
64     if (*CM == CodeModel::Small)
65       return false;
66     if (*CM == CodeModel::Large)
67       return true;
68   }
69 
70   // Treat all globals in explicit sections as small, except for the standard
71   // large sections of .lbss, .ldata, .lrodata. This reduces the risk of linking
72   // together small and large sections, resulting in small references to large
73   // data sections. The code model attribute overrides this above.
74   if (GV->hasSection()) {
75     StringRef Name = GV->getSection();
76     auto IsPrefix = [&](StringRef Prefix) {
77       StringRef S = Name;
78       return S.consume_front(Prefix) && (S.empty() || S[0] == '.');
79     };
80     return IsPrefix(".lbss") || IsPrefix(".ldata") || IsPrefix(".lrodata");
81   }
82 
83   // Respect large data threshold for medium and large code models.
84   if (getCodeModel() == CodeModel::Medium ||
85       getCodeModel() == CodeModel::Large) {
86     if (!GV->getValueType()->isSized())
87       return true;
88     const DataLayout &DL = GV->getParent()->getDataLayout();
89     uint64_t Size = DL.getTypeSizeInBits(GV->getValueType()) / 8;
90     return Size == 0 || Size > LargeDataThreshold;
91   }
92 
93   return false;
94 }
95 
isPositionIndependent() const96 bool TargetMachine::isPositionIndependent() const {
97   return getRelocationModel() == Reloc::PIC_;
98 }
99 
100 /// Reset the target options based on the function's attributes.
101 /// setFunctionAttributes should have made the raw attribute value consistent
102 /// with the command line flag if used.
103 //
104 // FIXME: This function needs to go away for a number of reasons:
105 // a) global state on the TargetMachine is terrible in general,
106 // b) these target options should be passed only on the function
107 //    and not on the TargetMachine (via TargetOptions) at all.
resetTargetOptions(const Function & F) const108 void TargetMachine::resetTargetOptions(const Function &F) const {
109 #define RESET_OPTION(X, Y)                                              \
110   do {                                                                  \
111     Options.X = F.getFnAttribute(Y).getValueAsBool();     \
112   } while (0)
113 
114   RESET_OPTION(UnsafeFPMath, "unsafe-fp-math");
115   RESET_OPTION(NoInfsFPMath, "no-infs-fp-math");
116   RESET_OPTION(NoNaNsFPMath, "no-nans-fp-math");
117   RESET_OPTION(NoSignedZerosFPMath, "no-signed-zeros-fp-math");
118   RESET_OPTION(ApproxFuncFPMath, "approx-func-fp-math");
119 }
120 
121 /// Returns the code generation relocation model. The choices are static, PIC,
122 /// and dynamic-no-pic.
getRelocationModel() const123 Reloc::Model TargetMachine::getRelocationModel() const { return RM; }
124 
getMaxCodeSize() const125 uint64_t TargetMachine::getMaxCodeSize() const {
126   switch (getCodeModel()) {
127   case CodeModel::Tiny:
128     return llvm::maxUIntN(10);
129   case CodeModel::Small:
130   case CodeModel::Kernel:
131   case CodeModel::Medium:
132     return llvm::maxUIntN(31);
133   case CodeModel::Large:
134     return llvm::maxUIntN(64);
135   }
136   llvm_unreachable("Unhandled CodeModel enum");
137 }
138 
139 /// Get the IR-specified TLS model for Var.
getSelectedTLSModel(const GlobalValue * GV)140 static TLSModel::Model getSelectedTLSModel(const GlobalValue *GV) {
141   switch (GV->getThreadLocalMode()) {
142   case GlobalVariable::NotThreadLocal:
143     llvm_unreachable("getSelectedTLSModel for non-TLS variable");
144     break;
145   case GlobalVariable::GeneralDynamicTLSModel:
146     return TLSModel::GeneralDynamic;
147   case GlobalVariable::LocalDynamicTLSModel:
148     return TLSModel::LocalDynamic;
149   case GlobalVariable::InitialExecTLSModel:
150     return TLSModel::InitialExec;
151   case GlobalVariable::LocalExecTLSModel:
152     return TLSModel::LocalExec;
153   }
154   llvm_unreachable("invalid TLS model");
155 }
156 
shouldAssumeDSOLocal(const Module & M,const GlobalValue * GV) const157 bool TargetMachine::shouldAssumeDSOLocal(const Module &M,
158                                          const GlobalValue *GV) const {
159   const Triple &TT = getTargetTriple();
160   Reloc::Model RM = getRelocationModel();
161 
162   // According to the llvm language reference, we should be able to
163   // just return false in here if we have a GV, as we know it is
164   // dso_preemptable.  At this point in time, the various IR producers
165   // have not been transitioned to always produce a dso_local when it
166   // is possible to do so.
167   //
168   // As a result we still have some logic in here to improve the quality of the
169   // generated code.
170   if (!GV)
171     return false;
172 
173   // If the IR producer requested that this GV be treated as dso local, obey.
174   if (GV->isDSOLocal())
175     return true;
176 
177   if (TT.isOSBinFormatCOFF()) {
178     // DLLImport explicitly marks the GV as external.
179     if (GV->hasDLLImportStorageClass())
180       return false;
181 
182     // On MinGW, variables that haven't been declared with DLLImport may still
183     // end up automatically imported by the linker. To make this feasible,
184     // don't assume the variables to be DSO local unless we actually know
185     // that for sure. This only has to be done for variables; for functions
186     // the linker can insert thunks for calling functions from another DLL.
187     if (TT.isWindowsGNUEnvironment() && GV->isDeclarationForLinker() &&
188         isa<GlobalVariable>(GV))
189       return false;
190 
191     // Don't mark 'extern_weak' symbols as DSO local. If these symbols remain
192     // unresolved in the link, they can be resolved to zero, which is outside
193     // the current DSO.
194     if (GV->hasExternalWeakLinkage())
195       return false;
196 
197     // Every other GV is local on COFF.
198     return true;
199   }
200 
201   if (TT.isOSBinFormatGOFF())
202     return true;
203 
204   if (TT.isOSBinFormatMachO()) {
205     if (RM == Reloc::Static)
206       return true;
207     return GV->isStrongDefinitionForLinker();
208   }
209 
210   assert(TT.isOSBinFormatELF() || TT.isOSBinFormatWasm() ||
211          TT.isOSBinFormatXCOFF());
212   return false;
213 }
214 
useEmulatedTLS() const215 bool TargetMachine::useEmulatedTLS() const { return Options.EmulatedTLS; }
useTLSDESC() const216 bool TargetMachine::useTLSDESC() const { return Options.EnableTLSDESC; }
217 
getTLSModel(const GlobalValue * GV) const218 TLSModel::Model TargetMachine::getTLSModel(const GlobalValue *GV) const {
219   bool IsPIE = GV->getParent()->getPIELevel() != PIELevel::Default;
220   Reloc::Model RM = getRelocationModel();
221   bool IsSharedLibrary = RM == Reloc::PIC_ && !IsPIE;
222   bool IsLocal = shouldAssumeDSOLocal(*GV->getParent(), GV);
223 
224   TLSModel::Model Model;
225   if (IsSharedLibrary) {
226     if (IsLocal)
227       Model = TLSModel::LocalDynamic;
228     else
229       Model = TLSModel::GeneralDynamic;
230   } else {
231     if (IsLocal)
232       Model = TLSModel::LocalExec;
233     else
234       Model = TLSModel::InitialExec;
235   }
236 
237   // If the user specified a more specific model, use that.
238   TLSModel::Model SelectedModel = getSelectedTLSModel(GV);
239   if (SelectedModel > Model)
240     return SelectedModel;
241 
242   return Model;
243 }
244 
245 /// Returns the optimization level: None, Less, Default, or Aggressive.
getOptLevel() const246 CodeGenOptLevel TargetMachine::getOptLevel() const { return OptLevel; }
247 
setOptLevel(CodeGenOptLevel Level)248 void TargetMachine::setOptLevel(CodeGenOptLevel Level) { OptLevel = Level; }
249 
250 TargetTransformInfo
getTargetTransformInfo(const Function & F) const251 TargetMachine::getTargetTransformInfo(const Function &F) const {
252   return TargetTransformInfo(F.getParent()->getDataLayout());
253 }
254 
getNameWithPrefix(SmallVectorImpl<char> & Name,const GlobalValue * GV,Mangler & Mang,bool MayAlwaysUsePrivate) const255 void TargetMachine::getNameWithPrefix(SmallVectorImpl<char> &Name,
256                                       const GlobalValue *GV, Mangler &Mang,
257                                       bool MayAlwaysUsePrivate) const {
258   if (MayAlwaysUsePrivate || !GV->hasPrivateLinkage()) {
259     // Simple case: If GV is not private, it is not important to find out if
260     // private labels are legal in this case or not.
261     Mang.getNameWithPrefix(Name, GV, false);
262     return;
263   }
264   const TargetLoweringObjectFile *TLOF = getObjFileLowering();
265   TLOF->getNameWithPrefix(Name, GV, *this);
266 }
267 
getSymbol(const GlobalValue * GV) const268 MCSymbol *TargetMachine::getSymbol(const GlobalValue *GV) const {
269   const TargetLoweringObjectFile *TLOF = getObjFileLowering();
270   // XCOFF symbols could have special naming convention.
271   if (MCSymbol *TargetSymbol = TLOF->getTargetSymbol(GV, *this))
272     return TargetSymbol;
273 
274   SmallString<128> NameStr;
275   getNameWithPrefix(NameStr, GV, TLOF->getMangler());
276   return TLOF->getContext().getOrCreateSymbol(NameStr);
277 }
278 
getTargetIRAnalysis() const279 TargetIRAnalysis TargetMachine::getTargetIRAnalysis() const {
280   // Since Analysis can't depend on Target, use a std::function to invert the
281   // dependency.
282   return TargetIRAnalysis(
283       [this](const Function &F) { return this->getTargetTransformInfo(F); });
284 }
285 
parseBinutilsVersion(StringRef Version)286 std::pair<int, int> TargetMachine::parseBinutilsVersion(StringRef Version) {
287   if (Version == "none")
288     return {INT_MAX, INT_MAX}; // Make binutilsIsAtLeast() return true.
289   std::pair<int, int> Ret;
290   if (!Version.consumeInteger(10, Ret.first) && Version.consume_front("."))
291     Version.consumeInteger(10, Ret.second);
292   return Ret;
293 }
294