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/SelectionDAGISel.h" 18 #include "llvm/Support/Debug.h" 19 #include "llvm/Support/MathExtras.h" 20 #include "llvm/Support/raw_ostream.h" 21 using namespace llvm; 22 23 #define DEBUG_TYPE "riscv-isel" 24 25 // RISCV-specific code to select RISCV machine instructions for 26 // SelectionDAG operations. 27 namespace { 28 class RISCVDAGToDAGISel final : public SelectionDAGISel { 29 const RISCVSubtarget *Subtarget; 30 31 public: 32 explicit RISCVDAGToDAGISel(RISCVTargetMachine &TargetMachine) 33 : SelectionDAGISel(TargetMachine) {} 34 35 StringRef getPassName() const override { 36 return "RISCV DAG->DAG Pattern Instruction Selection"; 37 } 38 39 bool runOnMachineFunction(MachineFunction &MF) override { 40 Subtarget = &MF.getSubtarget<RISCVSubtarget>(); 41 return SelectionDAGISel::runOnMachineFunction(MF); 42 } 43 44 void Select(SDNode *Node) override; 45 46 // Include the pieces autogenerated from the target description. 47 #include "RISCVGenDAGISel.inc" 48 }; 49 } 50 51 void RISCVDAGToDAGISel::Select(SDNode *Node) { 52 unsigned Opcode = Node->getOpcode(); 53 MVT XLenVT = Subtarget->getXLenVT(); 54 55 // Dump information about the Node being selected. 56 DEBUG(dbgs() << "Selecting: "; Node->dump(CurDAG); dbgs() << "\n"); 57 58 // If we have a custom node, we have already selected 59 if (Node->isMachineOpcode()) { 60 DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << "\n"); 61 Node->setNodeId(-1); 62 return; 63 } 64 65 // Instruction Selection not handled by the auto-generated tablegen selection 66 // should be handled here. 67 EVT VT = Node->getValueType(0); 68 if (Opcode == ISD::Constant && VT == XLenVT) { 69 auto *ConstNode = cast<ConstantSDNode>(Node); 70 // Materialize zero constants as copies from X0. This allows the coalescer 71 // to propagate these into other instructions. 72 if (ConstNode->isNullValue()) { 73 SDValue New = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), SDLoc(Node), 74 RISCV::X0, XLenVT); 75 ReplaceNode(Node, New.getNode()); 76 return; 77 } 78 } 79 80 // Select the default instruction. 81 SelectCode(Node); 82 } 83 84 // This pass converts a legalized DAG into a RISCV-specific DAG, ready 85 // for instruction scheduling. 86 FunctionPass *llvm::createRISCVISelDag(RISCVTargetMachine &TM) { 87 return new RISCVDAGToDAGISel(TM); 88 } 89