[WebAssembly] Add new target feature in support of 'extended-const' proposal
[llvm-project.git] / llvm / lib / Target / TargetMachine.cpp
blob967dcf63b4b5823d43bd6f232594ba4a9b3b9857
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.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/Target/TargetMachine.h"
14 #include "llvm/Analysis/TargetTransformInfo.h"
15 #include "llvm/IR/Function.h"
16 #include "llvm/IR/GlobalAlias.h"
17 #include "llvm/IR/GlobalValue.h"
18 #include "llvm/IR/GlobalVariable.h"
19 #include "llvm/IR/LegacyPassManager.h"
20 #include "llvm/IR/Mangler.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCInstrInfo.h"
24 #include "llvm/MC/MCRegisterInfo.h"
25 #include "llvm/MC/MCSectionMachO.h"
26 #include "llvm/MC/MCSubtargetInfo.h"
27 #include "llvm/MC/MCTargetOptions.h"
28 #include "llvm/MC/SectionKind.h"
29 #include "llvm/Target/TargetLoweringObjectFile.h"
30 using namespace llvm;
32 //---------------------------------------------------------------------------
33 // TargetMachine Class
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),
40 TargetCPU(std::string(CPU)), TargetFS(std::string(FS)), AsmInfo(nullptr),
41 MRI(nullptr), MII(nullptr), STI(nullptr), RequireStructuredCFG(false),
42 O0WantsFastISel(false), DefaultOptions(Options), Options(Options) {}
44 TargetMachine::~TargetMachine() = default;
46 bool TargetMachine::isPositionIndependent() const {
47 return getRelocationModel() == Reloc::PIC_;
50 /// Reset the target options based on the function's attributes.
51 /// setFunctionAttributes should have made the raw attribute value consistent
52 /// with the command line flag if used.
54 // FIXME: This function needs to go away for a number of reasons:
55 // a) global state on the TargetMachine is terrible in general,
56 // b) these target options should be passed only on the function
57 // and not on the TargetMachine (via TargetOptions) at all.
58 void TargetMachine::resetTargetOptions(const Function &F) const {
59 #define RESET_OPTION(X, Y) \
60 do { \
61 Options.X = F.getFnAttribute(Y).getValueAsBool(); \
62 } while (0)
64 RESET_OPTION(UnsafeFPMath, "unsafe-fp-math");
65 RESET_OPTION(NoInfsFPMath, "no-infs-fp-math");
66 RESET_OPTION(NoNaNsFPMath, "no-nans-fp-math");
67 RESET_OPTION(NoSignedZerosFPMath, "no-signed-zeros-fp-math");
68 RESET_OPTION(ApproxFuncFPMath, "approx-func-fp-math");
71 /// Returns the code generation relocation model. The choices are static, PIC,
72 /// and dynamic-no-pic.
73 Reloc::Model TargetMachine::getRelocationModel() const { return RM; }
75 /// Returns the code model. The choices are small, kernel, medium, large, and
76 /// target default.
77 CodeModel::Model TargetMachine::getCodeModel() const { return CMModel; }
79 /// Get the IR-specified TLS model for Var.
80 static TLSModel::Model getSelectedTLSModel(const GlobalValue *GV) {
81 switch (GV->getThreadLocalMode()) {
82 case GlobalVariable::NotThreadLocal:
83 llvm_unreachable("getSelectedTLSModel for non-TLS variable");
84 break;
85 case GlobalVariable::GeneralDynamicTLSModel:
86 return TLSModel::GeneralDynamic;
87 case GlobalVariable::LocalDynamicTLSModel:
88 return TLSModel::LocalDynamic;
89 case GlobalVariable::InitialExecTLSModel:
90 return TLSModel::InitialExec;
91 case GlobalVariable::LocalExecTLSModel:
92 return TLSModel::LocalExec;
94 llvm_unreachable("invalid TLS model");
97 bool TargetMachine::shouldAssumeDSOLocal(const Module &M,
98 const GlobalValue *GV) const {
99 const Triple &TT = getTargetTriple();
100 Reloc::Model RM = getRelocationModel();
102 // According to the llvm language reference, we should be able to
103 // just return false in here if we have a GV, as we know it is
104 // dso_preemptable. At this point in time, the various IR producers
105 // have not been transitioned to always produce a dso_local when it
106 // is possible to do so.
108 // As a result we still have some logic in here to improve the quality of the
109 // generated code.
110 if (!GV)
111 return false;
113 // If the IR producer requested that this GV be treated as dso local, obey.
114 if (GV->isDSOLocal())
115 return true;
117 if (TT.isOSBinFormatCOFF()) {
118 // DLLImport explicitly marks the GV as external.
119 if (GV->hasDLLImportStorageClass())
120 return false;
122 // On MinGW, variables that haven't been declared with DLLImport may still
123 // end up automatically imported by the linker. To make this feasible,
124 // don't assume the variables to be DSO local unless we actually know
125 // that for sure. This only has to be done for variables; for functions
126 // the linker can insert thunks for calling functions from another DLL.
127 if (TT.isWindowsGNUEnvironment() && GV->isDeclarationForLinker() &&
128 isa<GlobalVariable>(GV))
129 return false;
131 // Don't mark 'extern_weak' symbols as DSO local. If these symbols remain
132 // unresolved in the link, they can be resolved to zero, which is outside
133 // the current DSO.
134 if (GV->hasExternalWeakLinkage())
135 return false;
137 // Every other GV is local on COFF.
138 return true;
141 if (TT.isOSBinFormatGOFF())
142 return true;
144 if (TT.isOSBinFormatMachO()) {
145 if (RM == Reloc::Static)
146 return true;
147 return GV->isStrongDefinitionForLinker();
150 assert(TT.isOSBinFormatELF() || TT.isOSBinFormatWasm() ||
151 TT.isOSBinFormatXCOFF());
152 return false;
155 bool TargetMachine::useEmulatedTLS() const {
156 // Returns Options.EmulatedTLS if the -emulated-tls or -no-emulated-tls
157 // was specified explicitly; otherwise uses target triple to decide default.
158 if (Options.ExplicitEmulatedTLS)
159 return Options.EmulatedTLS;
160 return getTargetTriple().hasDefaultEmulatedTLS();
163 TLSModel::Model TargetMachine::getTLSModel(const GlobalValue *GV) const {
164 bool IsPIE = GV->getParent()->getPIELevel() != PIELevel::Default;
165 Reloc::Model RM = getRelocationModel();
166 bool IsSharedLibrary = RM == Reloc::PIC_ && !IsPIE;
167 bool IsLocal = shouldAssumeDSOLocal(*GV->getParent(), GV);
169 TLSModel::Model Model;
170 if (IsSharedLibrary) {
171 if (IsLocal)
172 Model = TLSModel::LocalDynamic;
173 else
174 Model = TLSModel::GeneralDynamic;
175 } else {
176 if (IsLocal)
177 Model = TLSModel::LocalExec;
178 else
179 Model = TLSModel::InitialExec;
182 // If the user specified a more specific model, use that.
183 TLSModel::Model SelectedModel = getSelectedTLSModel(GV);
184 if (SelectedModel > Model)
185 return SelectedModel;
187 return Model;
190 /// Returns the optimization level: None, Less, Default, or Aggressive.
191 CodeGenOpt::Level TargetMachine::getOptLevel() const { return OptLevel; }
193 void TargetMachine::setOptLevel(CodeGenOpt::Level Level) { OptLevel = Level; }
195 TargetTransformInfo
196 TargetMachine::getTargetTransformInfo(const Function &F) const {
197 return TargetTransformInfo(F.getParent()->getDataLayout());
200 void TargetMachine::getNameWithPrefix(SmallVectorImpl<char> &Name,
201 const GlobalValue *GV, Mangler &Mang,
202 bool MayAlwaysUsePrivate) const {
203 if (MayAlwaysUsePrivate || !GV->hasPrivateLinkage()) {
204 // Simple case: If GV is not private, it is not important to find out if
205 // private labels are legal in this case or not.
206 Mang.getNameWithPrefix(Name, GV, false);
207 return;
209 const TargetLoweringObjectFile *TLOF = getObjFileLowering();
210 TLOF->getNameWithPrefix(Name, GV, *this);
213 MCSymbol *TargetMachine::getSymbol(const GlobalValue *GV) const {
214 const TargetLoweringObjectFile *TLOF = getObjFileLowering();
215 // XCOFF symbols could have special naming convention.
216 if (MCSymbol *TargetSymbol = TLOF->getTargetSymbol(GV, *this))
217 return TargetSymbol;
219 SmallString<128> NameStr;
220 getNameWithPrefix(NameStr, GV, TLOF->getMangler());
221 return TLOF->getContext().getOrCreateSymbol(NameStr);
224 TargetIRAnalysis TargetMachine::getTargetIRAnalysis() const {
225 // Since Analysis can't depend on Target, use a std::function to invert the
226 // dependency.
227 return TargetIRAnalysis(
228 [this](const Function &F) { return this->getTargetTransformInfo(F); });
231 std::pair<int, int> TargetMachine::parseBinutilsVersion(StringRef Version) {
232 if (Version == "none")
233 return {INT_MAX, INT_MAX}; // Make binutilsIsAtLeast() return true.
234 std::pair<int, int> Ret;
235 if (!Version.consumeInteger(10, Ret.first) && Version.consume_front("."))
236 Version.consumeInteger(10, Ret.second);
237 return Ret;