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 "RISCV.h"
15 #include "RISCVTargetObjectFile.h"
16 #include "RISCVTargetTransformInfo.h"
17 #include "TargetInfo/RISCVTargetInfo.h"
18 #include "Utils/RISCVBaseInfo.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/Analysis/TargetTransformInfo.h"
21 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
22 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
23 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
24 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
27 #include "llvm/CodeGen/TargetPassConfig.h"
28 #include "llvm/IR/LegacyPassManager.h"
29 #include "llvm/InitializePasses.h"
30 #include "llvm/Support/FormattedStream.h"
31 #include "llvm/Support/TargetRegistry.h"
32 #include "llvm/Target/TargetOptions.h"
33 using namespace llvm;
34 
35 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeRISCVTarget() {
36   RegisterTargetMachine<RISCVTargetMachine> X(getTheRISCV32Target());
37   RegisterTargetMachine<RISCVTargetMachine> Y(getTheRISCV64Target());
38   auto PR = PassRegistry::getPassRegistry();
39   initializeGlobalISel(*PR);
40   initializeRISCVMergeBaseOffsetOptPass(*PR);
41   initializeRISCVExpandPseudoPass(*PR);
42   initializeRISCVCleanupVSETVLIPass(*PR);
43 }
44 
45 static StringRef computeDataLayout(const Triple &TT) {
46   if (TT.isArch64Bit()) {
47     return "e-m:e-p:64:64-i64:64-i128:128-n64-S128";
48   } else {
49     assert(TT.isArch32Bit() && "only RV32 and RV64 are currently supported");
50     return "e-m:e-p:32:32-i64:64-n32-S128";
51   }
52 }
53 
54 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
55                                            Optional<Reloc::Model> RM) {
56   if (!RM.hasValue())
57     return Reloc::Static;
58   return *RM;
59 }
60 
61 RISCVTargetMachine::RISCVTargetMachine(const Target &T, const Triple &TT,
62                                        StringRef CPU, StringRef FS,
63                                        const TargetOptions &Options,
64                                        Optional<Reloc::Model> RM,
65                                        Optional<CodeModel::Model> CM,
66                                        CodeGenOpt::Level OL, bool JIT)
67     : LLVMTargetMachine(T, computeDataLayout(TT), TT, CPU, FS, Options,
68                         getEffectiveRelocModel(TT, RM),
69                         getEffectiveCodeModel(CM, CodeModel::Small), OL),
70       TLOF(std::make_unique<RISCVELFTargetObjectFile>()) {
71   initAsmInfo();
72 
73   // RISC-V supports the MachineOutliner.
74   setMachineOutliner(true);
75 }
76 
77 const RISCVSubtarget *
78 RISCVTargetMachine::getSubtargetImpl(const Function &F) const {
79   Attribute CPUAttr = F.getFnAttribute("target-cpu");
80   Attribute TuneAttr = F.getFnAttribute("tune-cpu");
81   Attribute FSAttr = F.getFnAttribute("target-features");
82 
83   std::string CPU =
84       CPUAttr.isValid() ? CPUAttr.getValueAsString().str() : TargetCPU;
85   std::string TuneCPU =
86       TuneAttr.isValid() ? TuneAttr.getValueAsString().str() : CPU;
87   std::string FS =
88       FSAttr.isValid() ? FSAttr.getValueAsString().str() : TargetFS;
89   std::string Key = CPU + TuneCPU + FS;
90   auto &I = SubtargetMap[Key];
91   if (!I) {
92     // This needs to be done before we create a new subtarget since any
93     // creation will depend on the TM and the code generation flags on the
94     // function that reside in TargetOptions.
95     resetTargetOptions(F);
96     auto ABIName = Options.MCOptions.getABIName();
97     if (const MDString *ModuleTargetABI = dyn_cast_or_null<MDString>(
98             F.getParent()->getModuleFlag("target-abi"))) {
99       auto TargetABI = RISCVABI::getTargetABI(ABIName);
100       if (TargetABI != RISCVABI::ABI_Unknown &&
101           ModuleTargetABI->getString() != ABIName) {
102         report_fatal_error("-target-abi option != target-abi module flag");
103       }
104       ABIName = ModuleTargetABI->getString();
105     }
106     I = std::make_unique<RISCVSubtarget>(TargetTriple, CPU, TuneCPU, FS, ABIName, *this);
107   }
108   return I.get();
109 }
110 
111 TargetTransformInfo
112 RISCVTargetMachine::getTargetTransformInfo(const Function &F) {
113   return TargetTransformInfo(RISCVTTIImpl(this, F));
114 }
115 
116 // A RISC-V hart has a single byte-addressable address space of 2^XLEN bytes
117 // for all memory accesses, so it is reasonable to assume that an
118 // implementation has no-op address space casts. If an implementation makes a
119 // change to this, they can override it here.
120 bool RISCVTargetMachine::isNoopAddrSpaceCast(unsigned SrcAS,
121                                              unsigned DstAS) const {
122   return true;
123 }
124 
125 namespace {
126 class RISCVPassConfig : public TargetPassConfig {
127 public:
128   RISCVPassConfig(RISCVTargetMachine &TM, PassManagerBase &PM)
129       : TargetPassConfig(TM, PM) {}
130 
131   RISCVTargetMachine &getRISCVTargetMachine() const {
132     return getTM<RISCVTargetMachine>();
133   }
134 
135   void addIRPasses() override;
136   bool addInstSelector() override;
137   bool addIRTranslator() override;
138   bool addLegalizeMachineIR() override;
139   bool addRegBankSelect() override;
140   bool addGlobalInstructionSelect() override;
141   void addPreEmitPass() override;
142   void addPreEmitPass2() override;
143   void addPreSched2() override;
144   void addPreRegAlloc() override;
145 };
146 }
147 
148 TargetPassConfig *RISCVTargetMachine::createPassConfig(PassManagerBase &PM) {
149   return new RISCVPassConfig(*this, PM);
150 }
151 
152 void RISCVPassConfig::addIRPasses() {
153   addPass(createAtomicExpandPass());
154   TargetPassConfig::addIRPasses();
155 }
156 
157 bool RISCVPassConfig::addInstSelector() {
158   addPass(createRISCVISelDag(getRISCVTargetMachine()));
159 
160   return false;
161 }
162 
163 bool RISCVPassConfig::addIRTranslator() {
164   addPass(new IRTranslator(getOptLevel()));
165   return false;
166 }
167 
168 bool RISCVPassConfig::addLegalizeMachineIR() {
169   addPass(new Legalizer());
170   return false;
171 }
172 
173 bool RISCVPassConfig::addRegBankSelect() {
174   addPass(new RegBankSelect());
175   return false;
176 }
177 
178 bool RISCVPassConfig::addGlobalInstructionSelect() {
179   addPass(new InstructionSelect());
180   return false;
181 }
182 
183 void RISCVPassConfig::addPreSched2() {}
184 
185 void RISCVPassConfig::addPreEmitPass() { addPass(&BranchRelaxationPassID); }
186 
187 void RISCVPassConfig::addPreEmitPass2() {
188   addPass(createRISCVExpandPseudoPass());
189   // Schedule the expansion of AMOs at the last possible moment, avoiding the
190   // possibility for other passes to break the requirements for forward
191   // progress in the LR/SC block.
192   addPass(createRISCVExpandAtomicPseudoPass());
193 }
194 
195 void RISCVPassConfig::addPreRegAlloc() {
196   if (TM->getOptLevel() != CodeGenOpt::None) {
197     addPass(createRISCVMergeBaseOffsetOptPass());
198     addPass(createRISCVCleanupVSETVLIPass());
199   }
200 }
201