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