LLVM  4.0.0
Thumb2ITBlockPass.cpp
Go to the documentation of this file.
1 //===-- Thumb2ITBlockPass.cpp - Insert Thumb-2 IT blocks ------------------===//
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 #include "ARM.h"
11 #include "ARMMachineFunctionInfo.h"
12 #include "Thumb2InstrInfo.h"
13 #include "llvm/ADT/SmallSet.h"
14 #include "llvm/ADT/Statistic.h"
19 using namespace llvm;
20 
21 #define DEBUG_TYPE "thumb2-it"
22 
23 STATISTIC(NumITs, "Number of IT blocks inserted");
24 STATISTIC(NumMovedInsts, "Number of predicated instructions moved");
25 
26 namespace {
27  class Thumb2ITBlockPass : public MachineFunctionPass {
28  public:
29  static char ID;
30  Thumb2ITBlockPass() : MachineFunctionPass(ID) {}
31 
32  bool restrictIT;
33  const Thumb2InstrInfo *TII;
34  const TargetRegisterInfo *TRI;
35  ARMFunctionInfo *AFI;
36 
37  bool runOnMachineFunction(MachineFunction &Fn) override;
38 
39  MachineFunctionProperties getRequiredProperties() const override {
42  }
43 
44  StringRef getPassName() const override {
45  return "Thumb IT blocks insertion pass";
46  }
47 
48  private:
49  bool MoveCopyOutOfITBlock(MachineInstr *MI,
52  SmallSet<unsigned, 4> &Uses);
53  bool InsertITInstructions(MachineBasicBlock &MBB);
54  };
55  char Thumb2ITBlockPass::ID = 0;
56 }
57 
58 /// TrackDefUses - Tracking what registers are being defined and used by
59 /// instructions in the IT block. This also tracks "dependencies", i.e. uses
60 /// in the IT block that are defined before the IT instruction.
64  const TargetRegisterInfo *TRI) {
65  SmallVector<unsigned, 4> LocalDefs;
66  SmallVector<unsigned, 4> LocalUses;
67 
68  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
69  MachineOperand &MO = MI->getOperand(i);
70  if (!MO.isReg())
71  continue;
72  unsigned Reg = MO.getReg();
73  if (!Reg || Reg == ARM::ITSTATE || Reg == ARM::SP)
74  continue;
75  if (MO.isUse())
76  LocalUses.push_back(Reg);
77  else
78  LocalDefs.push_back(Reg);
79  }
80 
81  for (unsigned i = 0, e = LocalUses.size(); i != e; ++i) {
82  unsigned Reg = LocalUses[i];
83  for (MCSubRegIterator Subreg(Reg, TRI, /*IncludeSelf=*/true);
84  Subreg.isValid(); ++Subreg)
85  Uses.insert(*Subreg);
86  }
87 
88  for (unsigned i = 0, e = LocalDefs.size(); i != e; ++i) {
89  unsigned Reg = LocalDefs[i];
90  for (MCSubRegIterator Subreg(Reg, TRI, /*IncludeSelf=*/true);
91  Subreg.isValid(); ++Subreg)
92  Defs.insert(*Subreg);
93  if (Reg == ARM::CPSR)
94  continue;
95  }
96 }
97 
98 /// Clear kill flags for any uses in the given set. This will likely
99 /// conservatively remove more kill flags than are necessary, but removing them
100 /// is safer than incorrect kill flags remaining on instructions.
102  for (MachineOperand &MO : MI->operands()) {
103  if (!MO.isReg() || MO.isDef() || !MO.isKill())
104  continue;
105  if (!Uses.count(MO.getReg()))
106  continue;
107  MO.setIsKill(false);
108  }
109 }
110 
111 static bool isCopy(MachineInstr *MI) {
112  switch (MI->getOpcode()) {
113  default:
114  return false;
115  case ARM::MOVr:
116  case ARM::MOVr_TC:
117  case ARM::tMOVr:
118  case ARM::t2MOVr:
119  return true;
120  }
121 }
122 
123 bool
124 Thumb2ITBlockPass::MoveCopyOutOfITBlock(MachineInstr *MI,
126  SmallSet<unsigned, 4> &Defs,
127  SmallSet<unsigned, 4> &Uses) {
128  if (!isCopy(MI))
129  return false;
130  // llvm models select's as two-address instructions. That means a copy
131  // is inserted before a t2MOVccr, etc. If the copy is scheduled in
132  // between selects we would end up creating multiple IT blocks.
133  assert(MI->getOperand(0).getSubReg() == 0 &&
134  MI->getOperand(1).getSubReg() == 0 &&
135  "Sub-register indices still around?");
136 
137  unsigned DstReg = MI->getOperand(0).getReg();
138  unsigned SrcReg = MI->getOperand(1).getReg();
139 
140  // First check if it's safe to move it.
141  if (Uses.count(DstReg) || Defs.count(SrcReg))
142  return false;
143 
144  // If the CPSR is defined by this copy, then we don't want to move it. E.g.,
145  // if we have:
146  //
147  // movs r1, r1
148  // rsb r1, 0
149  // movs r2, r2
150  // rsb r2, 0
151  //
152  // we don't want this to be converted to:
153  //
154  // movs r1, r1
155  // movs r2, r2
156  // itt mi
157  // rsb r1, 0
158  // rsb r2, 0
159  //
160  const MCInstrDesc &MCID = MI->getDesc();
161  if (MI->hasOptionalDef() &&
162  MI->getOperand(MCID.getNumOperands() - 1).getReg() == ARM::CPSR)
163  return false;
164 
165  // Then peek at the next instruction to see if it's predicated on CC or OCC.
166  // If not, then there is nothing to be gained by moving the copy.
169  while (I != E && I->isDebugValue())
170  ++I;
171  if (I != E) {
172  unsigned NPredReg = 0;
173  ARMCC::CondCodes NCC = getITInstrPredicate(*I, NPredReg);
174  if (NCC == CC || NCC == OCC)
175  return true;
176  }
177  return false;
178 }
179 
180 bool Thumb2ITBlockPass::InsertITInstructions(MachineBasicBlock &MBB) {
181  bool Modified = false;
182 
185  MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
186  while (MBBI != E) {
187  MachineInstr *MI = &*MBBI;
188  DebugLoc dl = MI->getDebugLoc();
189  unsigned PredReg = 0;
190  ARMCC::CondCodes CC = getITInstrPredicate(*MI, PredReg);
191  if (CC == ARMCC::AL) {
192  ++MBBI;
193  continue;
194  }
195 
196  Defs.clear();
197  Uses.clear();
198  TrackDefUses(MI, Defs, Uses, TRI);
199 
200  // Insert an IT instruction.
201  MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII->get(ARM::t2IT))
202  .addImm(CC);
203 
204  // Add implicit use of ITSTATE to IT block instructions.
205  MI->addOperand(MachineOperand::CreateReg(ARM::ITSTATE, false/*ifDef*/,
206  true/*isImp*/, false/*isKill*/));
207 
208  MachineInstr *LastITMI = MI;
209  MachineBasicBlock::iterator InsertPos = MIB.getInstr();
210  ++MBBI;
211 
212  // Form IT block.
214  unsigned Mask = 0, Pos = 3;
215 
216  // v8 IT blocks are limited to one conditional op unless -arm-no-restrict-it
217  // is set: skip the loop
218  if (!restrictIT) {
219  // Branches, including tricky ones like LDM_RET, need to end an IT
220  // block so check the instruction we just put in the block.
221  for (; MBBI != E && Pos &&
222  (!MI->isBranch() && !MI->isReturn()) ; ++MBBI) {
223  if (MBBI->isDebugValue())
224  continue;
225 
226  MachineInstr *NMI = &*MBBI;
227  MI = NMI;
228 
229  unsigned NPredReg = 0;
230  ARMCC::CondCodes NCC = getITInstrPredicate(*NMI, NPredReg);
231  if (NCC == CC || NCC == OCC) {
232  Mask |= (NCC & 1) << Pos;
233  // Add implicit use of ITSTATE.
234  NMI->addOperand(MachineOperand::CreateReg(ARM::ITSTATE, false/*ifDef*/,
235  true/*isImp*/, false/*isKill*/));
236  LastITMI = NMI;
237  } else {
238  if (NCC == ARMCC::AL &&
239  MoveCopyOutOfITBlock(NMI, CC, OCC, Defs, Uses)) {
240  --MBBI;
241  MBB.remove(NMI);
242  MBB.insert(InsertPos, NMI);
243  ClearKillFlags(MI, Uses);
244  ++NumMovedInsts;
245  continue;
246  }
247  break;
248  }
249  TrackDefUses(NMI, Defs, Uses, TRI);
250  --Pos;
251  }
252  }
253 
254  // Finalize IT mask.
255  Mask |= (1 << Pos);
256  // Tag along (firstcond[0] << 4) with the mask.
257  Mask |= (CC & 1) << 4;
258  MIB.addImm(Mask);
259 
260  // Last instruction in IT block kills ITSTATE.
261  LastITMI->findRegisterUseOperand(ARM::ITSTATE)->setIsKill();
262 
263  // Finalize the bundle.
264  finalizeBundle(MBB, InsertPos.getInstrIterator(),
265  ++LastITMI->getIterator());
266 
267  Modified = true;
268  ++NumITs;
269  }
270 
271  return Modified;
272 }
273 
274 bool Thumb2ITBlockPass::runOnMachineFunction(MachineFunction &Fn) {
275  const ARMSubtarget &STI =
276  static_cast<const ARMSubtarget &>(Fn.getSubtarget());
277  if (!STI.isThumb2())
278  return false;
279  AFI = Fn.getInfo<ARMFunctionInfo>();
280  TII = static_cast<const Thumb2InstrInfo *>(STI.getInstrInfo());
281  TRI = STI.getRegisterInfo();
282  restrictIT = STI.restrictIT();
283 
284  if (!AFI->isThumbFunction())
285  return false;
286 
287  bool Modified = false;
288  for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E; ) {
289  MachineBasicBlock &MBB = *MFI;
290  ++MFI;
291  Modified |= InsertITInstructions(MBB);
292  }
293 
294  if (Modified)
295  AFI->setHasITBlocks(true);
296 
297  return Modified;
298 }
299 
300 /// createThumb2ITBlockPass - Returns an instance of the Thumb2 IT blocks
301 /// insertion pass.
303  return new Thumb2ITBlockPass();
304 }
void push_back(const T &Elt)
Definition: SmallVector.h:211
static bool isCopy(MachineInstr *MI)
bool isBranch(QueryType Type=AnyInBundle) const
Returns true if this is a conditional, unconditional, or indirect branch.
Definition: MachineInstr.h:448
STATISTIC(NumFunctions,"Total number of functions")
size_t i
bool isValid() const
isValid - returns true if this iterator is not yet at the end.
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:163
MachineOperand * findRegisterUseOperand(unsigned Reg, bool isKill=false, const TargetRegisterInfo *TRI=nullptr)
Wrapper for findRegisterUseOperandIdx, it returns a pointer to the MachineOperand rather than an inde...
Definition: MachineInstr.h:927
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
Definition: MachineInstr.h:270
A debug info location.
Definition: DebugLoc.h:34
static void ClearKillFlags(MachineInstr *MI, SmallSet< unsigned, 4 > &Uses)
Clear kill flags for any uses in the given set.
iterator_range< mop_iterator > operands()
Definition: MachineInstr.h:301
bool restrictIT() const
Definition: ARMSubtarget.h:609
const ARMBaseInstrInfo * getInstrInfo() const override
Definition: ARMSubtarget.h:376
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
static MachineOperand CreateReg(unsigned Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false)
bool isReg() const
isReg - Tests if this is a MO_Register operand.
Reg
All possible values of the reg field in the ModR/M byte.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
unsigned getNumOperands() const
Access to explicit operands of the instruction.
Definition: MachineInstr.h:277
void clear()
Definition: SmallSet.h:118
MachineBasicBlock * MBB
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:273
static GCRegistry::Add< CoreCLRGC > E("coreclr","CoreCLR-compatible GC")
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:131
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
bool isReturn(QueryType Type=AnyInBundle) const
Definition: MachineInstr.h:420
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:36
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:279
static void TrackDefUses(MachineInstr *MI, SmallSet< unsigned, 4 > &Defs, SmallSet< unsigned, 4 > &Uses, const TargetRegisterInfo *TRI)
TrackDefUses - Tracking what registers are being defined and used by instructions in the IT block...
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
self_iterator getIterator()
Definition: ilist_node.h:81
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition: SmallSet.h:80
unsigned getSubReg() const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
MCSubRegIterator enumerates all sub-registers of Reg.
void setIsKill(bool Val=true)
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition: SmallSet.h:64
Iterator for intrusive lists based on ilist_node.
void addOperand(MachineFunction &MF, const MachineOperand &Op)
Add the specified operand to the instruction.
ARMCC::CondCodes getITInstrPredicate(const MachineInstr &MI, unsigned &PredReg)
getITInstrPredicate - Valid only in Thumb2 mode.
MachineOperand class - Representation of each machine instruction operand.
MachineInstr * remove(MachineInstr *I)
Remove the unbundled instruction from the instruction list without deleting it.
static unsigned getReg(const void *D, unsigned RC, unsigned RegNo)
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
Definition: MachineInstr.h:250
MachineFunctionProperties & set(Property P)
Representation of each machine instruction.
Definition: MachineInstr.h:52
static CondCodes getOppositeCondition(CondCodes CC)
Definition: ARMBaseInfo.h:47
bool isThumb2() const
Definition: ARMSubtarget.h:578
ARMFunctionInfo - This class is derived from MachineFunctionInfo and contains private ARM-specific in...
#define I(x, y, z)
Definition: MD5.cpp:54
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:135
const ARMBaseRegisterInfo * getRegisterInfo() const override
Definition: ARMSubtarget.h:385
instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
unsigned getReg() const
getReg - Returns the register number.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
Definition: MCInstrDesc.h:210
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
Definition: BitmaskEnum.h:81
IRTranslator LLVM IR MI
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:47
FunctionPass * createThumb2ITBlockPass()
createThumb2ITBlockPass - Returns an instance of the Thumb2 IT blocks insertion pass.
bool hasOptionalDef(QueryType Type=IgnoreBundle) const
Set if this instruction has an optional definition, e.g.
Definition: MachineInstr.h:410
void finalizeBundle(MachineBasicBlock &MBB, MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
finalizeBundle - Finalize a machine instruction bundle which includes a sequence of instructions star...
Properties which a MachineFunction may have at a given point in time.
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly. ...