LLVM 20.0.0git
MipsTargetMachine.cpp
Go to the documentation of this file.
1//===-- MipsTargetMachine.cpp - Define TargetMachine for Mips -------------===//
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// Implements the info about Mips target spec.
10//
11//===----------------------------------------------------------------------===//
12
13#include "MipsTargetMachine.h"
16#include "Mips.h"
17#include "Mips16ISelDAGToDAG.h"
18#include "MipsMachineFunction.h"
19#include "MipsSEISelDAGToDAG.h"
20#include "MipsSubtarget.h"
24#include "llvm/ADT/StringRef.h"
33#include "llvm/CodeGen/Passes.h"
35#include "llvm/IR/Attributes.h"
36#include "llvm/IR/Function.h"
40#include "llvm/Support/Debug.h"
43#include <optional>
44#include <string>
45
46using namespace llvm;
47
48#define DEBUG_TYPE "mips"
49
50static cl::opt<bool>
51 EnableMulMulFix("mfix4300", cl::init(false),
52 cl::desc("Enable the VR4300 mulmul bug fix."), cl::Hidden);
53
55 // Register the target.
60
70}
71
72static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
73 if (TT.isOSBinFormatCOFF())
74 return std::make_unique<TargetLoweringObjectFileCOFF>();
75 return std::make_unique<MipsTargetObjectFile>();
76}
77
78static std::string computeDataLayout(const Triple &TT, StringRef CPU,
80 bool isLittle) {
81 std::string Ret;
82 MipsABIInfo ABI = MipsABIInfo::computeTargetABI(TT, CPU, Options.MCOptions);
83
84 // There are both little and big endian mips.
85 if (isLittle)
86 Ret += "e";
87 else
88 Ret += "E";
89
90 if (ABI.IsO32())
91 Ret += "-m:m";
92 else
93 Ret += "-m:e";
94
95 // Pointers are 32 bit on some ABIs.
96 if (!ABI.IsN64())
97 Ret += "-p:32:32";
98
99 // 8 and 16 bit integers only need to have natural alignment, but try to
100 // align them to 32 bits. 64 bit integers have natural alignment.
101 Ret += "-i8:8:32-i16:16:32-i64:64";
102
103 // 32 bit registers are always available and the stack is at least 64 bit
104 // aligned. On N64 64 bit registers are also available and the stack is
105 // 128 bit aligned.
106 if (ABI.IsN64() || ABI.IsN32())
107 Ret += "-i128:128-n32:64-S128";
108 else
109 Ret += "-n32-S64";
110
111 return Ret;
112}
113
115 std::optional<Reloc::Model> RM) {
116 if (!RM || JIT)
117 return Reloc::Static;
118 return *RM;
119}
120
121// On function prologue, the stack is created by decrementing
122// its pointer. Once decremented, all references are done with positive
123// offset from the stack/frame pointer, using StackGrowsUp enables
124// an easier handling.
125// Using CodeModel::Large enables different CALL behavior.
127 StringRef CPU, StringRef FS,
128 const TargetOptions &Options,
129 std::optional<Reloc::Model> RM,
130 std::optional<CodeModel::Model> CM,
131 CodeGenOptLevel OL, bool JIT,
132 bool isLittle)
134 TT, CPU, FS, Options,
135 getEffectiveRelocModel(JIT, RM),
136 getEffectiveCodeModel(CM, CodeModel::Small), OL),
137 isLittle(isLittle), TLOF(createTLOF(getTargetTriple())),
138 ABI(MipsABIInfo::computeTargetABI(TT, CPU, Options.MCOptions)),
139 Subtarget(nullptr),
140 DefaultSubtarget(TT, CPU, FS, isLittle, *this, std::nullopt),
141 NoMips16Subtarget(TT, CPU, FS.empty() ? "-mips16" : FS.str() + ",-mips16",
142 isLittle, *this, std::nullopt),
143 Mips16Subtarget(TT, CPU, FS.empty() ? "+mips16" : FS.str() + ",+mips16",
144 isLittle, *this, std::nullopt) {
145 Subtarget = &DefaultSubtarget;
146 initAsmInfo();
147
148 // Mips supports the debug entry values.
150}
151
153
154void MipsebTargetMachine::anchor() {}
155
157 StringRef CPU, StringRef FS,
158 const TargetOptions &Options,
159 std::optional<Reloc::Model> RM,
160 std::optional<CodeModel::Model> CM,
161 CodeGenOptLevel OL, bool JIT)
162 : MipsTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, false) {}
163
164void MipselTargetMachine::anchor() {}
165
167 StringRef CPU, StringRef FS,
168 const TargetOptions &Options,
169 std::optional<Reloc::Model> RM,
170 std::optional<CodeModel::Model> CM,
171 CodeGenOptLevel OL, bool JIT)
172 : MipsTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, true) {}
173
174const MipsSubtarget *
176 Attribute CPUAttr = F.getFnAttribute("target-cpu");
177 Attribute FSAttr = F.getFnAttribute("target-features");
178
179 std::string CPU =
180 CPUAttr.isValid() ? CPUAttr.getValueAsString().str() : TargetCPU;
181 std::string FS =
182 FSAttr.isValid() ? FSAttr.getValueAsString().str() : TargetFS;
183 bool hasMips16Attr = F.getFnAttribute("mips16").isValid();
184 bool hasNoMips16Attr = F.getFnAttribute("nomips16").isValid();
185
186 bool HasMicroMipsAttr = F.getFnAttribute("micromips").isValid();
187 bool HasNoMicroMipsAttr = F.getFnAttribute("nomicromips").isValid();
188
189 // FIXME: This is related to the code below to reset the target options,
190 // we need to know whether or not the soft float flag is set on the
191 // function, so we can enable it as a subtarget feature.
192 bool softFloat = F.getFnAttribute("use-soft-float").getValueAsBool();
193
194 if (hasMips16Attr)
195 FS += FS.empty() ? "+mips16" : ",+mips16";
196 else if (hasNoMips16Attr)
197 FS += FS.empty() ? "-mips16" : ",-mips16";
198 if (HasMicroMipsAttr)
199 FS += FS.empty() ? "+micromips" : ",+micromips";
200 else if (HasNoMicroMipsAttr)
201 FS += FS.empty() ? "-micromips" : ",-micromips";
202 if (softFloat)
203 FS += FS.empty() ? "+soft-float" : ",+soft-float";
204
205 auto &I = SubtargetMap[CPU + FS];
206 if (!I) {
207 // This needs to be done before we create a new subtarget since any
208 // creation will depend on the TM and the code generation flags on the
209 // function that reside in TargetOptions.
211 I = std::make_unique<MipsSubtarget>(
212 TargetTriple, CPU, FS, isLittle, *this,
213 MaybeAlign(F.getParent()->getOverrideStackAlignment()));
214 }
215 return I.get();
216}
217
219 LLVM_DEBUG(dbgs() << "resetSubtarget\n");
220
221 Subtarget = &MF->getSubtarget<MipsSubtarget>();
222}
223
224namespace {
225
226/// Mips Code Generator Pass Configuration Options.
227class MipsPassConfig : public TargetPassConfig {
228public:
229 MipsPassConfig(MipsTargetMachine &TM, PassManagerBase &PM)
230 : TargetPassConfig(TM, PM) {
231 // The current implementation of long branch pass requires a scratch
232 // register ($at) to be available before branch instructions. Tail merging
233 // can break this requirement, so disable it when long branch pass is
234 // enabled.
235 EnableTailMerge = !getMipsSubtarget().enableLongBranchPass();
236 }
237
238 MipsTargetMachine &getMipsTargetMachine() const {
239 return getTM<MipsTargetMachine>();
240 }
241
242 const MipsSubtarget &getMipsSubtarget() const {
243 return *getMipsTargetMachine().getSubtargetImpl();
244 }
245
246 void addIRPasses() override;
247 bool addInstSelector() override;
248 void addPreEmitPass() override;
249 void addPreRegAlloc() override;
250 bool addIRTranslator() override;
251 void addPreLegalizeMachineIR() override;
252 bool addLegalizeMachineIR() override;
253 void addPreRegBankSelect() override;
254 bool addRegBankSelect() override;
255 bool addGlobalInstructionSelect() override;
256
257 std::unique_ptr<CSEConfigBase> getCSEConfig() const override;
258};
259
260} // end anonymous namespace
261
263 return new MipsPassConfig(*this, PM);
264}
265
266std::unique_ptr<CSEConfigBase> MipsPassConfig::getCSEConfig() const {
267 return getStandardCSEConfigForOpt(TM->getOptLevel());
268}
269
270void MipsPassConfig::addIRPasses() {
273 if (getMipsSubtarget().os16())
274 addPass(createMipsOs16Pass());
275 if (getMipsSubtarget().inMips16HardFloat())
276 addPass(createMips16HardFloatPass());
277}
278// Install an instruction selector pass using
279// the ISelDag to gen Mips code.
280bool MipsPassConfig::addInstSelector() {
282 addPass(createMips16ISelDag(getMipsTargetMachine(), getOptLevel()));
283 addPass(createMipsSEISelDag(getMipsTargetMachine(), getOptLevel()));
284 return false;
285}
286
287void MipsPassConfig::addPreRegAlloc() {
289}
290
293 if (Subtarget->allowMixed16_32()) {
294 LLVM_DEBUG(errs() << "No Target Transform Info Pass Added\n");
295 // FIXME: This is no longer necessary as the TTI returned is per-function.
296 return TargetTransformInfo(F.getDataLayout());
297 }
298
299 LLVM_DEBUG(errs() << "Target Transform Info Pass Added\n");
300 return TargetTransformInfo(MipsTTIImpl(this, F));
301}
302
304 BumpPtrAllocator &Allocator, const Function &F,
305 const TargetSubtargetInfo *STI) const {
306 return MipsFunctionInfo::create<MipsFunctionInfo>(Allocator, F, STI);
307}
308
309// Implemented by targets that want to run passes immediately before
310// machine code is emitted.
311void MipsPassConfig::addPreEmitPass() {
312 // Expand pseudo instructions that are sensitive to register allocation.
314
315 // The microMIPS size reduction pass performs instruction reselection for
316 // instructions which can be remapped to a 16 bit instruction.
318
319 // This pass inserts a nop instruction between two back-to-back multiplication
320 // instructions when the "mfix4300" flag is passed.
321 if (EnableMulMulFix)
322 addPass(createMipsMulMulBugPass());
323
324 // The delay slot filler pass can potientially create forbidden slot hazards
325 // for MIPSR6 and therefore it should go before MipsBranchExpansion pass.
327
328 // This pass expands branches and takes care about the forbidden slot hazards.
329 // Expanding branches may potentially create forbidden slot hazards for
330 // MIPSR6, and fixing such hazard may potentially break a branch by extending
331 // its offset out of range. That's why this pass combine these two tasks, and
332 // runs them alternately until one of them finishes without any changes. Only
333 // then we can be sure that all branches are expanded properly and no hazards
334 // exists.
335 // Any new pass should go before this pass.
336 addPass(createMipsBranchExpansion());
337
339}
340
341bool MipsPassConfig::addIRTranslator() {
342 addPass(new IRTranslator(getOptLevel()));
343 return false;
344}
345
346void MipsPassConfig::addPreLegalizeMachineIR() {
348}
349
350bool MipsPassConfig::addLegalizeMachineIR() {
351 addPass(new Legalizer());
352 return false;
353}
354
355void MipsPassConfig::addPreRegBankSelect() {
356 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
357 addPass(createMipsPostLegalizeCombiner(IsOptNone));
358}
359
360bool MipsPassConfig::addRegBankSelect() {
361 addPass(new RegBankSelect());
362 return false;
363}
364
365bool MipsPassConfig::addGlobalInstructionSelect() {
366 addPass(new InstructionSelect(getOptLevel()));
367 return false;
368}
static ARMBaseTargetMachine::ARMABI computeTargetABI(const Triple &TT, StringRef CPU, const TargetOptions &Options)
This file contains the simple types necessary to represent the attributes associated with functions a...
basic Basic Alias true
This file provides a helper that implements much of the TTI interface in terms of the target-independ...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Provides analysis for continuously CSEing during GISel passes.
#define LLVM_EXTERNAL_VISIBILITY
Definition: Compiler.h:128
#define LLVM_DEBUG(...)
Definition: Debug.h:106
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
This file declares the IRTranslator pass.
static LVOptions Options
Definition: LVOptions.cpp:25
static std::string computeDataLayout()
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
static Reloc::Model getEffectiveRelocModel(bool JIT, std::optional< Reloc::Model > RM)
LLVM_EXTERNAL_VISIBILITY void LLVMInitializeMipsTarget()
static cl::opt< bool > EnableMulMulFix("mfix4300", cl::init(false), cl::desc("Enable the VR4300 mulmul bug fix."), cl::Hidden)
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
Basic Register Allocator
This file describes the interface of the MachineFunctionPass responsible for assigning the generic vi...
Target-Independent Code Generator Pass Configuration Options pass.
This pass exposes codegen information to IR-level passes.
static std::unique_ptr< TargetLoweringObjectFile > createTLOF()
StringRef getValueAsString() const
Return the attribute's value as a string.
Definition: Attributes.cpp:392
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition: Attributes.h:208
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:66
implements a set of functionality in the TargetMachine class for targets that make use of the indepen...
This pass is responsible for selecting generic machine instructions to target-specific instructions.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
static MipsABIInfo computeTargetABI(const Triple &TT, StringRef CPU, const MCTargetOptions &Options)
Definition: MipsABIInfo.cpp:56
bool allowMixed16_32() const
TargetTransformInfo getTargetTransformInfo(const Function &F) const override
Get a TargetTransformInfo implementation for the target.
MachineFunctionInfo * createMachineFunctionInfo(BumpPtrAllocator &Allocator, const Function &F, const TargetSubtargetInfo *STI) const override
Create the target's instance of MachineFunctionInfo.
MipsTargetMachine(const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, std::optional< Reloc::Model > RM, std::optional< CodeModel::Model > CM, CodeGenOptLevel OL, bool JIT, bool isLittle)
TargetPassConfig * createPassConfig(PassManagerBase &PM) override
Create a pass configuration object to be used by addPassToEmitX methods for generating a pipeline of ...
~MipsTargetMachine() override
void resetSubtarget(MachineFunction *MF)
Reset the subtarget for the Mips target.
const MipsSubtarget * getSubtargetImpl() const
MipsebTargetMachine(const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, std::optional< Reloc::Model > RM, std::optional< CodeModel::Model > CM, CodeGenOptLevel OL, bool JIT)
MipselTargetMachine(const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, std::optional< Reloc::Model > RM, std::optional< CodeModel::Model > CM, CodeGenOptLevel OL, bool JIT)
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
Definition: PassRegistry.h:37
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
This pass implements the reg bank selector pass used in the GlobalISel pipeline.
Definition: RegBankSelect.h:91
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:229
void setSupportsDebugEntryValues(bool Enable)
Triple TargetTriple
Triple string, CPU name, and target feature strings the TargetMachine instance is created with.
Definition: TargetMachine.h:96
std::string TargetFS
Definition: TargetMachine.h:98
std::string TargetCPU
Definition: TargetMachine.h:97
std::unique_ptr< const MCSubtargetInfo > STI
void resetTargetOptions(const Function &F) const
Reset the target options based on the function's attributes.
Target-Independent Code Generator Pass Configuration Options.
virtual void addIRPasses()
Add common target configurable passes that perform LLVM IR to IR transforms following machine indepen...
TargetSubtargetInfo - Generic base class for all target subtargets.
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:44
PassManagerBase - An abstract interface to allow code to add passes to a pass manager without having ...
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
Target & getTheMips64Target()
FunctionPass * createMipsConstantIslandPass()
Returns a pass that converts branches to long branches.
void initializeMipsPreLegalizerCombinerPass(PassRegistry &)
void initializeMipsBranchExpansionPass(PassRegistry &)
void initializeMipsDelaySlotFillerPass(PassRegistry &)
void initializeMipsMulMulBugFixPass(PassRegistry &)
FunctionPass * createMipsOptimizePICCallPass()
Return an OptimizeCall object.
void initializeMipsDAGToDAGISelLegacyPass(PassRegistry &)
std::unique_ptr< CSEConfigBase > getStandardCSEConfigForOpt(CodeGenOptLevel Level)
Definition: CSEInfo.cpp:79
FunctionPass * createMipsModuleISelDagPass()
CodeModel::Model getEffectiveCodeModel(std::optional< CodeModel::Model > CM, CodeModel::Model Default)
Helper method for getting the code model, returning Default if CM does not have a value.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
FunctionPass * createMipsPreLegalizeCombiner()
void initializeMipsPostLegalizerCombinerPass(PassRegistry &)
FunctionPass * createMicroMipsSizeReducePass()
Returns an instance of the MicroMips size reduction pass.
FunctionPass * createMipsSEISelDag(MipsTargetMachine &TM, CodeGenOptLevel OptLevel)
CodeGenOptLevel
Code generation optimization level.
Definition: CodeGen.h:54
FunctionPass * createMipsBranchExpansion()
Target & getTheMips64elTarget()
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
FunctionPass * createMipsMulMulBugPass()
void initializeMicroMipsSizeReducePass(PassRegistry &)
void initializeGlobalISel(PassRegistry &)
Initialize all passes linked into the GlobalISel library.
Definition: GlobalISel.cpp:17
Target & getTheMipselTarget()
FunctionPass * createMips16ISelDag(MipsTargetMachine &TM, CodeGenOptLevel OptLevel)
ModulePass * createMips16HardFloatPass()
FunctionPass * createMipsExpandPseudoPass()
createMipsExpandPseudoPass - returns an instance of the pseudo instruction expansion pass.
FunctionPass * createMipsDelaySlotFillerPass()
createMipsDelaySlotFillerPass - Returns a pass that fills in delay slots in Mips MachineFunctions
FunctionPass * createAtomicExpandLegacyPass()
AtomicExpandPass - At IR level this pass replace atomic instructions with __atomic_* library calls,...
Target & getTheMipsTarget()
ModulePass * createMipsOs16Pass()
Definition: MipsOs16.cpp:160
FunctionPass * createMipsPostLegalizeCombiner(bool IsOptNone)
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
MachineFunctionInfo - This class can be derived from and used by targets to hold private target-speci...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition: Alignment.h:117
RegisterTargetMachine - Helper template for registering a target machine implementation,...