LLVM  12.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 "MipsSEISelDAGToDAG.h"
19 #include "MipsSubtarget.h"
20 #include "MipsTargetObjectFile.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/StringRef.h"
32 #include "llvm/CodeGen/Passes.h"
34 #include "llvm/IR/Attributes.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/InitializePasses.h"
37 #include "llvm/Support/CodeGen.h"
38 #include "llvm/Support/Debug.h"
42 #include <string>
43 
44 using namespace llvm;
45 
46 #define DEBUG_TYPE "mips"
47 
49  // Register the target.
54 
61 }
62 
63 static std::string computeDataLayout(const Triple &TT, StringRef CPU,
64  const TargetOptions &Options,
65  bool isLittle) {
66  std::string Ret;
68 
69  // There are both little and big endian mips.
70  if (isLittle)
71  Ret += "e";
72  else
73  Ret += "E";
74 
75  if (ABI.IsO32())
76  Ret += "-m:m";
77  else
78  Ret += "-m:e";
79 
80  // Pointers are 32 bit on some ABIs.
81  if (!ABI.IsN64())
82  Ret += "-p:32:32";
83 
84  // 8 and 16 bit integers only need to have natural alignment, but try to
85  // align them to 32 bits. 64 bit integers have natural alignment.
86  Ret += "-i8:8:32-i16:16:32-i64:64";
87 
88  // 32 bit registers are always available and the stack is at least 64 bit
89  // aligned. On N64 64 bit registers are also available and the stack is
90  // 128 bit aligned.
91  if (ABI.IsN64() || ABI.IsN32())
92  Ret += "-n32:64-S128";
93  else
94  Ret += "-n32-S64";
95 
96  return Ret;
97 }
98 
101  if (!RM.hasValue() || JIT)
102  return Reloc::Static;
103  return *RM;
104 }
105 
106 // On function prologue, the stack is created by decrementing
107 // its pointer. Once decremented, all references are done with positive
108 // offset from the stack/frame pointer, using StackGrowsUp enables
109 // an easier handling.
110 // Using CodeModel::Large enables different CALL behavior.
112  StringRef CPU, StringRef FS,
113  const TargetOptions &Options,
116  CodeGenOpt::Level OL, bool JIT,
117  bool isLittle)
118  : LLVMTargetMachine(T, computeDataLayout(TT, CPU, Options, isLittle), TT,
119  CPU, FS, Options, getEffectiveRelocModel(JIT, RM),
120  getEffectiveCodeModel(CM, CodeModel::Small), OL),
121  isLittle(isLittle), TLOF(std::make_unique<MipsTargetObjectFile>()),
122  ABI(MipsABIInfo::computeTargetABI(TT, CPU, Options.MCOptions)),
123  Subtarget(nullptr),
124  DefaultSubtarget(TT, CPU, FS, isLittle, *this,
125  MaybeAlign(Options.StackAlignmentOverride)),
126  NoMips16Subtarget(TT, CPU, FS.empty() ? "-mips16" : FS.str() + ",-mips16",
127  isLittle, *this,
128  MaybeAlign(Options.StackAlignmentOverride)),
129  Mips16Subtarget(TT, CPU, FS.empty() ? "+mips16" : FS.str() + ",+mips16",
130  isLittle, *this,
131  MaybeAlign(Options.StackAlignmentOverride)) {
132  Subtarget = &DefaultSubtarget;
133  initAsmInfo();
134 
135  // Mips supports the debug entry values.
137 }
138 
140 
141 void MipsebTargetMachine::anchor() {}
142 
144  StringRef CPU, StringRef FS,
145  const TargetOptions &Options,
148  CodeGenOpt::Level OL, bool JIT)
149  : MipsTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, false) {}
150 
151 void MipselTargetMachine::anchor() {}
152 
154  StringRef CPU, StringRef FS,
155  const TargetOptions &Options,
158  CodeGenOpt::Level OL, bool JIT)
159  : MipsTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, true) {}
160 
161 const MipsSubtarget *
163  Attribute CPUAttr = F.getFnAttribute("target-cpu");
164  Attribute FSAttr = F.getFnAttribute("target-features");
165 
166  std::string CPU =
167  CPUAttr.isValid() ? CPUAttr.getValueAsString().str() : TargetCPU;
168  std::string FS =
169  FSAttr.isValid() ? FSAttr.getValueAsString().str() : TargetFS;
170  bool hasMips16Attr = F.getFnAttribute("mips16").isValid();
171  bool hasNoMips16Attr = F.getFnAttribute("nomips16").isValid();
172 
173  bool HasMicroMipsAttr = F.getFnAttribute("micromips").isValid();
174  bool HasNoMicroMipsAttr = F.getFnAttribute("nomicromips").isValid();
175 
176  // FIXME: This is related to the code below to reset the target options,
177  // we need to know whether or not the soft float flag is set on the
178  // function, so we can enable it as a subtarget feature.
179  bool softFloat =
180  F.hasFnAttribute("use-soft-float") &&
181  F.getFnAttribute("use-soft-float").getValueAsString() == "true";
182 
183  if (hasMips16Attr)
184  FS += FS.empty() ? "+mips16" : ",+mips16";
185  else if (hasNoMips16Attr)
186  FS += FS.empty() ? "-mips16" : ",-mips16";
187  if (HasMicroMipsAttr)
188  FS += FS.empty() ? "+micromips" : ",+micromips";
189  else if (HasNoMicroMipsAttr)
190  FS += FS.empty() ? "-micromips" : ",-micromips";
191  if (softFloat)
192  FS += FS.empty() ? "+soft-float" : ",+soft-float";
193 
194  auto &I = SubtargetMap[CPU + FS];
195  if (!I) {
196  // This needs to be done before we create a new subtarget since any
197  // creation will depend on the TM and the code generation flags on the
198  // function that reside in TargetOptions.
200  I = std::make_unique<MipsSubtarget>(
201  TargetTriple, CPU, FS, isLittle, *this,
203  }
204  return I.get();
205 }
206 
208  LLVM_DEBUG(dbgs() << "resetSubtarget\n");
209 
210  Subtarget = &MF->getSubtarget<MipsSubtarget>();
211 }
212 
213 namespace {
214 
215 /// Mips Code Generator Pass Configuration Options.
216 class MipsPassConfig : public TargetPassConfig {
217 public:
218  MipsPassConfig(MipsTargetMachine &TM, PassManagerBase &PM)
219  : TargetPassConfig(TM, PM) {
220  // The current implementation of long branch pass requires a scratch
221  // register ($at) to be available before branch instructions. Tail merging
222  // can break this requirement, so disable it when long branch pass is
223  // enabled.
224  EnableTailMerge = !getMipsSubtarget().enableLongBranchPass();
225  }
226 
227  MipsTargetMachine &getMipsTargetMachine() const {
228  return getTM<MipsTargetMachine>();
229  }
230 
231  const MipsSubtarget &getMipsSubtarget() const {
232  return *getMipsTargetMachine().getSubtargetImpl();
233  }
234 
235  void addIRPasses() override;
236  bool addInstSelector() override;
237  void addPreEmitPass() override;
238  void addPreRegAlloc() override;
239  bool addIRTranslator() override;
240  void addPreLegalizeMachineIR() override;
241  bool addLegalizeMachineIR() override;
242  bool addRegBankSelect() override;
243  bool addGlobalInstructionSelect() override;
244 
245  std::unique_ptr<CSEConfigBase> getCSEConfig() const override;
246 };
247 
248 } // end anonymous namespace
249 
251  return new MipsPassConfig(*this, PM);
252 }
253 
254 std::unique_ptr<CSEConfigBase> MipsPassConfig::getCSEConfig() const {
255  return getStandardCSEConfigForOpt(TM->getOptLevel());
256 }
257 
258 void MipsPassConfig::addIRPasses() {
260  addPass(createAtomicExpandPass());
261  if (getMipsSubtarget().os16())
262  addPass(createMipsOs16Pass());
263  if (getMipsSubtarget().inMips16HardFloat())
264  addPass(createMips16HardFloatPass());
265 }
266 // Install an instruction selector pass using
267 // the ISelDag to gen Mips code.
268 bool MipsPassConfig::addInstSelector() {
269  addPass(createMipsModuleISelDagPass());
270  addPass(createMips16ISelDag(getMipsTargetMachine(), getOptLevel()));
271  addPass(createMipsSEISelDag(getMipsTargetMachine(), getOptLevel()));
272  return false;
273 }
274 
275 void MipsPassConfig::addPreRegAlloc() {
277 }
278 
281  if (Subtarget->allowMixed16_32()) {
282  LLVM_DEBUG(errs() << "No Target Transform Info Pass Added\n");
283  // FIXME: This is no longer necessary as the TTI returned is per-function.
284  return TargetTransformInfo(F.getParent()->getDataLayout());
285  }
286 
287  LLVM_DEBUG(errs() << "Target Transform Info Pass Added\n");
288  return TargetTransformInfo(BasicTTIImpl(this, F));
289 }
290 
291 // Implemented by targets that want to run passes immediately before
292 // machine code is emitted.
293 void MipsPassConfig::addPreEmitPass() {
294  // Expand pseudo instructions that are sensitive to register allocation.
295  addPass(createMipsExpandPseudoPass());
296 
297  // The microMIPS size reduction pass performs instruction reselection for
298  // instructions which can be remapped to a 16 bit instruction.
300 
301  // The delay slot filler pass can potientially create forbidden slot hazards
302  // for MIPSR6 and therefore it should go before MipsBranchExpansion pass.
304 
305  // This pass expands branches and takes care about the forbidden slot hazards.
306  // Expanding branches may potentially create forbidden slot hazards for
307  // MIPSR6, and fixing such hazard may potentially break a branch by extending
308  // its offset out of range. That's why this pass combine these two tasks, and
309  // runs them alternately until one of them finishes without any changes. Only
310  // then we can be sure that all branches are expanded properly and no hazards
311  // exists.
312  // Any new pass should go before this pass.
313  addPass(createMipsBranchExpansion());
314 
315  addPass(createMipsConstantIslandPass());
316 }
317 
318 bool MipsPassConfig::addIRTranslator() {
319  addPass(new IRTranslator(getOptLevel()));
320  return false;
321 }
322 
323 void MipsPassConfig::addPreLegalizeMachineIR() {
325 }
326 
327 bool MipsPassConfig::addLegalizeMachineIR() {
328  addPass(new Legalizer());
329  return false;
330 }
331 
332 bool MipsPassConfig::addRegBankSelect() {
333  addPass(new RegBankSelect());
334  return false;
335 }
336 
337 bool MipsPassConfig::addGlobalInstructionSelect() {
338  addPass(new InstructionSelect());
339  return false;
340 }
void initializeMipsBranchExpansionPass(PassRegistry &)
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)
static ARMBaseTargetMachine::ARMABI computeTargetABI(const Triple &TT, StringRef CPU, const TargetOptions &Options)
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
CodeModel::Model getEffectiveCodeModel(Optional< CodeModel::Model > CM, CodeModel::Model Default)
Helper method for getting the code model, returning Default if CM does not have a value.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:248
MCTargetOptions MCOptions
Machine level options.
This class represents lattice values for constants.
Definition: AllocatorList.h:23
virtual void addIRPasses()
Add common target configurable passes that perform LLVM IR to IR transforms following machine indepen...
FunctionPass * createMipsSEISelDag(MipsTargetMachine &TM, CodeGenOpt::Level OptLevel)
Triple TargetTriple
Triple string, CPU name, and target feature strings the TargetMachine instance is created with.
Definition: TargetMachine.h:96
FunctionPass * createMipsBranchExpansion()
Target & getTheMipselTarget()
FunctionPass * createMipsDelaySlotFillerPass()
createMipsDelaySlotFillerPass - Returns a pass that fills in delay slots in Mips MachineFunctions
void resetSubtarget(MachineFunction *MF)
Reset the subtarget for the Mips target.
F(f)
TargetPassConfig * createPassConfig(PassManagerBase &PM) override
Create a pass configuration object to be used by addPassToEmitX methods for generating a pipeline of ...
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
Definition: BitVector.h:941
void resetTargetOptions(const Function &F) const
Reset the target options based on the function's attributes.
This file contains the simple types necessary to represent the attributes associated with functions a...
Target-Independent Code Generator Pass Configuration Options.
RegisterTargetMachine - Helper template for registering a target machine implementation,...
Target & getTheMips64Target()
ModulePass * createMipsOs16Pass()
Definition: MipsOs16.cpp:159
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition: Attributes.h:151
const MipsSubtarget * getSubtargetImpl() const
static std::string computeDataLayout(const Triple &TT, StringRef CPU, const TargetOptions &Options, bool isLittle)
std::unique_ptr< CSEConfigBase > getStandardCSEConfigForOpt(CodeGenOpt::Level Level)
Definition: CSEInfo.cpp:73
Target & getTheMips64elTarget()
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Concrete BasicTTIImpl that can be used if no further customization is needed.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
static Reloc::Model getEffectiveRelocModel(Optional< Reloc::Model > RM)
This pass implements the reg bank selector pass used in the GlobalISel pipeline.
Definition: RegBankSelect.h:90
FunctionPass * createMipsOptimizePICCallPass()
Return an OptimizeCall object.
~MipsTargetMachine() override
FunctionPass * createMipsPreLegalizeCombiner()
This class describes a target machine that is implemented with the LLVM target-independent code gener...
FunctionPass * createMipsConstantIslandPass()
Returns a pass that converts branches to long branches.
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
This file provides a helper that implements much of the TTI interface in terms of the target-independ...
FunctionPass * createMips16ISelDag(MipsTargetMachine &TM, CodeGenOpt::Level OptLevel)
ModulePass * createMips16HardFloatPass()
FunctionPass * createMipsExpandPseudoPass()
createMipsExpandPseudoPass - returns an instance of the pseudo instruction expansion pass.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:45
constexpr bool empty(const T &RangeOrContainer)
Test whether RangeOrContainer is empty. Similar to C++17 std::empty.
Definition: STLExtras.h:263
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
PassManagerBase - An abstract interface to allow code to add passes to a pass manager without having ...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition: Alignment.h:119
unsigned StackAlignmentOverride
StackAlignmentOverride - Override default stack alignment for target.
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)
#define LLVM_EXTERNAL_VISIBILITY
Definition: Compiler.h:131
This pass is responsible for selecting generic machine instructions to target-specific instructions.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
Target - Wrapper for Target specific information.
std::string TargetCPU
Definition: TargetMachine.h:97
void initializeMicroMipsSizeReducePass(PassRegistry &)
Target & getTheMipsTarget()
FunctionPass * createMicroMipsSizeReducePass()
Returns an instance of the MicroMips size reduction pass.
basic Basic Alias true
StringRef getValueAsString() const
Return the attribute's value as a string.
Definition: Attributes.cpp:275
TargetOptions Options
#define I(x, y, z)
Definition: MD5.cpp:59
FunctionPass * createMipsModuleISelDagPass()
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)
std::string TargetFS
Definition: TargetMachine.h:98
bool allowMixed16_32() const
This file declares the IRTranslator pass.
static MipsABIInfo computeTargetABI(const Triple &TT, StringRef CPU, const MCTargetOptions &Options)
Definition: MipsABIInfo.cpp:57
TargetTransformInfo getTargetTransformInfo(const Function &F) override
Get a TargetTransformInfo implementation for the target.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:57
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
Definition: PassRegistry.h:38
void setSupportsDebugEntryValues(bool Enable)
This pass exposes codegen information to IR-level passes.
void initializeMipsDelaySlotFillerPass(PassRegistry &)
#define LLVM_DEBUG(X)
Definition: Debug.h:122
FunctionPass * createAtomicExpandPass()
void initializeGlobalISel(PassRegistry &)
Initialize all passes linked into the GlobalISel library.
Definition: GlobalISel.cpp:18
void initializeMipsPreLegalizerCombinerPass(PassRegistry &)
LLVM_EXTERNAL_VISIBILITY void LLVMInitializeMipsTarget()