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"
14#include "MCTargetDesc/MipsABIInfo.h"
15#include "MCTargetDesc/MipsMCTargetDesc.h"
16#include "Mips.h"
17#include "Mips16ISelDAGToDAG.h"
18#include "MipsMachineFunction.h"
19#include "MipsSEISelDAGToDAG.h"
20#include "MipsSubtarget.h"
21#include "MipsTargetObjectFile.h"
22#include "MipsTargetTransformInfo.h"
23#include "TargetInfo/MipsTargetInfo.h"
24#include "llvm/ADT/StringRef.h"
25#include "llvm/Analysis/TargetTransformInfo.h"
26#include "llvm/CodeGen/BasicTTIImpl.h"
27#include "llvm/CodeGen/GlobalISel/CSEInfo.h"
28#include "llvm/CodeGen/GlobalISel/IRTranslator.h"
29#include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
30#include "llvm/CodeGen/GlobalISel/Legalizer.h"
31#include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
32#include "llvm/CodeGen/MachineFunction.h"
33#include "llvm/CodeGen/Passes.h"
34#include "llvm/CodeGen/TargetPassConfig.h"
35#include "llvm/IR/Attributes.h"
36#include "llvm/IR/Function.h"
37#include "llvm/InitializePasses.h"
38#include "llvm/MC/TargetRegistry.h"
39#include "llvm/Option/LibraryOptions.h"
40#include "llvm/Support/CodeGen.h"
41#include "llvm/Support/Compiler.h"
42#include "llvm/Support/Debug.h"
43#include "llvm/Support/raw_ostream.h"
44#include "llvm/Target/TargetOptions.h"
45#include <optional>
46#include <string>
47
48using namespace llvm;
49
50#define DEBUG_TYPE "mips"
51
52extern "C" LLVM_ABI LLVM_EXTERNAL_VISIBILITY void LLVMInitializeMipsTarget() {
53 static opt::RegisterLibraryOptions<MipsOptions> O;
54 // Register the target.
55 RegisterTargetMachine<MipsebTargetMachine> X(getTheMipsTarget());
56 RegisterTargetMachine<MipselTargetMachine> Y(getTheMipselTarget());
57 RegisterTargetMachine<MipsebTargetMachine> A(getTheMips64Target());
58 RegisterTargetMachine<MipselTargetMachine> B(getTheMips64elTarget());
59
60 PassRegistry *PR = PassRegistry::getPassRegistry();
61 initializeGlobalISel(*PR);
62 initializeMipsAsmPrinterPass(*PR);
63 initializeMipsDelaySlotFillerPass(*PR);
64 initializeMipsBranchExpansionPass(*PR);
65 initializeMicroMipsSizeReducePass(*PR);
66 initializeMipsPreLegalizerCombinerPass(*PR);
67 initializeMipsPostLegalizerCombinerPass(*PR);
68 initializeMipsMulMulBugFixPass(*PR);
69 initializeMipsDAGToDAGISelLegacyPass(*PR);
70}
71
72static std::unique_ptr<TargetLoweringObjectFile>
73createTLOF(const Triple &TT, bool UseSmallSection) {
74 if (TT.isOSBinFormatCOFF())
75 return std::make_unique<TargetLoweringObjectFileCOFF>();
76 return std::make_unique<MipsTargetObjectFile>(args&: UseSmallSection);
77}
78
79static Reloc::Model getEffectiveRelocModel(std::optional<Reloc::Model> RM) {
80 return RM.value_or(u: Reloc::Static);
81}
82
83// On function prologue, the stack is created by decrementing
84// its pointer. Once decremented, all references are done with positive
85// offset from the stack/frame pointer, using StackGrowsUp enables
86// an easier handling.
87// Using CodeModel::Large enables different CALL behavior.
88MipsTargetMachine::MipsTargetMachine(const Target &T, const Triple &TT,
89 StringRef CPU, StringRef FS,
90 const TargetOptions &Options,
91 std::optional<Reloc::Model> RM,
92 std::optional<CodeModel::Model> CM,
93 CodeGenOptLevel OL, bool JIT,
94 bool isLittle)
95 : CodeGenTargetMachineImpl(T, TT, CPU, FS, Options,
96 getEffectiveRelocModel(RM),
97 getEffectiveCodeModel(CM, Default: CodeModel::Small), OL),
98 CLOpts(cl::LibraryOptionsContext::get<MipsOptions>(
99 C: Options.MCOptions.LibraryOptions)),
100 MCCLOpts(MIPS_MC::getCLOpts(Options: Options.MCOptions)), isLittle(isLittle),
101 IsJIT(JIT), DefaultSubtarget(TT, CPU, FS, Options.MCOptions.getABIName(),
102 isLittle, *this, std::nullopt),
103 TLOF(createTLOF(TT, UseSmallSection: DefaultSubtarget.useSmallSection())) {
104 initAsmInfo();
105
106 // Mips supports the debug entry values.
107 setSupportsDebugEntryValues(true);
108}
109
110MipsTargetMachine::~MipsTargetMachine() = default;
111
112void MipsebTargetMachine::anchor() {}
113
114MipsebTargetMachine::MipsebTargetMachine(const Target &T, const Triple &TT,
115 StringRef CPU, StringRef FS,
116 const TargetOptions &Options,
117 std::optional<Reloc::Model> RM,
118 std::optional<CodeModel::Model> CM,
119 CodeGenOptLevel OL, bool JIT)
120 : MipsTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, false) {}
121
122void MipselTargetMachine::anchor() {}
123
124MipselTargetMachine::MipselTargetMachine(const Target &T, const Triple &TT,
125 StringRef CPU, StringRef FS,
126 const TargetOptions &Options,
127 std::optional<Reloc::Model> RM,
128 std::optional<CodeModel::Model> CM,
129 CodeGenOptLevel OL, bool JIT)
130 : MipsTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, true) {}
131
132const MipsSubtarget *
133MipsTargetMachine::getSubtargetImpl(const Function &F) const {
134 Attribute CPUAttr = F.getFnAttribute(Kind: "target-cpu");
135 Attribute FSAttr = F.getFnAttribute(Kind: "target-features");
136
137 std::string CPU =
138 CPUAttr.isValid() ? CPUAttr.getValueAsString().str() : TargetCPU;
139 std::string FS =
140 FSAttr.isValid() ? FSAttr.getValueAsString().str() : TargetFS;
141 bool hasMips16Attr = F.getFnAttribute(Kind: "mips16").isValid();
142 bool hasNoMips16Attr = F.getFnAttribute(Kind: "nomips16").isValid();
143
144 bool HasMicroMipsAttr = F.getFnAttribute(Kind: "micromips").isValid();
145 bool HasNoMicroMipsAttr = F.getFnAttribute(Kind: "nomicromips").isValid();
146
147 // FIXME: This is related to the code below to reset the target options,
148 // we need to know whether or not the soft float flag is set on the
149 // function, so we can enable it as a subtarget feature.
150 bool softFloat = F.getFnAttribute(Kind: "use-soft-float").getValueAsBool();
151
152 if (hasMips16Attr)
153 FS += FS.empty() ? "+mips16" : ",+mips16";
154 else if (hasNoMips16Attr)
155 FS += FS.empty() ? "-mips16" : ",-mips16";
156 if (HasMicroMipsAttr)
157 FS += FS.empty() ? "+micromips" : ",+micromips";
158 else if (HasNoMicroMipsAttr)
159 FS += FS.empty() ? "-micromips" : ",-micromips";
160 if (softFloat)
161 FS += FS.empty() ? "+soft-float" : ",+soft-float";
162
163 StringRef ABIName = getTargetABIName(M: *F.getParent());
164
165 auto &I = SubtargetMap[CPU + FS + ABIName.str()];
166 if (!I) {
167 I = std::make_unique<MipsSubtarget>(
168 args: TargetTriple, args&: CPU, args&: FS, args&: ABIName, args: isLittle, args: *this,
169 args: MaybeAlign(F.getParent()->getOverrideStackAlignment()));
170 }
171 return I.get();
172}
173
174namespace {
175
176/// Mips Code Generator Pass Configuration Options.
177class MipsPassConfig : public TargetPassConfig {
178public:
179 MipsPassConfig(MipsTargetMachine &TM, PassManagerBase &PM)
180 : TargetPassConfig(TM, PM) {
181 // The current implementation of long branch pass requires a scratch
182 // register ($at) to be available before branch instructions. Tail merging
183 // can break this requirement.
184 EnableTailMerge = false;
185 EnableLoopTermFold = true;
186 }
187
188 MipsTargetMachine &getMipsTargetMachine() const {
189 return getTM<MipsTargetMachine>();
190 }
191
192 void addIRPasses() override;
193 bool addInstSelector() override;
194 void addPreEmitPass() override;
195 void addPreRegAlloc() override;
196 bool addIRTranslator() override;
197 void addPreLegalizeMachineIR() override;
198 bool addLegalizeMachineIR() override;
199 void addPreRegBankSelect() override;
200 bool addRegBankSelect() override;
201 bool addGlobalInstructionSelect() override;
202
203 std::unique_ptr<CSEConfigBase> getCSEConfig() const override;
204};
205
206} // end anonymous namespace
207
208TargetPassConfig *MipsTargetMachine::createPassConfig(PassManagerBase &PM) {
209 return new MipsPassConfig(*this, PM);
210}
211
212std::unique_ptr<CSEConfigBase> MipsPassConfig::getCSEConfig() const {
213 return getStandardCSEConfigForOpt(Level: TM->getOptLevel());
214}
215
216void MipsPassConfig::addIRPasses() {
217 TargetPassConfig::addIRPasses();
218 addPass(P: createAtomicExpandLegacyPass());
219 if (getMipsTargetMachine().getCLOpts().os16)
220 addPass(P: createMipsOs16Pass());
221 addPass(P: createMips16HardFloatPass());
222}
223// Install an instruction selector pass using
224// the ISelDag to gen Mips code.
225bool MipsPassConfig::addInstSelector() {
226 addPass(P: createMips16ISelDag(TM&: getMipsTargetMachine(), OptLevel: getOptLevel()));
227 addPass(P: createMipsSEISelDag(TM&: getMipsTargetMachine(), OptLevel: getOptLevel()));
228 return false;
229}
230
231void MipsPassConfig::addPreRegAlloc() {
232 addPass(P: createMipsOptimizePICCallPass());
233}
234
235TargetTransformInfo
236MipsTargetMachine::getTargetTransformInfo(const Function &F) const {
237 LLVM_DEBUG(errs() << "Target Transform Info Pass Added\n");
238 return TargetTransformInfo(std::make_unique<MipsTTIImpl>(args: this, args: F));
239}
240
241MachineFunctionInfo *MipsTargetMachine::createMachineFunctionInfo(
242 BumpPtrAllocator &Allocator, const Function &F,
243 const TargetSubtargetInfo *STI) const {
244 return MipsFunctionInfo::create<MipsFunctionInfo>(Allocator, F, STI);
245}
246
247// Implemented by targets that want to run passes immediately before
248// machine code is emitted.
249void MipsPassConfig::addPreEmitPass() {
250 // Expand pseudo instructions that are sensitive to register allocation.
251 addPass(P: createMipsExpandPseudoPass());
252
253 // The microMIPS size reduction pass performs instruction reselection for
254 // instructions which can be remapped to a 16 bit instruction.
255 addPass(P: createMicroMipsSizeReducePass());
256
257 // This pass inserts a nop instruction between two back-to-back multiplication
258 // instructions when the "mfix4300" flag is passed.
259 if (getMipsTargetMachine().getCLOpts().mfix4300)
260 addPass(P: createMipsMulMulBugPass());
261
262 // The delay slot filler pass can potientially create forbidden slot hazards
263 // for MIPSR6 and therefore it should go before MipsBranchExpansion pass.
264 addPass(P: createMipsDelaySlotFillerPass());
265
266 // This pass expands branches and takes care about the forbidden slot hazards.
267 // Expanding branches may potentially create forbidden slot hazards for
268 // MIPSR6, and fixing such hazard may potentially break a branch by extending
269 // its offset out of range. That's why this pass combine these two tasks, and
270 // runs them alternately until one of them finishes without any changes. Only
271 // then we can be sure that all branches are expanded properly and no hazards
272 // exists.
273 // Any new pass should go before this pass.
274 addPass(P: createMipsBranchExpansion());
275
276 addPass(P: createMipsConstantIslandPass());
277}
278
279bool MipsPassConfig::addIRTranslator() {
280 addPass(P: new IRTranslatorLegacy(getOptLevel()));
281 return false;
282}
283
284void MipsPassConfig::addPreLegalizeMachineIR() {
285 addPass(P: createMipsPreLegalizeCombiner());
286}
287
288bool MipsPassConfig::addLegalizeMachineIR() {
289 addPass(P: new LegalizerLegacy());
290 return false;
291}
292
293void MipsPassConfig::addPreRegBankSelect() {
294 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
295 addPass(P: createMipsPostLegalizeCombiner(IsOptNone));
296}
297
298bool MipsPassConfig::addRegBankSelect() {
299 addPass(P: new RegBankSelectLegacy());
300 return false;
301}
302
303bool MipsPassConfig::addGlobalInstructionSelect() {
304 addPass(P: new InstructionSelectLegacy(getOptLevel()));
305 return false;
306}
307