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