xref: /llvm-project/llvm/lib/Target/TargetMachine.cpp (revision 63c378d3436d15ec92cd3f30f6ff41d86cd4036d)
1 //===-- TargetMachine.cpp - General Target Information ---------------------==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file describes the general parts of a Target machine.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Target/TargetMachine.h"
15 #include "llvm/Analysis/TargetTransformInfo.h"
16 #include "llvm/CodeGen/TargetLoweringObjectFile.h"
17 #include "llvm/CodeGen/TargetSubtargetInfo.h"
18 #include "llvm/IR/Function.h"
19 #include "llvm/IR/GlobalAlias.h"
20 #include "llvm/IR/GlobalValue.h"
21 #include "llvm/IR/GlobalVariable.h"
22 #include "llvm/IR/LegacyPassManager.h"
23 #include "llvm/IR/Mangler.h"
24 #include "llvm/MC/MCAsmInfo.h"
25 #include "llvm/MC/MCContext.h"
26 #include "llvm/MC/MCInstrInfo.h"
27 #include "llvm/MC/MCSectionMachO.h"
28 #include "llvm/MC/MCTargetOptions.h"
29 #include "llvm/MC/SectionKind.h"
30 using namespace llvm;
31 
32 //---------------------------------------------------------------------------
33 // TargetMachine Class
34 //
35 
36 TargetMachine::TargetMachine(const Target &T, StringRef DataLayoutString,
37                              const Triple &TT, StringRef CPU, StringRef FS,
38                              const TargetOptions &Options)
39     : TheTarget(T), DL(DataLayoutString), TargetTriple(TT), TargetCPU(CPU),
40       TargetFS(FS), AsmInfo(nullptr), MRI(nullptr), MII(nullptr), STI(nullptr),
41       RequireStructuredCFG(false), DefaultOptions(Options), Options(Options) {
42 }
43 
44 TargetMachine::~TargetMachine() {
45   delete AsmInfo;
46   delete MRI;
47   delete MII;
48   delete STI;
49 }
50 
51 bool TargetMachine::isPositionIndependent() const {
52   return getRelocationModel() == Reloc::PIC_;
53 }
54 
55 /// \brief Reset the target options based on the function's attributes.
56 // FIXME: This function needs to go away for a number of reasons:
57 // a) global state on the TargetMachine is terrible in general,
58 // b) these target options should be passed only on the function
59 //    and not on the TargetMachine (via TargetOptions) at all.
60 void TargetMachine::resetTargetOptions(const Function &F) const {
61 #define RESET_OPTION(X, Y)                                                     \
62   do {                                                                         \
63     if (F.hasFnAttribute(Y))                                                   \
64       Options.X = (F.getFnAttribute(Y).getValueAsString() == "true");          \
65     else                                                                       \
66       Options.X = DefaultOptions.X;                                            \
67   } while (0)
68 
69   RESET_OPTION(UnsafeFPMath, "unsafe-fp-math");
70   RESET_OPTION(NoInfsFPMath, "no-infs-fp-math");
71   RESET_OPTION(NoNaNsFPMath, "no-nans-fp-math");
72   RESET_OPTION(NoSignedZerosFPMath, "no-signed-zeros-fp-math");
73   RESET_OPTION(NoTrappingFPMath, "no-trapping-math");
74 
75   StringRef Denormal =
76     F.getFnAttribute("denormal-fp-math").getValueAsString();
77   if (Denormal == "ieee")
78     Options.FPDenormalMode = FPDenormal::IEEE;
79   else if (Denormal == "preserve-sign")
80     Options.FPDenormalMode = FPDenormal::PreserveSign;
81   else if (Denormal == "positive-zero")
82     Options.FPDenormalMode = FPDenormal::PositiveZero;
83   else
84     Options.FPDenormalMode = DefaultOptions.FPDenormalMode;
85 }
86 
87 /// Returns the code generation relocation model. The choices are static, PIC,
88 /// and dynamic-no-pic.
89 Reloc::Model TargetMachine::getRelocationModel() const { return RM; }
90 
91 /// Returns the code model. The choices are small, kernel, medium, large, and
92 /// target default.
93 CodeModel::Model TargetMachine::getCodeModel() const { return CMModel; }
94 
95 /// Get the IR-specified TLS model for Var.
96 static TLSModel::Model getSelectedTLSModel(const GlobalValue *GV) {
97   switch (GV->getThreadLocalMode()) {
98   case GlobalVariable::NotThreadLocal:
99     llvm_unreachable("getSelectedTLSModel for non-TLS variable");
100     break;
101   case GlobalVariable::GeneralDynamicTLSModel:
102     return TLSModel::GeneralDynamic;
103   case GlobalVariable::LocalDynamicTLSModel:
104     return TLSModel::LocalDynamic;
105   case GlobalVariable::InitialExecTLSModel:
106     return TLSModel::InitialExec;
107   case GlobalVariable::LocalExecTLSModel:
108     return TLSModel::LocalExec;
109   }
110   llvm_unreachable("invalid TLS model");
111 }
112 
113 bool TargetMachine::shouldAssumeDSOLocal(const Module &M,
114                                          const GlobalValue *GV) const {
115   // If the IR producer requested that this GV be treated as dso local, obey.
116   if (GV && GV->isDSOLocal())
117     return true;
118 
119   // If we are not supossed to use a PLT, we cannot assume that intrinsics are
120   // local since the linker can convert some direct access to access via plt.
121   if (M.getRtLibUseGOT() && !GV)
122     return false;
123 
124   // According to the llvm language reference, we should be able to
125   // just return false in here if we have a GV, as we know it is
126   // dso_preemptable.  At this point in time, the various IR producers
127   // have not been transitioned to always produce a dso_local when it
128   // is possible to do so.
129   // In the case of intrinsics, GV is null and there is nowhere to put
130   // dso_local. Returning false for those will produce worse code in some
131   // architectures. For example, on x86 the caller has to set ebx before calling
132   // a plt.
133   // As a result we still have some logic in here to improve the quality of the
134   // generated code.
135   // FIXME: Add a module level metadata for whether intrinsics should be assumed
136   // local.
137 
138   Reloc::Model RM = getRelocationModel();
139   const Triple &TT = getTargetTriple();
140 
141   // DLLImport explicitly marks the GV as external.
142   if (GV && GV->hasDLLImportStorageClass())
143     return false;
144 
145   // Every other GV is local on COFF.
146   // Make an exception for windows OS in the triple: Some firmware builds use
147   // *-win32-macho triples. This (accidentally?) produced windows relocations
148   // without GOT tables in older clang versions; Keep this behaviour.
149   if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
150     return true;
151 
152   // Most PIC code sequences that assume that a symbol is local cannot
153   // produce a 0 if it turns out the symbol is undefined. While this
154   // is ABI and relocation depended, it seems worth it to handle it
155   // here.
156   if (GV && isPositionIndependent() && GV->hasExternalWeakLinkage())
157     return false;
158 
159   if (GV && !GV->hasDefaultVisibility())
160     return true;
161 
162   if (TT.isOSBinFormatMachO()) {
163     if (RM == Reloc::Static)
164       return true;
165     return GV && GV->isStrongDefinitionForLinker();
166   }
167 
168   assert(TT.isOSBinFormatELF());
169   assert(RM != Reloc::DynamicNoPIC);
170 
171   bool IsExecutable =
172       RM == Reloc::Static || M.getPIELevel() != PIELevel::Default;
173   if (IsExecutable) {
174     // If the symbol is defined, it cannot be preempted.
175     if (GV && !GV->isDeclarationForLinker())
176       return true;
177 
178     // A symbol marked nonlazybind should not be accessed with a plt. If the
179     // symbol turns out to be external, the linker will convert a direct
180     // access to an access via the plt, so don't assume it is local.
181     const Function *F = dyn_cast_or_null<Function>(GV);
182     if (F && F->hasFnAttribute(Attribute::NonLazyBind))
183       return false;
184 
185     bool IsTLS = GV && GV->isThreadLocal();
186     bool IsAccessViaCopyRelocs =
187         GV && Options.MCOptions.MCPIECopyRelocations && isa<GlobalVariable>(GV);
188     Triple::ArchType Arch = TT.getArch();
189     bool IsPPC =
190         Arch == Triple::ppc || Arch == Triple::ppc64 || Arch == Triple::ppc64le;
191     // Check if we can use copy relocations. PowerPC has no copy relocations.
192     if (!IsTLS && !IsPPC && (RM == Reloc::Static || IsAccessViaCopyRelocs))
193       return true;
194   }
195 
196   // ELF supports preemption of other symbols.
197   return false;
198 }
199 
200 bool TargetMachine::useEmulatedTLS() const {
201   // Returns Options.EmulatedTLS if the -emulated-tls or -no-emulated-tls
202   // was specified explicitly; otherwise uses target triple to decide default.
203   if (Options.ExplicitEmulatedTLS)
204     return Options.EmulatedTLS;
205   return getTargetTriple().hasDefaultEmulatedTLS();
206 }
207 
208 TLSModel::Model TargetMachine::getTLSModel(const GlobalValue *GV) const {
209   bool IsPIE = GV->getParent()->getPIELevel() != PIELevel::Default;
210   Reloc::Model RM = getRelocationModel();
211   bool IsSharedLibrary = RM == Reloc::PIC_ && !IsPIE;
212   bool IsLocal = shouldAssumeDSOLocal(*GV->getParent(), GV);
213 
214   TLSModel::Model Model;
215   if (IsSharedLibrary) {
216     if (IsLocal)
217       Model = TLSModel::LocalDynamic;
218     else
219       Model = TLSModel::GeneralDynamic;
220   } else {
221     if (IsLocal)
222       Model = TLSModel::LocalExec;
223     else
224       Model = TLSModel::InitialExec;
225   }
226 
227   // If the user specified a more specific model, use that.
228   TLSModel::Model SelectedModel = getSelectedTLSModel(GV);
229   if (SelectedModel > Model)
230     return SelectedModel;
231 
232   return Model;
233 }
234 
235 /// Returns the optimization level: None, Less, Default, or Aggressive.
236 CodeGenOpt::Level TargetMachine::getOptLevel() const { return OptLevel; }
237 
238 void TargetMachine::setOptLevel(CodeGenOpt::Level Level) { OptLevel = Level; }
239 
240 TargetTransformInfo TargetMachine::getTargetTransformInfo(const Function &F) {
241   return TargetTransformInfo(F.getParent()->getDataLayout());
242 }
243 
244 void TargetMachine::getNameWithPrefix(SmallVectorImpl<char> &Name,
245                                       const GlobalValue *GV, Mangler &Mang,
246                                       bool MayAlwaysUsePrivate) const {
247   if (MayAlwaysUsePrivate || !GV->hasPrivateLinkage()) {
248     // Simple case: If GV is not private, it is not important to find out if
249     // private labels are legal in this case or not.
250     Mang.getNameWithPrefix(Name, GV, false);
251     return;
252   }
253   const TargetLoweringObjectFile *TLOF = getObjFileLowering();
254   TLOF->getNameWithPrefix(Name, GV, *this);
255 }
256 
257 MCSymbol *TargetMachine::getSymbol(const GlobalValue *GV) const {
258   const TargetLoweringObjectFile *TLOF = getObjFileLowering();
259   SmallString<128> NameStr;
260   getNameWithPrefix(NameStr, GV, TLOF->getMangler());
261   return TLOF->getContext().getOrCreateSymbol(NameStr);
262 }
263 
264 TargetIRAnalysis TargetMachine::getTargetIRAnalysis() {
265   // Since Analysis can't depend on Target, use a std::function to invert the
266   // dependency.
267   return TargetIRAnalysis(
268       [this](const Function &F) { return this->getTargetTransformInfo(F); });
269 }
270