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