eliminate the CheckMultiOpcodeMatcher code and have each
[oota-llvm.git] / lib / CodeGen / TargetInstrInfoImpl.cpp
1 //===-- TargetInstrInfoImpl.cpp - Target Instruction Information ----------===//
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 implements the TargetInstrInfoImpl class, it just provides default
11 // implementations of various methods.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Target/TargetInstrInfo.h"
16 #include "llvm/Target/TargetMachine.h"
17 #include "llvm/Target/TargetRegisterInfo.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineMemOperand.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/PseudoSourceValue.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
27 using namespace llvm;
28
29 // commuteInstruction - The default implementation of this method just exchanges
30 // the two operands returned by findCommutedOpIndices.
31 MachineInstr *TargetInstrInfoImpl::commuteInstruction(MachineInstr *MI,
32                                                       bool NewMI) const {
33   const TargetInstrDesc &TID = MI->getDesc();
34   bool HasDef = TID.getNumDefs();
35   if (HasDef && !MI->getOperand(0).isReg())
36     // No idea how to commute this instruction. Target should implement its own.
37     return 0;
38   unsigned Idx1, Idx2;
39   if (!findCommutedOpIndices(MI, Idx1, Idx2)) {
40     std::string msg;
41     raw_string_ostream Msg(msg);
42     Msg << "Don't know how to commute: " << *MI;
43     llvm_report_error(Msg.str());
44   }
45
46   assert(MI->getOperand(Idx1).isReg() && MI->getOperand(Idx2).isReg() &&
47          "This only knows how to commute register operands so far");
48   unsigned Reg1 = MI->getOperand(Idx1).getReg();
49   unsigned Reg2 = MI->getOperand(Idx2).getReg();
50   bool Reg1IsKill = MI->getOperand(Idx1).isKill();
51   bool Reg2IsKill = MI->getOperand(Idx2).isKill();
52   bool ChangeReg0 = false;
53   if (HasDef && MI->getOperand(0).getReg() == Reg1) {
54     // Must be two address instruction!
55     assert(MI->getDesc().getOperandConstraint(0, TOI::TIED_TO) &&
56            "Expecting a two-address instruction!");
57     Reg2IsKill = false;
58     ChangeReg0 = true;
59   }
60
61   if (NewMI) {
62     // Create a new instruction.
63     unsigned Reg0 = HasDef
64       ? (ChangeReg0 ? Reg2 : MI->getOperand(0).getReg()) : 0;
65     bool Reg0IsDead = HasDef ? MI->getOperand(0).isDead() : false;
66     MachineFunction &MF = *MI->getParent()->getParent();
67     if (HasDef)
68       return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
69         .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
70         .addReg(Reg2, getKillRegState(Reg2IsKill))
71         .addReg(Reg1, getKillRegState(Reg2IsKill));
72     else
73       return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
74         .addReg(Reg2, getKillRegState(Reg2IsKill))
75         .addReg(Reg1, getKillRegState(Reg2IsKill));
76   }
77
78   if (ChangeReg0)
79     MI->getOperand(0).setReg(Reg2);
80   MI->getOperand(Idx2).setReg(Reg1);
81   MI->getOperand(Idx1).setReg(Reg2);
82   MI->getOperand(Idx2).setIsKill(Reg1IsKill);
83   MI->getOperand(Idx1).setIsKill(Reg2IsKill);
84   return MI;
85 }
86
87 /// findCommutedOpIndices - If specified MI is commutable, return the two
88 /// operand indices that would swap value. Return true if the instruction
89 /// is not in a form which this routine understands.
90 bool TargetInstrInfoImpl::findCommutedOpIndices(MachineInstr *MI,
91                                                 unsigned &SrcOpIdx1,
92                                                 unsigned &SrcOpIdx2) const {
93   const TargetInstrDesc &TID = MI->getDesc();
94   if (!TID.isCommutable())
95     return false;
96   // This assumes v0 = op v1, v2 and commuting would swap v1 and v2. If this
97   // is not true, then the target must implement this.
98   SrcOpIdx1 = TID.getNumDefs();
99   SrcOpIdx2 = SrcOpIdx1 + 1;
100   if (!MI->getOperand(SrcOpIdx1).isReg() ||
101       !MI->getOperand(SrcOpIdx2).isReg())
102     // No idea.
103     return false;
104   return true;
105 }
106
107
108 bool TargetInstrInfoImpl::PredicateInstruction(MachineInstr *MI,
109                             const SmallVectorImpl<MachineOperand> &Pred) const {
110   bool MadeChange = false;
111   const TargetInstrDesc &TID = MI->getDesc();
112   if (!TID.isPredicable())
113     return false;
114   
115   for (unsigned j = 0, i = 0, e = MI->getNumOperands(); i != e; ++i) {
116     if (TID.OpInfo[i].isPredicate()) {
117       MachineOperand &MO = MI->getOperand(i);
118       if (MO.isReg()) {
119         MO.setReg(Pred[j].getReg());
120         MadeChange = true;
121       } else if (MO.isImm()) {
122         MO.setImm(Pred[j].getImm());
123         MadeChange = true;
124       } else if (MO.isMBB()) {
125         MO.setMBB(Pred[j].getMBB());
126         MadeChange = true;
127       }
128       ++j;
129     }
130   }
131   return MadeChange;
132 }
133
134 void TargetInstrInfoImpl::reMaterialize(MachineBasicBlock &MBB,
135                                         MachineBasicBlock::iterator I,
136                                         unsigned DestReg,
137                                         unsigned SubIdx,
138                                         const MachineInstr *Orig,
139                                         const TargetRegisterInfo *TRI) const {
140   MachineInstr *MI = MBB.getParent()->CloneMachineInstr(Orig);
141   MachineOperand &MO = MI->getOperand(0);
142   if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
143     MO.setReg(DestReg);
144     MO.setSubReg(SubIdx);
145   } else if (SubIdx) {
146     MO.setReg(TRI->getSubReg(DestReg, SubIdx));
147   } else {
148     MO.setReg(DestReg);
149   }
150   MBB.insert(I, MI);
151 }
152
153 MachineInstr *TargetInstrInfoImpl::duplicate(MachineInstr *Orig,
154                                              MachineFunction &MF) const {
155   assert(!Orig->getDesc().isNotDuplicable() &&
156          "Instruction cannot be duplicated");
157   return MF.CloneMachineInstr(Orig);
158 }
159
160 bool
161 TargetInstrInfoImpl::isIdentical(const MachineInstr *MI,
162                                  const MachineInstr *Other,
163                                  const MachineRegisterInfo *MRI) const {
164   if (MI->getOpcode() != Other->getOpcode() ||
165       MI->getNumOperands() != Other->getNumOperands())
166     return false;
167
168   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
169     const MachineOperand &MO = MI->getOperand(i);
170     const MachineOperand &OMO = Other->getOperand(i);
171     if (MO.isReg() && MO.isDef()) {
172       assert(OMO.isReg() && OMO.isDef());
173       unsigned Reg = MO.getReg();
174       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
175         if (Reg != OMO.getReg())
176           return false;
177       } else if (MRI->getRegClass(MO.getReg()) !=
178                  MRI->getRegClass(OMO.getReg()))
179         return false;
180
181       continue;
182     }
183
184     if (!MO.isIdenticalTo(OMO))
185       return false;
186   }
187
188   return true;
189 }
190
191 unsigned
192 TargetInstrInfoImpl::GetFunctionSizeInBytes(const MachineFunction &MF) const {
193   unsigned FnSize = 0;
194   for (MachineFunction::const_iterator MBBI = MF.begin(), E = MF.end();
195        MBBI != E; ++MBBI) {
196     const MachineBasicBlock &MBB = *MBBI;
197     for (MachineBasicBlock::const_iterator I = MBB.begin(),E = MBB.end();
198          I != E; ++I)
199       FnSize += GetInstSizeInBytes(I);
200   }
201   return FnSize;
202 }
203
204 /// foldMemoryOperand - Attempt to fold a load or store of the specified stack
205 /// slot into the specified machine instruction for the specified operand(s).
206 /// If this is possible, a new instruction is returned with the specified
207 /// operand folded, otherwise NULL is returned. The client is responsible for
208 /// removing the old instruction and adding the new one in the instruction
209 /// stream.
210 MachineInstr*
211 TargetInstrInfo::foldMemoryOperand(MachineFunction &MF,
212                                    MachineInstr* MI,
213                                    const SmallVectorImpl<unsigned> &Ops,
214                                    int FrameIndex) const {
215   unsigned Flags = 0;
216   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
217     if (MI->getOperand(Ops[i]).isDef())
218       Flags |= MachineMemOperand::MOStore;
219     else
220       Flags |= MachineMemOperand::MOLoad;
221
222   // Ask the target to do the actual folding.
223   MachineInstr *NewMI = foldMemoryOperandImpl(MF, MI, Ops, FrameIndex);
224   if (!NewMI) return 0;
225
226   assert((!(Flags & MachineMemOperand::MOStore) ||
227           NewMI->getDesc().mayStore()) &&
228          "Folded a def to a non-store!");
229   assert((!(Flags & MachineMemOperand::MOLoad) ||
230           NewMI->getDesc().mayLoad()) &&
231          "Folded a use to a non-load!");
232   const MachineFrameInfo &MFI = *MF.getFrameInfo();
233   assert(MFI.getObjectOffset(FrameIndex) != -1);
234   MachineMemOperand *MMO =
235     MF.getMachineMemOperand(PseudoSourceValue::getFixedStack(FrameIndex),
236                             Flags, /*Offset=*/0,
237                             MFI.getObjectSize(FrameIndex),
238                             MFI.getObjectAlignment(FrameIndex));
239   NewMI->addMemOperand(MF, MMO);
240
241   return NewMI;
242 }
243
244 /// foldMemoryOperand - Same as the previous version except it allows folding
245 /// of any load and store from / to any address, not just from a specific
246 /// stack slot.
247 MachineInstr*
248 TargetInstrInfo::foldMemoryOperand(MachineFunction &MF,
249                                    MachineInstr* MI,
250                                    const SmallVectorImpl<unsigned> &Ops,
251                                    MachineInstr* LoadMI) const {
252   assert(LoadMI->getDesc().canFoldAsLoad() && "LoadMI isn't foldable!");
253 #ifndef NDEBUG
254   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
255     assert(MI->getOperand(Ops[i]).isUse() && "Folding load into def!");
256 #endif
257
258   // Ask the target to do the actual folding.
259   MachineInstr *NewMI = foldMemoryOperandImpl(MF, MI, Ops, LoadMI);
260   if (!NewMI) return 0;
261
262   // Copy the memoperands from the load to the folded instruction.
263   NewMI->setMemRefs(LoadMI->memoperands_begin(),
264                     LoadMI->memoperands_end());
265
266   return NewMI;
267 }
268
269 bool
270 TargetInstrInfo::isReallyTriviallyReMaterializableGeneric(const MachineInstr *
271                                                             MI,
272                                                           AliasAnalysis *
273                                                             AA) const {
274   const MachineFunction &MF = *MI->getParent()->getParent();
275   const MachineRegisterInfo &MRI = MF.getRegInfo();
276   const TargetMachine &TM = MF.getTarget();
277   const TargetInstrInfo &TII = *TM.getInstrInfo();
278   const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
279
280   // A load from a fixed stack slot can be rematerialized. This may be
281   // redundant with subsequent checks, but it's target-independent,
282   // simple, and a common case.
283   int FrameIdx = 0;
284   if (TII.isLoadFromStackSlot(MI, FrameIdx) &&
285       MF.getFrameInfo()->isImmutableObjectIndex(FrameIdx))
286     return true;
287
288   const TargetInstrDesc &TID = MI->getDesc();
289
290   // Avoid instructions obviously unsafe for remat.
291   if (TID.hasUnmodeledSideEffects() || TID.isNotDuplicable() ||
292       TID.mayStore())
293     return false;
294
295   // Avoid instructions which load from potentially varying memory.
296   if (TID.mayLoad() && !MI->isInvariantLoad(AA))
297     return false;
298
299   // If any of the registers accessed are non-constant, conservatively assume
300   // the instruction is not rematerializable.
301   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
302     const MachineOperand &MO = MI->getOperand(i);
303     if (!MO.isReg()) continue;
304     unsigned Reg = MO.getReg();
305     if (Reg == 0)
306       continue;
307
308     // Check for a well-behaved physical register.
309     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
310       if (MO.isUse()) {
311         // If the physreg has no defs anywhere, it's just an ambient register
312         // and we can freely move its uses. Alternatively, if it's allocatable,
313         // it could get allocated to something with a def during allocation.
314         if (!MRI.def_empty(Reg))
315           return false;
316         BitVector AllocatableRegs = TRI.getAllocatableSet(MF, 0);
317         if (AllocatableRegs.test(Reg))
318           return false;
319         // Check for a def among the register's aliases too.
320         for (const unsigned *Alias = TRI.getAliasSet(Reg); *Alias; ++Alias) {
321           unsigned AliasReg = *Alias;
322           if (!MRI.def_empty(AliasReg))
323             return false;
324           if (AllocatableRegs.test(AliasReg))
325             return false;
326         }
327       } else {
328         // A physreg def. We can't remat it.
329         return false;
330       }
331       continue;
332     }
333
334     // Only allow one virtual-register def, and that in the first operand.
335     if (MO.isDef() != (i == 0))
336       return false;
337
338     // For the def, it should be the only def of that register.
339     if (MO.isDef() && (llvm::next(MRI.def_begin(Reg)) != MRI.def_end() ||
340                        MRI.isLiveIn(Reg)))
341       return false;
342
343     // Don't allow any virtual-register uses. Rematting an instruction with
344     // virtual register uses would length the live ranges of the uses, which
345     // is not necessarily a good idea, certainly not "trivial".
346     if (MO.isUse())
347       return false;
348   }
349
350   // Everything checked out.
351   return true;
352 }