Movatterモバイル変換


[0]ホーム

URL:


LLVM 20.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
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/IR/Module.h"
20#include "llvm/MC/MCAsmInfo.h"
21#include "llvm/MC/MCContext.h"
22#include "llvm/MC/MCInstrInfo.h"
23#include "llvm/MC/MCRegisterInfo.h"
24#include "llvm/MC/MCSubtargetInfo.h"
25#include "llvm/Support/CodeGen.h"
26#include "llvm/Target/TargetLoweringObjectFile.h"
27using namespacellvm;
28
29//---------------------------------------------------------------------------
30// TargetMachine Class
31//
32
33TargetMachine::TargetMachine(constTarget &T,StringRef DataLayoutString,
34constTriple &TT,StringRef CPU,StringRef FS,
35constTargetOptions &Options)
36 : TheTarget(T),DL(DataLayoutString), TargetTriple(TT),
37 TargetCPU(std::string(CPU)), TargetFS(std::string(FS)), AsmInfo(nullptr),
38MRI(nullptr), MII(nullptr), STI(nullptr), RequireStructuredCFG(false),
39 O0WantsFastISel(false),Options(Options) {}
40
41TargetMachine::~TargetMachine() =default;
42
43boolTargetMachine::isLargeGlobalValue(constGlobalValue *GVal) const{
44if (getTargetTriple().getArch() !=Triple::x86_64)
45returnfalse;
46
47// Remaining logic below is ELF-specific. For other object file formats where
48// the large code model is mostly used for JIT compilation, just look at the
49// code model.
50if (!getTargetTriple().isOSBinFormatELF())
51returngetCodeModel() ==CodeModel::Large;
52
53auto *GO = GVal->getAliaseeObject();
54
55// Be conservative if we can't find an underlying GlobalObject.
56if (!GO)
57returntrue;
58
59auto *GV = dyn_cast<GlobalVariable>(GO);
60
61auto IsPrefix = [](StringRefName,StringRef Prefix) {
62returnName.consume_front(Prefix) && (Name.empty() ||Name[0] =='.');
63 };
64
65// Functions/GlobalIFuncs are only large under the large code model.
66if (!GV) {
67// Handle explicit sections as we do for GlobalVariables with an explicit
68// section, see comments below.
69if (GO->hasSection()) {
70StringRefName = GO->getSection();
71return IsPrefix(Name,".ltext");
72 }
73returngetCodeModel() ==CodeModel::Large;
74 }
75
76if (GV->isThreadLocal())
77returnfalse;
78
79// For x86-64, we treat an explicit GlobalVariable small code model to mean
80// that the global should be placed in a small section, and ditto for large.
81if (auto CM = GV->getCodeModel()) {
82if (*CM ==CodeModel::Small)
83returnfalse;
84if (*CM ==CodeModel::Large)
85returntrue;
86 }
87
88// Treat all globals in explicit sections as small, except for the standard
89// large sections of .lbss, .ldata, .lrodata. This reduces the risk of linking
90// together small and large sections, resulting in small references to large
91// data sections. The code model attribute overrides this above.
92if (GV->hasSection()) {
93StringRefName = GV->getSection();
94return IsPrefix(Name,".lbss") || IsPrefix(Name,".ldata") ||
95 IsPrefix(Name,".lrodata");
96 }
97
98// Respect large data threshold for medium and large code models.
99if (getCodeModel() ==CodeModel::Medium ||
100getCodeModel() ==CodeModel::Large) {
101if (!GV->getValueType()->isSized())
102returntrue;
103// Linker defined start/stop symbols can point to arbitrary points in the
104// binary, so treat them as large.
105if (GV->isDeclaration() && (GV->getName() =="__ehdr_start" ||
106 GV->getName().starts_with("__start_") ||
107 GV->getName().starts_with("__stop_")))
108returntrue;
109constDataLayout &DL = GV->getDataLayout();
110uint64_tSize =DL.getTypeAllocSize(GV->getValueType());
111returnSize == 0 ||Size >LargeDataThreshold;
112 }
113
114returnfalse;
115}
116
117boolTargetMachine::isPositionIndependent() const{
118returngetRelocationModel() ==Reloc::PIC_;
119}
120
121/// Reset the target options based on the function's attributes.
122/// setFunctionAttributes should have made the raw attribute value consistent
123/// with the command line flag if used.
124//
125// FIXME: This function needs to go away for a number of reasons:
126// a) global state on the TargetMachine is terrible in general,
127// b) these target options should be passed only on the function
128// and not on the TargetMachine (via TargetOptions) at all.
129voidTargetMachine::resetTargetOptions(constFunction &F) const{
130#define RESET_OPTION(X, Y) \
131 do { \
132 Options.X = F.getFnAttribute(Y).getValueAsBool(); \
133 } while (0)
134
135RESET_OPTION(UnsafeFPMath,"unsafe-fp-math");
136RESET_OPTION(NoInfsFPMath,"no-infs-fp-math");
137RESET_OPTION(NoNaNsFPMath,"no-nans-fp-math");
138RESET_OPTION(NoSignedZerosFPMath,"no-signed-zeros-fp-math");
139RESET_OPTION(ApproxFuncFPMath,"approx-func-fp-math");
140}
141
142/// Returns the code generation relocation model. The choices are static, PIC,
143/// and dynamic-no-pic.
144Reloc::ModelTargetMachine::getRelocationModel() const{returnRM; }
145
146uint64_tTargetMachine::getMaxCodeSize() const{
147switch (getCodeModel()) {
148caseCodeModel::Tiny:
149returnllvm::maxUIntN(10);
150caseCodeModel::Small:
151caseCodeModel::Kernel:
152caseCodeModel::Medium:
153returnllvm::maxUIntN(31);
154caseCodeModel::Large:
155returnllvm::maxUIntN(64);
156 }
157llvm_unreachable("Unhandled CodeModel enum");
158}
159
160/// Get the IR-specified TLS model for Var.
161staticTLSModel::ModelgetSelectedTLSModel(constGlobalValue *GV) {
162switch (GV->getThreadLocalMode()) {
163caseGlobalVariable::NotThreadLocal:
164llvm_unreachable("getSelectedTLSModel for non-TLS variable");
165break;
166caseGlobalVariable::GeneralDynamicTLSModel:
167returnTLSModel::GeneralDynamic;
168caseGlobalVariable::LocalDynamicTLSModel:
169returnTLSModel::LocalDynamic;
170caseGlobalVariable::InitialExecTLSModel:
171returnTLSModel::InitialExec;
172caseGlobalVariable::LocalExecTLSModel:
173returnTLSModel::LocalExec;
174 }
175llvm_unreachable("invalid TLS model");
176}
177
178boolTargetMachine::shouldAssumeDSOLocal(constGlobalValue *GV) const{
179constTriple &TT =getTargetTriple();
180Reloc::ModelRM =getRelocationModel();
181
182// According to the llvm language reference, we should be able to
183// just return false in here if we have a GV, as we know it is
184// dso_preemptable. At this point in time, the various IR producers
185// have not been transitioned to always produce a dso_local when it
186// is possible to do so.
187//
188// As a result we still have some logic in here to improve the quality of the
189// generated code.
190if (!GV)
191returnfalse;
192
193// If the IR producer requested that this GV be treated as dso local, obey.
194if (GV->isDSOLocal())
195returntrue;
196
197if (TT.isOSBinFormatCOFF()) {
198// DLLImport explicitly marks the GV as external.
199if (GV->hasDLLImportStorageClass())
200returnfalse;
201
202// On MinGW, variables that haven't been declared with DLLImport may still
203// end up automatically imported by the linker. To make this feasible,
204// don't assume the variables to be DSO local unless we actually know
205// that for sure. This only has to be done for variables; for functions
206// the linker can insert thunks for calling functions from another DLL.
207if (TT.isOSCygMing() && GV->isDeclarationForLinker() &&
208 isa<GlobalVariable>(GV))
209returnfalse;
210
211// Don't mark 'extern_weak' symbols as DSO local. If these symbols remain
212// unresolved in the link, they can be resolved to zero, which is outside
213// the current DSO.
214if (GV->hasExternalWeakLinkage())
215returnfalse;
216
217// Every other GV is local on COFF.
218returntrue;
219 }
220
221if (TT.isOSBinFormatGOFF())
222returntrue;
223
224if (TT.isOSBinFormatMachO()) {
225if (RM ==Reloc::Static)
226returntrue;
227return GV->isStrongDefinitionForLinker();
228 }
229
230assert(TT.isOSBinFormatELF() || TT.isOSBinFormatWasm() ||
231 TT.isOSBinFormatXCOFF());
232returnfalse;
233}
234
235boolTargetMachine::useEmulatedTLS() const{returnOptions.EmulatedTLS; }
236boolTargetMachine::useTLSDESC() const{returnOptions.EnableTLSDESC; }
237
238TLSModel::ModelTargetMachine::getTLSModel(constGlobalValue *GV) const{
239bool IsPIE = GV->getParent()->getPIELevel() !=PIELevel::Default;
240Reloc::ModelRM =getRelocationModel();
241bool IsSharedLibrary =RM ==Reloc::PIC_ && !IsPIE;
242bool IsLocal =shouldAssumeDSOLocal(GV);
243
244TLSModel::Model Model;
245if (IsSharedLibrary) {
246if (IsLocal)
247 Model =TLSModel::LocalDynamic;
248else
249 Model =TLSModel::GeneralDynamic;
250 }else {
251if (IsLocal)
252 Model =TLSModel::LocalExec;
253else
254 Model =TLSModel::InitialExec;
255 }
256
257// If the user specified a more specific model, use that.
258TLSModel::Model SelectedModel =getSelectedTLSModel(GV);
259if (SelectedModel > Model)
260return SelectedModel;
261
262return Model;
263}
264
265TargetTransformInfo
266TargetMachine::getTargetTransformInfo(constFunction &F) const{
267returnTargetTransformInfo(F.getDataLayout());
268}
269
270voidTargetMachine::getNameWithPrefix(SmallVectorImpl<char> &Name,
271constGlobalValue *GV,Mangler &Mang,
272bool MayAlwaysUsePrivate) const{
273if (MayAlwaysUsePrivate || !GV->hasPrivateLinkage()) {
274// Simple case: If GV is not private, it is not important to find out if
275// private labels are legal in this case or not.
276 Mang.getNameWithPrefix(Name, GV,false);
277return;
278 }
279constTargetLoweringObjectFile *TLOF =getObjFileLowering();
280 TLOF->getNameWithPrefix(Name, GV, *this);
281}
282
283MCSymbol *TargetMachine::getSymbol(constGlobalValue *GV) const{
284constTargetLoweringObjectFile *TLOF =getObjFileLowering();
285// XCOFF symbols could have special naming convention.
286if (MCSymbol *TargetSymbol = TLOF->getTargetSymbol(GV, *this))
287return TargetSymbol;
288
289SmallString<128> NameStr;
290getNameWithPrefix(NameStr, GV, TLOF->getMangler());
291return TLOF->getContext().getOrCreateSymbol(NameStr);
292}
293
294TargetIRAnalysisTargetMachine::getTargetIRAnalysis() const{
295// Since Analysis can't depend on Target, use a std::function to invert the
296// dependency.
297returnTargetIRAnalysis(
298 [this](constFunction &F) {return this->getTargetTransformInfo(F); });
299}
300
301std::pair<int, int>TargetMachine::parseBinutilsVersion(StringRefVersion) {
302if (Version =="none")
303return {INT_MAX, INT_MAX};// Make binutilsIsAtLeast() return true.
304 std::pair<int, int> Ret;
305if (!Version.consumeInteger(10, Ret.first) &&Version.consume_front("."))
306Version.consumeInteger(10, Ret.second);
307return Ret;
308}
MRI
unsigned const MachineRegisterInfo * MRI
Definition:AArch64AdvSIMDScalarPass.cpp:105
DL
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Definition:ARMSLSHardening.cpp:73
CodeGen.h
Name
std::string Name
Definition:ELFObjHandler.cpp:77
Size
uint64_t Size
Definition:ELFObjHandler.cpp:81
GlobalValue.h
GlobalVariable.h
Function.h
Module.h
Module.h This file contains the declarations for the Module class.
SpecialSubKind::string
@ string
Options
static LVOptions Options
Definition:LVOptions.cpp:25
MCAsmInfo.h
MCContext.h
MCInstrInfo.h
MCRegisterInfo.h
MCSubtargetInfo.h
F
#define F(x, y, z)
Definition:MD5.cpp:55
Mangler.h
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
TargetLoweringObjectFile.h
getSelectedTLSModel
static TLSModel::Model getSelectedTLSModel(const GlobalValue *GV)
Get the IR-specified TLS model for Var.
Definition:TargetMachine.cpp:161
RESET_OPTION
#define RESET_OPTION(X, Y)
TargetTransformInfo.h
This pass exposes codegen information to IR-level passes.
T
llvm::DataLayout
A parsed version of the target data layout string in and methods for querying it.
Definition:DataLayout.h:63
llvm::DataLayout::getTypeAllocSize
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition:DataLayout.h:457
llvm::Function
Definition:Function.h:63
llvm::GlobalValue
Definition:GlobalValue.h:48
llvm::GlobalValue::LocalExecTLSModel
@ LocalExecTLSModel
Definition:GlobalValue.h:201
llvm::GlobalValue::GeneralDynamicTLSModel
@ GeneralDynamicTLSModel
Definition:GlobalValue.h:198
llvm::GlobalValue::NotThreadLocal
@ NotThreadLocal
Definition:GlobalValue.h:197
llvm::GlobalValue::InitialExecTLSModel
@ InitialExecTLSModel
Definition:GlobalValue.h:200
llvm::GlobalValue::LocalDynamicTLSModel
@ LocalDynamicTLSModel
Definition:GlobalValue.h:199
llvm::GlobalValue::isDSOLocal
bool isDSOLocal() const
Definition:GlobalValue.h:306
llvm::GlobalValue::hasPrivateLinkage
bool hasPrivateLinkage() const
Definition:GlobalValue.h:528
llvm::GlobalValue::hasExternalWeakLinkage
bool hasExternalWeakLinkage() const
Definition:GlobalValue.h:530
llvm::GlobalValue::getThreadLocalMode
ThreadLocalMode getThreadLocalMode() const
Definition:GlobalValue.h:272
llvm::GlobalValue::hasDLLImportStorageClass
bool hasDLLImportStorageClass() const
Definition:GlobalValue.h:279
llvm::GlobalValue::isDeclarationForLinker
bool isDeclarationForLinker() const
Definition:GlobalValue.h:619
llvm::GlobalValue::getParent
Module * getParent()
Get the module that this global value is contained inside of...
Definition:GlobalValue.h:657
llvm::GlobalValue::getAliaseeObject
const GlobalObject * getAliaseeObject() const
Definition:Globals.cpp:400
llvm::GlobalValue::isStrongDefinitionForLinker
bool isStrongDefinitionForLinker() const
Returns true if this global's definition will be the one chosen by the linker.
Definition:GlobalValue.h:632
llvm::MCContext::getOrCreateSymbol
MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Definition:MCContext.cpp:212
llvm::MCObjectFileInfo::getContext
MCContext & getContext() const
Definition:MCObjectFileInfo.h:252
llvm::MCSymbol
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition:MCSymbol.h:41
llvm::Mangler
Definition:Mangler.h:28
llvm::Mangler::getNameWithPrefix
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
llvm::Module::getPIELevel
PIELevel::Level getPIELevel() const
Returns the PIE level (small or large model)
Definition:Module.cpp:633
llvm::SmallString
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition:SmallString.h:26
llvm::SmallVectorImpl
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition:SmallVector.h:573
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition:StringRef.h:51
llvm::TargetIRAnalysis
Analysis pass providing the TargetTransformInfo.
Definition:TargetTransformInfo.h:3194
llvm::TargetLoweringObjectFile
Definition:TargetLoweringObjectFile.h:45
llvm::TargetLoweringObjectFile::getNameWithPrefix
virtual void getNameWithPrefix(SmallVectorImpl< char > &OutName, const GlobalValue *GV, const TargetMachine &TM) const
Definition:TargetLoweringObjectFile.cpp:432
llvm::TargetLoweringObjectFile::getMangler
Mangler & getMangler() const
Definition:TargetLoweringObjectFile.h:77
llvm::TargetLoweringObjectFile::getTargetSymbol
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 ...
Definition:TargetLoweringObjectFile.h:278
llvm::TargetMachine::getTLSModel
TLSModel::Model getTLSModel(const GlobalValue *GV) const
Returns the TLS model which should be used for the given global variable.
Definition:TargetMachine.cpp:238
llvm::TargetMachine::isPositionIndependent
bool isPositionIndependent() const
Definition:TargetMachine.cpp:117
llvm::TargetMachine::getMaxCodeSize
uint64_t getMaxCodeSize() const
Returns the maximum code size possible under the code model.
Definition:TargetMachine.cpp:146
llvm::TargetMachine::getTargetTriple
const Triple & getTargetTriple() const
Definition:TargetMachine.h:126
llvm::TargetMachine::useTLSDESC
bool useTLSDESC() const
Returns true if this target uses TLS Descriptors.
Definition:TargetMachine.cpp:236
llvm::TargetMachine::LargeDataThreshold
uint64_t LargeDataThreshold
Definition:TargetMachine.h:102
llvm::TargetMachine::RM
Reloc::Model RM
Definition:TargetMachine.h:100
llvm::TargetMachine::useEmulatedTLS
bool useEmulatedTLS() const
Returns true if this target uses emulated TLS.
Definition:TargetMachine.cpp:235
llvm::TargetMachine::getObjFileLowering
virtual TargetLoweringObjectFile * getObjFileLowering() const
Definition:TargetMachine.h:136
llvm::TargetMachine::getRelocationModel
Reloc::Model getRelocationModel() const
Returns the code generation relocation model.
Definition:TargetMachine.cpp:144
llvm::TargetMachine::getTargetTransformInfo
virtual TargetTransformInfo getTargetTransformInfo(const Function &F) const
Return a TargetTransformInfo for a given function.
Definition:TargetMachine.cpp:266
llvm::TargetMachine::DL
const DataLayout DL
DataLayout for the target: keep ABI type size and alignment.
Definition:TargetMachine.h:92
llvm::TargetMachine::shouldAssumeDSOLocal
bool shouldAssumeDSOLocal(const GlobalValue *GV) const
Definition:TargetMachine.cpp:178
llvm::TargetMachine::parseBinutilsVersion
static std::pair< int, int > parseBinutilsVersion(StringRef Version)
Definition:TargetMachine.cpp:301
llvm::TargetMachine::getTargetIRAnalysis
TargetIRAnalysis getTargetIRAnalysis() const
Get a TargetIRAnalysis appropriate for the target.
Definition:TargetMachine.cpp:294
llvm::TargetMachine::Options
TargetOptions Options
Definition:TargetMachine.h:118
llvm::TargetMachine::~TargetMachine
virtual ~TargetMachine()
llvm::TargetMachine::getSymbol
MCSymbol * getSymbol(const GlobalValue *GV) const
Definition:TargetMachine.cpp:283
llvm::TargetMachine::getCodeModel
CodeModel::Model getCodeModel() const
Returns the code model.
Definition:TargetMachine.h:232
llvm::TargetMachine::isLargeGlobalValue
bool isLargeGlobalValue(const GlobalValue *GV) const
Definition:TargetMachine.cpp:43
llvm::TargetMachine::resetTargetOptions
void resetTargetOptions(const Function &F) const
Reset the target options based on the function's attributes.
Definition:TargetMachine.cpp:129
llvm::TargetMachine::TargetMachine
TargetMachine(const Target &T, StringRef DataLayoutString, const Triple &TargetTriple, StringRef CPU, StringRef FS, const TargetOptions &Options)
Definition:TargetMachine.cpp:33
llvm::TargetMachine::getNameWithPrefix
void getNameWithPrefix(SmallVectorImpl< char > &Name, const GlobalValue *GV, Mangler &Mang, bool MayAlwaysUsePrivate=false) const
Definition:TargetMachine.cpp:270
llvm::TargetOptions
Definition:TargetOptions.h:132
llvm::TargetOptions::EnableTLSDESC
unsigned EnableTLSDESC
EnableTLSDESC - This flag enables TLS Descriptors.
Definition:TargetOptions.h:301
llvm::TargetOptions::EmulatedTLS
unsigned EmulatedTLS
EmulatedTLS - This flag enables emulated TLS model, using emutls function in the runtime library.
Definition:TargetOptions.h:298
llvm::TargetTransformInfo
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Definition:TargetTransformInfo.h:212
llvm::Target
Target - Wrapper for Target specific information.
Definition:TargetRegistry.h:144
llvm::Triple
Triple - Helper class for working with autoconf configuration names.
Definition:Triple.h:44
llvm::Triple::x86_64
@ x86_64
Definition:Triple.h:86
uint64_t
llvm_unreachable
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition:ErrorHandling.h:143
TargetMachine.h
false
Definition:StackSlotColoring.cpp:193
llvm::CodeModel::Medium
@ Medium
Definition:CodeGen.h:31
llvm::CodeModel::Large
@ Large
Definition:CodeGen.h:31
llvm::CodeModel::Tiny
@ Tiny
Definition:CodeGen.h:31
llvm::CodeModel::Small
@ Small
Definition:CodeGen.h:31
llvm::CodeModel::Kernel
@ Kernel
Definition:CodeGen.h:31
llvm::PIELevel::Default
@ Default
Definition:CodeGen.h:40
llvm::Reloc::Model
Model
Definition:CodeGen.h:25
llvm::Reloc::Static
@ Static
Definition:CodeGen.h:25
llvm::Reloc::PIC_
@ PIC_
Definition:CodeGen.h:25
llvm::TLSModel::Model
Model
Definition:CodeGen.h:45
llvm::TLSModel::LocalDynamic
@ LocalDynamic
Definition:CodeGen.h:47
llvm::TLSModel::InitialExec
@ InitialExec
Definition:CodeGen.h:48
llvm::TLSModel::GeneralDynamic
@ GeneralDynamic
Definition:CodeGen.h:46
llvm::TLSModel::LocalExec
@ LocalExec
Definition:CodeGen.h:49
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition:AddressRanges.h:18
llvm::Version
@ Version
Definition:PGOCtxProfWriter.h:22
llvm::maxUIntN
uint64_t maxUIntN(uint64_t N)
Gets the maximum value for a N-bit unsigned integer.
Definition:MathExtras.h:220
std
Implement std::hash so that hash_code can be used in STL containers.
Definition:BitVector.h:858

Generated on Thu Jul 17 2025 15:45:16 for LLVM by doxygen 1.9.6
[8]ページ先頭

©2009-2025 Movatter.jp