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