1 //===-- RISCVTargetMachine.cpp - Define TargetMachine for RISCV -----------===//
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 RISCV target spec.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "RISCVTargetMachine.h"
14 #include "MCTargetDesc/RISCVBaseInfo.h"
15 #include "RISCV.h"
16 #include "RISCVMachineFunctionInfo.h"
17 #include "RISCVTargetObjectFile.h"
18 #include "RISCVTargetTransformInfo.h"
19 #include "TargetInfo/RISCVTargetInfo.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
23 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
24 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
25 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
26 #include "llvm/CodeGen/MIRParser/MIParser.h"
27 #include "llvm/CodeGen/MIRYamlMapping.h"
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
30 #include "llvm/CodeGen/TargetPassConfig.h"
31 #include "llvm/IR/LegacyPassManager.h"
32 #include "llvm/InitializePasses.h"
33 #include "llvm/MC/TargetRegistry.h"
34 #include "llvm/Support/FormattedStream.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/Transforms/IPO.h"
37 using namespace llvm;
38 
39 static cl::opt<bool> EnableRedundantCopyElimination(
40     "riscv-enable-copyelim",
41     cl::desc("Enable the redundant copy elimination pass"), cl::init(true),
42     cl::Hidden);
43 
44 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeRISCVTarget() {
45   RegisterTargetMachine<RISCVTargetMachine> X(getTheRISCV32Target());
46   RegisterTargetMachine<RISCVTargetMachine> Y(getTheRISCV64Target());
47   auto *PR = PassRegistry::getPassRegistry();
48   initializeGlobalISel(*PR);
49   initializeRISCVMakeCompressibleOptPass(*PR);
50   initializeRISCVGatherScatterLoweringPass(*PR);
51   initializeRISCVMergeBaseOffsetOptPass(*PR);
52   initializeRISCVSExtWRemovalPass(*PR);
53   initializeRISCVExpandPseudoPass(*PR);
54   initializeRISCVInsertVSETVLIPass(*PR);
55 }
56 
57 static StringRef computeDataLayout(const Triple &TT) {
58   if (TT.isArch64Bit())
59     return "e-m:e-p:64:64-i64:64-i128:128-n64-S128";
60   assert(TT.isArch32Bit() && "only RV32 and RV64 are currently supported");
61   return "e-m:e-p:32:32-i64:64-n32-S128";
62 }
63 
64 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
65                                            Optional<Reloc::Model> RM) {
66   if (!RM.hasValue())
67     return Reloc::Static;
68   return *RM;
69 }
70 
71 RISCVTargetMachine::RISCVTargetMachine(const Target &T, const Triple &TT,
72                                        StringRef CPU, StringRef FS,
73                                        const TargetOptions &Options,
74                                        Optional<Reloc::Model> RM,
75                                        Optional<CodeModel::Model> CM,
76                                        CodeGenOpt::Level OL, bool JIT)
77     : LLVMTargetMachine(T, computeDataLayout(TT), TT, CPU, FS, Options,
78                         getEffectiveRelocModel(TT, RM),
79                         getEffectiveCodeModel(CM, CodeModel::Small), OL),
80       TLOF(std::make_unique<RISCVELFTargetObjectFile>()) {
81   initAsmInfo();
82 
83   // RISC-V supports the MachineOutliner.
84   setMachineOutliner(true);
85   setSupportsDefaultOutlining(true);
86 }
87 
88 const RISCVSubtarget *
89 RISCVTargetMachine::getSubtargetImpl(const Function &F) const {
90   Attribute CPUAttr = F.getFnAttribute("target-cpu");
91   Attribute TuneAttr = F.getFnAttribute("tune-cpu");
92   Attribute FSAttr = F.getFnAttribute("target-features");
93 
94   std::string CPU =
95       CPUAttr.isValid() ? CPUAttr.getValueAsString().str() : TargetCPU;
96   std::string TuneCPU =
97       TuneAttr.isValid() ? TuneAttr.getValueAsString().str() : CPU;
98   std::string FS =
99       FSAttr.isValid() ? FSAttr.getValueAsString().str() : TargetFS;
100   std::string Key = CPU + TuneCPU + FS;
101   auto &I = SubtargetMap[Key];
102   if (!I) {
103     // This needs to be done before we create a new subtarget since any
104     // creation will depend on the TM and the code generation flags on the
105     // function that reside in TargetOptions.
106     resetTargetOptions(F);
107     auto ABIName = Options.MCOptions.getABIName();
108     if (const MDString *ModuleTargetABI = dyn_cast_or_null<MDString>(
109             F.getParent()->getModuleFlag("target-abi"))) {
110       auto TargetABI = RISCVABI::getTargetABI(ABIName);
111       if (TargetABI != RISCVABI::ABI_Unknown &&
112           ModuleTargetABI->getString() != ABIName) {
113         report_fatal_error("-target-abi option != target-abi module flag");
114       }
115       ABIName = ModuleTargetABI->getString();
116     }
117     I = std::make_unique<RISCVSubtarget>(TargetTriple, CPU, TuneCPU, FS, ABIName, *this);
118   }
119   return I.get();
120 }
121 
122 TargetTransformInfo
123 RISCVTargetMachine::getTargetTransformInfo(const Function &F) const {
124   return TargetTransformInfo(RISCVTTIImpl(this, F));
125 }
126 
127 // A RISC-V hart has a single byte-addressable address space of 2^XLEN bytes
128 // for all memory accesses, so it is reasonable to assume that an
129 // implementation has no-op address space casts. If an implementation makes a
130 // change to this, they can override it here.
131 bool RISCVTargetMachine::isNoopAddrSpaceCast(unsigned SrcAS,
132                                              unsigned DstAS) const {
133   return true;
134 }
135 
136 namespace {
137 class RISCVPassConfig : public TargetPassConfig {
138 public:
139   RISCVPassConfig(RISCVTargetMachine &TM, PassManagerBase &PM)
140       : TargetPassConfig(TM, PM) {}
141 
142   RISCVTargetMachine &getRISCVTargetMachine() const {
143     return getTM<RISCVTargetMachine>();
144   }
145 
146   void addIRPasses() override;
147   bool addPreISel() override;
148   bool addInstSelector() override;
149   bool addIRTranslator() override;
150   bool addLegalizeMachineIR() override;
151   bool addRegBankSelect() override;
152   bool addGlobalInstructionSelect() override;
153   void addPreEmitPass() override;
154   void addPreEmitPass2() override;
155   void addPreSched2() override;
156   void addMachineSSAOptimization() override;
157   void addPreRegAlloc() override;
158   void addPostRegAlloc() override;
159 };
160 } // namespace
161 
162 TargetPassConfig *RISCVTargetMachine::createPassConfig(PassManagerBase &PM) {
163   return new RISCVPassConfig(*this, PM);
164 }
165 
166 void RISCVPassConfig::addIRPasses() {
167   addPass(createAtomicExpandPass());
168 
169   addPass(createRISCVGatherScatterLoweringPass());
170 
171   TargetPassConfig::addIRPasses();
172 }
173 
174 bool RISCVPassConfig::addPreISel() {
175   if (TM->getOptLevel() != CodeGenOpt::None) {
176     // Add a barrier before instruction selection so that we will not get
177     // deleted block address after enabling default outlining. See D99707 for
178     // more details.
179     addPass(createBarrierNoopPass());
180   }
181   return false;
182 }
183 
184 bool RISCVPassConfig::addInstSelector() {
185   addPass(createRISCVISelDag(getRISCVTargetMachine(), getOptLevel()));
186 
187   return false;
188 }
189 
190 bool RISCVPassConfig::addIRTranslator() {
191   addPass(new IRTranslator(getOptLevel()));
192   return false;
193 }
194 
195 bool RISCVPassConfig::addLegalizeMachineIR() {
196   addPass(new Legalizer());
197   return false;
198 }
199 
200 bool RISCVPassConfig::addRegBankSelect() {
201   addPass(new RegBankSelect());
202   return false;
203 }
204 
205 bool RISCVPassConfig::addGlobalInstructionSelect() {
206   addPass(new InstructionSelect(getOptLevel()));
207   return false;
208 }
209 
210 void RISCVPassConfig::addPreSched2() {}
211 
212 void RISCVPassConfig::addPreEmitPass() {
213   addPass(&BranchRelaxationPassID);
214   addPass(createRISCVMakeCompressibleOptPass());
215 }
216 
217 void RISCVPassConfig::addPreEmitPass2() {
218   addPass(createRISCVExpandPseudoPass());
219   // Schedule the expansion of AMOs at the last possible moment, avoiding the
220   // possibility for other passes to break the requirements for forward
221   // progress in the LR/SC block.
222   addPass(createRISCVExpandAtomicPseudoPass());
223 }
224 
225 void RISCVPassConfig::addMachineSSAOptimization() {
226   TargetPassConfig::addMachineSSAOptimization();
227 
228   if (TM->getTargetTriple().getArch() == Triple::riscv64)
229     addPass(createRISCVSExtWRemovalPass());
230 }
231 
232 void RISCVPassConfig::addPreRegAlloc() {
233   if (TM->getOptLevel() != CodeGenOpt::None)
234     addPass(createRISCVMergeBaseOffsetOptPass());
235   addPass(createRISCVInsertVSETVLIPass());
236 }
237 
238 void RISCVPassConfig::addPostRegAlloc() {
239   if (TM->getOptLevel() != CodeGenOpt::None && EnableRedundantCopyElimination)
240     addPass(createRISCVRedundantCopyEliminationPass());
241 }
242 
243 yaml::MachineFunctionInfo *
244 RISCVTargetMachine::createDefaultFuncInfoYAML() const {
245   return new yaml::RISCVMachineFunctionInfo();
246 }
247 
248 yaml::MachineFunctionInfo *
249 RISCVTargetMachine::convertFuncInfoToYAML(const MachineFunction &MF) const {
250   const auto *MFI = MF.getInfo<RISCVMachineFunctionInfo>();
251   return new yaml::RISCVMachineFunctionInfo(*MFI);
252 }
253 
254 bool RISCVTargetMachine::parseMachineFunctionInfo(
255     const yaml::MachineFunctionInfo &MFI, PerFunctionMIParsingState &PFS,
256     SMDiagnostic &Error, SMRange &SourceRange) const {
257   const auto &YamlMFI =
258       static_cast<const yaml::RISCVMachineFunctionInfo &>(MFI);
259   PFS.MF.getInfo<RISCVMachineFunctionInfo>()->initializeBaseYamlFields(YamlMFI);
260   return false;
261 }
262