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   // According to the llvm language reference, we should be able to just return
120   // false in here if we have a GV, as we know it is dso_preemptable.
121   // At this point in time, the various IR producers have not been transitioned
122   // to always produce a dso_local when it is possible to do so. As a result we
123   // still have some pre-dso_local logic in here to improve the quality of the
124   // generated code:
125 
126   Reloc::Model RM = getRelocationModel();
127   const Triple &TT = getTargetTriple();
128 
129   // DLLImport explicitly marks the GV as external.
130   if (GV && GV->hasDLLImportStorageClass())
131     return false;
132 
133   // Every other GV is local on COFF.
134   // Make an exception for windows OS in the triple: Some firmware builds use
135   // *-win32-macho triples. This (accidentally?) produced windows relocations
136   // without GOT tables in older clang versions; Keep this behaviour.
137   if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
138     return true;
139 
140   // If GV is null we know that this is a call to an intrinsic. For ELF and
141   // MachO we don't need to assume those are local since the liker can trivially
142   // convert a call to a PLT to a direct call if the target (in the runtime
143   // library) turns out to be local.
144   if (!GV)
145     return false;
146 
147   // Most PIC code sequences that assume that a symbol is local cannot
148   // produce a 0 if it turns out the symbol is undefined. While this
149   // is ABI and relocation depended, it seems worth it to handle it
150   // here.
151   if (isPositionIndependent() && GV->hasExternalWeakLinkage())
152     return false;
153 
154   if (!GV->hasDefaultVisibility())
155     return true;
156 
157   if (TT.isOSBinFormatMachO()) {
158     if (RM == Reloc::Static)
159       return true;
160     return GV->isStrongDefinitionForLinker();
161   }
162 
163   assert(TT.isOSBinFormatELF());
164   assert(RM != Reloc::DynamicNoPIC);
165 
166   bool IsExecutable =
167       RM == Reloc::Static || M.getPIELevel() != PIELevel::Default;
168   if (IsExecutable) {
169     // If the symbol is defined, it cannot be preempted.
170     if (!GV->isDeclarationForLinker())
171       return true;
172 
173     // A symbol marked nonlazybind should not be accessed with a plt. If the
174     // symbol turns out to be external, the linker will convert a direct
175     // access to an access via the plt, so don't assume it is local.
176     const Function *F = dyn_cast<Function>(GV);
177     if (F && F->hasFnAttribute(Attribute::NonLazyBind))
178       return false;
179 
180     bool IsTLS = GV->isThreadLocal();
181     bool IsAccessViaCopyRelocs =
182         Options.MCOptions.MCPIECopyRelocations && isa<GlobalVariable>(GV);
183     Triple::ArchType Arch = TT.getArch();
184     bool IsPPC =
185         Arch == Triple::ppc || Arch == Triple::ppc64 || Arch == Triple::ppc64le;
186     // Check if we can use copy relocations. PowerPC has no copy relocations.
187     if (!IsTLS && !IsPPC && (RM == Reloc::Static || IsAccessViaCopyRelocs))
188       return true;
189   }
190 
191   // ELF supports preemption of other symbols.
192   return false;
193 }
194 
195 bool TargetMachine::useEmulatedTLS() const {
196   // Returns Options.EmulatedTLS if the -emulated-tls or -no-emulated-tls
197   // was specified explicitly; otherwise uses target triple to decide default.
198   if (Options.ExplicitEmulatedTLS)
199     return Options.EmulatedTLS;
200   return getTargetTriple().hasDefaultEmulatedTLS();
201 }
202 
203 TLSModel::Model TargetMachine::getTLSModel(const GlobalValue *GV) const {
204   bool IsPIE = GV->getParent()->getPIELevel() != PIELevel::Default;
205   Reloc::Model RM = getRelocationModel();
206   bool IsSharedLibrary = RM == Reloc::PIC_ && !IsPIE;
207   bool IsLocal = shouldAssumeDSOLocal(*GV->getParent(), GV);
208 
209   TLSModel::Model Model;
210   if (IsSharedLibrary) {
211     if (IsLocal)
212       Model = TLSModel::LocalDynamic;
213     else
214       Model = TLSModel::GeneralDynamic;
215   } else {
216     if (IsLocal)
217       Model = TLSModel::LocalExec;
218     else
219       Model = TLSModel::InitialExec;
220   }
221 
222   // If the user specified a more specific model, use that.
223   TLSModel::Model SelectedModel = getSelectedTLSModel(GV);
224   if (SelectedModel > Model)
225     return SelectedModel;
226 
227   return Model;
228 }
229 
230 /// Returns the optimization level: None, Less, Default, or Aggressive.
231 CodeGenOpt::Level TargetMachine::getOptLevel() const { return OptLevel; }
232 
233 void TargetMachine::setOptLevel(CodeGenOpt::Level Level) { OptLevel = Level; }
234 
235 TargetTransformInfo TargetMachine::getTargetTransformInfo(const Function &F) {
236   return TargetTransformInfo(F.getParent()->getDataLayout());
237 }
238 
239 void TargetMachine::getNameWithPrefix(SmallVectorImpl<char> &Name,
240                                       const GlobalValue *GV, Mangler &Mang,
241                                       bool MayAlwaysUsePrivate) const {
242   if (MayAlwaysUsePrivate || !GV->hasPrivateLinkage()) {
243     // Simple case: If GV is not private, it is not important to find out if
244     // private labels are legal in this case or not.
245     Mang.getNameWithPrefix(Name, GV, false);
246     return;
247   }
248   const TargetLoweringObjectFile *TLOF = getObjFileLowering();
249   TLOF->getNameWithPrefix(Name, GV, *this);
250 }
251 
252 MCSymbol *TargetMachine::getSymbol(const GlobalValue *GV) const {
253   const TargetLoweringObjectFile *TLOF = getObjFileLowering();
254   SmallString<128> NameStr;
255   getNameWithPrefix(NameStr, GV, TLOF->getMangler());
256   return TLOF->getContext().getOrCreateSymbol(NameStr);
257 }
258 
259 TargetIRAnalysis TargetMachine::getTargetIRAnalysis() {
260   // Since Analysis can't depend on Target, use a std::function to invert the
261   // dependency.
262   return TargetIRAnalysis(
263       [this](const Function &F) { return this->getTargetTransformInfo(F); });
264 }
265