Commute the internal flag on MachineOperands.
[oota-llvm.git] / lib / CodeGen / TargetInstrInfo.cpp
1 //===-- TargetInstrInfo.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 TargetInstrInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Target/TargetInstrInfo.h"
15 #include "llvm/CodeGen/MachineFrameInfo.h"
16 #include "llvm/CodeGen/MachineInstrBuilder.h"
17 #include "llvm/CodeGen/MachineMemOperand.h"
18 #include "llvm/CodeGen/MachineRegisterInfo.h"
19 #include "llvm/CodeGen/PseudoSourceValue.h"
20 #include "llvm/CodeGen/ScoreboardHazardRecognizer.h"
21 #include "llvm/CodeGen/StackMaps.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/MC/MCInstrItineraries.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Target/TargetFrameLowering.h"
29 #include "llvm/Target/TargetLowering.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include <cctype>
33 using namespace llvm;
34
35 static cl::opt<bool> DisableHazardRecognizer(
36   "disable-sched-hazard", cl::Hidden, cl::init(false),
37   cl::desc("Disable hazard detection during preRA scheduling"));
38
39 TargetInstrInfo::~TargetInstrInfo() {
40 }
41
42 const TargetRegisterClass*
43 TargetInstrInfo::getRegClass(const MCInstrDesc &MCID, unsigned OpNum,
44                              const TargetRegisterInfo *TRI,
45                              const MachineFunction &MF) const {
46   if (OpNum >= MCID.getNumOperands())
47     return nullptr;
48
49   short RegClass = MCID.OpInfo[OpNum].RegClass;
50   if (MCID.OpInfo[OpNum].isLookupPtrRegClass())
51     return TRI->getPointerRegClass(MF, RegClass);
52
53   // Instructions like INSERT_SUBREG do not have fixed register classes.
54   if (RegClass < 0)
55     return nullptr;
56
57   // Otherwise just look it up normally.
58   return TRI->getRegClass(RegClass);
59 }
60
61 /// insertNoop - Insert a noop into the instruction stream at the specified
62 /// point.
63 void TargetInstrInfo::insertNoop(MachineBasicBlock &MBB,
64                                  MachineBasicBlock::iterator MI) const {
65   llvm_unreachable("Target didn't implement insertNoop!");
66 }
67
68 /// Measure the specified inline asm to determine an approximation of its
69 /// length.
70 /// Comments (which run till the next SeparatorString or newline) do not
71 /// count as an instruction.
72 /// Any other non-whitespace text is considered an instruction, with
73 /// multiple instructions separated by SeparatorString or newlines.
74 /// Variable-length instructions are not handled here; this function
75 /// may be overloaded in the target code to do that.
76 unsigned TargetInstrInfo::getInlineAsmLength(const char *Str,
77                                              const MCAsmInfo &MAI) const {
78
79
80   // Count the number of instructions in the asm.
81   bool atInsnStart = true;
82   unsigned Length = 0;
83   for (; *Str; ++Str) {
84     if (*Str == '\n' || strncmp(Str, MAI.getSeparatorString(),
85                                 strlen(MAI.getSeparatorString())) == 0)
86       atInsnStart = true;
87     if (atInsnStart && !std::isspace(static_cast<unsigned char>(*Str))) {
88       Length += MAI.getMaxInstLength();
89       atInsnStart = false;
90     }
91     if (atInsnStart && strncmp(Str, MAI.getCommentString(),
92                                strlen(MAI.getCommentString())) == 0)
93       atInsnStart = false;
94   }
95
96   return Length;
97 }
98
99 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
100 /// after it, replacing it with an unconditional branch to NewDest.
101 void
102 TargetInstrInfo::ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail,
103                                          MachineBasicBlock *NewDest) const {
104   MachineBasicBlock *MBB = Tail->getParent();
105
106   // Remove all the old successors of MBB from the CFG.
107   while (!MBB->succ_empty())
108     MBB->removeSuccessor(MBB->succ_begin());
109
110   // Remove all the dead instructions from the end of MBB.
111   MBB->erase(Tail, MBB->end());
112
113   // If MBB isn't immediately before MBB, insert a branch to it.
114   if (++MachineFunction::iterator(MBB) != MachineFunction::iterator(NewDest))
115     InsertBranch(*MBB, NewDest, nullptr, SmallVector<MachineOperand, 0>(),
116                  Tail->getDebugLoc());
117   MBB->addSuccessor(NewDest);
118 }
119
120 // commuteInstruction - The default implementation of this method just exchanges
121 // the two operands returned by findCommutedOpIndices.
122 MachineInstr *TargetInstrInfo::commuteInstruction(MachineInstr *MI,
123                                                   bool NewMI) const {
124   const MCInstrDesc &MCID = MI->getDesc();
125   bool HasDef = MCID.getNumDefs();
126   if (HasDef && !MI->getOperand(0).isReg())
127     // No idea how to commute this instruction. Target should implement its own.
128     return nullptr;
129   unsigned Idx1, Idx2;
130   if (!findCommutedOpIndices(MI, Idx1, Idx2)) {
131     assert(MI->isCommutable() && "Precondition violation: MI must be commutable.");
132     return nullptr;
133   }
134
135   assert(MI->getOperand(Idx1).isReg() && MI->getOperand(Idx2).isReg() &&
136          "This only knows how to commute register operands so far");
137   unsigned Reg0 = HasDef ? MI->getOperand(0).getReg() : 0;
138   unsigned Reg1 = MI->getOperand(Idx1).getReg();
139   unsigned Reg2 = MI->getOperand(Idx2).getReg();
140   unsigned SubReg0 = HasDef ? MI->getOperand(0).getSubReg() : 0;
141   unsigned SubReg1 = MI->getOperand(Idx1).getSubReg();
142   unsigned SubReg2 = MI->getOperand(Idx2).getSubReg();
143   bool Reg1IsKill = MI->getOperand(Idx1).isKill();
144   bool Reg2IsKill = MI->getOperand(Idx2).isKill();
145   bool Reg1IsUndef = MI->getOperand(Idx1).isUndef();
146   bool Reg2IsUndef = MI->getOperand(Idx2).isUndef();
147   bool Reg1IsInternal = MI->getOperand(Idx1).isInternalRead();
148   bool Reg2IsInternal = MI->getOperand(Idx2).isInternalRead();
149   // If destination is tied to either of the commuted source register, then
150   // it must be updated.
151   if (HasDef && Reg0 == Reg1 &&
152       MI->getDesc().getOperandConstraint(Idx1, MCOI::TIED_TO) == 0) {
153     Reg2IsKill = false;
154     Reg0 = Reg2;
155     SubReg0 = SubReg2;
156   } else if (HasDef && Reg0 == Reg2 &&
157              MI->getDesc().getOperandConstraint(Idx2, MCOI::TIED_TO) == 0) {
158     Reg1IsKill = false;
159     Reg0 = Reg1;
160     SubReg0 = SubReg1;
161   }
162
163   if (NewMI) {
164     // Create a new instruction.
165     MachineFunction &MF = *MI->getParent()->getParent();
166     MI = MF.CloneMachineInstr(MI);
167   }
168
169   if (HasDef) {
170     MI->getOperand(0).setReg(Reg0);
171     MI->getOperand(0).setSubReg(SubReg0);
172   }
173   MI->getOperand(Idx2).setReg(Reg1);
174   MI->getOperand(Idx1).setReg(Reg2);
175   MI->getOperand(Idx2).setSubReg(SubReg1);
176   MI->getOperand(Idx1).setSubReg(SubReg2);
177   MI->getOperand(Idx2).setIsKill(Reg1IsKill);
178   MI->getOperand(Idx1).setIsKill(Reg2IsKill);
179   MI->getOperand(Idx2).setIsUndef(Reg1IsUndef);
180   MI->getOperand(Idx1).setIsUndef(Reg2IsUndef);
181   MI->getOperand(Idx2).setIsInternalRead(Reg1IsInternal);
182   MI->getOperand(Idx1).setIsInternalRead(Reg2IsInternal);
183   return MI;
184 }
185
186 /// findCommutedOpIndices - If specified MI is commutable, return the two
187 /// operand indices that would swap value. Return true if the instruction
188 /// is not in a form which this routine understands.
189 bool TargetInstrInfo::findCommutedOpIndices(MachineInstr *MI,
190                                             unsigned &SrcOpIdx1,
191                                             unsigned &SrcOpIdx2) const {
192   assert(!MI->isBundle() &&
193          "TargetInstrInfo::findCommutedOpIndices() can't handle bundles");
194
195   const MCInstrDesc &MCID = MI->getDesc();
196   if (!MCID.isCommutable())
197     return false;
198   // This assumes v0 = op v1, v2 and commuting would swap v1 and v2. If this
199   // is not true, then the target must implement this.
200   SrcOpIdx1 = MCID.getNumDefs();
201   SrcOpIdx2 = SrcOpIdx1 + 1;
202   if (!MI->getOperand(SrcOpIdx1).isReg() ||
203       !MI->getOperand(SrcOpIdx2).isReg())
204     // No idea.
205     return false;
206   return true;
207 }
208
209
210 bool
211 TargetInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
212   if (!MI->isTerminator()) return false;
213
214   // Conditional branch is a special case.
215   if (MI->isBranch() && !MI->isBarrier())
216     return true;
217   if (!MI->isPredicable())
218     return true;
219   return !isPredicated(MI);
220 }
221
222
223 bool TargetInstrInfo::PredicateInstruction(MachineInstr *MI,
224                             const SmallVectorImpl<MachineOperand> &Pred) const {
225   bool MadeChange = false;
226
227   assert(!MI->isBundle() &&
228          "TargetInstrInfo::PredicateInstruction() can't handle bundles");
229
230   const MCInstrDesc &MCID = MI->getDesc();
231   if (!MI->isPredicable())
232     return false;
233
234   for (unsigned j = 0, i = 0, e = MI->getNumOperands(); i != e; ++i) {
235     if (MCID.OpInfo[i].isPredicate()) {
236       MachineOperand &MO = MI->getOperand(i);
237       if (MO.isReg()) {
238         MO.setReg(Pred[j].getReg());
239         MadeChange = true;
240       } else if (MO.isImm()) {
241         MO.setImm(Pred[j].getImm());
242         MadeChange = true;
243       } else if (MO.isMBB()) {
244         MO.setMBB(Pred[j].getMBB());
245         MadeChange = true;
246       }
247       ++j;
248     }
249   }
250   return MadeChange;
251 }
252
253 bool TargetInstrInfo::hasLoadFromStackSlot(const MachineInstr *MI,
254                                            const MachineMemOperand *&MMO,
255                                            int &FrameIndex) const {
256   for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
257          oe = MI->memoperands_end();
258        o != oe;
259        ++o) {
260     if ((*o)->isLoad()) {
261       if (const FixedStackPseudoSourceValue *Value =
262           dyn_cast_or_null<FixedStackPseudoSourceValue>(
263               (*o)->getPseudoValue())) {
264         FrameIndex = Value->getFrameIndex();
265         MMO = *o;
266         return true;
267       }
268     }
269   }
270   return false;
271 }
272
273 bool TargetInstrInfo::hasStoreToStackSlot(const MachineInstr *MI,
274                                           const MachineMemOperand *&MMO,
275                                           int &FrameIndex) const {
276   for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
277          oe = MI->memoperands_end();
278        o != oe;
279        ++o) {
280     if ((*o)->isStore()) {
281       if (const FixedStackPseudoSourceValue *Value =
282           dyn_cast_or_null<FixedStackPseudoSourceValue>(
283               (*o)->getPseudoValue())) {
284         FrameIndex = Value->getFrameIndex();
285         MMO = *o;
286         return true;
287       }
288     }
289   }
290   return false;
291 }
292
293 bool TargetInstrInfo::getStackSlotRange(const TargetRegisterClass *RC,
294                                         unsigned SubIdx, unsigned &Size,
295                                         unsigned &Offset,
296                                         const MachineFunction &MF) const {
297   if (!SubIdx) {
298     Size = RC->getSize();
299     Offset = 0;
300     return true;
301   }
302   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
303   unsigned BitSize = TRI->getSubRegIdxSize(SubIdx);
304   // Convert bit size to byte size to be consistent with
305   // MCRegisterClass::getSize().
306   if (BitSize % 8)
307     return false;
308
309   int BitOffset = TRI->getSubRegIdxOffset(SubIdx);
310   if (BitOffset < 0 || BitOffset % 8)
311     return false;
312
313   Size = BitSize /= 8;
314   Offset = (unsigned)BitOffset / 8;
315
316   assert(RC->getSize() >= (Offset + Size) && "bad subregister range");
317
318   if (!MF.getTarget().getDataLayout()->isLittleEndian()) {
319     Offset = RC->getSize() - (Offset + Size);
320   }
321   return true;
322 }
323
324 void TargetInstrInfo::reMaterialize(MachineBasicBlock &MBB,
325                                     MachineBasicBlock::iterator I,
326                                     unsigned DestReg,
327                                     unsigned SubIdx,
328                                     const MachineInstr *Orig,
329                                     const TargetRegisterInfo &TRI) const {
330   MachineInstr *MI = MBB.getParent()->CloneMachineInstr(Orig);
331   MI->substituteRegister(MI->getOperand(0).getReg(), DestReg, SubIdx, TRI);
332   MBB.insert(I, MI);
333 }
334
335 bool
336 TargetInstrInfo::produceSameValue(const MachineInstr *MI0,
337                                   const MachineInstr *MI1,
338                                   const MachineRegisterInfo *MRI) const {
339   return MI0->isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs);
340 }
341
342 MachineInstr *TargetInstrInfo::duplicate(MachineInstr *Orig,
343                                          MachineFunction &MF) const {
344   assert(!Orig->isNotDuplicable() &&
345          "Instruction cannot be duplicated");
346   return MF.CloneMachineInstr(Orig);
347 }
348
349 // If the COPY instruction in MI can be folded to a stack operation, return
350 // the register class to use.
351 static const TargetRegisterClass *canFoldCopy(const MachineInstr *MI,
352                                               unsigned FoldIdx) {
353   assert(MI->isCopy() && "MI must be a COPY instruction");
354   if (MI->getNumOperands() != 2)
355     return nullptr;
356   assert(FoldIdx<2 && "FoldIdx refers no nonexistent operand");
357
358   const MachineOperand &FoldOp = MI->getOperand(FoldIdx);
359   const MachineOperand &LiveOp = MI->getOperand(1-FoldIdx);
360
361   if (FoldOp.getSubReg() || LiveOp.getSubReg())
362     return nullptr;
363
364   unsigned FoldReg = FoldOp.getReg();
365   unsigned LiveReg = LiveOp.getReg();
366
367   assert(TargetRegisterInfo::isVirtualRegister(FoldReg) &&
368          "Cannot fold physregs");
369
370   const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
371   const TargetRegisterClass *RC = MRI.getRegClass(FoldReg);
372
373   if (TargetRegisterInfo::isPhysicalRegister(LiveOp.getReg()))
374     return RC->contains(LiveOp.getReg()) ? RC : nullptr;
375
376   if (RC->hasSubClassEq(MRI.getRegClass(LiveReg)))
377     return RC;
378
379   // FIXME: Allow folding when register classes are memory compatible.
380   return nullptr;
381 }
382
383 void TargetInstrInfo::getNoopForMachoTarget(MCInst &NopInst) const {
384   llvm_unreachable("Not a MachO target");
385 }
386
387 bool TargetInstrInfo::canFoldMemoryOperand(const MachineInstr *MI,
388                                            ArrayRef<unsigned> Ops) const {
389   return MI->isCopy() && Ops.size() == 1 && canFoldCopy(MI, Ops[0]);
390 }
391
392 static MachineInstr *foldPatchpoint(MachineFunction &MF, MachineInstr *MI,
393                                     ArrayRef<unsigned> Ops, int FrameIndex,
394                                     const TargetInstrInfo &TII) {
395   unsigned StartIdx = 0;
396   switch (MI->getOpcode()) {
397   case TargetOpcode::STACKMAP:
398     StartIdx = 2; // Skip ID, nShadowBytes.
399     break;
400   case TargetOpcode::PATCHPOINT: {
401     // For PatchPoint, the call args are not foldable.
402     PatchPointOpers opers(MI);
403     StartIdx = opers.getVarIdx();
404     break;
405   }
406   default:
407     llvm_unreachable("unexpected stackmap opcode");
408   }
409
410   // Return false if any operands requested for folding are not foldable (not
411   // part of the stackmap's live values).
412   for (unsigned Op : Ops) {
413     if (Op < StartIdx)
414       return nullptr;
415   }
416
417   MachineInstr *NewMI =
418     MF.CreateMachineInstr(TII.get(MI->getOpcode()), MI->getDebugLoc(), true);
419   MachineInstrBuilder MIB(MF, NewMI);
420
421   // No need to fold return, the meta data, and function arguments
422   for (unsigned i = 0; i < StartIdx; ++i)
423     MIB.addOperand(MI->getOperand(i));
424
425   for (unsigned i = StartIdx; i < MI->getNumOperands(); ++i) {
426     MachineOperand &MO = MI->getOperand(i);
427     if (std::find(Ops.begin(), Ops.end(), i) != Ops.end()) {
428       unsigned SpillSize;
429       unsigned SpillOffset;
430       // Compute the spill slot size and offset.
431       const TargetRegisterClass *RC =
432         MF.getRegInfo().getRegClass(MO.getReg());
433       bool Valid =
434           TII.getStackSlotRange(RC, MO.getSubReg(), SpillSize, SpillOffset, MF);
435       if (!Valid)
436         report_fatal_error("cannot spill patchpoint subregister operand");
437       MIB.addImm(StackMaps::IndirectMemRefOp);
438       MIB.addImm(SpillSize);
439       MIB.addFrameIndex(FrameIndex);
440       MIB.addImm(SpillOffset);
441     }
442     else
443       MIB.addOperand(MO);
444   }
445   return NewMI;
446 }
447
448 /// foldMemoryOperand - Attempt to fold a load or store of the specified stack
449 /// slot into the specified machine instruction for the specified operand(s).
450 /// If this is possible, a new instruction is returned with the specified
451 /// operand folded, otherwise NULL is returned. The client is responsible for
452 /// removing the old instruction and adding the new one in the instruction
453 /// stream.
454 MachineInstr *TargetInstrInfo::foldMemoryOperand(MachineBasicBlock::iterator MI,
455                                                  ArrayRef<unsigned> Ops,
456                                                  int FI) const {
457   unsigned Flags = 0;
458   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
459     if (MI->getOperand(Ops[i]).isDef())
460       Flags |= MachineMemOperand::MOStore;
461     else
462       Flags |= MachineMemOperand::MOLoad;
463
464   MachineBasicBlock *MBB = MI->getParent();
465   assert(MBB && "foldMemoryOperand needs an inserted instruction");
466   MachineFunction &MF = *MBB->getParent();
467
468   MachineInstr *NewMI = nullptr;
469
470   if (MI->getOpcode() == TargetOpcode::STACKMAP ||
471       MI->getOpcode() == TargetOpcode::PATCHPOINT) {
472     // Fold stackmap/patchpoint.
473     NewMI = foldPatchpoint(MF, MI, Ops, FI, *this);
474   } else {
475     // Ask the target to do the actual folding.
476     NewMI =foldMemoryOperandImpl(MF, MI, Ops, FI);
477   }
478  
479   if (NewMI) {
480     NewMI->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
481     // Add a memory operand, foldMemoryOperandImpl doesn't do that.
482     assert((!(Flags & MachineMemOperand::MOStore) ||
483             NewMI->mayStore()) &&
484            "Folded a def to a non-store!");
485     assert((!(Flags & MachineMemOperand::MOLoad) ||
486             NewMI->mayLoad()) &&
487            "Folded a use to a non-load!");
488     const MachineFrameInfo &MFI = *MF.getFrameInfo();
489     assert(MFI.getObjectOffset(FI) != -1);
490     MachineMemOperand *MMO =
491       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
492                               Flags, MFI.getObjectSize(FI),
493                               MFI.getObjectAlignment(FI));
494     NewMI->addMemOperand(MF, MMO);
495
496     // FIXME: change foldMemoryOperandImpl semantics to also insert NewMI.
497     return MBB->insert(MI, NewMI);
498   }
499
500   // Straight COPY may fold as load/store.
501   if (!MI->isCopy() || Ops.size() != 1)
502     return nullptr;
503
504   const TargetRegisterClass *RC = canFoldCopy(MI, Ops[0]);
505   if (!RC)
506     return nullptr;
507
508   const MachineOperand &MO = MI->getOperand(1-Ops[0]);
509   MachineBasicBlock::iterator Pos = MI;
510   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
511
512   if (Flags == MachineMemOperand::MOStore)
513     storeRegToStackSlot(*MBB, Pos, MO.getReg(), MO.isKill(), FI, RC, TRI);
514   else
515     loadRegFromStackSlot(*MBB, Pos, MO.getReg(), FI, RC, TRI);
516   return --Pos;
517 }
518
519 /// foldMemoryOperand - Same as the previous version except it allows folding
520 /// of any load and store from / to any address, not just from a specific
521 /// stack slot.
522 MachineInstr *TargetInstrInfo::foldMemoryOperand(MachineBasicBlock::iterator MI,
523                                                  ArrayRef<unsigned> Ops,
524                                                  MachineInstr *LoadMI) const {
525   assert(LoadMI->canFoldAsLoad() && "LoadMI isn't foldable!");
526 #ifndef NDEBUG
527   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
528     assert(MI->getOperand(Ops[i]).isUse() && "Folding load into def!");
529 #endif
530   MachineBasicBlock &MBB = *MI->getParent();
531   MachineFunction &MF = *MBB.getParent();
532
533   // Ask the target to do the actual folding.
534   MachineInstr *NewMI = nullptr;
535   int FrameIndex = 0;
536
537   if ((MI->getOpcode() == TargetOpcode::STACKMAP ||
538        MI->getOpcode() == TargetOpcode::PATCHPOINT) &&
539       isLoadFromStackSlot(LoadMI, FrameIndex)) {
540     // Fold stackmap/patchpoint.
541     NewMI = foldPatchpoint(MF, MI, Ops, FrameIndex, *this);
542   } else {
543     // Ask the target to do the actual folding.
544     NewMI = foldMemoryOperandImpl(MF, MI, Ops, LoadMI);
545   }
546
547   if (!NewMI) return nullptr;
548
549   NewMI = MBB.insert(MI, NewMI);
550
551   // Copy the memoperands from the load to the folded instruction.
552   if (MI->memoperands_empty()) {
553     NewMI->setMemRefs(LoadMI->memoperands_begin(),
554                       LoadMI->memoperands_end());
555   }
556   else {
557     // Handle the rare case of folding multiple loads.
558     NewMI->setMemRefs(MI->memoperands_begin(),
559                       MI->memoperands_end());
560     for (MachineInstr::mmo_iterator I = LoadMI->memoperands_begin(),
561            E = LoadMI->memoperands_end(); I != E; ++I) {
562       NewMI->addMemOperand(MF, *I);
563     }
564   }
565   return NewMI;
566 }
567
568 bool TargetInstrInfo::
569 isReallyTriviallyReMaterializableGeneric(const MachineInstr *MI,
570                                          AliasAnalysis *AA) const {
571   const MachineFunction &MF = *MI->getParent()->getParent();
572   const MachineRegisterInfo &MRI = MF.getRegInfo();
573
574   // Remat clients assume operand 0 is the defined register.
575   if (!MI->getNumOperands() || !MI->getOperand(0).isReg())
576     return false;
577   unsigned DefReg = MI->getOperand(0).getReg();
578
579   // A sub-register definition can only be rematerialized if the instruction
580   // doesn't read the other parts of the register.  Otherwise it is really a
581   // read-modify-write operation on the full virtual register which cannot be
582   // moved safely.
583   if (TargetRegisterInfo::isVirtualRegister(DefReg) &&
584       MI->getOperand(0).getSubReg() && MI->readsVirtualRegister(DefReg))
585     return false;
586
587   // A load from a fixed stack slot can be rematerialized. This may be
588   // redundant with subsequent checks, but it's target-independent,
589   // simple, and a common case.
590   int FrameIdx = 0;
591   if (isLoadFromStackSlot(MI, FrameIdx) &&
592       MF.getFrameInfo()->isImmutableObjectIndex(FrameIdx))
593     return true;
594
595   // Avoid instructions obviously unsafe for remat.
596   if (MI->isNotDuplicable() || MI->mayStore() ||
597       MI->hasUnmodeledSideEffects())
598     return false;
599
600   // Don't remat inline asm. We have no idea how expensive it is
601   // even if it's side effect free.
602   if (MI->isInlineAsm())
603     return false;
604
605   // Avoid instructions which load from potentially varying memory.
606   if (MI->mayLoad() && !MI->isInvariantLoad(AA))
607     return false;
608
609   // If any of the registers accessed are non-constant, conservatively assume
610   // the instruction is not rematerializable.
611   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
612     const MachineOperand &MO = MI->getOperand(i);
613     if (!MO.isReg()) continue;
614     unsigned Reg = MO.getReg();
615     if (Reg == 0)
616       continue;
617
618     // Check for a well-behaved physical register.
619     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
620       if (MO.isUse()) {
621         // If the physreg has no defs anywhere, it's just an ambient register
622         // and we can freely move its uses. Alternatively, if it's allocatable,
623         // it could get allocated to something with a def during allocation.
624         if (!MRI.isConstantPhysReg(Reg, MF))
625           return false;
626       } else {
627         // A physreg def. We can't remat it.
628         return false;
629       }
630       continue;
631     }
632
633     // Only allow one virtual-register def.  There may be multiple defs of the
634     // same virtual register, though.
635     if (MO.isDef() && Reg != DefReg)
636       return false;
637
638     // Don't allow any virtual-register uses. Rematting an instruction with
639     // virtual register uses would length the live ranges of the uses, which
640     // is not necessarily a good idea, certainly not "trivial".
641     if (MO.isUse())
642       return false;
643   }
644
645   // Everything checked out.
646   return true;
647 }
648
649 int TargetInstrInfo::getSPAdjust(const MachineInstr *MI) const {
650   const MachineFunction *MF = MI->getParent()->getParent();
651   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
652   bool StackGrowsDown =
653     TFI->getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
654
655   int FrameSetupOpcode = getCallFrameSetupOpcode();
656   int FrameDestroyOpcode = getCallFrameDestroyOpcode();
657
658   if (MI->getOpcode() != FrameSetupOpcode &&
659       MI->getOpcode() != FrameDestroyOpcode)
660     return 0;
661  
662   int SPAdj = MI->getOperand(0).getImm();
663
664   if ((!StackGrowsDown && MI->getOpcode() == FrameSetupOpcode) ||
665        (StackGrowsDown && MI->getOpcode() == FrameDestroyOpcode))
666     SPAdj = -SPAdj;
667
668   return SPAdj;
669 }
670
671 /// isSchedulingBoundary - Test if the given instruction should be
672 /// considered a scheduling boundary. This primarily includes labels
673 /// and terminators.
674 bool TargetInstrInfo::isSchedulingBoundary(const MachineInstr *MI,
675                                            const MachineBasicBlock *MBB,
676                                            const MachineFunction &MF) const {
677   // Terminators and labels can't be scheduled around.
678   if (MI->isTerminator() || MI->isPosition())
679     return true;
680
681   // Don't attempt to schedule around any instruction that defines
682   // a stack-oriented pointer, as it's unlikely to be profitable. This
683   // saves compile time, because it doesn't require every single
684   // stack slot reference to depend on the instruction that does the
685   // modification.
686   const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering();
687   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
688   if (MI->modifiesRegister(TLI.getStackPointerRegisterToSaveRestore(), TRI))
689     return true;
690
691   return false;
692 }
693
694 // Provide a global flag for disabling the PreRA hazard recognizer that targets
695 // may choose to honor.
696 bool TargetInstrInfo::usePreRAHazardRecognizer() const {
697   return !DisableHazardRecognizer;
698 }
699
700 // Default implementation of CreateTargetRAHazardRecognizer.
701 ScheduleHazardRecognizer *TargetInstrInfo::
702 CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
703                              const ScheduleDAG *DAG) const {
704   // Dummy hazard recognizer allows all instructions to issue.
705   return new ScheduleHazardRecognizer();
706 }
707
708 // Default implementation of CreateTargetMIHazardRecognizer.
709 ScheduleHazardRecognizer *TargetInstrInfo::
710 CreateTargetMIHazardRecognizer(const InstrItineraryData *II,
711                                const ScheduleDAG *DAG) const {
712   return (ScheduleHazardRecognizer *)
713     new ScoreboardHazardRecognizer(II, DAG, "misched");
714 }
715
716 // Default implementation of CreateTargetPostRAHazardRecognizer.
717 ScheduleHazardRecognizer *TargetInstrInfo::
718 CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
719                                    const ScheduleDAG *DAG) const {
720   return (ScheduleHazardRecognizer *)
721     new ScoreboardHazardRecognizer(II, DAG, "post-RA-sched");
722 }
723
724 //===----------------------------------------------------------------------===//
725 //  SelectionDAG latency interface.
726 //===----------------------------------------------------------------------===//
727
728 int
729 TargetInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
730                                    SDNode *DefNode, unsigned DefIdx,
731                                    SDNode *UseNode, unsigned UseIdx) const {
732   if (!ItinData || ItinData->isEmpty())
733     return -1;
734
735   if (!DefNode->isMachineOpcode())
736     return -1;
737
738   unsigned DefClass = get(DefNode->getMachineOpcode()).getSchedClass();
739   if (!UseNode->isMachineOpcode())
740     return ItinData->getOperandCycle(DefClass, DefIdx);
741   unsigned UseClass = get(UseNode->getMachineOpcode()).getSchedClass();
742   return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
743 }
744
745 int TargetInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
746                                      SDNode *N) const {
747   if (!ItinData || ItinData->isEmpty())
748     return 1;
749
750   if (!N->isMachineOpcode())
751     return 1;
752
753   return ItinData->getStageLatency(get(N->getMachineOpcode()).getSchedClass());
754 }
755
756 //===----------------------------------------------------------------------===//
757 //  MachineInstr latency interface.
758 //===----------------------------------------------------------------------===//
759
760 unsigned
761 TargetInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData,
762                                 const MachineInstr *MI) const {
763   if (!ItinData || ItinData->isEmpty())
764     return 1;
765
766   unsigned Class = MI->getDesc().getSchedClass();
767   int UOps = ItinData->Itineraries[Class].NumMicroOps;
768   if (UOps >= 0)
769     return UOps;
770
771   // The # of u-ops is dynamically determined. The specific target should
772   // override this function to return the right number.
773   return 1;
774 }
775
776 /// Return the default expected latency for a def based on it's opcode.
777 unsigned TargetInstrInfo::defaultDefLatency(const MCSchedModel &SchedModel,
778                                             const MachineInstr *DefMI) const {
779   if (DefMI->isTransient())
780     return 0;
781   if (DefMI->mayLoad())
782     return SchedModel.LoadLatency;
783   if (isHighLatencyDef(DefMI->getOpcode()))
784     return SchedModel.HighLatency;
785   return 1;
786 }
787
788 unsigned TargetInstrInfo::getPredicationCost(const MachineInstr *) const {
789   return 0;
790 }
791
792 unsigned TargetInstrInfo::
793 getInstrLatency(const InstrItineraryData *ItinData,
794                 const MachineInstr *MI,
795                 unsigned *PredCost) const {
796   // Default to one cycle for no itinerary. However, an "empty" itinerary may
797   // still have a MinLatency property, which getStageLatency checks.
798   if (!ItinData)
799     return MI->mayLoad() ? 2 : 1;
800
801   return ItinData->getStageLatency(MI->getDesc().getSchedClass());
802 }
803
804 bool TargetInstrInfo::hasLowDefLatency(const InstrItineraryData *ItinData,
805                                        const MachineInstr *DefMI,
806                                        unsigned DefIdx) const {
807   if (!ItinData || ItinData->isEmpty())
808     return false;
809
810   unsigned DefClass = DefMI->getDesc().getSchedClass();
811   int DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
812   return (DefCycle != -1 && DefCycle <= 1);
813 }
814
815 /// Both DefMI and UseMI must be valid.  By default, call directly to the
816 /// itinerary. This may be overriden by the target.
817 int TargetInstrInfo::
818 getOperandLatency(const InstrItineraryData *ItinData,
819                   const MachineInstr *DefMI, unsigned DefIdx,
820                   const MachineInstr *UseMI, unsigned UseIdx) const {
821   unsigned DefClass = DefMI->getDesc().getSchedClass();
822   unsigned UseClass = UseMI->getDesc().getSchedClass();
823   return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
824 }
825
826 /// If we can determine the operand latency from the def only, without itinerary
827 /// lookup, do so. Otherwise return -1.
828 int TargetInstrInfo::computeDefOperandLatency(
829   const InstrItineraryData *ItinData,
830   const MachineInstr *DefMI) const {
831
832   // Let the target hook getInstrLatency handle missing itineraries.
833   if (!ItinData)
834     return getInstrLatency(ItinData, DefMI);
835
836   if(ItinData->isEmpty())
837     return defaultDefLatency(ItinData->SchedModel, DefMI);
838
839   // ...operand lookup required
840   return -1;
841 }
842
843 /// computeOperandLatency - Compute and return the latency of the given data
844 /// dependent def and use when the operand indices are already known. UseMI may
845 /// be NULL for an unknown use.
846 ///
847 /// FindMin may be set to get the minimum vs. expected latency. Minimum
848 /// latency is used for scheduling groups, while expected latency is for
849 /// instruction cost and critical path.
850 ///
851 /// Depending on the subtarget's itinerary properties, this may or may not need
852 /// to call getOperandLatency(). For most subtargets, we don't need DefIdx or
853 /// UseIdx to compute min latency.
854 unsigned TargetInstrInfo::
855 computeOperandLatency(const InstrItineraryData *ItinData,
856                       const MachineInstr *DefMI, unsigned DefIdx,
857                       const MachineInstr *UseMI, unsigned UseIdx) const {
858
859   int DefLatency = computeDefOperandLatency(ItinData, DefMI);
860   if (DefLatency >= 0)
861     return DefLatency;
862
863   assert(ItinData && !ItinData->isEmpty() && "computeDefOperandLatency fail");
864
865   int OperLatency = 0;
866   if (UseMI)
867     OperLatency = getOperandLatency(ItinData, DefMI, DefIdx, UseMI, UseIdx);
868   else {
869     unsigned DefClass = DefMI->getDesc().getSchedClass();
870     OperLatency = ItinData->getOperandCycle(DefClass, DefIdx);
871   }
872   if (OperLatency >= 0)
873     return OperLatency;
874
875   // No operand latency was found.
876   unsigned InstrLatency = getInstrLatency(ItinData, DefMI);
877
878   // Expected latency is the max of the stage latency and itinerary props.
879   InstrLatency = std::max(InstrLatency,
880                           defaultDefLatency(ItinData->SchedModel, DefMI));
881   return InstrLatency;
882 }
883
884 bool TargetInstrInfo::getRegSequenceInputs(
885     const MachineInstr &MI, unsigned DefIdx,
886     SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const {
887   assert((MI.isRegSequence() ||
888           MI.isRegSequenceLike()) && "Instruction do not have the proper type");
889
890   if (!MI.isRegSequence())
891     return getRegSequenceLikeInputs(MI, DefIdx, InputRegs);
892
893   // We are looking at:
894   // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
895   assert(DefIdx == 0 && "REG_SEQUENCE only has one def");
896   for (unsigned OpIdx = 1, EndOpIdx = MI.getNumOperands(); OpIdx != EndOpIdx;
897        OpIdx += 2) {
898     const MachineOperand &MOReg = MI.getOperand(OpIdx);
899     const MachineOperand &MOSubIdx = MI.getOperand(OpIdx + 1);
900     assert(MOSubIdx.isImm() &&
901            "One of the subindex of the reg_sequence is not an immediate");
902     // Record Reg:SubReg, SubIdx.
903     InputRegs.push_back(RegSubRegPairAndIdx(MOReg.getReg(), MOReg.getSubReg(),
904                                             (unsigned)MOSubIdx.getImm()));
905   }
906   return true;
907 }
908
909 bool TargetInstrInfo::getExtractSubregInputs(
910     const MachineInstr &MI, unsigned DefIdx,
911     RegSubRegPairAndIdx &InputReg) const {
912   assert((MI.isExtractSubreg() ||
913       MI.isExtractSubregLike()) && "Instruction do not have the proper type");
914
915   if (!MI.isExtractSubreg())
916     return getExtractSubregLikeInputs(MI, DefIdx, InputReg);
917
918   // We are looking at:
919   // Def = EXTRACT_SUBREG v0.sub1, sub0.
920   assert(DefIdx == 0 && "EXTRACT_SUBREG only has one def");
921   const MachineOperand &MOReg = MI.getOperand(1);
922   const MachineOperand &MOSubIdx = MI.getOperand(2);
923   assert(MOSubIdx.isImm() &&
924          "The subindex of the extract_subreg is not an immediate");
925
926   InputReg.Reg = MOReg.getReg();
927   InputReg.SubReg = MOReg.getSubReg();
928   InputReg.SubIdx = (unsigned)MOSubIdx.getImm();
929   return true;
930 }
931
932 bool TargetInstrInfo::getInsertSubregInputs(
933     const MachineInstr &MI, unsigned DefIdx,
934     RegSubRegPair &BaseReg, RegSubRegPairAndIdx &InsertedReg) const {
935   assert((MI.isInsertSubreg() ||
936       MI.isInsertSubregLike()) && "Instruction do not have the proper type");
937
938   if (!MI.isInsertSubreg())
939     return getInsertSubregLikeInputs(MI, DefIdx, BaseReg, InsertedReg);
940
941   // We are looking at:
942   // Def = INSERT_SEQUENCE v0, v1, sub0.
943   assert(DefIdx == 0 && "INSERT_SUBREG only has one def");
944   const MachineOperand &MOBaseReg = MI.getOperand(1);
945   const MachineOperand &MOInsertedReg = MI.getOperand(2);
946   const MachineOperand &MOSubIdx = MI.getOperand(3);
947   assert(MOSubIdx.isImm() &&
948          "One of the subindex of the reg_sequence is not an immediate");
949   BaseReg.Reg = MOBaseReg.getReg();
950   BaseReg.SubReg = MOBaseReg.getSubReg();
951
952   InsertedReg.Reg = MOInsertedReg.getReg();
953   InsertedReg.SubReg = MOInsertedReg.getSubReg();
954   InsertedReg.SubIdx = (unsigned)MOSubIdx.getImm();
955   return true;
956 }