LLVM  9.0.0svn
Go to the documentation of this file.
1 //===- llvm/CodeGen/GlobalISel/Utils.cpp -------------------------*- C++ -*-==//
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 /// \file This file implements the utility functions used by the GlobalISel
9 /// pipeline.
10 //===----------------------------------------------------------------------===//
13 #include "llvm/ADT/APFloat.h"
14 #include "llvm/ADT/Twine.h"
24 #include "llvm/IR/Constants.h"
26 #define DEBUG_TYPE "globalisel-utils"
28 using namespace llvm;
31  const TargetInstrInfo &TII,
32  const RegisterBankInfo &RBI,
33  MachineInstr &InsertPt, unsigned Reg,
34  const TargetRegisterClass &RegClass) {
35  if (!RBI.constrainGenericRegister(Reg, RegClass, MRI)) {
36  unsigned NewReg = MRI.createVirtualRegister(&RegClass);
37  BuildMI(*InsertPt.getParent(), InsertPt, InsertPt.getDebugLoc(),
38  TII.get(TargetOpcode::COPY), NewReg)
39  .addReg(Reg);
40  return NewReg;
41  }
43  return Reg;
44 }
47  const MachineFunction &MF, const TargetRegisterInfo &TRI,
49  const RegisterBankInfo &RBI, MachineInstr &InsertPt, const MCInstrDesc &II,
50  const MachineOperand &RegMO, unsigned OpIdx) {
51  unsigned Reg = RegMO.getReg();
52  // Assume physical registers are properly constrained.
54  "PhysReg not implemented");
56  const TargetRegisterClass *RegClass = TII.getRegClass(II, OpIdx, &TRI, MF);
57  // Some of the target independent instructions, like COPY, may not impose any
58  // register class constraints on some of their operands: If it's a use, we can
59  // skip constraining as the instruction defining the register would constrain
60  // it.
62  // We can't constrain unallocatable register classes, because we can't create
63  // virtual registers for these classes, so we need to let targets handled this
64  // case.
65  if (RegClass && !RegClass->isAllocatable())
66  RegClass = TRI.getConstrainedRegClassForOperand(RegMO, MRI);
68  if (!RegClass) {
69  assert((!isTargetSpecificOpcode(II.getOpcode()) || RegMO.isUse()) &&
70  "Register class constraint is required unless either the "
71  "instruction is target independent or the operand is a use");
72  // FIXME: Just bailing out like this here could be not enough, unless we
73  // expect the users of this function to do the right thing for PHIs and
74  // COPY:
75  // v1 = COPY v0
76  // v2 = COPY v1
77  // v1 here may end up not being constrained at all. Please notice that to
78  // reproduce the issue we likely need a destination pattern of a selection
79  // rule producing such extra copies, not just an input GMIR with them as
80  // every existing target using selectImpl handles copies before calling it
81  // and they never reach this function.
82  return Reg;
83  }
84  return constrainRegToClass(MRI, TII, RBI, InsertPt, Reg, *RegClass);
85 }
88  const TargetInstrInfo &TII,
89  const TargetRegisterInfo &TRI,
90  const RegisterBankInfo &RBI) {
92  "A selected instruction is expected");
93  MachineBasicBlock &MBB = *I.getParent();
94  MachineFunction &MF = *MBB.getParent();
97  for (unsigned OpI = 0, OpE = I.getNumExplicitOperands(); OpI != OpE; ++OpI) {
98  MachineOperand &MO = I.getOperand(OpI);
100  // There's nothing to be done on non-register operands.
101  if (!MO.isReg())
102  continue;
104  LLVM_DEBUG(dbgs() << "Converting operand: " << MO << '\n');
105  assert(MO.isReg() && "Unsupported non-reg operand");
107  unsigned Reg = MO.getReg();
108  // Physical registers don't need to be constrained.
109  if (TRI.isPhysicalRegister(Reg))
110  continue;
112  // Register operands with a value of 0 (e.g. predicate operands) don't need
113  // to be constrained.
114  if (Reg == 0)
115  continue;
117  // If the operand is a vreg, we should constrain its regclass, and only
118  // insert COPYs if that's impossible.
119  // constrainOperandRegClass does that for us.
120  MO.setReg(constrainOperandRegClass(MF, TRI, MRI, TII, RBI, I, I.getDesc(),
121  MO, OpI));
123  // Tie uses to defs as indicated in MCInstrDesc if this hasn't already been
124  // done.
125  if (MO.isUse()) {
126  int DefIdx = I.getDesc().getOperandConstraint(OpI, MCOI::TIED_TO);
127  if (DefIdx != -1 && !I.isRegTiedToUseOperand(DefIdx))
128  I.tieOperands(DefIdx, OpI);
129  }
130  }
131  return true;
132 }
135  const MachineRegisterInfo &MRI) {
136  // If we can move an instruction, we can remove it. Otherwise, it has
137  // a side-effect of some sort.
138  bool SawStore = false;
139  if (!MI.isSafeToMove(/*AA=*/nullptr, SawStore) && !MI.isPHI())
140  return false;
142  // Instructions without side-effects are dead iff they only define dead vregs.
143  for (auto &MO : MI.operands()) {
144  if (!MO.isReg() || !MO.isDef())
145  continue;
147  unsigned Reg = MO.getReg();
149  !MRI.use_nodbg_empty(Reg))
150  return false;
151  }
152  return true;
153 }
160  // Print the function name explicitly if we don't have a debug location (which
161  // makes the diagnostic less useful) or if we're going to emit a raw error.
162  if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled())
163  R << (" (in function: " + MF.getName() + ")").str();
165  if (TPC.isGlobalISelAbortEnabled())
167  else
168  MORE.emit(R);
169 }
173  const char *PassName, StringRef Msg,
174  const MachineInstr &MI) {
175  MachineOptimizationRemarkMissed R(PassName, "GISelFailure: ",
176  MI.getDebugLoc(), MI.getParent());
177  R << Msg;
178  // Printing MI is expensive; only do it if expensive remarks are enabled.
179  if (TPC.isGlobalISelAbortEnabled() || MORE.allowExtraAnalysis(PassName))
180  R << ": " << ore::MNV("Inst", MI);
181  reportGISelFailure(MF, TPC, MORE, R);
182 }
185  const MachineRegisterInfo &MRI) {
186  Optional<ValueAndVReg> ValAndVReg =
187  getConstantVRegValWithLookThrough(VReg, MRI, /*LookThroughInstrs*/ false);
188  assert((!ValAndVReg || ValAndVReg->VReg == VReg) &&
189  "Value found while looking through instrs");
190  if (!ValAndVReg)
191  return None;
192  return ValAndVReg->Value;
193 }
196  unsigned VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs) {
198  MachineInstr *MI;
199  while ((MI = MRI.getVRegDef(VReg)) &&
200  MI->getOpcode() != TargetOpcode::G_CONSTANT && LookThroughInstrs) {
201  switch (MI->getOpcode()) {
202  case TargetOpcode::G_TRUNC:
203  case TargetOpcode::G_SEXT:
204  case TargetOpcode::G_ZEXT:
205  SeenOpcodes.push_back(std::make_pair(
206  MI->getOpcode(),
207  MRI.getType(MI->getOperand(0).getReg()).getSizeInBits()));
208  VReg = MI->getOperand(1).getReg();
209  break;
210  case TargetOpcode::COPY:
211  VReg = MI->getOperand(1).getReg();
213  return None;
214  break;
215  default:
216  return None;
217  }
218  }
219  if (!MI || MI->getOpcode() != TargetOpcode::G_CONSTANT ||
220  (!MI->getOperand(1).isImm() && !MI->getOperand(1).isCImm()))
221  return None;
223  const MachineOperand &CstVal = MI->getOperand(1);
224  unsigned BitWidth = MRI.getType(MI->getOperand(0).getReg()).getSizeInBits();
225  APInt Val = CstVal.isImm() ? APInt(BitWidth, CstVal.getImm())
226  : CstVal.getCImm()->getValue();
227  assert(Val.getBitWidth() == BitWidth &&
228  "Value bitwidth doesn't match definition type");
229  while (!SeenOpcodes.empty()) {
230  std::pair<unsigned, unsigned> OpcodeAndSize = SeenOpcodes.pop_back_val();
231  switch (OpcodeAndSize.first) {
232  case TargetOpcode::G_TRUNC:
233  Val = Val.trunc(OpcodeAndSize.second);
234  break;
235  case TargetOpcode::G_SEXT:
236  Val = Val.sext(OpcodeAndSize.second);
237  break;
238  case TargetOpcode::G_ZEXT:
239  Val = Val.zext(OpcodeAndSize.second);
240  break;
241  }
242  }
244  if (Val.getBitWidth() > 64)
245  return None;
247  return ValueAndVReg{Val.getSExtValue(), VReg};
248 }
251  const MachineRegisterInfo &MRI) {
252  MachineInstr *MI = MRI.getVRegDef(VReg);
253  if (TargetOpcode::G_FCONSTANT != MI->getOpcode())
254  return nullptr;
255  return MI->getOperand(1).getFPImm();
256 }
258 llvm::MachineInstr *llvm::getOpcodeDef(unsigned Opcode, unsigned Reg,
259  const MachineRegisterInfo &MRI) {
260  auto *DefMI = MRI.getVRegDef(Reg);
261  auto DstTy = MRI.getType(DefMI->getOperand(0).getReg());
262  if (!DstTy.isValid())
263  return nullptr;
264  while (DefMI->getOpcode() == TargetOpcode::COPY) {
265  unsigned SrcReg = DefMI->getOperand(1).getReg();
266  auto SrcTy = MRI.getType(SrcReg);
267  if (!SrcTy.isValid() || SrcTy != DstTy)
268  break;
269  DefMI = MRI.getVRegDef(SrcReg);
270  }
271  return DefMI->getOpcode() == Opcode ? DefMI : nullptr;
272 }
274 APFloat llvm::getAPFloatFromSize(double Val, unsigned Size) {
275  if (Size == 32)
276  return APFloat(float(Val));
277  if (Size == 64)
278  return APFloat(Val);
279  if (Size != 16)
280  llvm_unreachable("Unsupported FPConstant size");
281  bool Ignored;
282  APFloat APF(Val);
284  return APF;
285 }
287 Optional<APInt> llvm::ConstantFoldBinOp(unsigned Opcode, const unsigned Op1,
288  const unsigned Op2,
289  const MachineRegisterInfo &MRI) {
290  auto MaybeOp1Cst = getConstantVRegVal(Op1, MRI);
291  auto MaybeOp2Cst = getConstantVRegVal(Op2, MRI);
292  if (MaybeOp1Cst && MaybeOp2Cst) {
293  LLT Ty = MRI.getType(Op1);
294  APInt C1(Ty.getSizeInBits(), *MaybeOp1Cst, true);
295  APInt C2(Ty.getSizeInBits(), *MaybeOp2Cst, true);
296  switch (Opcode) {
297  default:
298  break;
299  case TargetOpcode::G_ADD:
300  return C1 + C2;
301  case TargetOpcode::G_AND:
302  return C1 & C2;
303  case TargetOpcode::G_ASHR:
304  return C1.ashr(C2);
305  case TargetOpcode::G_LSHR:
306  return C1.lshr(C2);
307  case TargetOpcode::G_MUL:
308  return C1 * C2;
309  case TargetOpcode::G_OR:
310  return C1 | C2;
311  case TargetOpcode::G_SHL:
312  return C1 << C2;
313  case TargetOpcode::G_SUB:
314  return C1 - C2;
315  case TargetOpcode::G_XOR:
316  return C1 ^ C2;
317  case TargetOpcode::G_UDIV:
318  if (!C2.getBoolValue())
319  break;
320  return C1.udiv(C2);
321  case TargetOpcode::G_SDIV:
322  if (!C2.getBoolValue())
323  break;
324  return C1.sdiv(C2);
325  case TargetOpcode::G_UREM:
326  if (!C2.getBoolValue())
327  break;
328  return C1.urem(C2);
329  case TargetOpcode::G_SREM:
330  if (!C2.getBoolValue())
331  break;
332  return C1.srem(C2);
333  }
334  }
335  return None;
336 }
340 }
const NoneType None
Definition: None.h:23
Simple struct used to hold a constant integer value and a virtual register.
Definition: Utils.h:98
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
APInt sext(unsigned width) const
Sign extend to a new width.
Definition: APInt.cpp:833
bool use_nodbg_empty(unsigned RegNo) const
use_nodbg_empty - Return true if there are no non-Debug instructions using the specified register...
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:139
This class represents lattice values for constants.
Definition: AllocatorList.h:23
void getSelectionDAGFallbackAnalysisUsage(AnalysisUsage &AU)
Modify analysis usage so it preserves passes required for the SelectionDAG fallback.
Definition: Utils.cpp:338
APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition: APInt.cpp:1590
const MachineFunctionProperties & getProperties() const
Get the function properties.
const ConstantFP * getConstantFPVRegVal(unsigned VReg, const MachineRegisterInfo &MRI)
Definition: Utils.cpp:250
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
Definition: MachineInstr.h:382
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:163
unsigned getReg() const
getReg - Returns the register number.
APInt zext(unsigned width) const
Zero extend to a new width.
Definition: APInt.cpp:857
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition: APInt.cpp:1519
unsigned Reg
LLT getType(unsigned Reg) const
Get the low-level type of Reg or LLT{} if Reg is not a generic (target independent) virtual register...
APInt trunc(unsigned width) const
Truncate to new width.
Definition: APInt.cpp:810
unsigned const TargetRegisterInfo * TRI
iterator_range< mop_iterator > operands()
Definition: MachineInstr.h:458
bool isPHI() const
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1508
int64_t Value
Definition: Utils.h:99
void emit(DiagnosticInfoOptimizationBase &OptDiag)
Emit an optimization remark.
Holds all the information related to register banks.
const HexagonInstrInfo * TII
const ConstantFP * getFPImm() const
const TargetRegisterClass * getRegClass(const MCInstrDesc &MCID, unsigned OpNum, const TargetRegisterInfo *TRI, const MachineFunction &MF) const
Given a machine instruction descriptor, returns the register class constraint for OpNum...
Optional< APInt > ConstantFoldBinOp(unsigned Opcode, const unsigned Op1, const unsigned Op2, const MachineRegisterInfo &MRI)
Definition: Utils.cpp:287
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:408
Target-Independent Code Generator Pass Configuration Options.
APFloat getAPFloatFromSize(double Val, unsigned Size)
Returns an APFloat from Val converted to the appropriate size.
Definition: Utils.cpp:274
MachineInstr * getVRegDef(unsigned Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
int64_t getSExtValue() const
Get sign extended value.
Definition: APInt.h:1574
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
Definition: MachineInstr.h:405
opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition: APFloat.cpp:4446
bool allowExtraAnalysis(StringRef PassName) const
Whether we allow for extra compile-time budget to perform more analysis to be more informative...
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:137
MachineInstr * getOpcodeDef(unsigned Opcode, unsigned Reg, const MachineRegisterInfo &MRI)
See if Reg is defined by an single def instruction that is Opcode.
Definition: Utils.cpp:258
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
TargetInstrInfo - Interface to description of machine instruction set.
===- MachineOptimizationRemarkEmitter.h - Opt Diagnostics -*- C++ -*-—===//
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
unsigned const MachineRegisterInfo * MRI
APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition: APInt.cpp:1612
This file contains the declarations for the subclasses of Constant, which represent the different fla...
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:263
bool isCImm() const
isCImm - Test if this is a MO_CImmediate operand.
Represent the analysis usage information of a pass.
This file declares a class to represent arbitrary precision floating point values and provide a varie...
bool isTargetSpecificOpcode(unsigned Opcode)
Check whether the given Opcode is a target-specific opcode.
Definition: TargetOpcodes.h:36
unsigned VReg
Definition: Utils.h:100
void getLocation(StringRef &RelativePath, unsigned &Line, unsigned &Column) const
Return location information for this diagnostic in three parts: the relative source file path...
unsigned constrainRegToClass(MachineRegisterInfo &MRI, const TargetInstrInfo &TII, const RegisterBankInfo &RBI, MachineInstr &InsertPt, unsigned Reg, const TargetRegisterClass &RegClass)
Try to constrain Reg to the specified register class.
Definition: Utils.cpp:30
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned getNumExplicitOperands() const
Returns the number of non-implicit operands.
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition: APInt.h:970
int getOperandConstraint(unsigned OpNum, MCOI::OperandConstraint Constraint) const
Returns the value of the specific constraint if it is set.
Definition: MCInstrDesc.h:187
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition: APInt.h:946
Optional< ValueAndVReg > getConstantVRegValWithLookThrough(unsigned VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs=true)
If VReg is defined by a statically evaluable chain of instructions rooted on a G_CONSTANT (LookThroug...
Definition: Utils.cpp:195
bool isGlobalISelAbortEnabled() const
Check whether or not GlobalISel should abort on error.
static const fltSemantics & IEEEhalf() LLVM_READNONE
Definition: APFloat.cpp:116
The optimization diagnostic interface.
MachineOperand class - Representation of each machine instruction operand.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:841
MachineInstrBuilder MachineInstrBuilder & DefMI
unsigned getSizeInBits() const
Returns the total size of the type. Must only be called on sized types.
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:374
#define MORE()
Definition: regcomp.c:251
bool constrainSelectedInstRegOperands(MachineInstr &I, const TargetInstrInfo &TII, const TargetRegisterInfo &TRI, const RegisterBankInfo &RBI)
Mutate the newly-selected instruction I to constrain its (possibly generic) virtual register operands...
Definition: Utils.cpp:87
int64_t getImm() const
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
Class for arbitrary precision integers.
Definition: APInt.h:69
Optional< int64_t > getConstantVRegVal(unsigned VReg, const MachineRegisterInfo &MRI)
If VReg is defined by a G_CONSTANT fits in int64_t returns it.
Definition: Utils.cpp:184
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:253
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
MachineFunctionProperties & set(Property P)
bool isTriviallyDead(const MachineInstr &MI, const MachineRegisterInfo &MRI)
Check whether an instruction MI is dead: it only defines dead virtual registers, and doesn&#39;t have oth...
Definition: Utils.cpp:134
Representation of each machine instruction.
Definition: MachineInstr.h:63
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode...
Definition: MCInstrInfo.h:44
APInt srem(const APInt &RHS) const
Function for signed remainder operation.
Definition: APInt.cpp:1682
void setReg(unsigned Reg)
Change the register this operand corresponds to.
#define I(x, y, z)
Definition: MD5.cpp:58
static const TargetRegisterClass * constrainGenericRegister(unsigned Reg, const TargetRegisterClass &RC, MachineRegisterInfo &MRI)
Constrain the (possibly generic) virtual register Reg to RC.
uint32_t Size
Definition: Profile.cpp:46
bool isAllocatable() const
Return true if this register class may be used to create virtual registers.
bool isRegTiedToUseOperand(unsigned DefOpIdx, unsigned *UseOpIdx=nullptr) const
Given the index of a register def operand, check if the register def is tied to a source operand...
bool isReg() const
isReg - Tests if this is a MO_Register operand.
Diagnostic information for missed-optimization remarks.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool isPreISelGenericOpcode(unsigned Opcode)
Check whether the given Opcode is a generic opcode that is not supposed to appear after ISel...
Definition: TargetOpcodes.h:30
unsigned getSizeInBits(unsigned Reg, const MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI) const
Get the size in bits of Reg.
virtual const TargetRegisterClass * getConstrainedRegClassForOperand(const MachineOperand &MO, const MachineRegisterInfo &MRI) const
unsigned getOpcode() const
Return the opcode number for this descriptor.
Definition: MCInstrDesc.h:203
IRTranslator LLVM IR MI
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
unsigned constrainOperandRegClass(const MachineFunction &MF, const TargetRegisterInfo &TRI, MachineRegisterInfo &MRI, const TargetInstrInfo &TII, const RegisterBankInfo &RBI, MachineInstr &InsertPt, const MCInstrDesc &II, const MachineOperand &RegMO, unsigned OpIdx)
Try to constrain Reg so that it is usable by argument OpIdx of the provided MCInstrDesc II...
Definition: Utils.cpp:46
#define LLVM_DEBUG(X)
Definition: Debug.h:122
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:413
const ConstantInt * getCImm() const
void reportGISelFailure(MachineFunction &MF, const TargetPassConfig &TPC, MachineOptimizationRemarkEmitter &MORE, MachineOptimizationRemarkMissed &R)
Report an ISel error as a missed optimization remark to the LLVMContext&#39;s diagnostic stream...
Definition: Utils.cpp:155
bool isSafeToMove(AliasAnalysis *AA, bool &SawStore) const
Return true if it is safe to move this instruction.
unsigned createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
void tieOperands(unsigned DefIdx, unsigned UseIdx)
Add a tie between the register operands at DefIdx and UseIdx.