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