LLVM 22.0.0git
TargetMachine.cpp
Go to the documentation of this file.
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
15#include "llvm/IR/Function.h"
16#include "llvm/IR/GlobalValue.h"
18#include "llvm/IR/Mangler.h"
19#include "llvm/IR/Module.h"
20#include "llvm/MC/MCAsmInfo.h"
21#include "llvm/MC/MCContext.h"
22#include "llvm/MC/MCInstrInfo.h"
24#include "llvm/MC/MCStreamer.h"
28using namespace llvm;
29
31 "no-kernel-info-end-lto",
32 cl::desc("remove the kernel-info pass at the end of the full LTO pipeline"),
33 cl::init(false), cl::Hidden);
34
35//---------------------------------------------------------------------------
36// TargetMachine Class
37//
38
40 const Triple &TT, StringRef CPU, StringRef FS,
42 : TheTarget(T), DL(DataLayoutString), TargetTriple(TT),
43 TargetCPU(std::string(CPU)), TargetFS(std::string(FS)), AsmInfo(nullptr),
44 MRI(nullptr), MII(nullptr), STI(nullptr), RequireStructuredCFG(false),
45 O0WantsFastISel(false), Options(Options) {}
46
48
51 raw_pwrite_stream *DwoOut,
52 CodeGenFileType FileType, MCContext &Ctx) {
53 return nullptr;
54}
55
57 if (getTargetTriple().getArch() != Triple::x86_64)
58 return false;
59
60 // Remaining logic below is ELF-specific. For other object file formats where
61 // the large code model is mostly used for JIT compilation, just look at the
62 // code model.
63 if (!getTargetTriple().isOSBinFormatELF())
65
66 auto *GO = GVal->getAliaseeObject();
67
68 // Be conservative if we can't find an underlying GlobalObject.
69 if (!GO)
70 return true;
71
72 auto *GV = dyn_cast<GlobalVariable>(GO);
73
74 auto IsPrefix = [](StringRef Name, StringRef Prefix) {
75 return Name.consume_front(Prefix) && (Name.empty() || Name[0] == '.');
76 };
77
78 // Functions/GlobalIFuncs are only large under the large code model.
79 if (!GV) {
80 // Handle explicit sections as we do for GlobalVariables with an explicit
81 // section, see comments below.
82 if (GO->hasSection()) {
83 StringRef Name = GO->getSection();
84 return IsPrefix(Name, ".ltext");
85 }
87 }
88
89 if (GV->isThreadLocal())
90 return false;
91
92 // For x86-64, we treat an explicit GlobalVariable small code model to mean
93 // that the global should be placed in a small section, and ditto for large.
94 if (auto CM = GV->getCodeModel()) {
95 if (*CM == CodeModel::Small)
96 return false;
97 if (*CM == CodeModel::Large)
98 return true;
99 }
100
101 // Treat all globals in explicit sections as small, except for the standard
102 // large sections of .lbss, .ldata, .lrodata. This reduces the risk of linking
103 // together small and large sections, resulting in small references to large
104 // data sections. The code model attribute overrides this above.
105 if (GV->hasSection()) {
106 StringRef Name = GV->getSection();
107 return IsPrefix(Name, ".lbss") || IsPrefix(Name, ".ldata") ||
108 IsPrefix(Name, ".lrodata");
109 }
110
111 // Respect large data threshold for medium and large code models.
114 if (!GV->getValueType()->isSized())
115 return true;
116 // Linker defined start/stop symbols can point to arbitrary points in the
117 // binary, so treat them as large.
118 if (GV->isDeclaration() && (GV->getName() == "__ehdr_start" ||
119 GV->getName().starts_with("__start_") ||
120 GV->getName().starts_with("__stop_")))
121 return true;
122 // Linkers do not currently support PT_GNU_RELRO for SHF_X86_64_LARGE
123 // sections; that would require the linker to emit more than one
124 // PT_GNU_RELRO because large sections are discontiguous by design, and most
125 // ELF dynamic loaders do not support that (bionic appears to support it but
126 // glibc/musl/FreeBSD/NetBSD/OpenBSD appear not to). With current linkers
127 // these sections will end up in .ldata which results in silently disabling
128 // RELRO. If this ever gets supported by downstream components in the future
129 // we could add an opt-in flag for moving these sections to .ldata.rel.ro
130 // which would trigger the creation of a second PT_GNU_RELRO.
131 if (!GV->isDeclarationForLinker() &&
134 return false;
135 const DataLayout &DL = GV->getDataLayout();
136 uint64_t Size = DL.getTypeAllocSize(GV->getValueType());
137 return Size == 0 || Size > LargeDataThreshold;
138 }
139
140 return false;
141}
142
145}
146
147/// Reset the target options based on the function's attributes.
148/// setFunctionAttributes should have made the raw attribute value consistent
149/// with the command line flag if used.
150//
151// FIXME: This function needs to go away for a number of reasons:
152// a) global state on the TargetMachine is terrible in general,
153// b) these target options should be passed only on the function
154// and not on the TargetMachine (via TargetOptions) at all.
156#define RESET_OPTION(X, Y) \
157 do { \
158 Options.X = F.getFnAttribute(Y).getValueAsBool(); \
159 } while (0)
160
161 RESET_OPTION(UnsafeFPMath, "unsafe-fp-math");
162 RESET_OPTION(NoInfsFPMath, "no-infs-fp-math");
163 RESET_OPTION(NoNaNsFPMath, "no-nans-fp-math");
164 RESET_OPTION(NoSignedZerosFPMath, "no-signed-zeros-fp-math");
165}
166
167/// Returns the code generation relocation model. The choices are static, PIC,
168/// and dynamic-no-pic.
170
172 switch (getCodeModel()) {
173 case CodeModel::Tiny:
174 return llvm::maxUIntN(10);
175 case CodeModel::Small:
178 return llvm::maxUIntN(31);
179 case CodeModel::Large:
180 return llvm::maxUIntN(64);
181 }
182 llvm_unreachable("Unhandled CodeModel enum");
183}
184
185/// Get the IR-specified TLS model for Var.
187 switch (GV->getThreadLocalMode()) {
189 llvm_unreachable("getSelectedTLSModel for non-TLS variable");
190 break;
198 return TLSModel::LocalExec;
199 }
200 llvm_unreachable("invalid TLS model");
201}
202
204 const Triple &TT = getTargetTriple();
206
207 // According to the llvm language reference, we should be able to
208 // just return false in here if we have a GV, as we know it is
209 // dso_preemptable. At this point in time, the various IR producers
210 // have not been transitioned to always produce a dso_local when it
211 // is possible to do so.
212 //
213 // As a result we still have some logic in here to improve the quality of the
214 // generated code.
215 if (!GV)
216 return false;
217
218 // If the IR producer requested that this GV be treated as dso local, obey.
219 if (GV->isDSOLocal())
220 return true;
221
222 if (TT.isOSBinFormatCOFF()) {
223 // DLLImport explicitly marks the GV as external.
224 if (GV->hasDLLImportStorageClass())
225 return false;
226
227 // On MinGW, variables that haven't been declared with DLLImport may still
228 // end up automatically imported by the linker. To make this feasible,
229 // don't assume the variables to be DSO local unless we actually know
230 // that for sure. This only has to be done for variables; for functions
231 // the linker can insert thunks for calling functions from another DLL.
232 if (TT.isOSCygMing() && GV->isDeclarationForLinker() &&
233 isa<GlobalVariable>(GV))
234 return false;
235
236 // Don't mark 'extern_weak' symbols as DSO local. If these symbols remain
237 // unresolved in the link, they can be resolved to zero, which is outside
238 // the current DSO.
239 if (GV->hasExternalWeakLinkage())
240 return false;
241
242 // Every other GV is local on COFF.
243 return true;
244 }
245
246 if (TT.isOSBinFormatGOFF())
247 return true;
248
249 if (TT.isOSBinFormatMachO()) {
250 if (RM == Reloc::Static)
251 return true;
252 return GV->isStrongDefinitionForLinker();
253 }
254
255 assert(TT.isOSBinFormatELF() || TT.isOSBinFormatWasm() ||
256 TT.isOSBinFormatXCOFF());
257 return false;
258}
259
262
264 bool IsPIE = GV->getParent()->getPIELevel() != PIELevel::Default;
266 bool IsSharedLibrary = RM == Reloc::PIC_ && !IsPIE;
267 bool IsLocal = shouldAssumeDSOLocal(GV);
268
269 TLSModel::Model Model;
270 if (IsSharedLibrary) {
271 if (IsLocal)
273 else
275 } else {
276 if (IsLocal)
277 Model = TLSModel::LocalExec;
278 else
279 Model = TLSModel::InitialExec;
280 }
281
282 // If the user specified a more specific model, use that.
283 TLSModel::Model SelectedModel = getSelectedTLSModel(GV);
284 if (SelectedModel > Model)
285 return SelectedModel;
286
287 return Model;
288}
289
292 return TargetTransformInfo(F.getDataLayout());
293}
294
296 const GlobalValue *GV, Mangler &Mang,
297 bool MayAlwaysUsePrivate) const {
298 if (MayAlwaysUsePrivate || !GV->hasPrivateLinkage()) {
299 // Simple case: If GV is not private, it is not important to find out if
300 // private labels are legal in this case or not.
301 Mang.getNameWithPrefix(Name, GV, false);
302 return;
303 }
305 TLOF->getNameWithPrefix(Name, GV, *this);
306}
307
310 // XCOFF symbols could have special naming convention.
311 if (MCSymbol *TargetSymbol = TLOF->getTargetSymbol(GV, *this))
312 return TargetSymbol;
313
314 SmallString<128> NameStr;
315 getNameWithPrefix(NameStr, GV, TLOF->getMangler());
316 return TLOF->getContext().getOrCreateSymbol(NameStr);
317}
318
320 // Since Analysis can't depend on Target, use a std::function to invert the
321 // dependency.
322 return TargetIRAnalysis(
323 [this](const Function &F) { return this->getTargetTransformInfo(F); });
324}
325
327 if (Version == "none")
328 return {INT_MAX, INT_MAX}; // Make binutilsIsAtLeast() return true.
329 std::pair<int, int> Ret;
330 if (!Version.consumeInteger(10, Ret.first) && Version.consume_front("."))
331 Version.consumeInteger(10, Ret.second);
332 return Ret;
333}
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
std::string Name
uint64_t Size
Module.h This file contains the declarations for the Module class.
static LVOptions Options
Definition: LVOptions.cpp:25
#define F(x, y, z)
Definition: MD5.cpp:55
static TLSModel::Model getSelectedTLSModel(const GlobalValue *GV)
Get the IR-specified TLS model for Var.
cl::opt< bool > NoKernelInfoEndLTO("no-kernel-info-end-lto", cl::desc("remove the kernel-info pass at the end of the full LTO pipeline"), cl::init(false), cl::Hidden)
#define RESET_OPTION(X, Y)
This pass exposes codegen information to IR-level passes.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:63
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:504
Tagged union holding either a T or a Error.
Definition: Error.h:485
bool isDSOLocal() const
Definition: GlobalValue.h:307
bool hasPrivateLinkage() const
Definition: GlobalValue.h:529
bool hasExternalWeakLinkage() const
Definition: GlobalValue.h:531
ThreadLocalMode getThreadLocalMode() const
Definition: GlobalValue.h:273
bool hasDLLImportStorageClass() const
Definition: GlobalValue.h:280
bool isDeclarationForLinker() const
Definition: GlobalValue.h:625
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:663
LLVM_ABI const GlobalObject * getAliaseeObject() const
Definition: Globals.cpp:419
bool isStrongDefinitionForLinker() const
Returns true if this global's definition will be the one chosen by the linker.
Definition: GlobalValue.h:638
Context object for machine code objects.
Definition: MCContext.h:83
LLVM_ABI MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Definition: MCContext.cpp:203
MCContext & getContext() const
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:42
LLVM_ABI void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable's name.
Definition: Mangler.cpp:121
PIELevel::Level getPIELevel() const
Returns the PIE level (small or large model)
Definition: Module.cpp:631
bool isReadOnlyWithRel() const
Definition: SectionKind.h:177
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:574
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
Analysis pass providing the TargetTransformInfo.
virtual void getNameWithPrefix(SmallVectorImpl< char > &OutName, const GlobalValue *GV, const TargetMachine &TM) const
static SectionKind getKindForGlobal(const GlobalObject *GO, const TargetMachine &TM)
Classify the specified global variable into a set of target independent categories embodied in Sectio...
virtual MCSymbol * getTargetSymbol(const GlobalValue *GV, const TargetMachine &TM) const
Targets that have a special convention for their symbols could use this hook to return a specialized ...
TLSModel::Model getTLSModel(const GlobalValue *GV) const
Returns the TLS model which should be used for the given global variable.
bool isPositionIndependent() const
uint64_t getMaxCodeSize() const
Returns the maximum code size possible under the code model.
const Triple & getTargetTriple() const
bool useTLSDESC() const
Returns true if this target uses TLS Descriptors.
uint64_t LargeDataThreshold
bool useEmulatedTLS() const
Returns true if this target uses emulated TLS.
virtual TargetLoweringObjectFile * getObjFileLowering() const
Reloc::Model getRelocationModel() const
Returns the code generation relocation model.
virtual TargetTransformInfo getTargetTransformInfo(const Function &F) const
Return a TargetTransformInfo for a given function.
const DataLayout DL
DataLayout for the target: keep ABI type size and alignment.
Definition: TargetMachine.h:98
bool shouldAssumeDSOLocal(const GlobalValue *GV) const
virtual Expected< std::unique_ptr< MCStreamer > > createMCStreamer(raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType, MCContext &Ctx)
static std::pair< int, int > parseBinutilsVersion(StringRef Version)
TargetIRAnalysis getTargetIRAnalysis() const
Get a TargetIRAnalysis appropriate for the target.
TargetOptions Options
virtual ~TargetMachine()
MCSymbol * getSymbol(const GlobalValue *GV) const
CodeModel::Model getCodeModel() const
Returns the code model.
bool isLargeGlobalValue(const GlobalValue *GV) const
void resetTargetOptions(const Function &F) const
Reset the target options based on the function's attributes.
TargetMachine(const Target &T, StringRef DataLayoutString, const Triple &TargetTriple, StringRef CPU, StringRef FS, const TargetOptions &Options)
void getNameWithPrefix(SmallVectorImpl< char > &Name, const GlobalValue *GV, Mangler &Mang, bool MayAlwaysUsePrivate=false) const
unsigned EnableTLSDESC
EnableTLSDESC - This flag enables TLS Descriptors.
unsigned EmulatedTLS
EmulatedTLS - This flag enables emulated TLS model, using emutls function in the runtime library.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:47
An abstract base class for streams implementations that also support a pwrite operation.
Definition: raw_ostream.h:435
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ GeneralDynamic
Definition: CodeGen.h:46
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:444
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
constexpr uint64_t maxUIntN(uint64_t N)
Gets the maximum value for a N-bit unsigned integer.
Definition: MathExtras.h:216
CodeGenFileType
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit,...
Definition: CodeGen.h:111
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:856