misched: Use the TargetSchedModel interface wherever possible.
[oota-llvm.git] / lib / CodeGen / TargetSchedule.cpp
1 //===-- llvm/Target/TargetSchedule.cpp - Sched Machine Model ----*- C++ -*-===//
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 a wrapper around MCSchedModel that allows the interface
11 // to benefit from information currently only available in TargetInstrInfo.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/CodeGen/TargetSchedule.h"
16 #include "llvm/Target/TargetInstrInfo.h"
17 #include "llvm/Target/TargetMachine.h"
18 #include "llvm/Target/TargetRegisterInfo.h"
19 #include "llvm/Target/TargetSubtargetInfo.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/raw_ostream.h"
22
23 using namespace llvm;
24
25 static cl::opt<bool> EnableSchedModel("schedmodel", cl::Hidden, cl::init(true),
26   cl::desc("Use TargetSchedModel for latency lookup"));
27
28 static cl::opt<bool> EnableSchedItins("scheditins", cl::Hidden, cl::init(true),
29   cl::desc("Use InstrItineraryData for latency lookup"));
30
31 bool TargetSchedModel::hasInstrSchedModel() const {
32   return EnableSchedModel && SchedModel.hasInstrSchedModel();
33 }
34
35 bool TargetSchedModel::hasInstrItineraries() const {
36   return EnableSchedItins && !InstrItins.isEmpty();
37 }
38
39 void TargetSchedModel::init(const MCSchedModel &sm,
40                             const TargetSubtargetInfo *sti,
41                             const TargetInstrInfo *tii) {
42   SchedModel = sm;
43   STI = sti;
44   TII = tii;
45   STI->initInstrItins(InstrItins);
46 }
47
48 unsigned TargetSchedModel::getNumMicroOps(MachineInstr *MI) const {
49   if (hasInstrItineraries()) {
50     int UOps = InstrItins.getNumMicroOps(MI->getDesc().getSchedClass());
51     return (UOps >= 0) ? UOps : TII->getNumMicroOps(&InstrItins, MI);
52   }
53   if (hasInstrSchedModel())
54     return resolveSchedClass(MI)->NumMicroOps;
55
56   return 1;
57 }
58
59 /// If we can determine the operand latency from the def only, without machine
60 /// model or itinerary lookup, do so. Otherwise return -1.
61 int TargetSchedModel::getDefLatency(const MachineInstr *DefMI,
62                                     bool FindMin) const {
63
64   // Return a latency based on the itinerary properties and defining instruction
65   // if possible. Some common subtargets don't require per-operand latency,
66   // especially for minimum latencies.
67   if (FindMin) {
68     // If MinLatency is invalid, then use the itinerary for MinLatency. If no
69     // itinerary exists either, then use single cycle latency.
70     if (SchedModel.MinLatency < 0 && !hasInstrItineraries()) {
71       return 1;
72     }
73     return SchedModel.MinLatency;
74   }
75   else if (!hasInstrSchedModel() && !hasInstrItineraries()) {
76     return TII->defaultDefLatency(&SchedModel, DefMI);
77   }
78   // ...operand lookup required
79   return -1;
80 }
81
82 /// Return the MCSchedClassDesc for this instruction. Some SchedClasses require
83 /// evaluation of predicates that depend on instruction operands or flags.
84 const MCSchedClassDesc *TargetSchedModel::
85 resolveSchedClass(const MachineInstr *MI) const {
86
87   // Get the definition's scheduling class descriptor from this machine model.
88   unsigned SchedClass = MI->getDesc().getSchedClass();
89   const MCSchedClassDesc *SCDesc = SchedModel.getSchedClassDesc(SchedClass);
90
91 #ifndef NDEBUG
92   unsigned NIter = 0;
93 #endif
94   while (SCDesc->isVariant()) {
95     assert(++NIter < 6 && "Variants are nested deeper than the magic number");
96
97     SchedClass = STI->resolveSchedClass(SchedClass, MI, this);
98     SCDesc = SchedModel.getSchedClassDesc(SchedClass);
99   }
100   return SCDesc;
101 }
102
103 /// Find the def index of this operand. This index maps to the machine model and
104 /// is independent of use operands. Def operands may be reordered with uses or
105 /// merged with uses without affecting the def index (e.g. before/after
106 /// regalloc). However, an instruction's def operands must never be reordered
107 /// with respect to each other.
108 static unsigned findDefIdx(const MachineInstr *MI, unsigned DefOperIdx) {
109   unsigned DefIdx = 0;
110   for (unsigned i = 0; i != DefOperIdx; ++i) {
111     const MachineOperand &MO = MI->getOperand(i);
112     if (MO.isReg() && MO.isDef())
113       ++DefIdx;
114   }
115   return DefIdx;
116 }
117
118 /// Find the use index of this operand. This is independent of the instruction's
119 /// def operands.
120 ///
121 /// Note that uses are not determined by the operand's isUse property, which
122 /// is simply the inverse of isDef. Here we consider any readsReg operand to be
123 /// a "use". The machine model allows an operand to be both a Def and Use.
124 static unsigned findUseIdx(const MachineInstr *MI, unsigned UseOperIdx) {
125   unsigned UseIdx = 0;
126   for (unsigned i = 0; i != UseOperIdx; ++i) {
127     const MachineOperand &MO = MI->getOperand(i);
128     if (MO.isReg() && MO.readsReg())
129       ++UseIdx;
130   }
131   return UseIdx;
132 }
133
134 // Top-level API for clients that know the operand indices.
135 unsigned TargetSchedModel::computeOperandLatency(
136   const MachineInstr *DefMI, unsigned DefOperIdx,
137   const MachineInstr *UseMI, unsigned UseOperIdx,
138   bool FindMin) const {
139
140   int DefLatency = getDefLatency(DefMI, FindMin);
141   if (DefLatency >= 0)
142     return DefLatency;
143
144   if (hasInstrItineraries()) {
145     int OperLatency = 0;
146     if (UseMI) {
147       OperLatency =
148         TII->getOperandLatency(&InstrItins, DefMI, DefOperIdx, UseMI, UseOperIdx);
149     }
150     else {
151       unsigned DefClass = DefMI->getDesc().getSchedClass();
152       OperLatency = InstrItins.getOperandCycle(DefClass, DefOperIdx);
153     }
154     if (OperLatency >= 0)
155       return OperLatency;
156
157     // No operand latency was found.
158     unsigned InstrLatency = TII->getInstrLatency(&InstrItins, DefMI);
159
160     // Expected latency is the max of the stage latency and itinerary props.
161     // Rather than directly querying InstrItins stage latency, we call a TII
162     // hook to allow subtargets to specialize latency. This hook is only
163     // applicable to the InstrItins model. InstrSchedModel should model all
164     // special cases without TII hooks.
165     if (!FindMin)
166       InstrLatency = std::max(InstrLatency,
167                               TII->defaultDefLatency(&SchedModel, DefMI));
168     return InstrLatency;
169   }
170   assert(!FindMin && hasInstrSchedModel() &&
171          "Expected a SchedModel for this cpu");
172   const MCSchedClassDesc *SCDesc = resolveSchedClass(DefMI);
173   unsigned DefIdx = findDefIdx(DefMI, DefOperIdx);
174   if (DefIdx < SCDesc->NumWriteLatencyEntries) {
175     // Lookup the definition's write latency in SubtargetInfo.
176     const MCWriteLatencyEntry *WLEntry =
177       STI->getWriteLatencyEntry(SCDesc, DefIdx);
178     unsigned WriteID = WLEntry->WriteResourceID;
179     unsigned Latency = WLEntry->Cycles;
180     if (!UseMI)
181       return Latency;
182
183     // Lookup the use's latency adjustment in SubtargetInfo.
184     const MCSchedClassDesc *UseDesc = resolveSchedClass(UseMI);
185     if (UseDesc->NumReadAdvanceEntries == 0)
186       return Latency;
187     unsigned UseIdx = findUseIdx(UseMI, UseOperIdx);
188     return Latency - STI->getReadAdvanceCycles(UseDesc, UseIdx, WriteID);
189   }
190   // If DefIdx does not exist in the model (e.g. implicit defs), then return
191   // unit latency (defaultDefLatency may be too conservative).
192 #ifndef NDEBUG
193   if (SCDesc->isValid() && !DefMI->getOperand(DefOperIdx).isImplicit()
194       && !DefMI->getDesc().OpInfo[DefOperIdx].isOptionalDef()) {
195     std::string Err;
196     raw_string_ostream ss(Err);
197     ss << "DefIdx " << DefIdx << " exceeds machine model writes for "
198        << *DefMI;
199     report_fatal_error(ss.str());
200   }
201 #endif
202   return 1;
203 }
204
205 unsigned TargetSchedModel::computeInstrLatency(const MachineInstr *MI) const {
206   if (hasInstrItineraries()) {
207     // For the itinerary model, fall back to the old subtarget hook.
208     return TII->getInstrLatency(&InstrItins, MI);
209   }
210   if (hasInstrSchedModel()) {
211     unsigned Latency = 0;
212     const MCSchedClassDesc *SCDesc = resolveSchedClass(MI);
213     for (unsigned DefIdx = 0, DefEnd = SCDesc->NumWriteLatencyEntries;
214          DefIdx != DefEnd; ++DefIdx) {
215       // Lookup the definition's write latency in SubtargetInfo.
216       const MCWriteLatencyEntry *WLEntry =
217         STI->getWriteLatencyEntry(SCDesc, DefIdx);
218       Latency = std::max(Latency, WLEntry->Cycles);
219     }
220     return Latency;
221   }
222   return TII->defaultDefLatency(&SchedModel, MI);
223 }
224
225 unsigned TargetSchedModel::
226 computeOutputLatency(const MachineInstr *DefMI, unsigned DefOperIdx,
227                      const MachineInstr *DepMI) const {
228   // MinLatency == -1 is for in-order processors that always have unit
229   // MinLatency. MinLatency > 0 is for in-order processors with varying min
230   // latencies, but since this is not a RAW dep, we always use unit latency.
231   if (SchedModel.MinLatency != 0)
232     return 1;
233
234   // MinLatency == 0 indicates an out-of-order processor that can dispatch
235   // WAW dependencies in the same cycle.
236
237   // Treat predication as a data dependency for out-of-order cpus. In-order
238   // cpus do not need to treat predicated writes specially.
239   //
240   // TODO: The following hack exists because predication passes do not
241   // correctly append imp-use operands, and readsReg() strangely returns false
242   // for predicated defs.
243   unsigned Reg = DefMI->getOperand(DefOperIdx).getReg();
244   const MachineFunction &MF = *DefMI->getParent()->getParent();
245   const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
246   if (!DepMI->readsRegister(Reg, TRI) && TII->isPredicated(DepMI))
247     return computeInstrLatency(DefMI);
248
249   // If we have a per operand scheduling model, check if this def is writing
250   // an unbuffered resource. If so, it treated like an in-order cpu.
251   if (hasInstrSchedModel()) {
252     const MCSchedClassDesc *SCDesc = resolveSchedClass(DefMI);
253     for (const MCWriteProcResEntry *PRI = STI->getWriteProcResBegin(SCDesc),
254            *PRE = STI->getWriteProcResEnd(SCDesc); PRI != PRE; ++PRI) {
255       if (!SchedModel.getProcResource(PRI->ProcResourceIdx)->IsBuffered)
256         return 1;
257     }
258   }
259   return 0;
260 }