Chain dependencies used to enforce memory order should have latency of 0 (except...
[oota-llvm.git] / lib / CodeGen / ScheduleDAGInstrs.cpp
1 //===---- ScheduleDAGInstrs.cpp - MachineInstr Rescheduling ---------------===//
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 implements the ScheduleDAGInstrs class, which implements re-scheduling
11 // of MachineInstrs.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "sched-instrs"
16 #include "ScheduleDAGInstrs.h"
17 #include "llvm/Operator.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/CodeGen/MachineMemOperand.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/PseudoSourceValue.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Target/TargetRegisterInfo.h"
26 #include "llvm/Target/TargetSubtarget.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/ADT/SmallSet.h"
30 using namespace llvm;
31
32 ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
33                                      const MachineLoopInfo &mli,
34                                      const MachineDominatorTree &mdt)
35   : ScheduleDAG(mf), MLI(mli), MDT(mdt), LoopRegs(MLI, MDT) {
36   MFI = mf.getFrameInfo();
37 }
38
39 /// Run - perform scheduling.
40 ///
41 void ScheduleDAGInstrs::Run(MachineBasicBlock *bb,
42                             MachineBasicBlock::iterator begin,
43                             MachineBasicBlock::iterator end,
44                             unsigned endcount) {
45   BB = bb;
46   Begin = begin;
47   InsertPosIndex = endcount;
48
49   ScheduleDAG::Run(bb, end);
50 }
51
52 /// getUnderlyingObjectFromInt - This is the function that does the work of
53 /// looking through basic ptrtoint+arithmetic+inttoptr sequences.
54 static const Value *getUnderlyingObjectFromInt(const Value *V) {
55   do {
56     if (const Operator *U = dyn_cast<Operator>(V)) {
57       // If we find a ptrtoint, we can transfer control back to the
58       // regular getUnderlyingObjectFromInt.
59       if (U->getOpcode() == Instruction::PtrToInt)
60         return U->getOperand(0);
61       // If we find an add of a constant or a multiplied value, it's
62       // likely that the other operand will lead us to the base
63       // object. We don't have to worry about the case where the
64       // object address is somehow being computed by the multiply,
65       // because our callers only care when the result is an
66       // identifibale object.
67       if (U->getOpcode() != Instruction::Add ||
68           (!isa<ConstantInt>(U->getOperand(1)) &&
69            Operator::getOpcode(U->getOperand(1)) != Instruction::Mul))
70         return V;
71       V = U->getOperand(0);
72     } else {
73       return V;
74     }
75     assert(isa<IntegerType>(V->getType()) && "Unexpected operand type!");
76   } while (1);
77 }
78
79 /// getUnderlyingObject - This is a wrapper around Value::getUnderlyingObject
80 /// and adds support for basic ptrtoint+arithmetic+inttoptr sequences.
81 static const Value *getUnderlyingObject(const Value *V) {
82   // First just call Value::getUnderlyingObject to let it do what it does.
83   do {
84     V = V->getUnderlyingObject();
85     // If it found an inttoptr, use special code to continue climing.
86     if (Operator::getOpcode(V) != Instruction::IntToPtr)
87       break;
88     const Value *O = getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
89     // If that succeeded in finding a pointer, continue the search.
90     if (!isa<PointerType>(O->getType()))
91       break;
92     V = O;
93   } while (1);
94   return V;
95 }
96
97 /// getUnderlyingObjectForInstr - If this machine instr has memory reference
98 /// information and it can be tracked to a normal reference to a known
99 /// object, return the Value for that object. Otherwise return null.
100 static const Value *getUnderlyingObjectForInstr(const MachineInstr *MI,
101                                                 const MachineFrameInfo *MFI) {
102   if (!MI->hasOneMemOperand() ||
103       !(*MI->memoperands_begin())->getValue() ||
104       (*MI->memoperands_begin())->isVolatile())
105     return 0;
106
107   const Value *V = (*MI->memoperands_begin())->getValue();
108   if (!V)
109     return 0;
110
111   V = getUnderlyingObject(V);
112   if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
113     // For now, ignore PseudoSourceValues which may alias LLVM IR values
114     // because the code that uses this function has no way to cope with
115     // such aliases.
116     if (PSV->isAliased(MFI))
117       return 0;
118     return V;
119   }
120
121   if (isIdentifiedObject(V))
122     return V;
123
124   return 0;
125 }
126
127 void ScheduleDAGInstrs::StartBlock(MachineBasicBlock *BB) {
128   if (MachineLoop *ML = MLI.getLoopFor(BB))
129     if (BB == ML->getLoopLatch()) {
130       MachineBasicBlock *Header = ML->getHeader();
131       for (MachineBasicBlock::livein_iterator I = Header->livein_begin(),
132            E = Header->livein_end(); I != E; ++I)
133         LoopLiveInRegs.insert(*I);
134       LoopRegs.VisitLoop(ML);
135     }
136 }
137
138 void ScheduleDAGInstrs::BuildSchedGraph(AliasAnalysis *AA) {
139   // We'll be allocating one SUnit for each instruction, plus one for
140   // the region exit node.
141   SUnits.reserve(BB->size());
142
143   // We build scheduling units by walking a block's instruction list from bottom
144   // to top.
145
146   // Remember where a generic side-effecting instruction is as we procede. If
147   // ChainMMO is null, this is assumed to have arbitrary side-effects. If
148   // ChainMMO is non-null, then Chain makes only a single memory reference.
149   SUnit *Chain = 0;
150   MachineMemOperand *ChainMMO = 0;
151
152   // Memory references to specific known memory locations are tracked so that
153   // they can be given more precise dependencies.
154   std::map<const Value *, SUnit *> MemDefs;
155   std::map<const Value *, std::vector<SUnit *> > MemUses;
156
157   // Check to see if the scheduler cares about latencies.
158   bool UnitLatencies = ForceUnitLatencies();
159
160   // Ask the target if address-backscheduling is desirable, and if so how much.
161   const TargetSubtarget &ST = TM.getSubtarget<TargetSubtarget>();
162   unsigned SpecialAddressLatency = ST.getSpecialAddressLatency();
163
164   // Walk the list of instructions, from bottom moving up.
165   for (MachineBasicBlock::iterator MII = InsertPos, MIE = Begin;
166        MII != MIE; --MII) {
167     MachineInstr *MI = prior(MII);
168     const TargetInstrDesc &TID = MI->getDesc();
169     assert(!TID.isTerminator() && !MI->isLabel() &&
170            "Cannot schedule terminators or labels!");
171     // Create the SUnit for this MI.
172     SUnit *SU = NewSUnit(MI);
173
174     // Assign the Latency field of SU using target-provided information.
175     if (UnitLatencies)
176       SU->Latency = 1;
177     else
178       ComputeLatency(SU);
179
180     // Add register-based dependencies (data, anti, and output).
181     for (unsigned j = 0, n = MI->getNumOperands(); j != n; ++j) {
182       const MachineOperand &MO = MI->getOperand(j);
183       if (!MO.isReg()) continue;
184       unsigned Reg = MO.getReg();
185       if (Reg == 0) continue;
186
187       assert(TRI->isPhysicalRegister(Reg) && "Virtual register encountered!");
188       std::vector<SUnit *> &UseList = Uses[Reg];
189       std::vector<SUnit *> &DefList = Defs[Reg];
190       // Optionally add output and anti dependencies. For anti
191       // dependencies we use a latency of 0 because for a multi-issue
192       // target we want to allow the defining instruction to issue
193       // in the same cycle as the using instruction.
194       // TODO: Using a latency of 1 here for output dependencies assumes
195       //       there's no cost for reusing registers.
196       SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
197       unsigned AOLatency = (Kind == SDep::Anti) ? 0 : 1;
198       for (unsigned i = 0, e = DefList.size(); i != e; ++i) {
199         SUnit *DefSU = DefList[i];
200         if (DefSU != SU &&
201             (Kind != SDep::Output || !MO.isDead() ||
202              !DefSU->getInstr()->registerDefIsDead(Reg)))
203           DefSU->addPred(SDep(SU, Kind, AOLatency, /*Reg=*/Reg));
204       }
205       for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
206         std::vector<SUnit *> &DefList = Defs[*Alias];
207         for (unsigned i = 0, e = DefList.size(); i != e; ++i) {
208           SUnit *DefSU = DefList[i];
209           if (DefSU != SU &&
210               (Kind != SDep::Output || !MO.isDead() ||
211                !DefSU->getInstr()->registerDefIsDead(*Alias)))
212             DefSU->addPred(SDep(SU, Kind, AOLatency, /*Reg=*/ *Alias));
213         }
214       }
215
216       if (MO.isDef()) {
217         // Add any data dependencies.
218         unsigned DataLatency = SU->Latency;
219         for (unsigned i = 0, e = UseList.size(); i != e; ++i) {
220           SUnit *UseSU = UseList[i];
221           if (UseSU != SU) {
222             unsigned LDataLatency = DataLatency;
223             // Optionally add in a special extra latency for nodes that
224             // feed addresses.
225             // TODO: Do this for register aliases too.
226             // TODO: Perhaps we should get rid of
227             // SpecialAddressLatency and just move this into
228             // adjustSchedDependency for the targets that care about
229             // it.
230             if (SpecialAddressLatency != 0 && !UnitLatencies) {
231               MachineInstr *UseMI = UseSU->getInstr();
232               const TargetInstrDesc &UseTID = UseMI->getDesc();
233               int RegUseIndex = UseMI->findRegisterUseOperandIdx(Reg);
234               assert(RegUseIndex >= 0 && "UseMI doesn's use register!");
235               if ((UseTID.mayLoad() || UseTID.mayStore()) &&
236                   (unsigned)RegUseIndex < UseTID.getNumOperands() &&
237                   UseTID.OpInfo[RegUseIndex].isLookupPtrRegClass())
238                 LDataLatency += SpecialAddressLatency;
239             }
240             // Adjust the dependence latency using operand def/use
241             // information (if any), and then allow the target to
242             // perform its own adjustments.
243             const SDep& dep = SDep(SU, SDep::Data, LDataLatency, Reg);
244             if (!UnitLatencies) {
245               ComputeOperandLatency(SU, UseSU, (SDep &)dep);
246               ST.adjustSchedDependency(SU, UseSU, (SDep &)dep);
247             }
248             UseSU->addPred(dep);
249           }
250         }
251         for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
252           std::vector<SUnit *> &UseList = Uses[*Alias];
253           for (unsigned i = 0, e = UseList.size(); i != e; ++i) {
254             SUnit *UseSU = UseList[i];
255             if (UseSU != SU) {
256               const SDep& dep = SDep(SU, SDep::Data, DataLatency, *Alias);
257               if (!UnitLatencies) {
258                 ComputeOperandLatency(SU, UseSU, (SDep &)dep);
259                 ST.adjustSchedDependency(SU, UseSU, (SDep &)dep);
260               }
261               UseSU->addPred(dep);
262             }
263           }
264         }
265
266         // If a def is going to wrap back around to the top of the loop,
267         // backschedule it.
268         if (!UnitLatencies && DefList.empty()) {
269           LoopDependencies::LoopDeps::iterator I = LoopRegs.Deps.find(Reg);
270           if (I != LoopRegs.Deps.end()) {
271             const MachineOperand *UseMO = I->second.first;
272             unsigned Count = I->second.second;
273             const MachineInstr *UseMI = UseMO->getParent();
274             unsigned UseMOIdx = UseMO - &UseMI->getOperand(0);
275             const TargetInstrDesc &UseTID = UseMI->getDesc();
276             // TODO: If we knew the total depth of the region here, we could
277             // handle the case where the whole loop is inside the region but
278             // is large enough that the isScheduleHigh trick isn't needed.
279             if (UseMOIdx < UseTID.getNumOperands()) {
280               // Currently, we only support scheduling regions consisting of
281               // single basic blocks. Check to see if the instruction is in
282               // the same region by checking to see if it has the same parent.
283               if (UseMI->getParent() != MI->getParent()) {
284                 unsigned Latency = SU->Latency;
285                 if (UseTID.OpInfo[UseMOIdx].isLookupPtrRegClass())
286                   Latency += SpecialAddressLatency;
287                 // This is a wild guess as to the portion of the latency which
288                 // will be overlapped by work done outside the current
289                 // scheduling region.
290                 Latency -= std::min(Latency, Count);
291                 // Add the artifical edge.
292                 ExitSU.addPred(SDep(SU, SDep::Order, Latency,
293                                     /*Reg=*/0, /*isNormalMemory=*/false,
294                                     /*isMustAlias=*/false,
295                                     /*isArtificial=*/true));
296               } else if (SpecialAddressLatency > 0 &&
297                          UseTID.OpInfo[UseMOIdx].isLookupPtrRegClass()) {
298                 // The entire loop body is within the current scheduling region
299                 // and the latency of this operation is assumed to be greater
300                 // than the latency of the loop.
301                 // TODO: Recursively mark data-edge predecessors as
302                 //       isScheduleHigh too.
303                 SU->isScheduleHigh = true;
304               }
305             }
306             LoopRegs.Deps.erase(I);
307           }
308         }
309
310         UseList.clear();
311         if (!MO.isDead())
312           DefList.clear();
313         DefList.push_back(SU);
314       } else {
315         UseList.push_back(SU);
316       }
317     }
318
319     // Add chain dependencies.
320     // Chain dependencies used to enforce memory order should have
321     // latency of 0 (except for true dependency of Store followed by
322     // aliased Load... we estimate that with a single cycle of latency
323     // assuming the hardware will bypass)
324     // Note that isStoreToStackSlot and isLoadFromStackSLot are not usable
325     // after stack slots are lowered to actual addresses.
326     // TODO: Use an AliasAnalysis and do real alias-analysis queries, and
327     // produce more precise dependence information.
328 #define STORE_LOAD_LATENCY 1
329     unsigned TrueMemOrderLatency = 0;
330     if (TID.isCall() || TID.hasUnmodeledSideEffects()) {
331     new_chain:
332       // This is the conservative case. Add dependencies on all memory
333       // references.
334       if (Chain)
335         Chain->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
336       Chain = SU;
337       for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
338         PendingLoads[k]->addPred(SDep(SU, SDep::Order, TrueMemOrderLatency));
339       PendingLoads.clear();
340       for (std::map<const Value *, SUnit *>::iterator I = MemDefs.begin(),
341            E = MemDefs.end(); I != E; ++I) {
342         I->second->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
343         I->second = SU;
344       }
345       for (std::map<const Value *, std::vector<SUnit *> >::iterator I =
346            MemUses.begin(), E = MemUses.end(); I != E; ++I) {
347         for (unsigned i = 0, e = I->second.size(); i != e; ++i)
348           I->second[i]->addPred(SDep(SU, SDep::Order, TrueMemOrderLatency));
349         I->second.clear();
350       }
351       // See if it is known to just have a single memory reference.
352       MachineInstr *ChainMI = Chain->getInstr();
353       const TargetInstrDesc &ChainTID = ChainMI->getDesc();
354       if (!ChainTID.isCall() &&
355           !ChainTID.hasUnmodeledSideEffects() &&
356           ChainMI->hasOneMemOperand() &&
357           !(*ChainMI->memoperands_begin())->isVolatile() &&
358           (*ChainMI->memoperands_begin())->getValue())
359         // We know that the Chain accesses one specific memory location.
360         ChainMMO = *ChainMI->memoperands_begin();
361       else
362         // Unknown memory accesses. Assume the worst.
363         ChainMMO = 0;
364     } else if (TID.mayStore()) {
365       TrueMemOrderLatency = STORE_LOAD_LATENCY;
366       if (const Value *V = getUnderlyingObjectForInstr(MI, MFI)) {
367         // A store to a specific PseudoSourceValue. Add precise dependencies.
368         // Handle the def in MemDefs, if there is one.
369         std::map<const Value *, SUnit *>::iterator I = MemDefs.find(V);
370         if (I != MemDefs.end()) {
371           I->second->addPred(SDep(SU, SDep::Order, /*Latency=*/0, /*Reg=*/0,
372                                   /*isNormalMemory=*/true));
373           I->second = SU;
374         } else {
375           MemDefs[V] = SU;
376         }
377         // Handle the uses in MemUses, if there are any.
378         std::map<const Value *, std::vector<SUnit *> >::iterator J =
379           MemUses.find(V);
380         if (J != MemUses.end()) {
381           for (unsigned i = 0, e = J->second.size(); i != e; ++i)
382             J->second[i]->addPred(SDep(SU, SDep::Order, TrueMemOrderLatency,
383                                        /*Reg=*/0, /*isNormalMemory=*/true));
384           J->second.clear();
385         }
386         // Add dependencies from all the PendingLoads, since without
387         // memoperands we must assume they alias anything.
388         for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
389           PendingLoads[k]->addPred(SDep(SU, SDep::Order, TrueMemOrderLatency));
390         // Add a general dependence too, if needed.
391         if (Chain)
392           Chain->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
393       } else {
394         // Treat all other stores conservatively.
395         goto new_chain;
396       }
397     } else if (TID.mayLoad()) {
398       TrueMemOrderLatency = 0;
399       if (MI->isInvariantLoad(AA)) {
400         // Invariant load, no chain dependencies needed!
401       } else if (const Value *V = getUnderlyingObjectForInstr(MI, MFI)) {
402         // A load from a specific PseudoSourceValue. Add precise dependencies.
403         std::map<const Value *, SUnit *>::iterator I = MemDefs.find(V);
404         if (I != MemDefs.end())
405           I->second->addPred(SDep(SU, SDep::Order, /*Latency=*/0, /*Reg=*/0,
406                                   /*isNormalMemory=*/true));
407         MemUses[V].push_back(SU);
408
409         // Add a general dependence too, if needed.
410         if (Chain && (!ChainMMO ||
411                       (ChainMMO->isStore() || ChainMMO->isVolatile())))
412           Chain->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
413       } else if (MI->hasVolatileMemoryRef()) {
414         // Treat volatile loads conservatively. Note that this includes
415         // cases where memoperand information is unavailable.
416         goto new_chain;
417       } else {
418         // A normal load. Depend on the general chain, as well as on
419         // all stores. In the absense of MachineMemOperand information,
420         // we can't even assume that the load doesn't alias well-behaved
421         // memory locations.
422         if (Chain)
423           Chain->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
424         for (std::map<const Value *, SUnit *>::iterator I = MemDefs.begin(),
425              E = MemDefs.end(); I != E; ++I)
426           I->second->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
427         PendingLoads.push_back(SU);
428       }
429     }
430   }
431
432   for (int i = 0, e = TRI->getNumRegs(); i != e; ++i) {
433     Defs[i].clear();
434     Uses[i].clear();
435   }
436   PendingLoads.clear();
437 }
438
439 void ScheduleDAGInstrs::FinishBlock() {
440   // Nothing to do.
441 }
442
443 void ScheduleDAGInstrs::ComputeLatency(SUnit *SU) {
444   const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
445
446   // Compute the latency for the node.
447   SU->Latency =
448     InstrItins.getStageLatency(SU->getInstr()->getDesc().getSchedClass());
449
450   // Simplistic target-independent heuristic: assume that loads take
451   // extra time.
452   if (InstrItins.isEmpty())
453     if (SU->getInstr()->getDesc().mayLoad())
454       SU->Latency += 2;
455 }
456
457 void ScheduleDAGInstrs::ComputeOperandLatency(SUnit *Def, SUnit *Use, 
458                                               SDep& dep) const {
459   const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
460   if (InstrItins.isEmpty())
461     return;
462   
463   // For a data dependency with a known register...
464   if ((dep.getKind() != SDep::Data) || (dep.getReg() == 0))
465     return;
466
467   const unsigned Reg = dep.getReg();
468
469   // ... find the definition of the register in the defining
470   // instruction
471   MachineInstr *DefMI = Def->getInstr();
472   int DefIdx = DefMI->findRegisterDefOperandIdx(Reg);
473   if (DefIdx != -1) {
474     int DefCycle = InstrItins.getOperandCycle(DefMI->getDesc().getSchedClass(), DefIdx);
475     if (DefCycle >= 0) {
476       MachineInstr *UseMI = Use->getInstr();
477       const unsigned UseClass = UseMI->getDesc().getSchedClass();
478
479       // For all uses of the register, calculate the maxmimum latency
480       int Latency = -1;
481       for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
482         const MachineOperand &MO = UseMI->getOperand(i);
483         if (!MO.isReg() || !MO.isUse())
484           continue;
485         unsigned MOReg = MO.getReg();
486         if (MOReg != Reg)
487           continue;
488
489         int UseCycle = InstrItins.getOperandCycle(UseClass, i);
490         if (UseCycle >= 0)
491           Latency = std::max(Latency, DefCycle - UseCycle + 1);
492       }
493
494       // If we found a latency, then replace the existing dependence latency.
495       if (Latency >= 0)
496         dep.setLatency(Latency);
497     }
498   }
499 }
500
501 void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
502   SU->getInstr()->dump();
503 }
504
505 std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
506   std::string s;
507   raw_string_ostream oss(s);
508   if (SU == &EntrySU)
509     oss << "<entry>";
510   else if (SU == &ExitSU)
511     oss << "<exit>";
512   else
513     SU->getInstr()->print(oss);
514   return oss.str();
515 }
516
517 // EmitSchedule - Emit the machine code in scheduled order.
518 MachineBasicBlock *ScheduleDAGInstrs::
519 EmitSchedule(DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) {
520   // For MachineInstr-based scheduling, we're rescheduling the instructions in
521   // the block, so start by removing them from the block.
522   while (Begin != InsertPos) {
523     MachineBasicBlock::iterator I = Begin;
524     ++Begin;
525     BB->remove(I);
526   }
527
528   // Then re-insert them according to the given schedule.
529   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
530     SUnit *SU = Sequence[i];
531     if (!SU) {
532       // Null SUnit* is a noop.
533       EmitNoop();
534       continue;
535     }
536
537     BB->insert(InsertPos, SU->getInstr());
538   }
539
540   // Update the Begin iterator, as the first instruction in the block
541   // may have been scheduled later.
542   if (!Sequence.empty())
543     Begin = Sequence[0]->getInstr();
544
545   return BB;
546 }