1 //===- llvm/CodeGen/GlobalISel/Utils.cpp -------------------------*- C++ -*-==//
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 /// \file This file implements the utility functions used by the GlobalISel
10 /// pipeline.
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/GlobalISel/Utils.h"
14 #include "llvm/ADT/Twine.h"
15 #include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h"
16 #include "llvm/CodeGen/MachineInstr.h"
17 #include "llvm/CodeGen/MachineInstrBuilder.h"
18 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
19 #include "llvm/CodeGen/MachineRegisterInfo.h"
20 #include "llvm/CodeGen/TargetInstrInfo.h"
21 #include "llvm/CodeGen/TargetPassConfig.h"
22 #include "llvm/CodeGen/TargetRegisterInfo.h"
23 #include "llvm/IR/Constants.h"
24 
25 #define DEBUG_TYPE "globalisel-utils"
26 
27 using namespace llvm;
28 
29 unsigned llvm::constrainRegToClass(MachineRegisterInfo &MRI,
30                                    const TargetInstrInfo &TII,
31                                    const RegisterBankInfo &RBI,
32                                    MachineInstr &InsertPt, unsigned Reg,
33                                    const TargetRegisterClass &RegClass) {
34   if (!RBI.constrainGenericRegister(Reg, RegClass, MRI)) {
35     unsigned NewReg = MRI.createVirtualRegister(&RegClass);
36     BuildMI(*InsertPt.getParent(), InsertPt, InsertPt.getDebugLoc(),
37             TII.get(TargetOpcode::COPY), NewReg)
38         .addReg(Reg);
39     return NewReg;
40   }
41 
42   return Reg;
43 }
44 
45 unsigned llvm::constrainOperandRegClass(
46     const MachineFunction &MF, const TargetRegisterInfo &TRI,
47     MachineRegisterInfo &MRI, const TargetInstrInfo &TII,
48     const RegisterBankInfo &RBI, MachineInstr &InsertPt, const MCInstrDesc &II,
49     const MachineOperand &RegMO, unsigned OpIdx) {
50   unsigned Reg = RegMO.getReg();
51   // Assume physical registers are properly constrained.
52   assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
53          "PhysReg not implemented");
54 
55   const TargetRegisterClass *RegClass = TII.getRegClass(II, OpIdx, &TRI, MF);
56   // Some of the target independent instructions, like COPY, may not impose any
57   // register class constraints on some of their operands: If it's a use, we can
58   // skip constraining as the instruction defining the register would constrain
59   // it.
60   if (!RegClass) {
61     assert((!isTargetSpecificOpcode(II.getOpcode()) || RegMO.isUse()) &&
62            "Register class constraint is required unless either the "
63            "instruction is target independent or the operand is a use");
64     // FIXME: Just bailing out like this here could be not enough, unless we
65     // expect the users of this function to do the right thing for PHIs and
66     // COPY:
67     //   v1 = COPY v0
68     //   v2 = COPY v1
69     // v1 here may end up not being constrained at all. Please notice that to
70     // reproduce the issue we likely need a destination pattern of a selection
71     // rule producing such extra copies, not just an input GMIR with them as
72     // every existing target using selectImpl handles copies before calling it
73     // and they never reach this function.
74     return Reg;
75   }
76   return constrainRegToClass(MRI, TII, RBI, InsertPt, Reg, *RegClass);
77 }
78 
79 bool llvm::constrainSelectedInstRegOperands(MachineInstr &I,
80                                             const TargetInstrInfo &TII,
81                                             const TargetRegisterInfo &TRI,
82                                             const RegisterBankInfo &RBI) {
83   assert(!isPreISelGenericOpcode(I.getOpcode()) &&
84          "A selected instruction is expected");
85   MachineBasicBlock &MBB = *I.getParent();
86   MachineFunction &MF = *MBB.getParent();
87   MachineRegisterInfo &MRI = MF.getRegInfo();
88 
89   for (unsigned OpI = 0, OpE = I.getNumExplicitOperands(); OpI != OpE; ++OpI) {
90     MachineOperand &MO = I.getOperand(OpI);
91 
92     // There's nothing to be done on non-register operands.
93     if (!MO.isReg())
94       continue;
95 
96     DEBUG(dbgs() << "Converting operand: " << MO << '\n');
97     assert(MO.isReg() && "Unsupported non-reg operand");
98 
99     unsigned Reg = MO.getReg();
100     // Physical registers don't need to be constrained.
101     if (TRI.isPhysicalRegister(Reg))
102       continue;
103 
104     // Register operands with a value of 0 (e.g. predicate operands) don't need
105     // to be constrained.
106     if (Reg == 0)
107       continue;
108 
109     // If the operand is a vreg, we should constrain its regclass, and only
110     // insert COPYs if that's impossible.
111     // constrainOperandRegClass does that for us.
112     MO.setReg(constrainOperandRegClass(MF, TRI, MRI, TII, RBI, I, I.getDesc(),
113                                        MO, OpI));
114 
115     // Tie uses to defs as indicated in MCInstrDesc if this hasn't already been
116     // done.
117     if (MO.isUse()) {
118       int DefIdx = I.getDesc().getOperandConstraint(OpI, MCOI::TIED_TO);
119       if (DefIdx != -1 && !I.isRegTiedToUseOperand(DefIdx))
120         I.tieOperands(DefIdx, OpI);
121     }
122   }
123   return true;
124 }
125 
126 bool llvm::isTriviallyDead(const MachineInstr &MI,
127                            const MachineRegisterInfo &MRI) {
128   // If we can move an instruction, we can remove it.  Otherwise, it has
129   // a side-effect of some sort.
130   bool SawStore = false;
131   if (!MI.isSafeToMove(/*AA=*/nullptr, SawStore))
132     return false;
133 
134   // Instructions without side-effects are dead iff they only define dead vregs.
135   for (auto &MO : MI.operands()) {
136     if (!MO.isReg() || !MO.isDef())
137       continue;
138 
139     unsigned Reg = MO.getReg();
140     if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
141         !MRI.use_nodbg_empty(Reg))
142       return false;
143   }
144   return true;
145 }
146 
147 void llvm::reportGISelFailure(MachineFunction &MF, const TargetPassConfig &TPC,
148                               MachineOptimizationRemarkEmitter &MORE,
149                               MachineOptimizationRemarkMissed &R) {
150   MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
151 
152   // Print the function name explicitly if we don't have a debug location (which
153   // makes the diagnostic less useful) or if we're going to emit a raw error.
154   if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled())
155     R << (" (in function: " + MF.getName() + ")").str();
156 
157   if (TPC.isGlobalISelAbortEnabled())
158     report_fatal_error(R.getMsg());
159   else
160     MORE.emit(R);
161 }
162 
163 void llvm::reportGISelFailure(MachineFunction &MF, const TargetPassConfig &TPC,
164                               MachineOptimizationRemarkEmitter &MORE,
165                               const char *PassName, StringRef Msg,
166                               const MachineInstr &MI) {
167   MachineOptimizationRemarkMissed R(PassName, "GISelFailure: ",
168                                     MI.getDebugLoc(), MI.getParent());
169   R << Msg;
170   // Printing MI is expensive;  only do it if expensive remarks are enabled.
171   if (TPC.isGlobalISelAbortEnabled() || MORE.allowExtraAnalysis(PassName))
172     R << ": " << ore::MNV("Inst", MI);
173   reportGISelFailure(MF, TPC, MORE, R);
174 }
175 
176 Optional<int64_t> llvm::getConstantVRegVal(unsigned VReg,
177                                            const MachineRegisterInfo &MRI) {
178   MachineInstr *MI = MRI.getVRegDef(VReg);
179   if (MI->getOpcode() != TargetOpcode::G_CONSTANT)
180     return None;
181 
182   if (MI->getOperand(1).isImm())
183     return MI->getOperand(1).getImm();
184 
185   if (MI->getOperand(1).isCImm() &&
186       MI->getOperand(1).getCImm()->getBitWidth() <= 64)
187     return MI->getOperand(1).getCImm()->getSExtValue();
188 
189   return None;
190 }
191 
192 const llvm::ConstantFP* llvm::getConstantFPVRegVal(unsigned VReg,
193                                        const MachineRegisterInfo &MRI) {
194   MachineInstr *MI = MRI.getVRegDef(VReg);
195   if (TargetOpcode::G_FCONSTANT != MI->getOpcode())
196     return nullptr;
197   return MI->getOperand(1).getFPImm();
198 }
199 
200 llvm::MachineInstr *llvm::getOpcodeDef(unsigned Opcode, unsigned Reg,
201                                        const MachineRegisterInfo &MRI) {
202   auto *DefMI = MRI.getVRegDef(Reg);
203   auto DstTy = MRI.getType(DefMI->getOperand(0).getReg());
204   if (!DstTy.isValid())
205     return nullptr;
206   while (DefMI->getOpcode() == TargetOpcode::COPY) {
207     unsigned SrcReg = DefMI->getOperand(1).getReg();
208     auto SrcTy = MRI.getType(SrcReg);
209     if (!SrcTy.isValid() || SrcTy != DstTy)
210       break;
211     DefMI = MRI.getVRegDef(SrcReg);
212   }
213   return DefMI->getOpcode() == Opcode ? DefMI : nullptr;
214 }
215