use range-based for-loop; NFCI
[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 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
16 #include "llvm/ADT/MapVector.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineMemOperand.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/PseudoSourceValue.h"
28 #include "llvm/CodeGen/RegisterPressure.h"
29 #include "llvm/CodeGen/ScheduleDFS.h"
30 #include "llvm/IR/Operator.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/Format.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetSubtargetInfo.h"
39 #include <queue>
40
41 using namespace llvm;
42
43 #define DEBUG_TYPE "misched"
44
45 static cl::opt<bool> EnableAASchedMI("enable-aa-sched-mi", cl::Hidden,
46     cl::ZeroOrMore, cl::init(false),
47     cl::desc("Enable use of AA during MI DAG construction"));
48
49 static cl::opt<bool> UseTBAA("use-tbaa-in-sched-mi", cl::Hidden,
50     cl::init(true), cl::desc("Enable use of TBAA during MI DAG construction"));
51
52 ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
53                                      const MachineLoopInfo *mli,
54                                      bool IsPostRAFlag, bool RemoveKillFlags,
55                                      LiveIntervals *lis)
56     : ScheduleDAG(mf), MLI(mli), MFI(mf.getFrameInfo()), LIS(lis),
57       IsPostRA(IsPostRAFlag), RemoveKillFlags(RemoveKillFlags),
58       CanHandleTerminators(false), FirstDbgValue(nullptr) {
59   assert((IsPostRA || LIS) && "PreRA scheduling requires LiveIntervals");
60   DbgValues.clear();
61   assert(!(IsPostRA && MRI.getNumVirtRegs()) &&
62          "Virtual registers must be removed prior to PostRA scheduling");
63
64   const TargetSubtargetInfo &ST = mf.getSubtarget();
65   SchedModel.init(ST.getSchedModel(), &ST, TII);
66 }
67
68 /// getUnderlyingObjectFromInt - This is the function that does the work of
69 /// looking through basic ptrtoint+arithmetic+inttoptr sequences.
70 static const Value *getUnderlyingObjectFromInt(const Value *V) {
71   do {
72     if (const Operator *U = dyn_cast<Operator>(V)) {
73       // If we find a ptrtoint, we can transfer control back to the
74       // regular getUnderlyingObjectFromInt.
75       if (U->getOpcode() == Instruction::PtrToInt)
76         return U->getOperand(0);
77       // If we find an add of a constant, a multiplied value, or a phi, it's
78       // likely that the other operand will lead us to the base
79       // object. We don't have to worry about the case where the
80       // object address is somehow being computed by the multiply,
81       // because our callers only care when the result is an
82       // identifiable object.
83       if (U->getOpcode() != Instruction::Add ||
84           (!isa<ConstantInt>(U->getOperand(1)) &&
85            Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
86            !isa<PHINode>(U->getOperand(1))))
87         return V;
88       V = U->getOperand(0);
89     } else {
90       return V;
91     }
92     assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
93   } while (1);
94 }
95
96 /// getUnderlyingObjects - This is a wrapper around GetUnderlyingObjects
97 /// and adds support for basic ptrtoint+arithmetic+inttoptr sequences.
98 static void getUnderlyingObjects(const Value *V,
99                                  SmallVectorImpl<Value *> &Objects,
100                                  const DataLayout &DL) {
101   SmallPtrSet<const Value *, 16> Visited;
102   SmallVector<const Value *, 4> Working(1, V);
103   do {
104     V = Working.pop_back_val();
105
106     SmallVector<Value *, 4> Objs;
107     GetUnderlyingObjects(const_cast<Value *>(V), Objs, DL);
108
109     for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), IE = Objs.end();
110          I != IE; ++I) {
111       V = *I;
112       if (!Visited.insert(V).second)
113         continue;
114       if (Operator::getOpcode(V) == Instruction::IntToPtr) {
115         const Value *O =
116           getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
117         if (O->getType()->isPointerTy()) {
118           Working.push_back(O);
119           continue;
120         }
121       }
122       Objects.push_back(const_cast<Value *>(V));
123     }
124   } while (!Working.empty());
125 }
126
127 typedef PointerUnion<const Value *, const PseudoSourceValue *> ValueType;
128 typedef SmallVector<PointerIntPair<ValueType, 1, bool>, 4>
129 UnderlyingObjectsVector;
130
131 /// getUnderlyingObjectsForInstr - If this machine instr has memory reference
132 /// information and it can be tracked to a normal reference to a known
133 /// object, return the Value for that object.
134 static void getUnderlyingObjectsForInstr(const MachineInstr *MI,
135                                          const MachineFrameInfo *MFI,
136                                          UnderlyingObjectsVector &Objects,
137                                          const DataLayout &DL) {
138   if (!MI->hasOneMemOperand() ||
139       (!(*MI->memoperands_begin())->getValue() &&
140        !(*MI->memoperands_begin())->getPseudoValue()) ||
141       (*MI->memoperands_begin())->isVolatile())
142     return;
143
144   if (const PseudoSourceValue *PSV =
145       (*MI->memoperands_begin())->getPseudoValue()) {
146     // Function that contain tail calls don't have unique PseudoSourceValue
147     // objects. Two PseudoSourceValues might refer to the same or overlapping
148     // locations. The client code calling this function assumes this is not the
149     // case. So return a conservative answer of no known object.
150     if (MFI->hasTailCall())
151       return;
152
153     // For now, ignore PseudoSourceValues which may alias LLVM IR values
154     // because the code that uses this function has no way to cope with
155     // such aliases.
156     if (!PSV->isAliased(MFI)) {
157       bool MayAlias = PSV->mayAlias(MFI);
158       Objects.push_back(UnderlyingObjectsVector::value_type(PSV, MayAlias));
159     }
160     return;
161   }
162
163   const Value *V = (*MI->memoperands_begin())->getValue();
164   if (!V)
165     return;
166
167   SmallVector<Value *, 4> Objs;
168   getUnderlyingObjects(V, Objs, DL);
169
170   for (Value *V : Objs) {
171     if (!isIdentifiedObject(V)) {
172       Objects.clear();
173       return;
174     }
175
176     Objects.push_back(UnderlyingObjectsVector::value_type(V, true));
177   }
178 }
179
180 void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) {
181   BB = bb;
182 }
183
184 void ScheduleDAGInstrs::finishBlock() {
185   // Subclasses should no longer refer to the old block.
186   BB = nullptr;
187 }
188
189 /// Initialize the DAG and common scheduler state for the current scheduling
190 /// region. This does not actually create the DAG, only clears it. The
191 /// scheduling driver may call BuildSchedGraph multiple times per scheduling
192 /// region.
193 void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb,
194                                     MachineBasicBlock::iterator begin,
195                                     MachineBasicBlock::iterator end,
196                                     unsigned regioninstrs) {
197   assert(bb == BB && "startBlock should set BB");
198   RegionBegin = begin;
199   RegionEnd = end;
200   NumRegionInstrs = regioninstrs;
201 }
202
203 /// Close the current scheduling region. Don't clear any state in case the
204 /// driver wants to refer to the previous scheduling region.
205 void ScheduleDAGInstrs::exitRegion() {
206   // Nothing to do.
207 }
208
209 /// addSchedBarrierDeps - Add dependencies from instructions in the current
210 /// list of instructions being scheduled to scheduling barrier by adding
211 /// the exit SU to the register defs and use list. This is because we want to
212 /// make sure instructions which define registers that are either used by
213 /// the terminator or are live-out are properly scheduled. This is
214 /// especially important when the definition latency of the return value(s)
215 /// are too high to be hidden by the branch or when the liveout registers
216 /// used by instructions in the fallthrough block.
217 void ScheduleDAGInstrs::addSchedBarrierDeps() {
218   MachineInstr *ExitMI = RegionEnd != BB->end() ? &*RegionEnd : nullptr;
219   ExitSU.setInstr(ExitMI);
220   bool AllDepKnown = ExitMI &&
221     (ExitMI->isCall() || ExitMI->isBarrier());
222   if (ExitMI && AllDepKnown) {
223     // If it's a call or a barrier, add dependencies on the defs and uses of
224     // instruction.
225     for (unsigned i = 0, e = ExitMI->getNumOperands(); i != e; ++i) {
226       const MachineOperand &MO = ExitMI->getOperand(i);
227       if (!MO.isReg() || MO.isDef()) continue;
228       unsigned Reg = MO.getReg();
229       if (Reg == 0) continue;
230
231       if (TRI->isPhysicalRegister(Reg))
232         Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg));
233       else {
234         assert(!IsPostRA && "Virtual register encountered after regalloc.");
235         if (MO.readsReg()) // ignore undef operands
236           addVRegUseDeps(&ExitSU, i);
237       }
238     }
239   } else {
240     // For others, e.g. fallthrough, conditional branch, assume the exit
241     // uses all the registers that are livein to the successor blocks.
242     assert(Uses.empty() && "Uses in set before adding deps?");
243     for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
244            SE = BB->succ_end(); SI != SE; ++SI)
245       for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
246              E = (*SI)->livein_end(); I != E; ++I) {
247         unsigned Reg = *I;
248         if (!Uses.contains(Reg))
249           Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg));
250       }
251   }
252 }
253
254 /// MO is an operand of SU's instruction that defines a physical register. Add
255 /// data dependencies from SU to any uses of the physical register.
256 void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU, unsigned OperIdx) {
257   const MachineOperand &MO = SU->getInstr()->getOperand(OperIdx);
258   assert(MO.isDef() && "expect physreg def");
259
260   // Ask the target if address-backscheduling is desirable, and if so how much.
261   const TargetSubtargetInfo &ST = MF.getSubtarget();
262
263   for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
264        Alias.isValid(); ++Alias) {
265     if (!Uses.contains(*Alias))
266       continue;
267     for (Reg2SUnitsMap::iterator I = Uses.find(*Alias); I != Uses.end(); ++I) {
268       SUnit *UseSU = I->SU;
269       if (UseSU == SU)
270         continue;
271
272       // Adjust the dependence latency using operand def/use information,
273       // then allow the target to perform its own adjustments.
274       int UseOp = I->OpIdx;
275       MachineInstr *RegUse = nullptr;
276       SDep Dep;
277       if (UseOp < 0)
278         Dep = SDep(SU, SDep::Artificial);
279       else {
280         // Set the hasPhysRegDefs only for physreg defs that have a use within
281         // the scheduling region.
282         SU->hasPhysRegDefs = true;
283         Dep = SDep(SU, SDep::Data, *Alias);
284         RegUse = UseSU->getInstr();
285       }
286       Dep.setLatency(
287         SchedModel.computeOperandLatency(SU->getInstr(), OperIdx, RegUse,
288                                          UseOp));
289
290       ST.adjustSchedDependency(SU, UseSU, Dep);
291       UseSU->addPred(Dep);
292     }
293   }
294 }
295
296 /// addPhysRegDeps - Add register dependencies (data, anti, and output) from
297 /// this SUnit to following instructions in the same scheduling region that
298 /// depend the physical register referenced at OperIdx.
299 void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
300   MachineInstr *MI = SU->getInstr();
301   MachineOperand &MO = MI->getOperand(OperIdx);
302
303   // Optionally add output and anti dependencies. For anti
304   // dependencies we use a latency of 0 because for a multi-issue
305   // target we want to allow the defining instruction to issue
306   // in the same cycle as the using instruction.
307   // TODO: Using a latency of 1 here for output dependencies assumes
308   //       there's no cost for reusing registers.
309   SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
310   for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
311        Alias.isValid(); ++Alias) {
312     if (!Defs.contains(*Alias))
313       continue;
314     for (Reg2SUnitsMap::iterator I = Defs.find(*Alias); I != Defs.end(); ++I) {
315       SUnit *DefSU = I->SU;
316       if (DefSU == &ExitSU)
317         continue;
318       if (DefSU != SU &&
319           (Kind != SDep::Output || !MO.isDead() ||
320            !DefSU->getInstr()->registerDefIsDead(*Alias))) {
321         if (Kind == SDep::Anti)
322           DefSU->addPred(SDep(SU, Kind, /*Reg=*/*Alias));
323         else {
324           SDep Dep(SU, Kind, /*Reg=*/*Alias);
325           Dep.setLatency(
326             SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
327           DefSU->addPred(Dep);
328         }
329       }
330     }
331   }
332
333   if (!MO.isDef()) {
334     SU->hasPhysRegUses = true;
335     // Either insert a new Reg2SUnits entry with an empty SUnits list, or
336     // retrieve the existing SUnits list for this register's uses.
337     // Push this SUnit on the use list.
338     Uses.insert(PhysRegSUOper(SU, OperIdx, MO.getReg()));
339     if (RemoveKillFlags)
340       MO.setIsKill(false);
341   }
342   else {
343     addPhysRegDataDeps(SU, OperIdx);
344     unsigned Reg = MO.getReg();
345
346     // clear this register's use list
347     if (Uses.contains(Reg))
348       Uses.eraseAll(Reg);
349
350     if (!MO.isDead()) {
351       Defs.eraseAll(Reg);
352     } else if (SU->isCall) {
353       // Calls will not be reordered because of chain dependencies (see
354       // below). Since call operands are dead, calls may continue to be added
355       // to the DefList making dependence checking quadratic in the size of
356       // the block. Instead, we leave only one call at the back of the
357       // DefList.
358       Reg2SUnitsMap::RangePair P = Defs.equal_range(Reg);
359       Reg2SUnitsMap::iterator B = P.first;
360       Reg2SUnitsMap::iterator I = P.second;
361       for (bool isBegin = I == B; !isBegin; /* empty */) {
362         isBegin = (--I) == B;
363         if (!I->SU->isCall)
364           break;
365         I = Defs.erase(I);
366       }
367     }
368
369     // Defs are pushed in the order they are visited and never reordered.
370     Defs.insert(PhysRegSUOper(SU, OperIdx, Reg));
371   }
372 }
373
374 /// addVRegDefDeps - Add register output and data dependencies from this SUnit
375 /// to instructions that occur later in the same scheduling region if they read
376 /// from or write to the virtual register defined at OperIdx.
377 ///
378 /// TODO: Hoist loop induction variable increments. This has to be
379 /// reevaluated. Generally, IV scheduling should be done before coalescing.
380 void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
381   const MachineInstr *MI = SU->getInstr();
382   unsigned Reg = MI->getOperand(OperIdx).getReg();
383
384   // Singly defined vregs do not have output/anti dependencies.
385   // The current operand is a def, so we have at least one.
386   // Check here if there are any others...
387   if (MRI.hasOneDef(Reg))
388     return;
389
390   // Add output dependence to the next nearest def of this vreg.
391   //
392   // Unless this definition is dead, the output dependence should be
393   // transitively redundant with antidependencies from this definition's
394   // uses. We're conservative for now until we have a way to guarantee the uses
395   // are not eliminated sometime during scheduling. The output dependence edge
396   // is also useful if output latency exceeds def-use latency.
397   VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
398   if (DefI == VRegDefs.end())
399     VRegDefs.insert(VReg2SUnit(Reg, SU));
400   else {
401     SUnit *DefSU = DefI->SU;
402     if (DefSU != SU && DefSU != &ExitSU) {
403       SDep Dep(SU, SDep::Output, Reg);
404       Dep.setLatency(
405         SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
406       DefSU->addPred(Dep);
407     }
408     DefI->SU = SU;
409   }
410 }
411
412 /// addVRegUseDeps - Add a register data dependency if the instruction that
413 /// defines the virtual register used at OperIdx is mapped to an SUnit. Add a
414 /// register antidependency from this SUnit to instructions that occur later in
415 /// the same scheduling region if they write the virtual register.
416 ///
417 /// TODO: Handle ExitSU "uses" properly.
418 void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
419   MachineInstr *MI = SU->getInstr();
420   unsigned Reg = MI->getOperand(OperIdx).getReg();
421
422   // Record this local VReg use.
423   VReg2UseMap::iterator UI = VRegUses.find(Reg);
424   for (; UI != VRegUses.end(); ++UI) {
425     if (UI->SU == SU)
426       break;
427   }
428   if (UI == VRegUses.end())
429     VRegUses.insert(VReg2SUnit(Reg, SU));
430
431   // Lookup this operand's reaching definition.
432   assert(LIS && "vreg dependencies requires LiveIntervals");
433   LiveQueryResult LRQ
434     = LIS->getInterval(Reg).Query(LIS->getInstructionIndex(MI));
435   VNInfo *VNI = LRQ.valueIn();
436
437   // VNI will be valid because MachineOperand::readsReg() is checked by caller.
438   assert(VNI && "No value to read by operand");
439   MachineInstr *Def = LIS->getInstructionFromIndex(VNI->def);
440   // Phis and other noninstructions (after coalescing) have a NULL Def.
441   if (Def) {
442     SUnit *DefSU = getSUnit(Def);
443     if (DefSU) {
444       // The reaching Def lives within this scheduling region.
445       // Create a data dependence.
446       SDep dep(DefSU, SDep::Data, Reg);
447       // Adjust the dependence latency using operand def/use information, then
448       // allow the target to perform its own adjustments.
449       int DefOp = Def->findRegisterDefOperandIdx(Reg);
450       dep.setLatency(SchedModel.computeOperandLatency(Def, DefOp, MI, OperIdx));
451
452       const TargetSubtargetInfo &ST = MF.getSubtarget();
453       ST.adjustSchedDependency(DefSU, SU, const_cast<SDep &>(dep));
454       SU->addPred(dep);
455     }
456   }
457
458   // Add antidependence to the following def of the vreg it uses.
459   VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
460   if (DefI != VRegDefs.end() && DefI->SU != SU)
461     DefI->SU->addPred(SDep(SU, SDep::Anti, Reg));
462 }
463
464 /// Return true if MI is an instruction we are unable to reason about
465 /// (like a call or something with unmodeled side effects).
466 static inline bool isGlobalMemoryObject(AliasAnalysis *AA, MachineInstr *MI) {
467   if (MI->isCall() || MI->hasUnmodeledSideEffects() ||
468       (MI->hasOrderedMemoryRef() &&
469        (!MI->mayLoad() || !MI->isInvariantLoad(AA))))
470     return true;
471   return false;
472 }
473
474 // This MI might have either incomplete info, or known to be unsafe
475 // to deal with (i.e. volatile object).
476 static inline bool isUnsafeMemoryObject(MachineInstr *MI,
477                                         const MachineFrameInfo *MFI,
478                                         const DataLayout &DL) {
479   if (!MI || MI->memoperands_empty())
480     return true;
481   // We purposefully do no check for hasOneMemOperand() here
482   // in hope to trigger an assert downstream in order to
483   // finish implementation.
484   if ((*MI->memoperands_begin())->isVolatile() ||
485        MI->hasUnmodeledSideEffects())
486     return true;
487
488   if ((*MI->memoperands_begin())->getPseudoValue()) {
489     // Similarly to getUnderlyingObjectForInstr:
490     // For now, ignore PseudoSourceValues which may alias LLVM IR values
491     // because the code that uses this function has no way to cope with
492     // such aliases.
493     return true;
494   }
495
496   const Value *V = (*MI->memoperands_begin())->getValue();
497   if (!V)
498     return true;
499
500   SmallVector<Value *, 4> Objs;
501   getUnderlyingObjects(V, Objs, DL);
502   for (SmallVectorImpl<Value *>::iterator I = Objs.begin(),
503          IE = Objs.end(); I != IE; ++I) {
504     // Does this pointer refer to a distinct and identifiable object?
505     if (!isIdentifiedObject(*I))
506       return true;
507   }
508
509   return false;
510 }
511
512 /// This returns true if the two MIs need a chain edge betwee them.
513 /// If these are not even memory operations, we still may need
514 /// chain deps between them. The question really is - could
515 /// these two MIs be reordered during scheduling from memory dependency
516 /// point of view.
517 static bool MIsNeedChainEdge(AliasAnalysis *AA, const MachineFrameInfo *MFI,
518                              const DataLayout &DL, MachineInstr *MIa,
519                              MachineInstr *MIb) {
520   const MachineFunction *MF = MIa->getParent()->getParent();
521   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
522
523   // Cover a trivial case - no edge is need to itself.
524   if (MIa == MIb)
525     return false;
526  
527   // Let the target decide if memory accesses cannot possibly overlap.
528   if ((MIa->mayLoad() || MIa->mayStore()) &&
529       (MIb->mayLoad() || MIb->mayStore()))
530     if (TII->areMemAccessesTriviallyDisjoint(MIa, MIb, AA))
531       return false;
532
533   // FIXME: Need to handle multiple memory operands to support all targets.
534   if (!MIa->hasOneMemOperand() || !MIb->hasOneMemOperand())
535     return true;
536
537   if (isUnsafeMemoryObject(MIa, MFI, DL) || isUnsafeMemoryObject(MIb, MFI, DL))
538     return true;
539
540   // If we are dealing with two "normal" loads, we do not need an edge
541   // between them - they could be reordered.
542   if (!MIa->mayStore() && !MIb->mayStore())
543     return false;
544
545   // To this point analysis is generic. From here on we do need AA.
546   if (!AA)
547     return true;
548
549   MachineMemOperand *MMOa = *MIa->memoperands_begin();
550   MachineMemOperand *MMOb = *MIb->memoperands_begin();
551
552   if (!MMOa->getValue() || !MMOb->getValue())
553     return true;
554
555   // The following interface to AA is fashioned after DAGCombiner::isAlias
556   // and operates with MachineMemOperand offset with some important
557   // assumptions:
558   //   - LLVM fundamentally assumes flat address spaces.
559   //   - MachineOperand offset can *only* result from legalization and
560   //     cannot affect queries other than the trivial case of overlap
561   //     checking.
562   //   - These offsets never wrap and never step outside
563   //     of allocated objects.
564   //   - There should never be any negative offsets here.
565   //
566   // FIXME: Modify API to hide this math from "user"
567   // FIXME: Even before we go to AA we can reason locally about some
568   // memory objects. It can save compile time, and possibly catch some
569   // corner cases not currently covered.
570
571   assert ((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset");
572   assert ((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset");
573
574   int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset());
575   int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset;
576   int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset;
577
578   AliasAnalysis::AliasResult AAResult = AA->alias(
579       AliasAnalysis::Location(MMOa->getValue(), Overlapa,
580                               UseTBAA ? MMOa->getAAInfo() : AAMDNodes()),
581       AliasAnalysis::Location(MMOb->getValue(), Overlapb,
582                               UseTBAA ? MMOb->getAAInfo() : AAMDNodes()));
583
584   return (AAResult != AliasAnalysis::NoAlias);
585 }
586
587 /// This recursive function iterates over chain deps of SUb looking for
588 /// "latest" node that needs a chain edge to SUa.
589 static unsigned iterateChainSucc(AliasAnalysis *AA, const MachineFrameInfo *MFI,
590                                  const DataLayout &DL, SUnit *SUa, SUnit *SUb,
591                                  SUnit *ExitSU, unsigned *Depth,
592                                  SmallPtrSetImpl<const SUnit *> &Visited) {
593   if (!SUa || !SUb || SUb == ExitSU)
594     return *Depth;
595
596   // Remember visited nodes.
597   if (!Visited.insert(SUb).second)
598       return *Depth;
599   // If there is _some_ dependency already in place, do not
600   // descend any further.
601   // TODO: Need to make sure that if that dependency got eliminated or ignored
602   // for any reason in the future, we would not violate DAG topology.
603   // Currently it does not happen, but makes an implicit assumption about
604   // future implementation.
605   //
606   // Independently, if we encounter node that is some sort of global
607   // object (like a call) we already have full set of dependencies to it
608   // and we can stop descending.
609   if (SUa->isSucc(SUb) ||
610       isGlobalMemoryObject(AA, SUb->getInstr()))
611     return *Depth;
612
613   // If we do need an edge, or we have exceeded depth budget,
614   // add that edge to the predecessors chain of SUb,
615   // and stop descending.
616   if (*Depth > 200 ||
617       MIsNeedChainEdge(AA, MFI, DL, SUa->getInstr(), SUb->getInstr())) {
618     SUb->addPred(SDep(SUa, SDep::MayAliasMem));
619     return *Depth;
620   }
621   // Track current depth.
622   (*Depth)++;
623   // Iterate over memory dependencies only.
624   for (SUnit::const_succ_iterator I = SUb->Succs.begin(), E = SUb->Succs.end();
625        I != E; ++I)
626     if (I->isNormalMemoryOrBarrier())
627       iterateChainSucc(AA, MFI, DL, SUa, I->getSUnit(), ExitSU, Depth, Visited);
628   return *Depth;
629 }
630
631 /// This function assumes that "downward" from SU there exist
632 /// tail/leaf of already constructed DAG. It iterates downward and
633 /// checks whether SU can be aliasing any node dominated
634 /// by it.
635 static void adjustChainDeps(AliasAnalysis *AA, const MachineFrameInfo *MFI,
636                             const DataLayout &DL, SUnit *SU, SUnit *ExitSU,
637                             std::set<SUnit *> &CheckList,
638                             unsigned LatencyToLoad) {
639   if (!SU)
640     return;
641
642   SmallPtrSet<const SUnit*, 16> Visited;
643   unsigned Depth = 0;
644
645   for (std::set<SUnit *>::iterator I = CheckList.begin(), IE = CheckList.end();
646        I != IE; ++I) {
647     if (SU == *I)
648       continue;
649     if (MIsNeedChainEdge(AA, MFI, DL, SU->getInstr(), (*I)->getInstr())) {
650       SDep Dep(SU, SDep::MayAliasMem);
651       Dep.setLatency(((*I)->getInstr()->mayLoad()) ? LatencyToLoad : 0);
652       (*I)->addPred(Dep);
653     }
654
655     // Iterate recursively over all previously added memory chain
656     // successors. Keep track of visited nodes.
657     for (SUnit::const_succ_iterator J = (*I)->Succs.begin(),
658          JE = (*I)->Succs.end(); J != JE; ++J)
659       if (J->isNormalMemoryOrBarrier())
660         iterateChainSucc(AA, MFI, DL, SU, J->getSUnit(), ExitSU, &Depth,
661                          Visited);
662   }
663 }
664
665 /// Check whether two objects need a chain edge, if so, add it
666 /// otherwise remember the rejected SU.
667 static inline void addChainDependency(AliasAnalysis *AA,
668                                       const MachineFrameInfo *MFI,
669                                       const DataLayout &DL, SUnit *SUa,
670                                       SUnit *SUb, std::set<SUnit *> &RejectList,
671                                       unsigned TrueMemOrderLatency = 0,
672                                       bool isNormalMemory = false) {
673   // If this is a false dependency,
674   // do not add the edge, but rememeber the rejected node.
675   if (MIsNeedChainEdge(AA, MFI, DL, SUa->getInstr(), SUb->getInstr())) {
676     SDep Dep(SUa, isNormalMemory ? SDep::MayAliasMem : SDep::Barrier);
677     Dep.setLatency(TrueMemOrderLatency);
678     SUb->addPred(Dep);
679   }
680   else {
681     // Duplicate entries should be ignored.
682     RejectList.insert(SUb);
683     DEBUG(dbgs() << "\tReject chain dep between SU("
684           << SUa->NodeNum << ") and SU("
685           << SUb->NodeNum << ")\n");
686   }
687 }
688
689 /// Create an SUnit for each real instruction, numbered in top-down toplological
690 /// order. The instruction order A < B, implies that no edge exists from B to A.
691 ///
692 /// Map each real instruction to its SUnit.
693 ///
694 /// After initSUnits, the SUnits vector cannot be resized and the scheduler may
695 /// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
696 /// instead of pointers.
697 ///
698 /// MachineScheduler relies on initSUnits numbering the nodes by their order in
699 /// the original instruction list.
700 void ScheduleDAGInstrs::initSUnits() {
701   // We'll be allocating one SUnit for each real instruction in the region,
702   // which is contained within a basic block.
703   SUnits.reserve(NumRegionInstrs);
704
705   for (MachineBasicBlock::iterator I = RegionBegin; I != RegionEnd; ++I) {
706     MachineInstr *MI = I;
707     if (MI->isDebugValue())
708       continue;
709
710     SUnit *SU = newSUnit(MI);
711     MISUnitMap[MI] = SU;
712
713     SU->isCall = MI->isCall();
714     SU->isCommutable = MI->isCommutable();
715
716     // Assign the Latency field of SU using target-provided information.
717     SU->Latency = SchedModel.computeInstrLatency(SU->getInstr());
718
719     // If this SUnit uses a reserved or unbuffered resource, mark it as such.
720     //
721     // Reserved resources block an instruction from issuing and stall the
722     // entire pipeline. These are identified by BufferSize=0.
723     //
724     // Unbuffered resources prevent execution of subsequent instructions that
725     // require the same resources. This is used for in-order execution pipelines
726     // within an out-of-order core. These are identified by BufferSize=1.
727     if (SchedModel.hasInstrSchedModel()) {
728       const MCSchedClassDesc *SC = getSchedClass(SU);
729       for (TargetSchedModel::ProcResIter
730              PI = SchedModel.getWriteProcResBegin(SC),
731              PE = SchedModel.getWriteProcResEnd(SC); PI != PE; ++PI) {
732         switch (SchedModel.getProcResource(PI->ProcResourceIdx)->BufferSize) {
733         case 0:
734           SU->hasReservedResource = true;
735           break;
736         case 1:
737           SU->isUnbuffered = true;
738           break;
739         default:
740           break;
741         }
742       }
743     }
744   }
745 }
746
747 /// If RegPressure is non-null, compute register pressure as a side effect. The
748 /// DAG builder is an efficient place to do it because it already visits
749 /// operands.
750 void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA,
751                                         RegPressureTracker *RPTracker,
752                                         PressureDiffs *PDiffs) {
753   const TargetSubtargetInfo &ST = MF.getSubtarget();
754   bool UseAA = EnableAASchedMI.getNumOccurrences() > 0 ? EnableAASchedMI
755                                                        : ST.useAA();
756   AliasAnalysis *AAForDep = UseAA ? AA : nullptr;
757
758   MISUnitMap.clear();
759   ScheduleDAG::clearDAG();
760
761   // Create an SUnit for each real instruction.
762   initSUnits();
763
764   if (PDiffs)
765     PDiffs->init(SUnits.size());
766
767   // We build scheduling units by walking a block's instruction list from bottom
768   // to top.
769
770   // Remember where a generic side-effecting instruction is as we procede.
771   SUnit *BarrierChain = nullptr, *AliasChain = nullptr;
772
773   // Memory references to specific known memory locations are tracked
774   // so that they can be given more precise dependencies. We track
775   // separately the known memory locations that may alias and those
776   // that are known not to alias
777   MapVector<ValueType, std::vector<SUnit *> > AliasMemDefs, NonAliasMemDefs;
778   MapVector<ValueType, std::vector<SUnit *> > AliasMemUses, NonAliasMemUses;
779   std::set<SUnit*> RejectMemNodes;
780
781   // Remove any stale debug info; sometimes BuildSchedGraph is called again
782   // without emitting the info from the previous call.
783   DbgValues.clear();
784   FirstDbgValue = nullptr;
785
786   assert(Defs.empty() && Uses.empty() &&
787          "Only BuildGraph should update Defs/Uses");
788   Defs.setUniverse(TRI->getNumRegs());
789   Uses.setUniverse(TRI->getNumRegs());
790
791   assert(VRegDefs.empty() && "Only BuildSchedGraph may access VRegDefs");
792   VRegUses.clear();
793   VRegDefs.setUniverse(MRI.getNumVirtRegs());
794   VRegUses.setUniverse(MRI.getNumVirtRegs());
795
796   // Model data dependencies between instructions being scheduled and the
797   // ExitSU.
798   addSchedBarrierDeps();
799
800   // Walk the list of instructions, from bottom moving up.
801   MachineInstr *DbgMI = nullptr;
802   for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
803        MII != MIE; --MII) {
804     MachineInstr *MI = std::prev(MII);
805     if (MI && DbgMI) {
806       DbgValues.push_back(std::make_pair(DbgMI, MI));
807       DbgMI = nullptr;
808     }
809
810     if (MI->isDebugValue()) {
811       DbgMI = MI;
812       continue;
813     }
814     SUnit *SU = MISUnitMap[MI];
815     assert(SU && "No SUnit mapped to this MI");
816
817     if (RPTracker) {
818       PressureDiff *PDiff = PDiffs ? &(*PDiffs)[SU->NodeNum] : nullptr;
819       RPTracker->recede(/*LiveUses=*/nullptr, PDiff);
820       assert(RPTracker->getPos() == std::prev(MII) &&
821              "RPTracker can't find MI");
822     }
823
824     assert(
825         (CanHandleTerminators || (!MI->isTerminator() && !MI->isPosition())) &&
826         "Cannot schedule terminators or labels!");
827
828     // Add register-based dependencies (data, anti, and output).
829     bool HasVRegDef = false;
830     for (unsigned j = 0, n = MI->getNumOperands(); j != n; ++j) {
831       const MachineOperand &MO = MI->getOperand(j);
832       if (!MO.isReg()) continue;
833       unsigned Reg = MO.getReg();
834       if (Reg == 0) continue;
835
836       if (TRI->isPhysicalRegister(Reg))
837         addPhysRegDeps(SU, j);
838       else {
839         assert(!IsPostRA && "Virtual register encountered!");
840         if (MO.isDef()) {
841           HasVRegDef = true;
842           addVRegDefDeps(SU, j);
843         }
844         else if (MO.readsReg()) // ignore undef operands
845           addVRegUseDeps(SU, j);
846       }
847     }
848     // If we haven't seen any uses in this scheduling region, create a
849     // dependence edge to ExitSU to model the live-out latency. This is required
850     // for vreg defs with no in-region use, and prefetches with no vreg def.
851     //
852     // FIXME: NumDataSuccs would be more precise than NumSuccs here. This
853     // check currently relies on being called before adding chain deps.
854     if (SU->NumSuccs == 0 && SU->Latency > 1
855         && (HasVRegDef || MI->mayLoad())) {
856       SDep Dep(SU, SDep::Artificial);
857       Dep.setLatency(SU->Latency - 1);
858       ExitSU.addPred(Dep);
859     }
860
861     // Add chain dependencies.
862     // Chain dependencies used to enforce memory order should have
863     // latency of 0 (except for true dependency of Store followed by
864     // aliased Load... we estimate that with a single cycle of latency
865     // assuming the hardware will bypass)
866     // Note that isStoreToStackSlot and isLoadFromStackSLot are not usable
867     // after stack slots are lowered to actual addresses.
868     // TODO: Use an AliasAnalysis and do real alias-analysis queries, and
869     // produce more precise dependence information.
870     unsigned TrueMemOrderLatency = MI->mayStore() ? 1 : 0;
871     if (isGlobalMemoryObject(AA, MI)) {
872       // Be conservative with these and add dependencies on all memory
873       // references, even those that are known to not alias.
874       for (MapVector<ValueType, std::vector<SUnit *> >::iterator I =
875              NonAliasMemDefs.begin(), E = NonAliasMemDefs.end(); I != E; ++I) {
876         for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
877           I->second[i]->addPred(SDep(SU, SDep::Barrier));
878         }
879       }
880       for (MapVector<ValueType, std::vector<SUnit *> >::iterator I =
881              NonAliasMemUses.begin(), E = NonAliasMemUses.end(); I != E; ++I) {
882         for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
883           SDep Dep(SU, SDep::Barrier);
884           Dep.setLatency(TrueMemOrderLatency);
885           I->second[i]->addPred(Dep);
886         }
887       }
888       // Add SU to the barrier chain.
889       if (BarrierChain)
890         BarrierChain->addPred(SDep(SU, SDep::Barrier));
891       BarrierChain = SU;
892       // This is a barrier event that acts as a pivotal node in the DAG,
893       // so it is safe to clear list of exposed nodes.
894       adjustChainDeps(AA, MFI, *TM.getDataLayout(), SU, &ExitSU, RejectMemNodes,
895                       TrueMemOrderLatency);
896       RejectMemNodes.clear();
897       NonAliasMemDefs.clear();
898       NonAliasMemUses.clear();
899
900       // fall-through
901     new_alias_chain:
902       // Chain all possibly aliasing memory references through SU.
903       if (AliasChain) {
904         unsigned ChainLatency = 0;
905         if (AliasChain->getInstr()->mayLoad())
906           ChainLatency = TrueMemOrderLatency;
907         addChainDependency(AAForDep, MFI, *TM.getDataLayout(), SU, AliasChain,
908                            RejectMemNodes, ChainLatency);
909       }
910       AliasChain = SU;
911       for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
912         addChainDependency(AAForDep, MFI, *TM.getDataLayout(), SU,
913                            PendingLoads[k], RejectMemNodes,
914                            TrueMemOrderLatency);
915       for (MapVector<ValueType, std::vector<SUnit *> >::iterator I =
916            AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I) {
917         for (unsigned i = 0, e = I->second.size(); i != e; ++i)
918           addChainDependency(AAForDep, MFI, *TM.getDataLayout(), SU,
919                              I->second[i], RejectMemNodes);
920       }
921       for (MapVector<ValueType, std::vector<SUnit *> >::iterator I =
922            AliasMemUses.begin(), E = AliasMemUses.end(); I != E; ++I) {
923         for (unsigned i = 0, e = I->second.size(); i != e; ++i)
924           addChainDependency(AAForDep, MFI, *TM.getDataLayout(), SU,
925                              I->second[i], RejectMemNodes, TrueMemOrderLatency);
926       }
927       adjustChainDeps(AA, MFI, *TM.getDataLayout(), SU, &ExitSU, RejectMemNodes,
928                       TrueMemOrderLatency);
929       PendingLoads.clear();
930       AliasMemDefs.clear();
931       AliasMemUses.clear();
932     } else if (MI->mayStore()) {
933       // Add dependence on barrier chain, if needed.
934       // There is no point to check aliasing on barrier event. Even if
935       // SU and barrier _could_ be reordered, they should not. In addition,
936       // we have lost all RejectMemNodes below barrier.
937       if (BarrierChain)
938         BarrierChain->addPred(SDep(SU, SDep::Barrier));
939
940       UnderlyingObjectsVector Objs;
941       getUnderlyingObjectsForInstr(MI, MFI, Objs, *TM.getDataLayout());
942
943       if (Objs.empty()) {
944         // Treat all other stores conservatively.
945         goto new_alias_chain;
946       }
947
948       bool MayAlias = false;
949       for (UnderlyingObjectsVector::iterator K = Objs.begin(), KE = Objs.end();
950            K != KE; ++K) {
951         ValueType V = K->getPointer();
952         bool ThisMayAlias = K->getInt();
953         if (ThisMayAlias)
954           MayAlias = true;
955
956         // A store to a specific PseudoSourceValue. Add precise dependencies.
957         // Record the def in MemDefs, first adding a dep if there is
958         // an existing def.
959         MapVector<ValueType, std::vector<SUnit *> >::iterator I =
960           ((ThisMayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
961         MapVector<ValueType, std::vector<SUnit *> >::iterator IE =
962           ((ThisMayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
963         if (I != IE) {
964           for (unsigned i = 0, e = I->second.size(); i != e; ++i)
965             addChainDependency(AAForDep, MFI, *TM.getDataLayout(), SU,
966                                I->second[i], RejectMemNodes, 0, true);
967
968           // If we're not using AA, then we only need one store per object.
969           if (!AAForDep)
970             I->second.clear();
971           I->second.push_back(SU);
972         } else {
973           if (ThisMayAlias) {
974             if (!AAForDep)
975               AliasMemDefs[V].clear();
976             AliasMemDefs[V].push_back(SU);
977           } else {
978             if (!AAForDep)
979               NonAliasMemDefs[V].clear();
980             NonAliasMemDefs[V].push_back(SU);
981           }
982         }
983         // Handle the uses in MemUses, if there are any.
984         MapVector<ValueType, std::vector<SUnit *> >::iterator J =
985           ((ThisMayAlias) ? AliasMemUses.find(V) : NonAliasMemUses.find(V));
986         MapVector<ValueType, std::vector<SUnit *> >::iterator JE =
987           ((ThisMayAlias) ? AliasMemUses.end() : NonAliasMemUses.end());
988         if (J != JE) {
989           for (unsigned i = 0, e = J->second.size(); i != e; ++i)
990             addChainDependency(AAForDep, MFI, *TM.getDataLayout(), SU,
991                                J->second[i], RejectMemNodes,
992                                TrueMemOrderLatency, true);
993           J->second.clear();
994         }
995       }
996       if (MayAlias) {
997         // Add dependencies from all the PendingLoads, i.e. loads
998         // with no underlying object.
999         for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
1000           addChainDependency(AAForDep, MFI, *TM.getDataLayout(), SU,
1001                              PendingLoads[k], RejectMemNodes,
1002                              TrueMemOrderLatency);
1003         // Add dependence on alias chain, if needed.
1004         if (AliasChain)
1005           addChainDependency(AAForDep, MFI, *TM.getDataLayout(), SU, AliasChain,
1006                              RejectMemNodes);
1007       }
1008       adjustChainDeps(AA, MFI, *TM.getDataLayout(), SU, &ExitSU, RejectMemNodes,
1009                       TrueMemOrderLatency);
1010     } else if (MI->mayLoad()) {
1011       bool MayAlias = true;
1012       if (MI->isInvariantLoad(AA)) {
1013         // Invariant load, no chain dependencies needed!
1014       } else {
1015         UnderlyingObjectsVector Objs;
1016         getUnderlyingObjectsForInstr(MI, MFI, Objs, *TM.getDataLayout());
1017
1018         if (Objs.empty()) {
1019           // A load with no underlying object. Depend on all
1020           // potentially aliasing stores.
1021           for (MapVector<ValueType, std::vector<SUnit *> >::iterator I =
1022                  AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I)
1023             for (unsigned i = 0, e = I->second.size(); i != e; ++i)
1024               addChainDependency(AAForDep, MFI, *TM.getDataLayout(), SU,
1025                                  I->second[i], RejectMemNodes);
1026
1027           PendingLoads.push_back(SU);
1028           MayAlias = true;
1029         } else {
1030           MayAlias = false;
1031         }
1032
1033         for (UnderlyingObjectsVector::iterator
1034              J = Objs.begin(), JE = Objs.end(); J != JE; ++J) {
1035           ValueType V = J->getPointer();
1036           bool ThisMayAlias = J->getInt();
1037
1038           if (ThisMayAlias)
1039             MayAlias = true;
1040
1041           // A load from a specific PseudoSourceValue. Add precise dependencies.
1042           MapVector<ValueType, std::vector<SUnit *> >::iterator I =
1043             ((ThisMayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
1044           MapVector<ValueType, std::vector<SUnit *> >::iterator IE =
1045             ((ThisMayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
1046           if (I != IE)
1047             for (unsigned i = 0, e = I->second.size(); i != e; ++i)
1048               addChainDependency(AAForDep, MFI, *TM.getDataLayout(), SU,
1049                                  I->second[i], RejectMemNodes, 0, true);
1050           if (ThisMayAlias)
1051             AliasMemUses[V].push_back(SU);
1052           else
1053             NonAliasMemUses[V].push_back(SU);
1054         }
1055         if (MayAlias)
1056           adjustChainDeps(AA, MFI, *TM.getDataLayout(), SU, &ExitSU,
1057                           RejectMemNodes, /*Latency=*/0);
1058         // Add dependencies on alias and barrier chains, if needed.
1059         if (MayAlias && AliasChain)
1060           addChainDependency(AAForDep, MFI, *TM.getDataLayout(), SU, AliasChain,
1061                              RejectMemNodes);
1062         if (BarrierChain)
1063           BarrierChain->addPred(SDep(SU, SDep::Barrier));
1064       }
1065     }
1066   }
1067   if (DbgMI)
1068     FirstDbgValue = DbgMI;
1069
1070   Defs.clear();
1071   Uses.clear();
1072   VRegDefs.clear();
1073   PendingLoads.clear();
1074 }
1075
1076 /// \brief Initialize register live-range state for updating kills.
1077 void ScheduleDAGInstrs::startBlockForKills(MachineBasicBlock *BB) {
1078   // Start with no live registers.
1079   LiveRegs.reset();
1080
1081   // Examine the live-in regs of all successors.
1082   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
1083        SE = BB->succ_end(); SI != SE; ++SI) {
1084     for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
1085          E = (*SI)->livein_end(); I != E; ++I) {
1086       unsigned Reg = *I;
1087       // Repeat, for reg and all subregs.
1088       for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1089            SubRegs.isValid(); ++SubRegs)
1090         LiveRegs.set(*SubRegs);
1091     }
1092   }
1093 }
1094
1095 /// \brief If we change a kill flag on the bundle instruction implicit register
1096 /// operands, then we also need to propagate that to any instructions inside
1097 /// the bundle which had the same kill state.
1098 static void toggleBundleKillFlag(MachineInstr *MI, unsigned Reg,
1099                                  bool NewKillState) {
1100   if (MI->getOpcode() != TargetOpcode::BUNDLE)
1101     return;
1102
1103   // Walk backwards from the last instruction in the bundle to the first.
1104   // Once we set a kill flag on an instruction, we bail out, as otherwise we
1105   // might set it on too many operands.  We will clear as many flags as we
1106   // can though.
1107   MachineBasicBlock::instr_iterator Begin = MI;
1108   MachineBasicBlock::instr_iterator End = getBundleEnd(MI);
1109   while (Begin != End) {
1110     for (MIOperands MO(--End); MO.isValid(); ++MO) {
1111       if (!MO->isReg() || MO->isDef() || Reg != MO->getReg())
1112         continue;
1113
1114       // DEBUG_VALUE nodes do not contribute to code generation and should
1115       // always be ignored.  Failure to do so may result in trying to modify
1116       // KILL flags on DEBUG_VALUE nodes, which is distressing.
1117       if (MO->isDebug())
1118         continue;
1119
1120       // If the register has the internal flag then it could be killing an
1121       // internal def of the register.  In this case, just skip.  We only want
1122       // to toggle the flag on operands visible outside the bundle.
1123       if (MO->isInternalRead())
1124         continue;
1125
1126       if (MO->isKill() == NewKillState)
1127         continue;
1128       MO->setIsKill(NewKillState);
1129       if (NewKillState)
1130         return;
1131     }
1132   }
1133 }
1134
1135 bool ScheduleDAGInstrs::toggleKillFlag(MachineInstr *MI, MachineOperand &MO) {
1136   // Setting kill flag...
1137   if (!MO.isKill()) {
1138     MO.setIsKill(true);
1139     toggleBundleKillFlag(MI, MO.getReg(), true);
1140     return false;
1141   }
1142
1143   // If MO itself is live, clear the kill flag...
1144   if (LiveRegs.test(MO.getReg())) {
1145     MO.setIsKill(false);
1146     toggleBundleKillFlag(MI, MO.getReg(), false);
1147     return false;
1148   }
1149
1150   // If any subreg of MO is live, then create an imp-def for that
1151   // subreg and keep MO marked as killed.
1152   MO.setIsKill(false);
1153   toggleBundleKillFlag(MI, MO.getReg(), false);
1154   bool AllDead = true;
1155   const unsigned SuperReg = MO.getReg();
1156   MachineInstrBuilder MIB(MF, MI);
1157   for (MCSubRegIterator SubRegs(SuperReg, TRI); SubRegs.isValid(); ++SubRegs) {
1158     if (LiveRegs.test(*SubRegs)) {
1159       MIB.addReg(*SubRegs, RegState::ImplicitDefine);
1160       AllDead = false;
1161     }
1162   }
1163
1164   if(AllDead) {
1165     MO.setIsKill(true);
1166     toggleBundleKillFlag(MI, MO.getReg(), true);
1167   }
1168   return false;
1169 }
1170
1171 // FIXME: Reuse the LivePhysRegs utility for this.
1172 void ScheduleDAGInstrs::fixupKills(MachineBasicBlock *MBB) {
1173   DEBUG(dbgs() << "Fixup kills for BB#" << MBB->getNumber() << '\n');
1174
1175   LiveRegs.resize(TRI->getNumRegs());
1176   BitVector killedRegs(TRI->getNumRegs());
1177
1178   startBlockForKills(MBB);
1179
1180   // Examine block from end to start...
1181   unsigned Count = MBB->size();
1182   for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
1183        I != E; --Count) {
1184     MachineInstr *MI = --I;
1185     if (MI->isDebugValue())
1186       continue;
1187
1188     // Update liveness.  Registers that are defed but not used in this
1189     // instruction are now dead. Mark register and all subregs as they
1190     // are completely defined.
1191     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1192       MachineOperand &MO = MI->getOperand(i);
1193       if (MO.isRegMask())
1194         LiveRegs.clearBitsNotInMask(MO.getRegMask());
1195       if (!MO.isReg()) continue;
1196       unsigned Reg = MO.getReg();
1197       if (Reg == 0) continue;
1198       if (!MO.isDef()) continue;
1199       // Ignore two-addr defs.
1200       if (MI->isRegTiedToUseOperand(i)) continue;
1201
1202       // Repeat for reg and all subregs.
1203       for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1204            SubRegs.isValid(); ++SubRegs)
1205         LiveRegs.reset(*SubRegs);
1206     }
1207
1208     // Examine all used registers and set/clear kill flag. When a
1209     // register is used multiple times we only set the kill flag on
1210     // the first use. Don't set kill flags on undef operands.
1211     killedRegs.reset();
1212     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1213       MachineOperand &MO = MI->getOperand(i);
1214       if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
1215       unsigned Reg = MO.getReg();
1216       if ((Reg == 0) || MRI.isReserved(Reg)) continue;
1217
1218       bool kill = false;
1219       if (!killedRegs.test(Reg)) {
1220         kill = true;
1221         // A register is not killed if any subregs are live...
1222         for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
1223           if (LiveRegs.test(*SubRegs)) {
1224             kill = false;
1225             break;
1226           }
1227         }
1228
1229         // If subreg is not live, then register is killed if it became
1230         // live in this instruction
1231         if (kill)
1232           kill = !LiveRegs.test(Reg);
1233       }
1234
1235       if (MO.isKill() != kill) {
1236         DEBUG(dbgs() << "Fixing " << MO << " in ");
1237         // Warning: toggleKillFlag may invalidate MO.
1238         toggleKillFlag(MI, MO);
1239         DEBUG(MI->dump());
1240         DEBUG(if (MI->getOpcode() == TargetOpcode::BUNDLE) {
1241           MachineBasicBlock::instr_iterator Begin = MI;
1242           MachineBasicBlock::instr_iterator End = getBundleEnd(MI);
1243           while (++Begin != End)
1244             DEBUG(Begin->dump());
1245         });
1246       }
1247
1248       killedRegs.set(Reg);
1249     }
1250
1251     // Mark any used register (that is not using undef) and subregs as
1252     // now live...
1253     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1254       MachineOperand &MO = MI->getOperand(i);
1255       if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
1256       unsigned Reg = MO.getReg();
1257       if ((Reg == 0) || MRI.isReserved(Reg)) continue;
1258
1259       for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1260            SubRegs.isValid(); ++SubRegs)
1261         LiveRegs.set(*SubRegs);
1262     }
1263   }
1264 }
1265
1266 void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
1267 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1268   SU->getInstr()->dump();
1269 #endif
1270 }
1271
1272 std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
1273   std::string s;
1274   raw_string_ostream oss(s);
1275   if (SU == &EntrySU)
1276     oss << "<entry>";
1277   else if (SU == &ExitSU)
1278     oss << "<exit>";
1279   else
1280     SU->getInstr()->print(oss, /*SkipOpers=*/true);
1281   return oss.str();
1282 }
1283
1284 /// Return the basic block label. It is not necessarilly unique because a block
1285 /// contains multiple scheduling regions. But it is fine for visualization.
1286 std::string ScheduleDAGInstrs::getDAGName() const {
1287   return "dag." + BB->getFullName();
1288 }
1289
1290 //===----------------------------------------------------------------------===//
1291 // SchedDFSResult Implementation
1292 //===----------------------------------------------------------------------===//
1293
1294 namespace llvm {
1295 /// \brief Internal state used to compute SchedDFSResult.
1296 class SchedDFSImpl {
1297   SchedDFSResult &R;
1298
1299   /// Join DAG nodes into equivalence classes by their subtree.
1300   IntEqClasses SubtreeClasses;
1301   /// List PredSU, SuccSU pairs that represent data edges between subtrees.
1302   std::vector<std::pair<const SUnit*, const SUnit*> > ConnectionPairs;
1303
1304   struct RootData {
1305     unsigned NodeID;
1306     unsigned ParentNodeID;  // Parent node (member of the parent subtree).
1307     unsigned SubInstrCount; // Instr count in this tree only, not children.
1308
1309     RootData(unsigned id): NodeID(id),
1310                            ParentNodeID(SchedDFSResult::InvalidSubtreeID),
1311                            SubInstrCount(0) {}
1312
1313     unsigned getSparseSetIndex() const { return NodeID; }
1314   };
1315
1316   SparseSet<RootData> RootSet;
1317
1318 public:
1319   SchedDFSImpl(SchedDFSResult &r): R(r), SubtreeClasses(R.DFSNodeData.size()) {
1320     RootSet.setUniverse(R.DFSNodeData.size());
1321   }
1322
1323   /// Return true if this node been visited by the DFS traversal.
1324   ///
1325   /// During visitPostorderNode the Node's SubtreeID is assigned to the Node
1326   /// ID. Later, SubtreeID is updated but remains valid.
1327   bool isVisited(const SUnit *SU) const {
1328     return R.DFSNodeData[SU->NodeNum].SubtreeID
1329       != SchedDFSResult::InvalidSubtreeID;
1330   }
1331
1332   /// Initialize this node's instruction count. We don't need to flag the node
1333   /// visited until visitPostorder because the DAG cannot have cycles.
1334   void visitPreorder(const SUnit *SU) {
1335     R.DFSNodeData[SU->NodeNum].InstrCount =
1336       SU->getInstr()->isTransient() ? 0 : 1;
1337   }
1338
1339   /// Called once for each node after all predecessors are visited. Revisit this
1340   /// node's predecessors and potentially join them now that we know the ILP of
1341   /// the other predecessors.
1342   void visitPostorderNode(const SUnit *SU) {
1343     // Mark this node as the root of a subtree. It may be joined with its
1344     // successors later.
1345     R.DFSNodeData[SU->NodeNum].SubtreeID = SU->NodeNum;
1346     RootData RData(SU->NodeNum);
1347     RData.SubInstrCount = SU->getInstr()->isTransient() ? 0 : 1;
1348
1349     // If any predecessors are still in their own subtree, they either cannot be
1350     // joined or are large enough to remain separate. If this parent node's
1351     // total instruction count is not greater than a child subtree by at least
1352     // the subtree limit, then try to join it now since splitting subtrees is
1353     // only useful if multiple high-pressure paths are possible.
1354     unsigned InstrCount = R.DFSNodeData[SU->NodeNum].InstrCount;
1355     for (SUnit::const_pred_iterator
1356            PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
1357       if (PI->getKind() != SDep::Data)
1358         continue;
1359       unsigned PredNum = PI->getSUnit()->NodeNum;
1360       if ((InstrCount - R.DFSNodeData[PredNum].InstrCount) < R.SubtreeLimit)
1361         joinPredSubtree(*PI, SU, /*CheckLimit=*/false);
1362
1363       // Either link or merge the TreeData entry from the child to the parent.
1364       if (R.DFSNodeData[PredNum].SubtreeID == PredNum) {
1365         // If the predecessor's parent is invalid, this is a tree edge and the
1366         // current node is the parent.
1367         if (RootSet[PredNum].ParentNodeID == SchedDFSResult::InvalidSubtreeID)
1368           RootSet[PredNum].ParentNodeID = SU->NodeNum;
1369       }
1370       else if (RootSet.count(PredNum)) {
1371         // The predecessor is not a root, but is still in the root set. This
1372         // must be the new parent that it was just joined to. Note that
1373         // RootSet[PredNum].ParentNodeID may either be invalid or may still be
1374         // set to the original parent.
1375         RData.SubInstrCount += RootSet[PredNum].SubInstrCount;
1376         RootSet.erase(PredNum);
1377       }
1378     }
1379     RootSet[SU->NodeNum] = RData;
1380   }
1381
1382   /// Called once for each tree edge after calling visitPostOrderNode on the
1383   /// predecessor. Increment the parent node's instruction count and
1384   /// preemptively join this subtree to its parent's if it is small enough.
1385   void visitPostorderEdge(const SDep &PredDep, const SUnit *Succ) {
1386     R.DFSNodeData[Succ->NodeNum].InstrCount
1387       += R.DFSNodeData[PredDep.getSUnit()->NodeNum].InstrCount;
1388     joinPredSubtree(PredDep, Succ);
1389   }
1390
1391   /// Add a connection for cross edges.
1392   void visitCrossEdge(const SDep &PredDep, const SUnit *Succ) {
1393     ConnectionPairs.push_back(std::make_pair(PredDep.getSUnit(), Succ));
1394   }
1395
1396   /// Set each node's subtree ID to the representative ID and record connections
1397   /// between trees.
1398   void finalize() {
1399     SubtreeClasses.compress();
1400     R.DFSTreeData.resize(SubtreeClasses.getNumClasses());
1401     assert(SubtreeClasses.getNumClasses() == RootSet.size()
1402            && "number of roots should match trees");
1403     for (SparseSet<RootData>::const_iterator
1404            RI = RootSet.begin(), RE = RootSet.end(); RI != RE; ++RI) {
1405       unsigned TreeID = SubtreeClasses[RI->NodeID];
1406       if (RI->ParentNodeID != SchedDFSResult::InvalidSubtreeID)
1407         R.DFSTreeData[TreeID].ParentTreeID = SubtreeClasses[RI->ParentNodeID];
1408       R.DFSTreeData[TreeID].SubInstrCount = RI->SubInstrCount;
1409       // Note that SubInstrCount may be greater than InstrCount if we joined
1410       // subtrees across a cross edge. InstrCount will be attributed to the
1411       // original parent, while SubInstrCount will be attributed to the joined
1412       // parent.
1413     }
1414     R.SubtreeConnections.resize(SubtreeClasses.getNumClasses());
1415     R.SubtreeConnectLevels.resize(SubtreeClasses.getNumClasses());
1416     DEBUG(dbgs() << R.getNumSubtrees() << " subtrees:\n");
1417     for (unsigned Idx = 0, End = R.DFSNodeData.size(); Idx != End; ++Idx) {
1418       R.DFSNodeData[Idx].SubtreeID = SubtreeClasses[Idx];
1419       DEBUG(dbgs() << "  SU(" << Idx << ") in tree "
1420             << R.DFSNodeData[Idx].SubtreeID << '\n');
1421     }
1422     for (std::vector<std::pair<const SUnit*, const SUnit*> >::const_iterator
1423            I = ConnectionPairs.begin(), E = ConnectionPairs.end();
1424          I != E; ++I) {
1425       unsigned PredTree = SubtreeClasses[I->first->NodeNum];
1426       unsigned SuccTree = SubtreeClasses[I->second->NodeNum];
1427       if (PredTree == SuccTree)
1428         continue;
1429       unsigned Depth = I->first->getDepth();
1430       addConnection(PredTree, SuccTree, Depth);
1431       addConnection(SuccTree, PredTree, Depth);
1432     }
1433   }
1434
1435 protected:
1436   /// Join the predecessor subtree with the successor that is its DFS
1437   /// parent. Apply some heuristics before joining.
1438   bool joinPredSubtree(const SDep &PredDep, const SUnit *Succ,
1439                        bool CheckLimit = true) {
1440     assert(PredDep.getKind() == SDep::Data && "Subtrees are for data edges");
1441
1442     // Check if the predecessor is already joined.
1443     const SUnit *PredSU = PredDep.getSUnit();
1444     unsigned PredNum = PredSU->NodeNum;
1445     if (R.DFSNodeData[PredNum].SubtreeID != PredNum)
1446       return false;
1447
1448     // Four is the magic number of successors before a node is considered a
1449     // pinch point.
1450     unsigned NumDataSucs = 0;
1451     for (SUnit::const_succ_iterator SI = PredSU->Succs.begin(),
1452            SE = PredSU->Succs.end(); SI != SE; ++SI) {
1453       if (SI->getKind() == SDep::Data) {
1454         if (++NumDataSucs >= 4)
1455           return false;
1456       }
1457     }
1458     if (CheckLimit && R.DFSNodeData[PredNum].InstrCount > R.SubtreeLimit)
1459       return false;
1460     R.DFSNodeData[PredNum].SubtreeID = Succ->NodeNum;
1461     SubtreeClasses.join(Succ->NodeNum, PredNum);
1462     return true;
1463   }
1464
1465   /// Called by finalize() to record a connection between trees.
1466   void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth) {
1467     if (!Depth)
1468       return;
1469
1470     do {
1471       SmallVectorImpl<SchedDFSResult::Connection> &Connections =
1472         R.SubtreeConnections[FromTree];
1473       for (SmallVectorImpl<SchedDFSResult::Connection>::iterator
1474              I = Connections.begin(), E = Connections.end(); I != E; ++I) {
1475         if (I->TreeID == ToTree) {
1476           I->Level = std::max(I->Level, Depth);
1477           return;
1478         }
1479       }
1480       Connections.push_back(SchedDFSResult::Connection(ToTree, Depth));
1481       FromTree = R.DFSTreeData[FromTree].ParentTreeID;
1482     } while (FromTree != SchedDFSResult::InvalidSubtreeID);
1483   }
1484 };
1485 } // namespace llvm
1486
1487 namespace {
1488 /// \brief Manage the stack used by a reverse depth-first search over the DAG.
1489 class SchedDAGReverseDFS {
1490   std::vector<std::pair<const SUnit*, SUnit::const_pred_iterator> > DFSStack;
1491 public:
1492   bool isComplete() const { return DFSStack.empty(); }
1493
1494   void follow(const SUnit *SU) {
1495     DFSStack.push_back(std::make_pair(SU, SU->Preds.begin()));
1496   }
1497   void advance() { ++DFSStack.back().second; }
1498
1499   const SDep *backtrack() {
1500     DFSStack.pop_back();
1501     return DFSStack.empty() ? nullptr : std::prev(DFSStack.back().second);
1502   }
1503
1504   const SUnit *getCurr() const { return DFSStack.back().first; }
1505
1506   SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
1507
1508   SUnit::const_pred_iterator getPredEnd() const {
1509     return getCurr()->Preds.end();
1510   }
1511 };
1512 } // anonymous
1513
1514 static bool hasDataSucc(const SUnit *SU) {
1515   for (SUnit::const_succ_iterator
1516          SI = SU->Succs.begin(), SE = SU->Succs.end(); SI != SE; ++SI) {
1517     if (SI->getKind() == SDep::Data && !SI->getSUnit()->isBoundaryNode())
1518       return true;
1519   }
1520   return false;
1521 }
1522
1523 /// Compute an ILP metric for all nodes in the subDAG reachable via depth-first
1524 /// search from this root.
1525 void SchedDFSResult::compute(ArrayRef<SUnit> SUnits) {
1526   if (!IsBottomUp)
1527     llvm_unreachable("Top-down ILP metric is unimplemnted");
1528
1529   SchedDFSImpl Impl(*this);
1530   for (ArrayRef<SUnit>::const_iterator
1531          SI = SUnits.begin(), SE = SUnits.end(); SI != SE; ++SI) {
1532     const SUnit *SU = &*SI;
1533     if (Impl.isVisited(SU) || hasDataSucc(SU))
1534       continue;
1535
1536     SchedDAGReverseDFS DFS;
1537     Impl.visitPreorder(SU);
1538     DFS.follow(SU);
1539     for (;;) {
1540       // Traverse the leftmost path as far as possible.
1541       while (DFS.getPred() != DFS.getPredEnd()) {
1542         const SDep &PredDep = *DFS.getPred();
1543         DFS.advance();
1544         // Ignore non-data edges.
1545         if (PredDep.getKind() != SDep::Data
1546             || PredDep.getSUnit()->isBoundaryNode()) {
1547           continue;
1548         }
1549         // An already visited edge is a cross edge, assuming an acyclic DAG.
1550         if (Impl.isVisited(PredDep.getSUnit())) {
1551           Impl.visitCrossEdge(PredDep, DFS.getCurr());
1552           continue;
1553         }
1554         Impl.visitPreorder(PredDep.getSUnit());
1555         DFS.follow(PredDep.getSUnit());
1556       }
1557       // Visit the top of the stack in postorder and backtrack.
1558       const SUnit *Child = DFS.getCurr();
1559       const SDep *PredDep = DFS.backtrack();
1560       Impl.visitPostorderNode(Child);
1561       if (PredDep)
1562         Impl.visitPostorderEdge(*PredDep, DFS.getCurr());
1563       if (DFS.isComplete())
1564         break;
1565     }
1566   }
1567   Impl.finalize();
1568 }
1569
1570 /// The root of the given SubtreeID was just scheduled. For all subtrees
1571 /// connected to this tree, record the depth of the connection so that the
1572 /// nearest connected subtrees can be prioritized.
1573 void SchedDFSResult::scheduleTree(unsigned SubtreeID) {
1574   for (SmallVectorImpl<Connection>::const_iterator
1575          I = SubtreeConnections[SubtreeID].begin(),
1576          E = SubtreeConnections[SubtreeID].end(); I != E; ++I) {
1577     SubtreeConnectLevels[I->TreeID] =
1578       std::max(SubtreeConnectLevels[I->TreeID], I->Level);
1579     DEBUG(dbgs() << "  Tree: " << I->TreeID
1580           << " @" << SubtreeConnectLevels[I->TreeID] << '\n');
1581   }
1582 }
1583
1584 LLVM_DUMP_METHOD
1585 void ILPValue::print(raw_ostream &OS) const {
1586   OS << InstrCount << " / " << Length << " = ";
1587   if (!Length)
1588     OS << "BADILP";
1589   else
1590     OS << format("%g", ((double)InstrCount / Length));
1591 }
1592
1593 LLVM_DUMP_METHOD
1594 void ILPValue::dump() const {
1595   dbgs() << *this << '\n';
1596 }
1597
1598 namespace llvm {
1599
1600 LLVM_DUMP_METHOD
1601 raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) {
1602   Val.print(OS);
1603   return OS;
1604 }
1605
1606 } // namespace llvm