LLVM  10.0.0svn
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/Support/CodeGen.h"
37 #include "llvm/Support/Debug.h"
41 #include <string>
42 
43 using namespace llvm;
44 
45 #define DEBUG_TYPE "mips"
46 
47 extern "C" void LLVMInitializeMipsTarget() {
48  // Register the target.
53 
60 }
61 
62 static std::string computeDataLayout(const Triple &TT, StringRef CPU,
63  const TargetOptions &Options,
64  bool isLittle) {
65  std::string Ret;
67 
68  // There are both little and big endian mips.
69  if (isLittle)
70  Ret += "e";
71  else
72  Ret += "E";
73 
74  if (ABI.IsO32())
75  Ret += "-m:m";
76  else
77  Ret += "-m:e";
78 
79  // Pointers are 32 bit on some ABIs.
80  if (!ABI.IsN64())
81  Ret += "-p:32:32";
82 
83  // 8 and 16 bit integers only need to have natural alignment, but try to
84  // align them to 32 bits. 64 bit integers have natural alignment.
85  Ret += "-i8:8:32-i16:16:32-i64:64";
86 
87  // 32 bit registers are always available and the stack is at least 64 bit
88  // aligned. On N64 64 bit registers are also available and the stack is
89  // 128 bit aligned.
90  if (ABI.IsN64() || ABI.IsN32())
91  Ret += "-n32:64-S128";
92  else
93  Ret += "-n32-S64";
94 
95  return Ret;
96 }
97 
100  if (!RM.hasValue() || JIT)
101  return Reloc::Static;
102  return *RM;
103 }
104 
105 // On function prologue, the stack is created by decrementing
106 // its pointer. Once decremented, all references are done with positive
107 // offset from the stack/frame pointer, using StackGrowsUp enables
108 // an easier handling.
109 // Using CodeModel::Large enables different CALL behavior.
111  StringRef CPU, StringRef FS,
112  const TargetOptions &Options,
115  CodeGenOpt::Level OL, bool JIT,
116  bool isLittle)
117  : LLVMTargetMachine(T, computeDataLayout(TT, CPU, Options, isLittle), TT,
118  CPU, FS, Options, getEffectiveRelocModel(JIT, RM),
119  getEffectiveCodeModel(CM, CodeModel::Small), OL),
120  isLittle(isLittle), TLOF(llvm::make_unique<MipsTargetObjectFile>()),
121  ABI(MipsABIInfo::computeTargetABI(TT, CPU, Options.MCOptions)),
122  Subtarget(nullptr), DefaultSubtarget(TT, CPU, FS, isLittle, *this,
123  Options.StackAlignmentOverride),
124  NoMips16Subtarget(TT, CPU, FS.empty() ? "-mips16" : FS.str() + ",-mips16",
125  isLittle, *this, Options.StackAlignmentOverride),
126  Mips16Subtarget(TT, CPU, FS.empty() ? "+mips16" : FS.str() + ",+mips16",
127  isLittle, *this, Options.StackAlignmentOverride) {
128  Subtarget = &DefaultSubtarget;
129  initAsmInfo();
130 }
131 
133 
134 void MipsebTargetMachine::anchor() {}
135 
137  StringRef CPU, StringRef FS,
138  const TargetOptions &Options,
141  CodeGenOpt::Level OL, bool JIT)
142  : MipsTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, false) {}
143 
144 void MipselTargetMachine::anchor() {}
145 
147  StringRef CPU, StringRef FS,
148  const TargetOptions &Options,
151  CodeGenOpt::Level OL, bool JIT)
152  : MipsTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, true) {}
153 
154 const MipsSubtarget *
156  Attribute CPUAttr = F.getFnAttribute("target-cpu");
157  Attribute FSAttr = F.getFnAttribute("target-features");
158 
159  std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
160  ? CPUAttr.getValueAsString().str()
161  : TargetCPU;
162  std::string FS = !FSAttr.hasAttribute(Attribute::None)
163  ? FSAttr.getValueAsString().str()
164  : TargetFS;
165  bool hasMips16Attr =
167  bool hasNoMips16Attr =
169 
170  bool HasMicroMipsAttr =
172  bool HasNoMicroMipsAttr =
173  !F.getFnAttribute("nomicromips").hasAttribute(Attribute::None);
174 
175  // FIXME: This is related to the code below to reset the target options,
176  // we need to know whether or not the soft float flag is set on the
177  // function, so we can enable it as a subtarget feature.
178  bool softFloat =
179  F.hasFnAttribute("use-soft-float") &&
180  F.getFnAttribute("use-soft-float").getValueAsString() == "true";
181 
182  if (hasMips16Attr)
183  FS += FS.empty() ? "+mips16" : ",+mips16";
184  else if (hasNoMips16Attr)
185  FS += FS.empty() ? "-mips16" : ",-mips16";
186  if (HasMicroMipsAttr)
187  FS += FS.empty() ? "+micromips" : ",+micromips";
188  else if (HasNoMicroMipsAttr)
189  FS += FS.empty() ? "-micromips" : ",-micromips";
190  if (softFloat)
191  FS += FS.empty() ? "+soft-float" : ",+soft-float";
192 
193  auto &I = SubtargetMap[CPU + FS];
194  if (!I) {
195  // This needs to be done before we create a new subtarget since any
196  // creation will depend on the TM and the code generation flags on the
197  // function that reside in TargetOptions.
199  I = llvm::make_unique<MipsSubtarget>(TargetTriple, CPU, FS, isLittle, *this,
201  }
202  return I.get();
203 }
204 
206  LLVM_DEBUG(dbgs() << "resetSubtarget\n");
207 
208  Subtarget = &MF->getSubtarget<MipsSubtarget>();
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  std::unique_ptr<CSEConfigBase> getCSEConfig() const override;
244 };
245 
246 } // end anonymous namespace
247 
249  return new MipsPassConfig(*this, PM);
250 }
251 
252 std::unique_ptr<CSEConfigBase> MipsPassConfig::getCSEConfig() const {
253  return getStandardCSEConfigForOpt(TM->getOptLevel());
254 }
255 
256 void MipsPassConfig::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.
266 bool MipsPassConfig::addInstSelector() {
267  addPass(createMipsModuleISelDagPass());
268  addPass(createMips16ISelDag(getMipsTargetMachine(), getOptLevel()));
269  addPass(createMipsSEISelDag(getMipsTargetMachine(), getOptLevel()));
270  return false;
271 }
272 
273 void MipsPassConfig::addPreRegAlloc() {
275 }
276 
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.
283  }
284 
285  LLVM_DEBUG(errs() << "Target Transform Info Pass Added\n");
286  return TargetTransformInfo(BasicTTIImpl(this, F));
287 }
288 
289 // Implemented by targets that want to run passes immediately before
290 // machine code is emitted. return true if -print-machineinstrs should
291 // print out the code after the passes.
292 void MipsPassConfig::addPreEmitPass() {
293  // Expand pseudo instructions that are sensitive to register allocation.
294  addPass(createMipsExpandPseudoPass());
295 
296  // The microMIPS size reduction pass performs instruction reselection for
297  // instructions which can be remapped to a 16 bit instruction.
299 
300  // The delay slot filler pass can potientially create forbidden slot hazards
301  // for MIPSR6 and therefore it should go before MipsBranchExpansion pass.
303 
304  // This pass expands branches and takes care about the forbidden slot hazards.
305  // Expanding branches may potentially create forbidden slot hazards for
306  // MIPSR6, and fixing such hazard may potentially break a branch by extending
307  // its offset out of range. That's why this pass combine these two tasks, and
308  // runs them alternately until one of them finishes without any changes. Only
309  // then we can be sure that all branches are expanded properly and no hazards
310  // exists.
311  // Any new pass should go before this pass.
312  addPass(createMipsBranchExpansion());
313 
314  addPass(createMipsConstantIslandPass());
315 }
316 
317 bool MipsPassConfig::addIRTranslator() {
318  addPass(new IRTranslator());
319  return false;
320 }
321 
322 void MipsPassConfig::addPreLegalizeMachineIR() {
324 }
325 
326 bool MipsPassConfig::addLegalizeMachineIR() {
327  addPass(new Legalizer());
328  return false;
329 }
330 
331 bool MipsPassConfig::addRegBankSelect() {
332  addPass(new RegBankSelect());
333  return false;
334 }
335 
336 bool MipsPassConfig::addGlobalInstructionSelect() {
337  addPass(new InstructionSelect());
338  return false;
339 }
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")
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
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:218
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:84
FunctionPass * createMipsBranchExpansion()
Target & getTheMipselTarget()
FunctionPass * createMipsDelaySlotFillerPass()
createMipsDelaySlotFillerPass - Returns a pass that fills in delay slots in Mips MachineFunctions ...
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.h:323
void resetSubtarget(MachineFunction *MF)
Reset the subtarget for the Mips target.
F(f)
block Block Frequency true
std::enable_if<!std::is_array< T >::value, std::unique_ptr< T > >::type make_unique(Args &&... args)
Constructs a new T() with the given args and returns a unique_ptr<T> which owns the object...
Definition: STLExtras.h:1405
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")
void resetTargetOptions(const Function &F) const
Reset the target options based on the function&#39;s attributes.
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:369
This file contains the simple types necessary to represent the attributes associated with functions a...
No attributes have been set.
Definition: Attributes.h:71
bool IsN32() const
Definition: MipsABIInfo.h:42
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:126
Target-Independent Code Generator Pass Configuration Options.
bool IsN64() const
Definition: MipsABIInfo.h:43
RegisterTargetMachine - Helper template for registering a target machine implementation, for use in the target machine initialization function.
Target & getTheMips64Target()
ModulePass * createMipsOs16Pass()
Definition: MipsOs16.cpp:159
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:65
bool hasAttribute(AttrKind Val) const
Return true if the attribute is present.
Definition: Attributes.cpp:238
Target & getTheMips64elTarget()
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
CodeGenOpt::Level getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
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...
bool IsO32() const
Definition: MipsABIInfo.h:41
FunctionPass * createMipsConstantIslandPass()
Returns a pass that converts branches to long branches.
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:43
constexpr bool empty(const T &RangeOrContainer)
Test whether RangeOrContainer is empty. Similar to C++17 std::empty.
Definition: STLExtras.h:209
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 ...
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)
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:85
void initializeMicroMipsSizeReducePass(PassRegistry &)
Target & getTheMipsTarget()
FunctionPass * createMicroMipsSizeReducePass()
Returns an instance of the MicroMips size reduction pass.
bool hasValue() const
Definition: Optional.h:259
StringRef getValueAsString() const
Return the attribute&#39;s value as a string.
Definition: Attributes.cpp:223
TargetOptions Options
#define I(x, y, z)
Definition: MD5.cpp:58
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:86
This file declares the IRTranslator pass.
static MipsABIInfo computeTargetABI(const Triple &TT, StringRef CPU, const MCTargetOptions &Options)
Definition: MipsABIInfo.cpp:56
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:575
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition: Function.h:333
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:48
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
Definition: PassRegistry.h:38
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 &)
void LLVMInitializeMipsTarget()