1 //===-- RISCVISelDAGToDAG.cpp - A dag to dag inst selector for RISCV ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines an instruction selector for the RISCV target.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "RISCV.h"
15 #include "MCTargetDesc/RISCVMCTargetDesc.h"
16 #include "RISCVTargetMachine.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/CodeGen/SelectionDAGISel.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/MathExtras.h"
21 #include "llvm/Support/raw_ostream.h"
22 using namespace llvm;
23 
24 #define DEBUG_TYPE "riscv-isel"
25 
26 // RISCV-specific code to select RISCV machine instructions for
27 // SelectionDAG operations.
28 namespace {
29 class RISCVDAGToDAGISel final : public SelectionDAGISel {
30   const RISCVSubtarget *Subtarget;
31 
32 public:
33   explicit RISCVDAGToDAGISel(RISCVTargetMachine &TargetMachine)
34       : SelectionDAGISel(TargetMachine) {}
35 
36   StringRef getPassName() const override {
37     return "RISCV DAG->DAG Pattern Instruction Selection";
38   }
39 
40   bool runOnMachineFunction(MachineFunction &MF) override {
41     Subtarget = &MF.getSubtarget<RISCVSubtarget>();
42     return SelectionDAGISel::runOnMachineFunction(MF);
43   }
44 
45   void PostprocessISelDAG() override;
46 
47   void Select(SDNode *Node) override;
48 
49   bool SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
50                                     std::vector<SDValue> &OutOps) override;
51 
52   bool SelectAddrFI(SDValue Addr, SDValue &Base);
53 
54 // Include the pieces autogenerated from the target description.
55 #include "RISCVGenDAGISel.inc"
56 
57 private:
58   void doPeepholeLoadStoreADDI();
59 };
60 }
61 
62 void RISCVDAGToDAGISel::PostprocessISelDAG() {
63   doPeepholeLoadStoreADDI();
64 }
65 
66 void RISCVDAGToDAGISel::Select(SDNode *Node) {
67   // If we have a custom node, we have already selected.
68   if (Node->isMachineOpcode()) {
69     LLVM_DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << "\n");
70     Node->setNodeId(-1);
71     return;
72   }
73 
74   // Instruction Selection not handled by the auto-generated tablegen selection
75   // should be handled here.
76   unsigned Opcode = Node->getOpcode();
77   MVT XLenVT = Subtarget->getXLenVT();
78   SDLoc DL(Node);
79   EVT VT = Node->getValueType(0);
80 
81   switch (Opcode) {
82   case ISD::Constant: {
83     auto ConstNode = cast<ConstantSDNode>(Node);
84     if (VT == XLenVT && ConstNode->isNullValue()) {
85       SDValue New = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), SDLoc(Node),
86                                            RISCV::X0, XLenVT);
87       ReplaceNode(Node, New.getNode());
88       return;
89     }
90     break;
91   }
92   case ISD::FrameIndex: {
93     SDValue Imm = CurDAG->getTargetConstant(0, DL, XLenVT);
94     int FI = cast<FrameIndexSDNode>(Node)->getIndex();
95     SDValue TFI = CurDAG->getTargetFrameIndex(FI, VT);
96     ReplaceNode(Node, CurDAG->getMachineNode(RISCV::ADDI, DL, VT, TFI, Imm));
97     return;
98   }
99   }
100 
101   // Select the default instruction.
102   SelectCode(Node);
103 }
104 
105 bool RISCVDAGToDAGISel::SelectInlineAsmMemoryOperand(
106     const SDValue &Op, unsigned ConstraintID, std::vector<SDValue> &OutOps) {
107   switch (ConstraintID) {
108   case InlineAsm::Constraint_i:
109   case InlineAsm::Constraint_m:
110     // We just support simple memory operands that have a single address
111     // operand and need no special handling.
112     OutOps.push_back(Op);
113     return false;
114   default:
115     break;
116   }
117 
118   return true;
119 }
120 
121 bool RISCVDAGToDAGISel::SelectAddrFI(SDValue Addr, SDValue &Base) {
122   if (auto FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
123     Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), Subtarget->getXLenVT());
124     return true;
125   }
126   return false;
127 }
128 
129 // Merge an ADDI into the offset of a load/store instruction where possible.
130 // (load (add base, off), 0) -> (load base, off)
131 // (store val, (add base, off)) -> (store val, base, off)
132 void RISCVDAGToDAGISel::doPeepholeLoadStoreADDI() {
133   SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
134   ++Position;
135 
136   while (Position != CurDAG->allnodes_begin()) {
137     SDNode *N = &*--Position;
138     // Skip dead nodes and any non-machine opcodes.
139     if (N->use_empty() || !N->isMachineOpcode())
140       continue;
141 
142     int OffsetOpIdx;
143     int BaseOpIdx;
144 
145     // Only attempt this optimisation for I-type loads and S-type stores.
146     switch (N->getMachineOpcode()) {
147     default:
148       continue;
149     case RISCV::LB:
150     case RISCV::LH:
151     case RISCV::LW:
152     case RISCV::LBU:
153     case RISCV::LHU:
154     case RISCV::LWU:
155     case RISCV::LD:
156     case RISCV::FLW:
157     case RISCV::FLD:
158       BaseOpIdx = 0;
159       OffsetOpIdx = 1;
160       break;
161     case RISCV::SB:
162     case RISCV::SH:
163     case RISCV::SW:
164     case RISCV::SD:
165     case RISCV::FSW:
166     case RISCV::FSD:
167       BaseOpIdx = 1;
168       OffsetOpIdx = 2;
169       break;
170     }
171 
172     // Currently, the load/store offset must be 0 to be considered for this
173     // peephole optimisation.
174     if (!isa<ConstantSDNode>(N->getOperand(OffsetOpIdx)) ||
175         N->getConstantOperandVal(OffsetOpIdx) != 0)
176       continue;
177 
178     SDValue Base = N->getOperand(BaseOpIdx);
179 
180     // If the base is an ADDI, we can merge it in to the load/store.
181     if (!Base.isMachineOpcode() || Base.getMachineOpcode() != RISCV::ADDI)
182       continue;
183 
184     SDValue ImmOperand = Base.getOperand(1);
185 
186     if (auto Const = dyn_cast<ConstantSDNode>(ImmOperand)) {
187       ImmOperand = CurDAG->getTargetConstant(
188           Const->getSExtValue(), SDLoc(ImmOperand), ImmOperand.getValueType());
189     } else if (auto GA = dyn_cast<GlobalAddressSDNode>(ImmOperand)) {
190       ImmOperand = CurDAG->getTargetGlobalAddress(
191           GA->getGlobal(), SDLoc(ImmOperand), ImmOperand.getValueType(),
192           GA->getOffset(), GA->getTargetFlags());
193     } else {
194       continue;
195     }
196 
197     LLVM_DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase:    ");
198     LLVM_DEBUG(Base->dump(CurDAG));
199     LLVM_DEBUG(dbgs() << "\nN: ");
200     LLVM_DEBUG(N->dump(CurDAG));
201     LLVM_DEBUG(dbgs() << "\n");
202 
203     // Modify the offset operand of the load/store.
204     if (BaseOpIdx == 0) // Load
205       CurDAG->UpdateNodeOperands(N, Base.getOperand(0), ImmOperand,
206                                  N->getOperand(2));
207     else // Store
208       CurDAG->UpdateNodeOperands(N, N->getOperand(0), Base.getOperand(0),
209                                  ImmOperand, N->getOperand(3));
210 
211     // The add-immediate may now be dead, in which case remove it.
212     if (Base.getNode()->use_empty())
213       CurDAG->RemoveDeadNode(Base.getNode());
214   }
215 }
216 
217 // This pass converts a legalized DAG into a RISCV-specific DAG, ready
218 // for instruction scheduling.
219 FunctionPass *llvm::createRISCVISelDag(RISCVTargetMachine &TM) {
220   return new RISCVDAGToDAGISel(TM);
221 }
222