LLVM  8.0.0svn
Utils.cpp
Go to the documentation of this file.
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 
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/Twine.h"
25 #include "llvm/IR/Constants.h"
26 
27 #define DEBUG_TYPE "globalisel-utils"
28 
29 using namespace llvm;
30 
32  const TargetInstrInfo &TII,
33  const RegisterBankInfo &RBI,
34  MachineInstr &InsertPt, unsigned Reg,
35  const TargetRegisterClass &RegClass) {
36  if (!RBI.constrainGenericRegister(Reg, RegClass, MRI)) {
37  unsigned NewReg = MRI.createVirtualRegister(&RegClass);
38  BuildMI(*InsertPt.getParent(), InsertPt, InsertPt.getDebugLoc(),
39  TII.get(TargetOpcode::COPY), NewReg)
40  .addReg(Reg);
41  return NewReg;
42  }
43 
44  return Reg;
45 }
46 
48  const MachineFunction &MF, const TargetRegisterInfo &TRI,
50  const RegisterBankInfo &RBI, MachineInstr &InsertPt, const MCInstrDesc &II,
51  const MachineOperand &RegMO, unsigned OpIdx) {
52  unsigned Reg = RegMO.getReg();
53  // Assume physical registers are properly constrained.
55  "PhysReg not implemented");
56 
57  const TargetRegisterClass *RegClass = TII.getRegClass(II, OpIdx, &TRI, MF);
58  // Some of the target independent instructions, like COPY, may not impose any
59  // register class constraints on some of their operands: If it's a use, we can
60  // skip constraining as the instruction defining the register would constrain
61  // it.
62 
63  // We can't constrain unallocatable register classes, because we can't create
64  // virtual registers for these classes, so we need to let targets handled this
65  // case.
66  if (RegClass && !RegClass->isAllocatable())
67  RegClass = TRI.getConstrainedRegClassForOperand(RegMO, MRI);
68 
69  if (!RegClass) {
70  assert((!isTargetSpecificOpcode(II.getOpcode()) || RegMO.isUse()) &&
71  "Register class constraint is required unless either the "
72  "instruction is target independent or the operand is a use");
73  // FIXME: Just bailing out like this here could be not enough, unless we
74  // expect the users of this function to do the right thing for PHIs and
75  // COPY:
76  // v1 = COPY v0
77  // v2 = COPY v1
78  // v1 here may end up not being constrained at all. Please notice that to
79  // reproduce the issue we likely need a destination pattern of a selection
80  // rule producing such extra copies, not just an input GMIR with them as
81  // every existing target using selectImpl handles copies before calling it
82  // and they never reach this function.
83  return Reg;
84  }
85  return constrainRegToClass(MRI, TII, RBI, InsertPt, Reg, *RegClass);
86 }
87 
89  const TargetInstrInfo &TII,
90  const TargetRegisterInfo &TRI,
91  const RegisterBankInfo &RBI) {
93  "A selected instruction is expected");
94  MachineBasicBlock &MBB = *I.getParent();
95  MachineFunction &MF = *MBB.getParent();
97 
98  for (unsigned OpI = 0, OpE = I.getNumExplicitOperands(); OpI != OpE; ++OpI) {
99  MachineOperand &MO = I.getOperand(OpI);
100 
101  // There's nothing to be done on non-register operands.
102  if (!MO.isReg())
103  continue;
104 
105  LLVM_DEBUG(dbgs() << "Converting operand: " << MO << '\n');
106  assert(MO.isReg() && "Unsupported non-reg operand");
107 
108  unsigned Reg = MO.getReg();
109  // Physical registers don't need to be constrained.
110  if (TRI.isPhysicalRegister(Reg))
111  continue;
112 
113  // Register operands with a value of 0 (e.g. predicate operands) don't need
114  // to be constrained.
115  if (Reg == 0)
116  continue;
117 
118  // If the operand is a vreg, we should constrain its regclass, and only
119  // insert COPYs if that's impossible.
120  // constrainOperandRegClass does that for us.
121  MO.setReg(constrainOperandRegClass(MF, TRI, MRI, TII, RBI, I, I.getDesc(),
122  MO, OpI));
123 
124  // Tie uses to defs as indicated in MCInstrDesc if this hasn't already been
125  // done.
126  if (MO.isUse()) {
127  int DefIdx = I.getDesc().getOperandConstraint(OpI, MCOI::TIED_TO);
128  if (DefIdx != -1 && !I.isRegTiedToUseOperand(DefIdx))
129  I.tieOperands(DefIdx, OpI);
130  }
131  }
132  return true;
133 }
134 
136  const MachineRegisterInfo &MRI) {
137  // If we can move an instruction, we can remove it. Otherwise, it has
138  // a side-effect of some sort.
139  bool SawStore = false;
140  if (!MI.isSafeToMove(/*AA=*/nullptr, SawStore) && !MI.isPHI())
141  return false;
142 
143  // Instructions without side-effects are dead iff they only define dead vregs.
144  for (auto &MO : MI.operands()) {
145  if (!MO.isReg() || !MO.isDef())
146  continue;
147 
148  unsigned Reg = MO.getReg();
150  !MRI.use_nodbg_empty(Reg))
151  return false;
152  }
153  return true;
154 }
155 
160 
161  // Print the function name explicitly if we don't have a debug location (which
162  // makes the diagnostic less useful) or if we're going to emit a raw error.
163  if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled())
164  R << (" (in function: " + MF.getName() + ")").str();
165 
166  if (TPC.isGlobalISelAbortEnabled())
168  else
169  MORE.emit(R);
170 }
171 
174  const char *PassName, StringRef Msg,
175  const MachineInstr &MI) {
176  MachineOptimizationRemarkMissed R(PassName, "GISelFailure: ",
177  MI.getDebugLoc(), MI.getParent());
178  R << Msg;
179  // Printing MI is expensive; only do it if expensive remarks are enabled.
180  if (TPC.isGlobalISelAbortEnabled() || MORE.allowExtraAnalysis(PassName))
181  R << ": " << ore::MNV("Inst", MI);
182  reportGISelFailure(MF, TPC, MORE, R);
183 }
184 
186  const MachineRegisterInfo &MRI) {
187  MachineInstr *MI = MRI.getVRegDef(VReg);
188  if (MI->getOpcode() != TargetOpcode::G_CONSTANT)
189  return None;
190 
191  if (MI->getOperand(1).isImm())
192  return MI->getOperand(1).getImm();
193 
194  if (MI->getOperand(1).isCImm() &&
195  MI->getOperand(1).getCImm()->getBitWidth() <= 64)
196  return MI->getOperand(1).getCImm()->getSExtValue();
197 
198  return None;
199 }
200 
202  const MachineRegisterInfo &MRI) {
203  MachineInstr *MI = MRI.getVRegDef(VReg);
204  if (TargetOpcode::G_FCONSTANT != MI->getOpcode())
205  return nullptr;
206  return MI->getOperand(1).getFPImm();
207 }
208 
209 llvm::MachineInstr *llvm::getOpcodeDef(unsigned Opcode, unsigned Reg,
210  const MachineRegisterInfo &MRI) {
211  auto *DefMI = MRI.getVRegDef(Reg);
212  auto DstTy = MRI.getType(DefMI->getOperand(0).getReg());
213  if (!DstTy.isValid())
214  return nullptr;
215  while (DefMI->getOpcode() == TargetOpcode::COPY) {
216  unsigned SrcReg = DefMI->getOperand(1).getReg();
217  auto SrcTy = MRI.getType(SrcReg);
218  if (!SrcTy.isValid() || SrcTy != DstTy)
219  break;
220  DefMI = MRI.getVRegDef(SrcReg);
221  }
222  return DefMI->getOpcode() == Opcode ? DefMI : nullptr;
223 }
224 
225 APFloat llvm::getAPFloatFromSize(double Val, unsigned Size) {
226  if (Size == 32)
227  return APFloat(float(Val));
228  if (Size == 64)
229  return APFloat(Val);
230  if (Size != 16)
231  llvm_unreachable("Unsupported FPConstant size");
232  bool Ignored;
233  APFloat APF(Val);
235  return APF;
236 }
237 
240 }
const NoneType None
Definition: None.h:24
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
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:24
void getSelectionDAGFallbackAnalysisUsage(AnalysisUsage &AU)
Modify analysis usage so it preserves passes required for the SelectionDAG fallback.
Definition: Utils.cpp:238
const MachineFunctionProperties & getProperties() const
Get the function properties.
const ConstantFP * getConstantFPVRegVal(unsigned VReg, const MachineRegisterInfo &MRI)
Definition: Utils.cpp:201
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
Definition: MachineInstr.h:383
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:164
unsigned getReg() const
getReg - Returns the register number.
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
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...
unsigned const TargetRegisterInfo * TRI
iterator_range< mop_iterator > operands()
Definition: MachineInstr.h:459
bool isPHI() const
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
unsigned getBitWidth() const
getBitWidth - Return the bitwidth of this constant.
Definition: Constants.h:143
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...
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:409
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:225
MachineInstr * getVRegDef(unsigned Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
Definition: MachineInstr.h:406
opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition: APFloat.cpp:4444
bool allowExtraAnalysis(StringRef PassName) const
Whether we allow for extra compile-time budget to perform more analysis to be more informative...
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:209
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
This file contains the declarations for the subclasses of Constant, which represent the different fla...
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:264
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:37
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:31
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.
int getOperandConstraint(unsigned OpNum, MCOI::OperandConstraint Constraint) const
Returns the value of the specific constraint if it is set.
Definition: MCInstrDesc.h:188
bool isGlobalISelAbortEnabled() const
Check whether or not GlobalISel should abort on error.
static const fltSemantics & IEEEhalf() LLVM_READNONE
Definition: APFloat.cpp:117
The optimization diagnostic interface.
MachineOperand class - Representation of each machine instruction operand.
MachineInstrBuilder MachineInstrBuilder & DefMI
#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:88
int64_t getImm() const
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:133
Optional< int64_t > getConstantVRegVal(unsigned VReg, const MachineRegisterInfo &MRI)
Definition: Utils.cpp:185
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:254
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:135
Representation of each machine instruction.
Definition: MachineInstr.h:64
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.
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode...
Definition: MCInstrInfo.h:45
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:47
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:31
virtual const TargetRegisterClass * getConstrainedRegClassForOperand(const MachineOperand &MO, const MachineRegisterInfo &MRI) const
unsigned getOpcode() const
Return the opcode number for this descriptor.
Definition: MCInstrDesc.h:204
IRTranslator LLVM IR MI
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
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:47
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition: Constants.h:157
#define LLVM_DEBUG(X)
Definition: Debug.h:123
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:414
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:156
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.