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/MCStreamer.h"
25#include "llvm/MC/MCSubtargetInfo.h"
26#include "llvm/Support/CodeGen.h"
27#include "llvm/Target/TargetLoweringObjectFile.h"
28using namespace llvm;
29
30cl::opt<bool> llvm::NoKernelInfoEndLTO(
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(Val: false), cl::Hidden);
34
35//---------------------------------------------------------------------------
36// TargetMachine Class
37//
38
39TargetMachine::TargetMachine(const Target &T, StringRef DataLayoutString,
40 const Triple &TT, StringRef CPU, StringRef FS,
41 const TargetOptions &Options)
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
47TargetMachine::~TargetMachine() = default;
48
49Expected<std::unique_ptr<MCStreamer>>
50TargetMachine::createMCStreamer(raw_pwrite_stream &Out,
51 raw_pwrite_stream *DwoOut,
52 CodeGenFileType FileType, MCContext &Ctx) {
53 return nullptr;
54}
55
56bool TargetMachine::isLargeGlobalValue(const GlobalValue *GVal) const {
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())
64 return getCodeModel() == CodeModel::Large;
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>(Val: 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 }
86 return getCodeModel() == CodeModel::Large;
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.
112 if (getCodeModel() == CodeModel::Medium ||
113 getCodeModel() == CodeModel::Large) {
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(Prefix: "__start_") ||
120 GV->getName().starts_with(Prefix: "__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() &&
132 TargetLoweringObjectFile::getKindForGlobal(GO: GV, TM: *this)
133 .isReadOnlyWithRel())
134 return false;
135 const DataLayout &DL = GV->getDataLayout();
136 uint64_t Size = GV->getGlobalSize(DL);
137 return Size == 0 || Size > LargeDataThreshold;
138 }
139
140 return false;
141}
142
143bool TargetMachine::isPositionIndependent() const {
144 return getRelocationModel() == Reloc::PIC_;
145}
146
147/// Returns the code generation relocation model. The choices are static, PIC,
148/// and dynamic-no-pic.
149Reloc::Model TargetMachine::getRelocationModel() const { return RM; }
150
151uint64_t TargetMachine::getMaxCodeSize() const {
152 switch (getCodeModel()) {
153 case CodeModel::Tiny:
154 return llvm::maxUIntN(N: 10);
155 case CodeModel::Small:
156 case CodeModel::Kernel:
157 case CodeModel::Medium:
158 return llvm::maxUIntN(N: 31);
159 case CodeModel::Large:
160 return llvm::maxUIntN(N: 64);
161 }
162 llvm_unreachable("Unhandled CodeModel enum");
163}
164
165/// Get the IR-specified TLS model for Var.
166static TLSModel::Model getSelectedTLSModel(const GlobalValue *GV) {
167 switch (GV->getThreadLocalMode()) {
168 case GlobalVariable::NotThreadLocal:
169 llvm_unreachable("getSelectedTLSModel for non-TLS variable");
170 break;
171 case GlobalVariable::GeneralDynamicTLSModel:
172 return TLSModel::GeneralDynamic;
173 case GlobalVariable::LocalDynamicTLSModel:
174 return TLSModel::LocalDynamic;
175 case GlobalVariable::InitialExecTLSModel:
176 return TLSModel::InitialExec;
177 case GlobalVariable::LocalExecTLSModel:
178 return TLSModel::LocalExec;
179 }
180 llvm_unreachable("invalid TLS model");
181}
182
183bool TargetMachine::shouldAssumeDSOLocal(const GlobalValue *GV) const {
184 const Triple &TT = getTargetTriple();
185 Reloc::Model RM = getRelocationModel();
186
187 // According to the llvm language reference, we should be able to
188 // just return false in here if we have a GV, as we know it is
189 // dso_preemptable. At this point in time, the various IR producers
190 // have not been transitioned to always produce a dso_local when it
191 // is possible to do so.
192 //
193 // As a result we still have some logic in here to improve the quality of the
194 // generated code.
195 if (!GV)
196 return false;
197
198 // If the IR producer requested that this GV be treated as dso local, obey.
199 if (GV->isDSOLocal())
200 return true;
201
202 if (TT.isOSBinFormatCOFF()) {
203 // DLLImport explicitly marks the GV as external.
204 if (GV->hasDLLImportStorageClass())
205 return false;
206
207 // On MinGW, variables that haven't been declared with DLLImport may still
208 // end up automatically imported by the linker. To make this feasible,
209 // don't assume the variables to be DSO local unless we actually know
210 // that for sure. This only has to be done for variables; for functions
211 // the linker can insert thunks for calling functions from another DLL.
212 if (TT.isOSCygMing() && GV->isDeclarationForLinker() &&
213 isa<GlobalVariable>(Val: GV))
214 return false;
215
216 // Don't mark 'extern_weak' symbols as DSO local. If these symbols remain
217 // unresolved in the link, they can be resolved to zero, which is outside
218 // the current DSO.
219 if (GV->hasExternalWeakLinkage())
220 return false;
221
222 // Every other GV is local on COFF.
223 return true;
224 }
225
226 if (TT.isOSBinFormatGOFF())
227 return true;
228
229 if (TT.isOSBinFormatMachO()) {
230 if (RM == Reloc::Static)
231 return true;
232 return GV->isStrongDefinitionForLinker();
233 }
234
235 assert(TT.isOSBinFormatELF() || TT.isOSBinFormatWasm() ||
236 TT.isOSBinFormatXCOFF());
237 return false;
238}
239
240bool TargetMachine::useEmulatedTLS() const { return Options.EmulatedTLS; }
241bool TargetMachine::useTLSDESC() const { return Options.EnableTLSDESC; }
242
243TLSModel::Model TargetMachine::getTLSModel(const GlobalValue *GV) const {
244 bool IsPIE = GV->getParent()->getPIELevel() != PIELevel::Default;
245 Reloc::Model RM = getRelocationModel();
246 bool IsSharedLibrary = RM == Reloc::PIC_ && !IsPIE;
247 bool IsLocal = shouldAssumeDSOLocal(GV);
248
249 TLSModel::Model Model;
250 if (IsSharedLibrary) {
251 if (IsLocal)
252 Model = TLSModel::LocalDynamic;
253 else
254 Model = TLSModel::GeneralDynamic;
255 } else {
256 if (IsLocal)
257 Model = TLSModel::LocalExec;
258 else
259 Model = TLSModel::InitialExec;
260 }
261
262 // If the user specified a more specific model, use that.
263 TLSModel::Model SelectedModel = getSelectedTLSModel(GV);
264 if (SelectedModel > Model)
265 return SelectedModel;
266
267 return Model;
268}
269
270TargetTransformInfo
271TargetMachine::getTargetTransformInfo(const Function &F) const {
272 return TargetTransformInfo(F.getDataLayout());
273}
274
275void TargetMachine::getNameWithPrefix(SmallVectorImpl<char> &Name,
276 const GlobalValue *GV, Mangler &Mang,
277 bool MayAlwaysUsePrivate) const {
278 if (MayAlwaysUsePrivate || !GV->hasPrivateLinkage()) {
279 // Simple case: If GV is not private, it is not important to find out if
280 // private labels are legal in this case or not.
281 Mang.getNameWithPrefix(OutName&: Name, GV, CannotUsePrivateLabel: false);
282 return;
283 }
284 const TargetLoweringObjectFile *TLOF = getObjFileLowering();
285 TLOF->getNameWithPrefix(OutName&: Name, GV, TM: *this);
286}
287
288MCSymbol *TargetMachine::getSymbol(const GlobalValue *GV) const {
289 const TargetLoweringObjectFile *TLOF = getObjFileLowering();
290 // XCOFF symbols could have special naming convention.
291 if (MCSymbol *TargetSymbol = TLOF->getTargetSymbol(GV, TM: *this))
292 return TargetSymbol;
293
294 SmallString<128> NameStr;
295 getNameWithPrefix(Name&: NameStr, GV, Mang&: TLOF->getMangler());
296 return TLOF->getContext().getOrCreateSymbol(Name: NameStr);
297}
298
299TargetIRAnalysis TargetMachine::getTargetIRAnalysis() const {
300 // Since Analysis can't depend on Target, use a std::function to invert the
301 // dependency.
302 return TargetIRAnalysis(
303 [this](const Function &F) { return this->getTargetTransformInfo(F); });
304}
305
306std::pair<int, int> TargetMachine::parseBinutilsVersion(StringRef Version) {
307 if (Version == "none")
308 return {INT_MAX, INT_MAX}; // Make binutilsIsAtLeast() return true.
309 std::pair<int, int> Ret;
310 if (!Version.consumeInteger(Radix: 10, Result&: Ret.first) && Version.consume_front(Prefix: "."))
311 Version.consumeInteger(Radix: 10, Result&: Ret.second);
312 return Ret;
313}
314