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/STLExtras.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/Analysis/TargetTransformInfo.h"
27 #include "llvm/CodeGen/BasicTTIImpl.h"
28 #include "llvm/CodeGen/GlobalISel/CSEInfo.h"
29 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
30 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
31 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
32 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/Passes.h"
35 #include "llvm/CodeGen/TargetPassConfig.h"
36 #include "llvm/IR/Attributes.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/InitializePasses.h"
39 #include "llvm/MC/TargetRegistry.h"
40 #include "llvm/Support/CodeGen.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include <optional>
45 #include <string>
46 
47 using namespace llvm;
48 
49 #define DEBUG_TYPE "mips"
50 
51 static cl::opt<bool>
52     EnableMulMulFix("mfix4300", cl::init(false),
53                     cl::desc("Enable the VR4300 mulmul bug fix."), cl::Hidden);
54 
55 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeMipsTarget() {
56   // Register the target.
57   RegisterTargetMachine<MipsebTargetMachine> X(getTheMipsTarget());
58   RegisterTargetMachine<MipselTargetMachine> Y(getTheMipselTarget());
59   RegisterTargetMachine<MipsebTargetMachine> A(getTheMips64Target());
60   RegisterTargetMachine<MipselTargetMachine> B(getTheMips64elTarget());
61 
62   PassRegistry *PR = PassRegistry::getPassRegistry();
63   initializeGlobalISel(*PR);
64   initializeMipsDelaySlotFillerPass(*PR);
65   initializeMipsBranchExpansionPass(*PR);
66   initializeMicroMipsSizeReducePass(*PR);
67   initializeMipsPreLegalizerCombinerPass(*PR);
68   initializeMipsPostLegalizerCombinerPass(*PR);
69   initializeMipsMulMulBugFixPass(*PR);
70   initializeMipsDAGToDAGISelPass(*PR);
71 }
72 
73 static std::string computeDataLayout(const Triple &TT, StringRef CPU,
74                                      const TargetOptions &Options,
75                                      bool isLittle) {
76   std::string Ret;
77   MipsABIInfo ABI = MipsABIInfo::computeTargetABI(TT, CPU, Options.MCOptions);
78 
79   // There are both little and big endian mips.
80   if (isLittle)
81     Ret += "e";
82   else
83     Ret += "E";
84 
85   if (ABI.IsO32())
86     Ret += "-m:m";
87   else
88     Ret += "-m:e";
89 
90   // Pointers are 32 bit on some ABIs.
91   if (!ABI.IsN64())
92     Ret += "-p:32:32";
93 
94   // 8 and 16 bit integers only need to have natural alignment, but try to
95   // align them to 32 bits. 64 bit integers have natural alignment.
96   Ret += "-i8:8:32-i16:16:32-i64:64";
97 
98   // 32 bit registers are always available and the stack is at least 64 bit
99   // aligned. On N64 64 bit registers are also available and the stack is
100   // 128 bit aligned.
101   if (ABI.IsN64() || ABI.IsN32())
102     Ret += "-n32:64-S128";
103   else
104     Ret += "-n32-S64";
105 
106   return Ret;
107 }
108 
109 static Reloc::Model getEffectiveRelocModel(bool JIT,
110                                            std::optional<Reloc::Model> RM) {
111   if (!RM || JIT)
112     return Reloc::Static;
113   return *RM;
114 }
115 
116 // On function prologue, the stack is created by decrementing
117 // its pointer. Once decremented, all references are done with positive
118 // offset from the stack/frame pointer, using StackGrowsUp enables
119 // an easier handling.
120 // Using CodeModel::Large enables different CALL behavior.
121 MipsTargetMachine::MipsTargetMachine(const Target &T, const Triple &TT,
122                                      StringRef CPU, StringRef FS,
123                                      const TargetOptions &Options,
124                                      std::optional<Reloc::Model> RM,
125                                      std::optional<CodeModel::Model> CM,
126                                      CodeGenOpt::Level OL, bool JIT,
127                                      bool isLittle)
128     : LLVMTargetMachine(T, computeDataLayout(TT, CPU, Options, isLittle), TT,
129                         CPU, FS, Options, getEffectiveRelocModel(JIT, RM),
130                         getEffectiveCodeModel(CM, CodeModel::Small), OL),
131       isLittle(isLittle), TLOF(std::make_unique<MipsTargetObjectFile>()),
132       ABI(MipsABIInfo::computeTargetABI(TT, CPU, Options.MCOptions)),
133       Subtarget(nullptr),
134       DefaultSubtarget(TT, CPU, FS, isLittle, *this, std::nullopt),
135       NoMips16Subtarget(TT, CPU, FS.empty() ? "-mips16" : FS.str() + ",-mips16",
136                         isLittle, *this, std::nullopt),
137       Mips16Subtarget(TT, CPU, FS.empty() ? "+mips16" : FS.str() + ",+mips16",
138                       isLittle, *this, std::nullopt) {
139   Subtarget = &DefaultSubtarget;
140   initAsmInfo();
141 
142   // Mips supports the debug entry values.
143   setSupportsDebugEntryValues(true);
144 }
145 
146 MipsTargetMachine::~MipsTargetMachine() = default;
147 
148 void MipsebTargetMachine::anchor() {}
149 
150 MipsebTargetMachine::MipsebTargetMachine(const Target &T, const Triple &TT,
151                                          StringRef CPU, StringRef FS,
152                                          const TargetOptions &Options,
153                                          std::optional<Reloc::Model> RM,
154                                          std::optional<CodeModel::Model> CM,
155                                          CodeGenOpt::Level OL, bool JIT)
156     : MipsTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, false) {}
157 
158 void MipselTargetMachine::anchor() {}
159 
160 MipselTargetMachine::MipselTargetMachine(const Target &T, const Triple &TT,
161                                          StringRef CPU, StringRef FS,
162                                          const TargetOptions &Options,
163                                          std::optional<Reloc::Model> RM,
164                                          std::optional<CodeModel::Model> CM,
165                                          CodeGenOpt::Level OL, bool JIT)
166     : MipsTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, true) {}
167 
168 const MipsSubtarget *
169 MipsTargetMachine::getSubtargetImpl(const Function &F) const {
170   Attribute CPUAttr = F.getFnAttribute("target-cpu");
171   Attribute FSAttr = F.getFnAttribute("target-features");
172 
173   std::string CPU =
174       CPUAttr.isValid() ? CPUAttr.getValueAsString().str() : TargetCPU;
175   std::string FS =
176       FSAttr.isValid() ? FSAttr.getValueAsString().str() : TargetFS;
177   bool hasMips16Attr = F.getFnAttribute("mips16").isValid();
178   bool hasNoMips16Attr = F.getFnAttribute("nomips16").isValid();
179 
180   bool HasMicroMipsAttr = F.getFnAttribute("micromips").isValid();
181   bool HasNoMicroMipsAttr = F.getFnAttribute("nomicromips").isValid();
182 
183   // FIXME: This is related to the code below to reset the target options,
184   // we need to know whether or not the soft float flag is set on the
185   // function, so we can enable it as a subtarget feature.
186   bool softFloat = F.getFnAttribute("use-soft-float").getValueAsBool();
187 
188   if (hasMips16Attr)
189     FS += FS.empty() ? "+mips16" : ",+mips16";
190   else if (hasNoMips16Attr)
191     FS += FS.empty() ? "-mips16" : ",-mips16";
192   if (HasMicroMipsAttr)
193     FS += FS.empty() ? "+micromips" : ",+micromips";
194   else if (HasNoMicroMipsAttr)
195     FS += FS.empty() ? "-micromips" : ",-micromips";
196   if (softFloat)
197     FS += FS.empty() ? "+soft-float" : ",+soft-float";
198 
199   auto &I = SubtargetMap[CPU + FS];
200   if (!I) {
201     // This needs to be done before we create a new subtarget since any
202     // creation will depend on the TM and the code generation flags on the
203     // function that reside in TargetOptions.
204     resetTargetOptions(F);
205     I = std::make_unique<MipsSubtarget>(
206         TargetTriple, CPU, FS, isLittle, *this,
207         MaybeAlign(F.getParent()->getOverrideStackAlignment()));
208   }
209   return I.get();
210 }
211 
212 void MipsTargetMachine::resetSubtarget(MachineFunction *MF) {
213   LLVM_DEBUG(dbgs() << "resetSubtarget\n");
214 
215   Subtarget = &MF->getSubtarget<MipsSubtarget>();
216 }
217 
218 namespace {
219 
220 /// Mips Code Generator Pass Configuration Options.
221 class MipsPassConfig : public TargetPassConfig {
222 public:
223   MipsPassConfig(MipsTargetMachine &TM, PassManagerBase &PM)
224       : TargetPassConfig(TM, PM) {
225     // The current implementation of long branch pass requires a scratch
226     // register ($at) to be available before branch instructions. Tail merging
227     // can break this requirement, so disable it when long branch pass is
228     // enabled.
229     EnableTailMerge = !getMipsSubtarget().enableLongBranchPass();
230   }
231 
232   MipsTargetMachine &getMipsTargetMachine() const {
233     return getTM<MipsTargetMachine>();
234   }
235 
236   const MipsSubtarget &getMipsSubtarget() const {
237     return *getMipsTargetMachine().getSubtargetImpl();
238   }
239 
240   void addIRPasses() override;
241   bool addInstSelector() override;
242   void addPreEmitPass() override;
243   void addPreRegAlloc() override;
244   bool addIRTranslator() override;
245   void addPreLegalizeMachineIR() override;
246   bool addLegalizeMachineIR() override;
247   void addPreRegBankSelect() override;
248   bool addRegBankSelect() override;
249   bool addGlobalInstructionSelect() override;
250 
251   std::unique_ptr<CSEConfigBase> getCSEConfig() const override;
252 };
253 
254 } // end anonymous namespace
255 
256 TargetPassConfig *MipsTargetMachine::createPassConfig(PassManagerBase &PM) {
257   return new MipsPassConfig(*this, PM);
258 }
259 
260 std::unique_ptr<CSEConfigBase> MipsPassConfig::getCSEConfig() const {
261   return getStandardCSEConfigForOpt(TM->getOptLevel());
262 }
263 
264 void MipsPassConfig::addIRPasses() {
265   TargetPassConfig::addIRPasses();
266   addPass(createAtomicExpandPass());
267   if (getMipsSubtarget().os16())
268     addPass(createMipsOs16Pass());
269   if (getMipsSubtarget().inMips16HardFloat())
270     addPass(createMips16HardFloatPass());
271 }
272 // Install an instruction selector pass using
273 // the ISelDag to gen Mips code.
274 bool MipsPassConfig::addInstSelector() {
275   addPass(createMipsModuleISelDagPass());
276   addPass(createMips16ISelDag(getMipsTargetMachine(), getOptLevel()));
277   addPass(createMipsSEISelDag(getMipsTargetMachine(), getOptLevel()));
278   return false;
279 }
280 
281 void MipsPassConfig::addPreRegAlloc() {
282   addPass(createMipsOptimizePICCallPass());
283 }
284 
285 TargetTransformInfo
286 MipsTargetMachine::getTargetTransformInfo(const Function &F) const {
287   if (Subtarget->allowMixed16_32()) {
288     LLVM_DEBUG(errs() << "No Target Transform Info Pass Added\n");
289     // FIXME: This is no longer necessary as the TTI returned is per-function.
290     return TargetTransformInfo(F.getParent()->getDataLayout());
291   }
292 
293   LLVM_DEBUG(errs() << "Target Transform Info Pass Added\n");
294   return TargetTransformInfo(MipsTTIImpl(this, F));
295 }
296 
297 MachineFunctionInfo *MipsTargetMachine::createMachineFunctionInfo(
298     BumpPtrAllocator &Allocator, const Function &F,
299     const TargetSubtargetInfo *STI) const {
300   return MipsFunctionInfo::create<MipsFunctionInfo>(Allocator, F, STI);
301 }
302 
303 // Implemented by targets that want to run passes immediately before
304 // machine code is emitted.
305 void MipsPassConfig::addPreEmitPass() {
306   // Expand pseudo instructions that are sensitive to register allocation.
307   addPass(createMipsExpandPseudoPass());
308 
309   // The microMIPS size reduction pass performs instruction reselection for
310   // instructions which can be remapped to a 16 bit instruction.
311   addPass(createMicroMipsSizeReducePass());
312 
313   // This pass inserts a nop instruction between two back-to-back multiplication
314   // instructions when the "mfix4300" flag is passed.
315   if (EnableMulMulFix)
316     addPass(createMipsMulMulBugPass());
317 
318   // The delay slot filler pass can potientially create forbidden slot hazards
319   // for MIPSR6 and therefore it should go before MipsBranchExpansion pass.
320   addPass(createMipsDelaySlotFillerPass());
321 
322   // This pass expands branches and takes care about the forbidden slot hazards.
323   // Expanding branches may potentially create forbidden slot hazards for
324   // MIPSR6, and fixing such hazard may potentially break a branch by extending
325   // its offset out of range. That's why this pass combine these two tasks, and
326   // runs them alternately until one of them finishes without any changes. Only
327   // then we can be sure that all branches are expanded properly and no hazards
328   // exists.
329   // Any new pass should go before this pass.
330   addPass(createMipsBranchExpansion());
331 
332   addPass(createMipsConstantIslandPass());
333 }
334 
335 bool MipsPassConfig::addIRTranslator() {
336   addPass(new IRTranslator(getOptLevel()));
337   return false;
338 }
339 
340 void MipsPassConfig::addPreLegalizeMachineIR() {
341   addPass(createMipsPreLegalizeCombiner());
342 }
343 
344 bool MipsPassConfig::addLegalizeMachineIR() {
345   addPass(new Legalizer());
346   return false;
347 }
348 
349 void MipsPassConfig::addPreRegBankSelect() {
350   bool IsOptNone = getOptLevel() == CodeGenOpt::None;
351   addPass(createMipsPostLegalizeCombiner(IsOptNone));
352 }
353 
354 bool MipsPassConfig::addRegBankSelect() {
355   addPass(new RegBankSelect());
356   return false;
357 }
358 
359 bool MipsPassConfig::addGlobalInstructionSelect() {
360   addPass(new InstructionSelect(getOptLevel()));
361   return false;
362 }
363