blob: d36322dc302bb4513d65e3896ed7f63a80ce038d [file] [log] [blame]
Dan Gohmanf90d3b02008-12-08 17:50:35 +00001//===---- ScheduleDAGInstrs.cpp - MachineInstr Rescheduling ---------------===//
Dan Gohman60cb69e2008-11-19 23:18:57 +00002//
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//
Dan Gohmanf90d3b02008-12-08 17:50:35 +000010// This implements the ScheduleDAGInstrs class, which implements re-scheduling
11// of MachineInstrs.
Dan Gohman60cb69e2008-11-19 23:18:57 +000012//
13//===----------------------------------------------------------------------===//
14
Andrew Trick48d392e2012-11-28 05:13:28 +000015#define DEBUG_TYPE "misched"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/CodeGen/ScheduleDAGInstrs.h"
17#include "llvm/ADT/MapVector.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/ADT/SmallSet.h"
Dan Gohman1ee0d412009-01-30 02:49:14 +000020#include "llvm/Analysis/AliasAnalysis.h"
Dan Gohmana4fcd242010-12-15 20:02:24 +000021#include "llvm/Analysis/ValueTracking.h"
Andrew Trick46cc9a42012-02-22 06:08:11 +000022#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Dan Gohmandddc1ac2008-12-16 03:25:46 +000023#include "llvm/CodeGen/MachineFunctionPass.h"
Andrew Trick6b104f82013-12-28 21:56:55 +000024#include "llvm/CodeGen/MachineInstrBuilder.h"
Dan Gohman48b185d2009-09-25 20:36:54 +000025#include "llvm/CodeGen/MachineMemOperand.h"
Dan Gohmandddc1ac2008-12-16 03:25:46 +000026#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman3aab10b2008-12-04 01:35:46 +000027#include "llvm/CodeGen/PseudoSourceValue.h"
Andrew Trick88517f62012-06-06 19:47:35 +000028#include "llvm/CodeGen/RegisterPressure.h"
Andrew Trickcd1c2f92012-11-28 05:13:24 +000029#include "llvm/CodeGen/ScheduleDFS.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/Operator.h"
Evan Cheng8264e272011-06-29 01:14:12 +000031#include "llvm/MC/MCInstrItineraries.h"
Andrew Trickda01ba32012-05-15 18:59:41 +000032#include "llvm/Support/CommandLine.h"
Dan Gohman60cb69e2008-11-19 23:18:57 +000033#include "llvm/Support/Debug.h"
Andrew Trick90f711d2012-10-15 18:02:27 +000034#include "llvm/Support/Format.h"
Dan Gohman60cb69e2008-11-19 23:18:57 +000035#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Target/TargetInstrInfo.h"
37#include "llvm/Target/TargetMachine.h"
38#include "llvm/Target/TargetRegisterInfo.h"
39#include "llvm/Target/TargetSubtargetInfo.h"
Andrew Trickc01b0042013-08-23 17:48:43 +000040#include <queue>
41
Dan Gohman60cb69e2008-11-19 23:18:57 +000042using namespace llvm;
43
Andrew Trickda01ba32012-05-15 18:59:41 +000044static cl::opt<bool> EnableAASchedMI("enable-aa-sched-mi", cl::Hidden,
45 cl::ZeroOrMore, cl::init(false),
46 cl::desc("Enable use of AA during MI GAD construction"));
47
Hal Finkeldbebb522014-01-25 19:24:54 +000048static cl::opt<bool> UseTBAA("use-tbaa-in-sched-mi", cl::Hidden,
Hal Finkel3b48d082014-04-12 01:26:00 +000049 cl::init(true), cl::desc("Enable use of TBAA during MI GAD construction"));
Hal Finkeldbebb522014-01-25 19:24:54 +000050
Dan Gohman619ef482009-01-15 19:20:50 +000051ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
Dan Gohmandddc1ac2008-12-16 03:25:46 +000052 const MachineLoopInfo &mli,
Andrew Trick1d028a32012-01-14 02:17:12 +000053 const MachineDominatorTree &mdt,
Andrew Trick46cc9a42012-02-22 06:08:11 +000054 bool IsPostRAFlag,
Andrew Trick6b104f82013-12-28 21:56:55 +000055 bool RemoveKillFlags,
Andrew Trick46cc9a42012-02-22 06:08:11 +000056 LiveIntervals *lis)
Andrew Trickdd79f0f2012-10-10 05:43:09 +000057 : ScheduleDAG(mf), MLI(mli), MDT(mdt), MFI(mf.getFrameInfo()), LIS(lis),
Andrew Trick6b104f82013-12-28 21:56:55 +000058 IsPostRA(IsPostRAFlag), RemoveKillFlags(RemoveKillFlags),
Craig Topperc0196b12014-04-14 00:51:57 +000059 CanHandleTerminators(false), FirstDbgValue(nullptr) {
Andrew Trick46cc9a42012-02-22 06:08:11 +000060 assert((IsPostRA || LIS) && "PreRA scheduling requires LiveIntervals");
Devang Patele5feef02011-06-02 20:07:12 +000061 DbgValues.clear();
Andrew Trickdb42c6f2012-02-22 06:08:13 +000062 assert(!(IsPostRA && MRI.getNumVirtRegs()) &&
Andrew Trickda84e642012-02-21 04:51:23 +000063 "Virtual registers must be removed prior to PostRA scheduling");
Andrew Trick9b635132012-09-18 18:20:00 +000064
65 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
66 SchedModel.init(*ST.getSchedModel(), &ST, TII);
Evan Chengf0236e02009-10-18 19:58:47 +000067}
Dan Gohman60cb69e2008-11-19 23:18:57 +000068
Dan Gohman1ee0d412009-01-30 02:49:14 +000069/// getUnderlyingObjectFromInt - This is the function that does the work of
70/// looking through basic ptrtoint+arithmetic+inttoptr sequences.
71static const Value *getUnderlyingObjectFromInt(const Value *V) {
72 do {
Dan Gohman58b0e712009-07-17 20:58:59 +000073 if (const Operator *U = dyn_cast<Operator>(V)) {
Dan Gohman1ee0d412009-01-30 02:49:14 +000074 // If we find a ptrtoint, we can transfer control back to the
75 // regular getUnderlyingObjectFromInt.
Dan Gohman58b0e712009-07-17 20:58:59 +000076 if (U->getOpcode() == Instruction::PtrToInt)
Dan Gohman1ee0d412009-01-30 02:49:14 +000077 return U->getOperand(0);
Andrew Trick0be19362012-11-28 03:42:49 +000078 // If we find an add of a constant, a multiplied value, or a phi, it's
Dan Gohman1ee0d412009-01-30 02:49:14 +000079 // likely that the other operand will lead us to the base
80 // object. We don't have to worry about the case where the
Dan Gohman6c0c2192009-08-07 01:26:06 +000081 // object address is somehow being computed by the multiply,
Dan Gohman1ee0d412009-01-30 02:49:14 +000082 // because our callers only care when the result is an
Nick Lewycky1a329542012-10-26 04:27:49 +000083 // identifiable object.
Dan Gohman58b0e712009-07-17 20:58:59 +000084 if (U->getOpcode() != Instruction::Add ||
Dan Gohman1ee0d412009-01-30 02:49:14 +000085 (!isa<ConstantInt>(U->getOperand(1)) &&
Andrew Trick0be19362012-11-28 03:42:49 +000086 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
87 !isa<PHINode>(U->getOperand(1))))
Dan Gohman1ee0d412009-01-30 02:49:14 +000088 return V;
89 V = U->getOperand(0);
90 } else {
91 return V;
92 }
Duncan Sands19d0b472010-02-16 11:11:14 +000093 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
Dan Gohman1ee0d412009-01-30 02:49:14 +000094 } while (1);
95}
96
Hal Finkel66859ae2012-12-10 18:49:16 +000097/// getUnderlyingObjects - This is a wrapper around GetUnderlyingObjects
Dan Gohman1ee0d412009-01-30 02:49:14 +000098/// and adds support for basic ptrtoint+arithmetic+inttoptr sequences.
Hal Finkel66859ae2012-12-10 18:49:16 +000099static void getUnderlyingObjects(const Value *V,
100 SmallVectorImpl<Value *> &Objects) {
101 SmallPtrSet<const Value*, 16> Visited;
102 SmallVector<const Value *, 4> Working(1, V);
Dan Gohman1ee0d412009-01-30 02:49:14 +0000103 do {
Hal Finkel66859ae2012-12-10 18:49:16 +0000104 V = Working.pop_back_val();
105
106 SmallVector<Value *, 4> Objs;
107 GetUnderlyingObjects(const_cast<Value *>(V), Objs);
108
Craig Toppere1c1d362013-07-03 05:11:49 +0000109 for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), IE = Objs.end();
Hal Finkel66859ae2012-12-10 18:49:16 +0000110 I != IE; ++I) {
111 V = *I;
112 if (!Visited.insert(V))
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());
Dan Gohman1ee0d412009-01-30 02:49:14 +0000125}
126
Benjamin Kramerfd510922013-06-29 18:41:17 +0000127typedef SmallVector<PointerIntPair<const Value *, 1, bool>, 4>
128UnderlyingObjectsVector;
129
Hal Finkel66859ae2012-12-10 18:49:16 +0000130/// getUnderlyingObjectsForInstr - If this machine instr has memory reference
Dan Gohman1ee0d412009-01-30 02:49:14 +0000131/// information and it can be tracked to a normal reference to a known
Hal Finkel66859ae2012-12-10 18:49:16 +0000132/// object, return the Value for that object.
133static void getUnderlyingObjectsForInstr(const MachineInstr *MI,
Benjamin Kramerfd510922013-06-29 18:41:17 +0000134 const MachineFrameInfo *MFI,
135 UnderlyingObjectsVector &Objects) {
Dan Gohman1ee0d412009-01-30 02:49:14 +0000136 if (!MI->hasOneMemOperand() ||
Dan Gohman48b185d2009-09-25 20:36:54 +0000137 !(*MI->memoperands_begin())->getValue() ||
138 (*MI->memoperands_begin())->isVolatile())
Hal Finkel66859ae2012-12-10 18:49:16 +0000139 return;
Dan Gohman1ee0d412009-01-30 02:49:14 +0000140
Dan Gohman48b185d2009-09-25 20:36:54 +0000141 const Value *V = (*MI->memoperands_begin())->getValue();
Dan Gohman1ee0d412009-01-30 02:49:14 +0000142 if (!V)
Hal Finkel66859ae2012-12-10 18:49:16 +0000143 return;
Dan Gohman1ee0d412009-01-30 02:49:14 +0000144
Nick Lewyckyb9e44d62014-02-20 05:06:26 +0000145 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
146 // For now, ignore PseudoSourceValues which may alias LLVM IR values
147 // because the code that uses this function has no way to cope with
148 // such aliases.
Nick Lewyckyc4a9f8a2014-02-20 06:35:31 +0000149 if (!PSV->isAliased(MFI)) {
150 bool MayAlias = PSV->mayAlias(MFI);
151 Objects.push_back(UnderlyingObjectsVector::value_type(V, MayAlias));
152 }
Nick Lewyckyb9e44d62014-02-20 05:06:26 +0000153 return;
154 }
155
Hal Finkel66859ae2012-12-10 18:49:16 +0000156 SmallVector<Value *, 4> Objs;
157 getUnderlyingObjects(V, Objs);
Andrew Trick24b1c482011-05-05 19:24:06 +0000158
Craig Toppere1c1d362013-07-03 05:11:49 +0000159 for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), IE = Objs.end();
160 I != IE; ++I) {
Hal Finkel66859ae2012-12-10 18:49:16 +0000161 V = *I;
162
Nick Lewyckyb9e44d62014-02-20 05:06:26 +0000163 assert(!isa<PseudoSourceValue>(V) && "Underlying value is a stack slot!");
Hal Finkel66859ae2012-12-10 18:49:16 +0000164
Nick Lewyckyb9e44d62014-02-20 05:06:26 +0000165 if (!isIdentifiedObject(V)) {
Hal Finkel66859ae2012-12-10 18:49:16 +0000166 Objects.clear();
167 return;
168 }
169
Nick Lewyckyb9e44d62014-02-20 05:06:26 +0000170 Objects.push_back(UnderlyingObjectsVector::value_type(V, true));
Evan Cheng0e9d9ca2009-10-18 18:16:27 +0000171 }
Dan Gohman1ee0d412009-01-30 02:49:14 +0000172}
173
Andrew Trick7405c6d2012-04-20 20:05:21 +0000174void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) {
175 BB = bb;
Dan Gohmanb9543432009-02-10 23:27:53 +0000176}
177
Andrew Trick52226d42012-03-07 23:00:49 +0000178void ScheduleDAGInstrs::finishBlock() {
Andrew Trick51ee9362012-04-20 20:24:33 +0000179 // Subclasses should no longer refer to the old block.
Craig Topperc0196b12014-04-14 00:51:57 +0000180 BB = nullptr;
Andrew Trick60cf03e2012-03-07 05:21:52 +0000181}
182
Andrew Trick60cf03e2012-03-07 05:21:52 +0000183/// Initialize the DAG and common scheduler state for the current scheduling
184/// region. This does not actually create the DAG, only clears it. The
185/// scheduling driver may call BuildSchedGraph multiple times per scheduling
186/// region.
187void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb,
188 MachineBasicBlock::iterator begin,
189 MachineBasicBlock::iterator end,
Andrew Tricka53e1012013-08-23 17:48:33 +0000190 unsigned regioninstrs) {
Andrew Trick7405c6d2012-04-20 20:05:21 +0000191 assert(bb == BB && "startBlock should set BB");
Andrew Trick8c207e42012-03-09 04:29:02 +0000192 RegionBegin = begin;
193 RegionEnd = end;
Andrew Tricka53e1012013-08-23 17:48:33 +0000194 NumRegionInstrs = regioninstrs;
Andrew Trick60cf03e2012-03-07 05:21:52 +0000195}
196
197/// Close the current scheduling region. Don't clear any state in case the
198/// driver wants to refer to the previous scheduling region.
199void ScheduleDAGInstrs::exitRegion() {
200 // Nothing to do.
201}
202
Andrew Trick52226d42012-03-07 23:00:49 +0000203/// addSchedBarrierDeps - Add dependencies from instructions in the current
Evan Cheng15459b62010-10-23 02:10:46 +0000204/// list of instructions being scheduled to scheduling barrier by adding
205/// the exit SU to the register defs and use list. This is because we want to
206/// make sure instructions which define registers that are either used by
207/// the terminator or are live-out are properly scheduled. This is
208/// especially important when the definition latency of the return value(s)
209/// are too high to be hidden by the branch or when the liveout registers
210/// used by instructions in the fallthrough block.
Andrew Trick52226d42012-03-07 23:00:49 +0000211void ScheduleDAGInstrs::addSchedBarrierDeps() {
Craig Topperc0196b12014-04-14 00:51:57 +0000212 MachineInstr *ExitMI = RegionEnd != BB->end() ? &*RegionEnd : nullptr;
Evan Cheng15459b62010-10-23 02:10:46 +0000213 ExitSU.setInstr(ExitMI);
214 bool AllDepKnown = ExitMI &&
Evan Cheng7f8e5632011-12-07 07:15:52 +0000215 (ExitMI->isCall() || ExitMI->isBarrier());
Evan Cheng15459b62010-10-23 02:10:46 +0000216 if (ExitMI && AllDepKnown) {
217 // If it's a call or a barrier, add dependencies on the defs and uses of
218 // instruction.
219 for (unsigned i = 0, e = ExitMI->getNumOperands(); i != e; ++i) {
220 const MachineOperand &MO = ExitMI->getOperand(i);
221 if (!MO.isReg() || MO.isDef()) continue;
222 unsigned Reg = MO.getReg();
223 if (Reg == 0) continue;
224
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000225 if (TRI->isPhysicalRegister(Reg))
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000226 Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg));
Andrew Tricke6913c72012-03-16 05:04:25 +0000227 else {
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000228 assert(!IsPostRA && "Virtual register encountered after regalloc.");
Andrew Trickd5953622012-12-01 01:22:44 +0000229 if (MO.readsReg()) // ignore undef operands
230 addVRegUseDeps(&ExitSU, i);
Andrew Tricke6913c72012-03-16 05:04:25 +0000231 }
Evan Cheng15459b62010-10-23 02:10:46 +0000232 }
233 } else {
234 // For others, e.g. fallthrough, conditional branch, assume the exit
Evan Chengcbdf7e82010-10-27 23:17:17 +0000235 // uses all the registers that are livein to the successor blocks.
Benjamin Kramer411d5a22012-03-16 17:38:19 +0000236 assert(Uses.empty() && "Uses in set before adding deps?");
Evan Chengcbdf7e82010-10-27 23:17:17 +0000237 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
238 SE = BB->succ_end(); SI != SE; ++SI)
239 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
Andrew Trick24b1c482011-05-05 19:24:06 +0000240 E = (*SI)->livein_end(); I != E; ++I) {
Evan Chengcbdf7e82010-10-27 23:17:17 +0000241 unsigned Reg = *I;
Benjamin Kramer411d5a22012-03-16 17:38:19 +0000242 if (!Uses.contains(Reg))
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000243 Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg));
Evan Chengcbdf7e82010-10-27 23:17:17 +0000244 }
Evan Cheng15459b62010-10-23 02:10:46 +0000245 }
246}
247
Andrew Trickd675a4c2012-02-23 01:52:38 +0000248/// MO is an operand of SU's instruction that defines a physical register. Add
249/// data dependencies from SU to any uses of the physical register.
Andrew Trickae535612012-08-23 00:39:43 +0000250void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU, unsigned OperIdx) {
251 const MachineOperand &MO = SU->getInstr()->getOperand(OperIdx);
Andrew Trickd675a4c2012-02-23 01:52:38 +0000252 assert(MO.isDef() && "expect physreg def");
253
254 // Ask the target if address-backscheduling is desirable, and if so how much.
255 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
Andrew Trickd675a4c2012-02-23 01:52:38 +0000256
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000257 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
258 Alias.isValid(); ++Alias) {
Andrew Trick9dbbd3e2012-02-24 07:04:55 +0000259 if (!Uses.contains(*Alias))
Andrew Trickd675a4c2012-02-23 01:52:38 +0000260 continue;
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000261 for (Reg2SUnitsMap::iterator I = Uses.find(*Alias); I != Uses.end(); ++I) {
262 SUnit *UseSU = I->SU;
Andrew Trickd675a4c2012-02-23 01:52:38 +0000263 if (UseSU == SU)
264 continue;
Andrew Trick07dced62012-10-08 18:54:00 +0000265
Andrew Trick07dced62012-10-08 18:54:00 +0000266 // Adjust the dependence latency using operand def/use information,
267 // then allow the target to perform its own adjustments.
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000268 int UseOp = I->OpIdx;
Craig Topperc0196b12014-04-14 00:51:57 +0000269 MachineInstr *RegUse = nullptr;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000270 SDep Dep;
271 if (UseOp < 0)
272 Dep = SDep(SU, SDep::Artificial);
273 else {
Andrew Tricke833e1c2013-04-13 06:07:40 +0000274 // Set the hasPhysRegDefs only for physreg defs that have a use within
275 // the scheduling region.
276 SU->hasPhysRegDefs = true;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000277 Dep = SDep(SU, SDep::Data, *Alias);
278 RegUse = UseSU->getInstr();
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000279 }
280 Dep.setLatency(
Andrew Trickde2109e2013-06-15 04:49:57 +0000281 SchedModel.computeOperandLatency(SU->getInstr(), OperIdx, RegUse,
282 UseOp));
Andrew Trick45446062012-06-05 21:11:27 +0000283
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000284 ST.adjustSchedDependency(SU, UseSU, Dep);
285 UseSU->addPred(Dep);
Andrew Trickd675a4c2012-02-23 01:52:38 +0000286 }
287 }
288}
289
Andrew Trickdbee9d82012-01-14 02:17:15 +0000290/// addPhysRegDeps - Add register dependencies (data, anti, and output) from
291/// this SUnit to following instructions in the same scheduling region that
292/// depend the physical register referenced at OperIdx.
293void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
Andrew Trick6b104f82013-12-28 21:56:55 +0000294 MachineInstr *MI = SU->getInstr();
295 MachineOperand &MO = MI->getOperand(OperIdx);
Andrew Trickdbee9d82012-01-14 02:17:15 +0000296
297 // Optionally add output and anti dependencies. For anti
298 // dependencies we use a latency of 0 because for a multi-issue
299 // target we want to allow the defining instruction to issue
300 // in the same cycle as the using instruction.
301 // TODO: Using a latency of 1 here for output dependencies assumes
302 // there's no cost for reusing registers.
303 SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000304 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
305 Alias.isValid(); ++Alias) {
Andrew Trick9dbbd3e2012-02-24 07:04:55 +0000306 if (!Defs.contains(*Alias))
Andrew Trickd675a4c2012-02-23 01:52:38 +0000307 continue;
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000308 for (Reg2SUnitsMap::iterator I = Defs.find(*Alias); I != Defs.end(); ++I) {
309 SUnit *DefSU = I->SU;
Andrew Trickdbee9d82012-01-14 02:17:15 +0000310 if (DefSU == &ExitSU)
311 continue;
312 if (DefSU != SU &&
313 (Kind != SDep::Output || !MO.isDead() ||
314 !DefSU->getInstr()->registerDefIsDead(*Alias))) {
315 if (Kind == SDep::Anti)
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000316 DefSU->addPred(SDep(SU, Kind, /*Reg=*/*Alias));
Andrew Trickdbee9d82012-01-14 02:17:15 +0000317 else {
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000318 SDep Dep(SU, Kind, /*Reg=*/*Alias);
Andrew Trickde2109e2013-06-15 04:49:57 +0000319 Dep.setLatency(
320 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000321 DefSU->addPred(Dep);
Andrew Trickdbee9d82012-01-14 02:17:15 +0000322 }
323 }
324 }
325 }
326
Andrew Trickd675a4c2012-02-23 01:52:38 +0000327 if (!MO.isDef()) {
Andrew Tricke833e1c2013-04-13 06:07:40 +0000328 SU->hasPhysRegUses = true;
Andrew Trickd675a4c2012-02-23 01:52:38 +0000329 // Either insert a new Reg2SUnits entry with an empty SUnits list, or
330 // retrieve the existing SUnits list for this register's uses.
331 // Push this SUnit on the use list.
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000332 Uses.insert(PhysRegSUOper(SU, OperIdx, MO.getReg()));
Andrew Trick6b104f82013-12-28 21:56:55 +0000333 if (RemoveKillFlags)
334 MO.setIsKill(false);
Andrew Trickd675a4c2012-02-23 01:52:38 +0000335 }
336 else {
Andrew Trickae535612012-08-23 00:39:43 +0000337 addPhysRegDataDeps(SU, OperIdx);
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000338 unsigned Reg = MO.getReg();
Andrew Trickdbee9d82012-01-14 02:17:15 +0000339
Andrew Trickd675a4c2012-02-23 01:52:38 +0000340 // clear this register's use list
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000341 if (Uses.contains(Reg))
342 Uses.eraseAll(Reg);
Andrew Trickd675a4c2012-02-23 01:52:38 +0000343
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000344 if (!MO.isDead()) {
345 Defs.eraseAll(Reg);
346 } else if (SU->isCall) {
347 // Calls will not be reordered because of chain dependencies (see
348 // below). Since call operands are dead, calls may continue to be added
349 // to the DefList making dependence checking quadratic in the size of
350 // the block. Instead, we leave only one call at the back of the
351 // DefList.
352 Reg2SUnitsMap::RangePair P = Defs.equal_range(Reg);
353 Reg2SUnitsMap::iterator B = P.first;
354 Reg2SUnitsMap::iterator I = P.second;
355 for (bool isBegin = I == B; !isBegin; /* empty */) {
356 isBegin = (--I) == B;
357 if (!I->SU->isCall)
358 break;
359 I = Defs.erase(I);
360 }
Andrew Trickdbee9d82012-01-14 02:17:15 +0000361 }
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000362
Andrew Trickd675a4c2012-02-23 01:52:38 +0000363 // Defs are pushed in the order they are visited and never reordered.
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000364 Defs.insert(PhysRegSUOper(SU, OperIdx, Reg));
Andrew Trickdbee9d82012-01-14 02:17:15 +0000365 }
366}
367
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000368/// addVRegDefDeps - Add register output and data dependencies from this SUnit
369/// to instructions that occur later in the same scheduling region if they read
370/// from or write to the virtual register defined at OperIdx.
371///
372/// TODO: Hoist loop induction variable increments. This has to be
373/// reevaluated. Generally, IV scheduling should be done before coalescing.
374void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
375 const MachineInstr *MI = SU->getInstr();
376 unsigned Reg = MI->getOperand(OperIdx).getReg();
377
Andrew Trick94053432012-07-28 01:48:15 +0000378 // Singly defined vregs do not have output/anti dependencies.
Andrew Trick64ca16e2012-02-22 18:34:49 +0000379 // The current operand is a def, so we have at least one.
Andrew Trick94053432012-07-28 01:48:15 +0000380 // Check here if there are any others...
Andrew Trick79795892012-07-30 23:48:17 +0000381 if (MRI.hasOneDef(Reg))
Andrew Trick94053432012-07-28 01:48:15 +0000382 return;
Andrew Trickdb42c6f2012-02-22 06:08:13 +0000383
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000384 // Add output dependence to the next nearest def of this vreg.
385 //
386 // Unless this definition is dead, the output dependence should be
387 // transitively redundant with antidependencies from this definition's
388 // uses. We're conservative for now until we have a way to guarantee the uses
389 // are not eliminated sometime during scheduling. The output dependence edge
390 // is also useful if output latency exceeds def-use latency.
Andrew Trick1eb4a0d2012-04-20 20:05:28 +0000391 VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
Andrew Trickd458e2d2012-02-22 21:59:00 +0000392 if (DefI == VRegDefs.end())
393 VRegDefs.insert(VReg2SUnit(Reg, SU));
394 else {
395 SUnit *DefSU = DefI->SU;
396 if (DefSU != SU && DefSU != &ExitSU) {
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000397 SDep Dep(SU, SDep::Output, Reg);
Andrew Trickde2109e2013-06-15 04:49:57 +0000398 Dep.setLatency(
399 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000400 DefSU->addPred(Dep);
Andrew Trickd458e2d2012-02-22 21:59:00 +0000401 }
402 DefI->SU = SU;
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000403 }
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000404}
405
Andrew Trick46cc9a42012-02-22 06:08:11 +0000406/// addVRegUseDeps - Add a register data dependency if the instruction that
407/// defines the virtual register used at OperIdx is mapped to an SUnit. Add a
408/// register antidependency from this SUnit to instructions that occur later in
409/// the same scheduling region if they write the virtual register.
410///
411/// TODO: Handle ExitSU "uses" properly.
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000412void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
Andrew Trick46cc9a42012-02-22 06:08:11 +0000413 MachineInstr *MI = SU->getInstr();
414 unsigned Reg = MI->getOperand(OperIdx).getReg();
415
Andrew Trick8dd26f02013-08-23 17:48:39 +0000416 // Record this local VReg use.
Andrew Trick2bc74c22013-08-30 04:36:57 +0000417 VReg2UseMap::iterator UI = VRegUses.find(Reg);
418 for (; UI != VRegUses.end(); ++UI) {
419 if (UI->SU == SU)
420 break;
421 }
422 if (UI == VRegUses.end())
423 VRegUses.insert(VReg2SUnit(Reg, SU));
Andrew Trick8dd26f02013-08-23 17:48:39 +0000424
Andrew Trick46cc9a42012-02-22 06:08:11 +0000425 // Lookup this operand's reaching definition.
426 assert(LIS && "vreg dependencies requires LiveIntervals");
Matthias Braun88dd0ab2013-10-10 21:28:52 +0000427 LiveQueryResult LRQ
428 = LIS->getInterval(Reg).Query(LIS->getInstructionIndex(MI));
Jakob Stoklund Olesenabc8c3d2012-05-20 02:44:38 +0000429 VNInfo *VNI = LRQ.valueIn();
Andrew Trick9e9a9f12012-04-24 18:04:41 +0000430
Andrew Trickda6a15d2012-02-23 03:16:24 +0000431 // VNI will be valid because MachineOperand::readsReg() is checked by caller.
Jakob Stoklund Olesenabc8c3d2012-05-20 02:44:38 +0000432 assert(VNI && "No value to read by operand");
Andrew Trick46cc9a42012-02-22 06:08:11 +0000433 MachineInstr *Def = LIS->getInstructionFromIndex(VNI->def);
Andrew Trickda6a15d2012-02-23 03:16:24 +0000434 // Phis and other noninstructions (after coalescing) have a NULL Def.
Andrew Trick46cc9a42012-02-22 06:08:11 +0000435 if (Def) {
436 SUnit *DefSU = getSUnit(Def);
437 if (DefSU) {
438 // The reaching Def lives within this scheduling region.
439 // Create a data dependence.
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000440 SDep dep(DefSU, SDep::Data, Reg);
Andrew Trick09650df2012-10-08 18:53:57 +0000441 // Adjust the dependence latency using operand def/use information, then
442 // allow the target to perform its own adjustments.
443 int DefOp = Def->findRegisterDefOperandIdx(Reg);
Andrew Trickde2109e2013-06-15 04:49:57 +0000444 dep.setLatency(SchedModel.computeOperandLatency(Def, DefOp, MI, OperIdx));
Andrew Trick45446062012-06-05 21:11:27 +0000445
Andrew Trick09650df2012-10-08 18:53:57 +0000446 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
447 ST.adjustSchedDependency(DefSU, SU, const_cast<SDep &>(dep));
Andrew Trick46cc9a42012-02-22 06:08:11 +0000448 SU->addPred(dep);
449 }
450 }
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000451
452 // Add antidependence to the following def of the vreg it uses.
Andrew Trick1eb4a0d2012-04-20 20:05:28 +0000453 VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
Andrew Trickd458e2d2012-02-22 21:59:00 +0000454 if (DefI != VRegDefs.end() && DefI->SU != SU)
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000455 DefI->SU->addPred(SDep(SU, SDep::Anti, Reg));
Andrew Trick46cc9a42012-02-22 06:08:11 +0000456}
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000457
Andrew Trickda01ba32012-05-15 18:59:41 +0000458/// Return true if MI is an instruction we are unable to reason about
459/// (like a call or something with unmodeled side effects).
460static inline bool isGlobalMemoryObject(AliasAnalysis *AA, MachineInstr *MI) {
461 if (MI->isCall() || MI->hasUnmodeledSideEffects() ||
Jakob Stoklund Olesencea3e772012-08-29 21:19:21 +0000462 (MI->hasOrderedMemoryRef() &&
Andrew Trickda01ba32012-05-15 18:59:41 +0000463 (!MI->mayLoad() || !MI->isInvariantLoad(AA))))
464 return true;
465 return false;
466}
467
468// This MI might have either incomplete info, or known to be unsafe
469// to deal with (i.e. volatile object).
470static inline bool isUnsafeMemoryObject(MachineInstr *MI,
471 const MachineFrameInfo *MFI) {
472 if (!MI || MI->memoperands_empty())
473 return true;
474 // We purposefully do no check for hasOneMemOperand() here
475 // in hope to trigger an assert downstream in order to
476 // finish implementation.
477 if ((*MI->memoperands_begin())->isVolatile() ||
478 MI->hasUnmodeledSideEffects())
479 return true;
Andrew Trickda01ba32012-05-15 18:59:41 +0000480 const Value *V = (*MI->memoperands_begin())->getValue();
481 if (!V)
482 return true;
483
Hal Finkel66859ae2012-12-10 18:49:16 +0000484 SmallVector<Value *, 4> Objs;
485 getUnderlyingObjects(V, Objs);
Craig Toppere1c1d362013-07-03 05:11:49 +0000486 for (SmallVectorImpl<Value *>::iterator I = Objs.begin(),
487 IE = Objs.end(); I != IE; ++I) {
Hal Finkel66859ae2012-12-10 18:49:16 +0000488 V = *I;
489
490 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
491 // Similarly to getUnderlyingObjectForInstr:
492 // For now, ignore PseudoSourceValues which may alias LLVM IR values
493 // because the code that uses this function has no way to cope with
494 // such aliases.
495 if (PSV->isAliased(MFI))
496 return true;
497 }
498
499 // Does this pointer refer to a distinct and identifiable object?
500 if (!isIdentifiedObject(V))
Andrew Trickda01ba32012-05-15 18:59:41 +0000501 return true;
502 }
Andrew Trickda01ba32012-05-15 18:59:41 +0000503
504 return false;
505}
506
507/// This returns true if the two MIs need a chain edge betwee them.
508/// If these are not even memory operations, we still may need
509/// chain deps between them. The question really is - could
510/// these two MIs be reordered during scheduling from memory dependency
511/// point of view.
512static bool MIsNeedChainEdge(AliasAnalysis *AA, const MachineFrameInfo *MFI,
513 MachineInstr *MIa,
514 MachineInstr *MIb) {
515 // Cover a trivial case - no edge is need to itself.
516 if (MIa == MIb)
517 return false;
518
Hal Finkel2150e3a2014-01-08 21:52:02 +0000519 // FIXME: Need to handle multiple memory operands to support all targets.
520 if (!MIa->hasOneMemOperand() || !MIb->hasOneMemOperand())
521 return true;
522
Andrew Trickda01ba32012-05-15 18:59:41 +0000523 if (isUnsafeMemoryObject(MIa, MFI) || isUnsafeMemoryObject(MIb, MFI))
524 return true;
525
526 // If we are dealing with two "normal" loads, we do not need an edge
527 // between them - they could be reordered.
528 if (!MIa->mayStore() && !MIb->mayStore())
529 return false;
530
531 // To this point analysis is generic. From here on we do need AA.
532 if (!AA)
533 return true;
534
535 MachineMemOperand *MMOa = *MIa->memoperands_begin();
536 MachineMemOperand *MMOb = *MIb->memoperands_begin();
537
Andrew Trickda01ba32012-05-15 18:59:41 +0000538 // The following interface to AA is fashioned after DAGCombiner::isAlias
539 // and operates with MachineMemOperand offset with some important
540 // assumptions:
541 // - LLVM fundamentally assumes flat address spaces.
542 // - MachineOperand offset can *only* result from legalization and
543 // cannot affect queries other than the trivial case of overlap
544 // checking.
545 // - These offsets never wrap and never step outside
546 // of allocated objects.
547 // - There should never be any negative offsets here.
548 //
549 // FIXME: Modify API to hide this math from "user"
550 // FIXME: Even before we go to AA we can reason locally about some
551 // memory objects. It can save compile time, and possibly catch some
552 // corner cases not currently covered.
553
554 assert ((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset");
555 assert ((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset");
556
557 int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset());
558 int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset;
559 int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset;
560
561 AliasAnalysis::AliasResult AAResult = AA->alias(
Nick Lewycky1ce017e2014-02-25 00:43:21 +0000562 AliasAnalysis::Location(MMOa->getValue(), Overlapa,
Craig Topperc0196b12014-04-14 00:51:57 +0000563 UseTBAA ? MMOa->getTBAAInfo() : nullptr),
Nick Lewycky1ce017e2014-02-25 00:43:21 +0000564 AliasAnalysis::Location(MMOb->getValue(), Overlapb,
Craig Topperc0196b12014-04-14 00:51:57 +0000565 UseTBAA ? MMOb->getTBAAInfo() : nullptr));
Andrew Trickda01ba32012-05-15 18:59:41 +0000566
567 return (AAResult != AliasAnalysis::NoAlias);
568}
569
570/// This recursive function iterates over chain deps of SUb looking for
571/// "latest" node that needs a chain edge to SUa.
572static unsigned
573iterateChainSucc(AliasAnalysis *AA, const MachineFrameInfo *MFI,
574 SUnit *SUa, SUnit *SUb, SUnit *ExitSU, unsigned *Depth,
575 SmallPtrSet<const SUnit*, 16> &Visited) {
576 if (!SUa || !SUb || SUb == ExitSU)
577 return *Depth;
578
579 // Remember visited nodes.
580 if (!Visited.insert(SUb))
581 return *Depth;
582 // If there is _some_ dependency already in place, do not
583 // descend any further.
584 // TODO: Need to make sure that if that dependency got eliminated or ignored
585 // for any reason in the future, we would not violate DAG topology.
586 // Currently it does not happen, but makes an implicit assumption about
587 // future implementation.
588 //
589 // Independently, if we encounter node that is some sort of global
590 // object (like a call) we already have full set of dependencies to it
591 // and we can stop descending.
592 if (SUa->isSucc(SUb) ||
593 isGlobalMemoryObject(AA, SUb->getInstr()))
594 return *Depth;
595
596 // If we do need an edge, or we have exceeded depth budget,
597 // add that edge to the predecessors chain of SUb,
598 // and stop descending.
599 if (*Depth > 200 ||
600 MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) {
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000601 SUb->addPred(SDep(SUa, SDep::MayAliasMem));
Andrew Trickda01ba32012-05-15 18:59:41 +0000602 return *Depth;
603 }
604 // Track current depth.
605 (*Depth)++;
606 // Iterate over chain dependencies only.
607 for (SUnit::const_succ_iterator I = SUb->Succs.begin(), E = SUb->Succs.end();
608 I != E; ++I)
609 if (I->isCtrl())
610 iterateChainSucc (AA, MFI, SUa, I->getSUnit(), ExitSU, Depth, Visited);
611 return *Depth;
612}
613
614/// This function assumes that "downward" from SU there exist
615/// tail/leaf of already constructed DAG. It iterates downward and
616/// checks whether SU can be aliasing any node dominated
617/// by it.
618static void adjustChainDeps(AliasAnalysis *AA, const MachineFrameInfo *MFI,
Andrew Trick344fb642012-06-13 02:39:03 +0000619 SUnit *SU, SUnit *ExitSU, std::set<SUnit *> &CheckList,
620 unsigned LatencyToLoad) {
Andrew Trickda01ba32012-05-15 18:59:41 +0000621 if (!SU)
622 return;
623
624 SmallPtrSet<const SUnit*, 16> Visited;
625 unsigned Depth = 0;
626
627 for (std::set<SUnit *>::iterator I = CheckList.begin(), IE = CheckList.end();
628 I != IE; ++I) {
629 if (SU == *I)
630 continue;
Andrew Trick344fb642012-06-13 02:39:03 +0000631 if (MIsNeedChainEdge(AA, MFI, SU->getInstr(), (*I)->getInstr())) {
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000632 SDep Dep(SU, SDep::MayAliasMem);
633 Dep.setLatency(((*I)->getInstr()->mayLoad()) ? LatencyToLoad : 0);
634 (*I)->addPred(Dep);
Andrew Trick344fb642012-06-13 02:39:03 +0000635 }
Andrew Trickda01ba32012-05-15 18:59:41 +0000636 // Now go through all the chain successors and iterate from them.
637 // Keep track of visited nodes.
638 for (SUnit::const_succ_iterator J = (*I)->Succs.begin(),
639 JE = (*I)->Succs.end(); J != JE; ++J)
640 if (J->isCtrl())
641 iterateChainSucc (AA, MFI, SU, J->getSUnit(),
642 ExitSU, &Depth, Visited);
643 }
644}
645
646/// Check whether two objects need a chain edge, if so, add it
647/// otherwise remember the rejected SU.
648static inline
649void addChainDependency (AliasAnalysis *AA, const MachineFrameInfo *MFI,
650 SUnit *SUa, SUnit *SUb,
651 std::set<SUnit *> &RejectList,
652 unsigned TrueMemOrderLatency = 0,
653 bool isNormalMemory = false) {
654 // If this is a false dependency,
655 // do not add the edge, but rememeber the rejected node.
Hal Finkelb350ffd2013-08-29 03:25:05 +0000656 if (!AA || MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) {
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000657 SDep Dep(SUa, isNormalMemory ? SDep::MayAliasMem : SDep::Barrier);
658 Dep.setLatency(TrueMemOrderLatency);
659 SUb->addPred(Dep);
660 }
Andrew Trickda01ba32012-05-15 18:59:41 +0000661 else {
662 // Duplicate entries should be ignored.
663 RejectList.insert(SUb);
664 DEBUG(dbgs() << "\tReject chain dep between SU("
665 << SUa->NodeNum << ") and SU("
666 << SUb->NodeNum << ")\n");
667 }
668}
669
Andrew Trick46cc9a42012-02-22 06:08:11 +0000670/// Create an SUnit for each real instruction, numbered in top-down toplological
671/// order. The instruction order A < B, implies that no edge exists from B to A.
672///
673/// Map each real instruction to its SUnit.
674///
Andrew Trick8823dec2012-03-14 04:00:41 +0000675/// After initSUnits, the SUnits vector cannot be resized and the scheduler may
676/// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
677/// instead of pointers.
678///
679/// MachineScheduler relies on initSUnits numbering the nodes by their order in
680/// the original instruction list.
Andrew Trick46cc9a42012-02-22 06:08:11 +0000681void ScheduleDAGInstrs::initSUnits() {
682 // We'll be allocating one SUnit for each real instruction in the region,
683 // which is contained within a basic block.
Andrew Tricka53e1012013-08-23 17:48:33 +0000684 SUnits.reserve(NumRegionInstrs);
Andrew Trick46cc9a42012-02-22 06:08:11 +0000685
Andrew Trick8c207e42012-03-09 04:29:02 +0000686 for (MachineBasicBlock::iterator I = RegionBegin; I != RegionEnd; ++I) {
Andrew Trick46cc9a42012-02-22 06:08:11 +0000687 MachineInstr *MI = I;
688 if (MI->isDebugValue())
689 continue;
690
Andrew Trick52226d42012-03-07 23:00:49 +0000691 SUnit *SU = newSUnit(MI);
Andrew Trick46cc9a42012-02-22 06:08:11 +0000692 MISUnitMap[MI] = SU;
693
694 SU->isCall = MI->isCall();
695 SU->isCommutable = MI->isCommutable();
696
697 // Assign the Latency field of SU using target-provided information.
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000698 SU->Latency = SchedModel.computeInstrLatency(SU->getInstr());
Andrew Trick880e5732013-12-05 17:55:58 +0000699
700 // If this SUnit uses an unbuffered resource, mark it as such.
701 // These resources are used for in-order execution pipelines within an
702 // out-of-order core and are identified by BufferSize=1. BufferSize=0 is
703 // used for dispatch/issue groups and is not considered here.
704 if (SchedModel.hasInstrSchedModel()) {
705 const MCSchedClassDesc *SC = getSchedClass(SU);
706 for (TargetSchedModel::ProcResIter
707 PI = SchedModel.getWriteProcResBegin(SC),
708 PE = SchedModel.getWriteProcResEnd(SC); PI != PE; ++PI) {
Andrew Trick5a22df42013-12-05 17:56:02 +0000709 switch (SchedModel.getProcResource(PI->ProcResourceIdx)->BufferSize) {
710 case 0:
711 SU->hasReservedResource = true;
712 break;
713 case 1:
Andrew Trick880e5732013-12-05 17:55:58 +0000714 SU->isUnbuffered = true;
715 break;
Andrew Trick5a22df42013-12-05 17:56:02 +0000716 default:
717 break;
Andrew Trick880e5732013-12-05 17:55:58 +0000718 }
719 }
720 }
Andrew Trick46cc9a42012-02-22 06:08:11 +0000721 }
Andrew Trickdbee9d82012-01-14 02:17:15 +0000722}
723
Alp Tokerf907b892013-12-05 05:44:44 +0000724/// If RegPressure is non-null, compute register pressure as a side effect. The
Andrew Trick88639922012-04-24 17:56:43 +0000725/// DAG builder is an efficient place to do it because it already visits
726/// operands.
727void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA,
Andrew Trick1a831342013-08-30 03:49:48 +0000728 RegPressureTracker *RPTracker,
729 PressureDiffs *PDiffs) {
Hal Finkelb350ffd2013-08-29 03:25:05 +0000730 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
731 bool UseAA = EnableAASchedMI.getNumOccurrences() > 0 ? EnableAASchedMI
732 : ST.useAA();
Craig Topperc0196b12014-04-14 00:51:57 +0000733 AliasAnalysis *AAForDep = UseAA ? AA : nullptr;
Hal Finkelb350ffd2013-08-29 03:25:05 +0000734
Andrew Trick310190e2013-09-04 21:00:02 +0000735 MISUnitMap.clear();
736 ScheduleDAG::clearDAG();
737
Andrew Trick46cc9a42012-02-22 06:08:11 +0000738 // Create an SUnit for each real instruction.
739 initSUnits();
Dan Gohman60cb69e2008-11-19 23:18:57 +0000740
Andrew Trick1a831342013-08-30 03:49:48 +0000741 if (PDiffs)
742 PDiffs->init(SUnits.size());
743
Dan Gohman3aab10b2008-12-04 01:35:46 +0000744 // We build scheduling units by walking a block's instruction list from bottom
745 // to top.
746
David Goodwind2f9c042009-11-09 19:22:17 +0000747 // Remember where a generic side-effecting instruction is as we procede.
Craig Topperc0196b12014-04-14 00:51:57 +0000748 SUnit *BarrierChain = nullptr, *AliasChain = nullptr;
Dan Gohman3aab10b2008-12-04 01:35:46 +0000749
David Goodwind2f9c042009-11-09 19:22:17 +0000750 // Memory references to specific known memory locations are tracked
751 // so that they can be given more precise dependencies. We track
752 // separately the known memory locations that may alias and those
753 // that are known not to alias
Hal Finkela228a812014-01-20 14:03:02 +0000754 MapVector<const Value *, std::vector<SUnit *> > AliasMemDefs, NonAliasMemDefs;
Sergei Larine8221482012-11-15 17:45:50 +0000755 MapVector<const Value *, std::vector<SUnit *> > AliasMemUses, NonAliasMemUses;
Andrew Trickda01ba32012-05-15 18:59:41 +0000756 std::set<SUnit*> RejectMemNodes;
Dan Gohman3aab10b2008-12-04 01:35:46 +0000757
Dale Johannesen49de0602010-03-10 22:13:47 +0000758 // Remove any stale debug info; sometimes BuildSchedGraph is called again
759 // without emitting the info from the previous call.
Devang Patele5feef02011-06-02 20:07:12 +0000760 DbgValues.clear();
Craig Topperc0196b12014-04-14 00:51:57 +0000761 FirstDbgValue = nullptr;
Dale Johannesen49de0602010-03-10 22:13:47 +0000762
Andrew Trickd675a4c2012-02-23 01:52:38 +0000763 assert(Defs.empty() && Uses.empty() &&
764 "Only BuildGraph should update Defs/Uses");
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000765 Defs.setUniverse(TRI->getNumRegs());
766 Uses.setUniverse(TRI->getNumRegs());
Andrew Trick2e116a42011-05-06 21:52:52 +0000767
Andrew Trickd458e2d2012-02-22 21:59:00 +0000768 assert(VRegDefs.empty() && "Only BuildSchedGraph may access VRegDefs");
Andrew Trick8dd26f02013-08-23 17:48:39 +0000769 VRegUses.clear();
Andrew Trickd458e2d2012-02-22 21:59:00 +0000770 VRegDefs.setUniverse(MRI.getNumVirtRegs());
Andrew Trick8dd26f02013-08-23 17:48:39 +0000771 VRegUses.setUniverse(MRI.getNumVirtRegs());
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000772
Andrew Trickd675a4c2012-02-23 01:52:38 +0000773 // Model data dependencies between instructions being scheduled and the
774 // ExitSU.
Andrew Trick52226d42012-03-07 23:00:49 +0000775 addSchedBarrierDeps();
Andrew Trickd675a4c2012-02-23 01:52:38 +0000776
Dan Gohmanb9543432009-02-10 23:27:53 +0000777 // Walk the list of instructions, from bottom moving up.
Craig Topperc0196b12014-04-14 00:51:57 +0000778 MachineInstr *DbgMI = nullptr;
Andrew Trick8c207e42012-03-09 04:29:02 +0000779 for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
Dan Gohman60cb69e2008-11-19 23:18:57 +0000780 MII != MIE; --MII) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000781 MachineInstr *MI = std::prev(MII);
Andrew Trickb767d1e2012-12-01 01:22:49 +0000782 if (MI && DbgMI) {
783 DbgValues.push_back(std::make_pair(DbgMI, MI));
Craig Topperc0196b12014-04-14 00:51:57 +0000784 DbgMI = nullptr;
Devang Patele5feef02011-06-02 20:07:12 +0000785 }
786
Dale Johannesen49de0602010-03-10 22:13:47 +0000787 if (MI->isDebugValue()) {
Andrew Trickb767d1e2012-12-01 01:22:49 +0000788 DbgMI = MI;
Dale Johannesen49de0602010-03-10 22:13:47 +0000789 continue;
790 }
Andrew Trick1a831342013-08-30 03:49:48 +0000791 SUnit *SU = MISUnitMap[MI];
792 assert(SU && "No SUnit mapped to this MI");
793
Andrew Trick88639922012-04-24 17:56:43 +0000794 if (RPTracker) {
Craig Topperc0196b12014-04-14 00:51:57 +0000795 PressureDiff *PDiff = PDiffs ? &(*PDiffs)[SU->NodeNum] : nullptr;
796 RPTracker->recede(/*LiveUses=*/nullptr, PDiff);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000797 assert(RPTracker->getPos() == std::prev(MII) &&
798 "RPTracker can't find MI");
Andrew Trick88639922012-04-24 17:56:43 +0000799 }
Devang Patele5feef02011-06-02 20:07:12 +0000800
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000801 assert(
802 (CanHandleTerminators || (!MI->isTerminator() && !MI->isPosition())) &&
803 "Cannot schedule terminators or labels!");
Dan Gohman60cb69e2008-11-19 23:18:57 +0000804
Dan Gohman3aab10b2008-12-04 01:35:46 +0000805 // Add register-based dependencies (data, anti, and output).
Andrew Trickec256482012-12-18 20:53:01 +0000806 bool HasVRegDef = false;
Dan Gohman60cb69e2008-11-19 23:18:57 +0000807 for (unsigned j = 0, n = MI->getNumOperands(); j != n; ++j) {
808 const MachineOperand &MO = MI->getOperand(j);
809 if (!MO.isReg()) continue;
810 unsigned Reg = MO.getReg();
811 if (Reg == 0) continue;
812
Andrew Trickdbee9d82012-01-14 02:17:15 +0000813 if (TRI->isPhysicalRegister(Reg))
814 addPhysRegDeps(SU, j);
815 else {
816 assert(!IsPostRA && "Virtual register encountered!");
Andrew Trickec256482012-12-18 20:53:01 +0000817 if (MO.isDef()) {
818 HasVRegDef = true;
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000819 addVRegDefDeps(SU, j);
Andrew Trickec256482012-12-18 20:53:01 +0000820 }
Andrew Trickda6a15d2012-02-23 03:16:24 +0000821 else if (MO.readsReg()) // ignore undef operands
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000822 addVRegUseDeps(SU, j);
Dan Gohman60cb69e2008-11-19 23:18:57 +0000823 }
824 }
Andrew Trickec256482012-12-18 20:53:01 +0000825 // If we haven't seen any uses in this scheduling region, create a
826 // dependence edge to ExitSU to model the live-out latency. This is required
827 // for vreg defs with no in-region use, and prefetches with no vreg def.
828 //
829 // FIXME: NumDataSuccs would be more precise than NumSuccs here. This
830 // check currently relies on being called before adding chain deps.
831 if (SU->NumSuccs == 0 && SU->Latency > 1
832 && (HasVRegDef || MI->mayLoad())) {
833 SDep Dep(SU, SDep::Artificial);
834 Dep.setLatency(SU->Latency - 1);
835 ExitSU.addPred(Dep);
836 }
Dan Gohman3aab10b2008-12-04 01:35:46 +0000837
838 // Add chain dependencies.
David Goodwin00822aa2009-11-02 17:06:28 +0000839 // Chain dependencies used to enforce memory order should have
840 // latency of 0 (except for true dependency of Store followed by
841 // aliased Load... we estimate that with a single cycle of latency
842 // assuming the hardware will bypass)
Dan Gohman3aab10b2008-12-04 01:35:46 +0000843 // Note that isStoreToStackSlot and isLoadFromStackSLot are not usable
844 // after stack slots are lowered to actual addresses.
845 // TODO: Use an AliasAnalysis and do real alias-analysis queries, and
846 // produce more precise dependence information.
Andrew Trick344fb642012-06-13 02:39:03 +0000847 unsigned TrueMemOrderLatency = MI->mayStore() ? 1 : 0;
Andrew Trickda01ba32012-05-15 18:59:41 +0000848 if (isGlobalMemoryObject(AA, MI)) {
David Goodwind2f9c042009-11-09 19:22:17 +0000849 // Be conservative with these and add dependencies on all memory
850 // references, even those that are known to not alias.
Hal Finkela228a812014-01-20 14:03:02 +0000851 for (MapVector<const Value *, std::vector<SUnit *> >::iterator I =
David Goodwind2f9c042009-11-09 19:22:17 +0000852 NonAliasMemDefs.begin(), E = NonAliasMemDefs.end(); I != E; ++I) {
Hal Finkela228a812014-01-20 14:03:02 +0000853 for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
854 I->second[i]->addPred(SDep(SU, SDep::Barrier));
855 }
Dan Gohman3aab10b2008-12-04 01:35:46 +0000856 }
Sergei Larine8221482012-11-15 17:45:50 +0000857 for (MapVector<const Value *, std::vector<SUnit *> >::iterator I =
David Goodwind2f9c042009-11-09 19:22:17 +0000858 NonAliasMemUses.begin(), E = NonAliasMemUses.end(); I != E; ++I) {
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000859 for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
860 SDep Dep(SU, SDep::Barrier);
861 Dep.setLatency(TrueMemOrderLatency);
862 I->second[i]->addPred(Dep);
863 }
Dan Gohman3aab10b2008-12-04 01:35:46 +0000864 }
David Goodwind2f9c042009-11-09 19:22:17 +0000865 // Add SU to the barrier chain.
866 if (BarrierChain)
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000867 BarrierChain->addPred(SDep(SU, SDep::Barrier));
David Goodwind2f9c042009-11-09 19:22:17 +0000868 BarrierChain = SU;
Andrew Trickda01ba32012-05-15 18:59:41 +0000869 // This is a barrier event that acts as a pivotal node in the DAG,
870 // so it is safe to clear list of exposed nodes.
Andrew Trick344fb642012-06-13 02:39:03 +0000871 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
872 TrueMemOrderLatency);
Andrew Trickda01ba32012-05-15 18:59:41 +0000873 RejectMemNodes.clear();
874 NonAliasMemDefs.clear();
875 NonAliasMemUses.clear();
David Goodwind2f9c042009-11-09 19:22:17 +0000876
877 // fall-through
878 new_alias_chain:
879 // Chain all possibly aliasing memory references though SU.
Andrew Trick344fb642012-06-13 02:39:03 +0000880 if (AliasChain) {
881 unsigned ChainLatency = 0;
882 if (AliasChain->getInstr()->mayLoad())
883 ChainLatency = TrueMemOrderLatency;
Hal Finkelb350ffd2013-08-29 03:25:05 +0000884 addChainDependency(AAForDep, MFI, SU, AliasChain, RejectMemNodes,
Andrew Trick344fb642012-06-13 02:39:03 +0000885 ChainLatency);
886 }
David Goodwind2f9c042009-11-09 19:22:17 +0000887 AliasChain = SU;
888 for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
Hal Finkelb350ffd2013-08-29 03:25:05 +0000889 addChainDependency(AAForDep, MFI, SU, PendingLoads[k], RejectMemNodes,
Andrew Trickda01ba32012-05-15 18:59:41 +0000890 TrueMemOrderLatency);
Hal Finkela228a812014-01-20 14:03:02 +0000891 for (MapVector<const Value *, std::vector<SUnit *> >::iterator I =
892 AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I) {
893 for (unsigned i = 0, e = I->second.size(); i != e; ++i)
894 addChainDependency(AAForDep, MFI, SU, I->second[i], RejectMemNodes);
895 }
Sergei Larine8221482012-11-15 17:45:50 +0000896 for (MapVector<const Value *, std::vector<SUnit *> >::iterator I =
David Goodwind2f9c042009-11-09 19:22:17 +0000897 AliasMemUses.begin(), E = AliasMemUses.end(); I != E; ++I) {
898 for (unsigned i = 0, e = I->second.size(); i != e; ++i)
Hal Finkelb350ffd2013-08-29 03:25:05 +0000899 addChainDependency(AAForDep, MFI, SU, I->second[i], RejectMemNodes,
Andrew Trickda01ba32012-05-15 18:59:41 +0000900 TrueMemOrderLatency);
David Goodwind2f9c042009-11-09 19:22:17 +0000901 }
Andrew Trick344fb642012-06-13 02:39:03 +0000902 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
903 TrueMemOrderLatency);
David Goodwind2f9c042009-11-09 19:22:17 +0000904 PendingLoads.clear();
905 AliasMemDefs.clear();
906 AliasMemUses.clear();
Evan Cheng7f8e5632011-12-07 07:15:52 +0000907 } else if (MI->mayStore()) {
Benjamin Kramerfd510922013-06-29 18:41:17 +0000908 UnderlyingObjectsVector Objs;
Hal Finkel66859ae2012-12-10 18:49:16 +0000909 getUnderlyingObjectsForInstr(MI, MFI, Objs);
910
911 if (Objs.empty()) {
912 // Treat all other stores conservatively.
913 goto new_alias_chain;
914 }
915
916 bool MayAlias = false;
Benjamin Kramerfd510922013-06-29 18:41:17 +0000917 for (UnderlyingObjectsVector::iterator K = Objs.begin(), KE = Objs.end();
918 K != KE; ++K) {
919 const Value *V = K->getPointer();
920 bool ThisMayAlias = K->getInt();
Hal Finkel66859ae2012-12-10 18:49:16 +0000921 if (ThisMayAlias)
922 MayAlias = true;
923
Dan Gohman3aab10b2008-12-04 01:35:46 +0000924 // A store to a specific PseudoSourceValue. Add precise dependencies.
David Goodwind2f9c042009-11-09 19:22:17 +0000925 // Record the def in MemDefs, first adding a dep if there is
926 // an existing def.
Hal Finkela228a812014-01-20 14:03:02 +0000927 MapVector<const Value *, std::vector<SUnit *> >::iterator I =
Hal Finkel66859ae2012-12-10 18:49:16 +0000928 ((ThisMayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
Hal Finkela228a812014-01-20 14:03:02 +0000929 MapVector<const Value *, std::vector<SUnit *> >::iterator IE =
Hal Finkel66859ae2012-12-10 18:49:16 +0000930 ((ThisMayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
David Goodwind2f9c042009-11-09 19:22:17 +0000931 if (I != IE) {
Hal Finkela228a812014-01-20 14:03:02 +0000932 for (unsigned i = 0, e = I->second.size(); i != e; ++i)
933 addChainDependency(AAForDep, MFI, SU, I->second[i], RejectMemNodes,
934 0, true);
935
936 // If we're not using AA, then we only need one store per object.
937 if (!AAForDep)
938 I->second.clear();
939 I->second.push_back(SU);
Dan Gohman3aab10b2008-12-04 01:35:46 +0000940 } else {
Hal Finkela228a812014-01-20 14:03:02 +0000941 if (ThisMayAlias) {
942 if (!AAForDep)
943 AliasMemDefs[V].clear();
944 AliasMemDefs[V].push_back(SU);
945 } else {
946 if (!AAForDep)
947 NonAliasMemDefs[V].clear();
948 NonAliasMemDefs[V].push_back(SU);
949 }
Dan Gohman3aab10b2008-12-04 01:35:46 +0000950 }
951 // Handle the uses in MemUses, if there are any.
Sergei Larine8221482012-11-15 17:45:50 +0000952 MapVector<const Value *, std::vector<SUnit *> >::iterator J =
Hal Finkel66859ae2012-12-10 18:49:16 +0000953 ((ThisMayAlias) ? AliasMemUses.find(V) : NonAliasMemUses.find(V));
Sergei Larine8221482012-11-15 17:45:50 +0000954 MapVector<const Value *, std::vector<SUnit *> >::iterator JE =
Hal Finkel66859ae2012-12-10 18:49:16 +0000955 ((ThisMayAlias) ? AliasMemUses.end() : NonAliasMemUses.end());
David Goodwind2f9c042009-11-09 19:22:17 +0000956 if (J != JE) {
Dan Gohman3aab10b2008-12-04 01:35:46 +0000957 for (unsigned i = 0, e = J->second.size(); i != e; ++i)
Hal Finkelb350ffd2013-08-29 03:25:05 +0000958 addChainDependency(AAForDep, MFI, SU, J->second[i], RejectMemNodes,
Andrew Trickda01ba32012-05-15 18:59:41 +0000959 TrueMemOrderLatency, true);
Dan Gohman3aab10b2008-12-04 01:35:46 +0000960 J->second.clear();
961 }
David Goodwin00822aa2009-11-02 17:06:28 +0000962 }
Hal Finkel66859ae2012-12-10 18:49:16 +0000963 if (MayAlias) {
964 // Add dependencies from all the PendingLoads, i.e. loads
965 // with no underlying object.
966 for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
Hal Finkelb350ffd2013-08-29 03:25:05 +0000967 addChainDependency(AAForDep, MFI, SU, PendingLoads[k], RejectMemNodes,
Hal Finkel66859ae2012-12-10 18:49:16 +0000968 TrueMemOrderLatency);
969 // Add dependence on alias chain, if needed.
970 if (AliasChain)
Hal Finkelb350ffd2013-08-29 03:25:05 +0000971 addChainDependency(AAForDep, MFI, SU, AliasChain, RejectMemNodes);
Hal Finkel66859ae2012-12-10 18:49:16 +0000972 // But we also should check dependent instructions for the
973 // SU in question.
974 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
975 TrueMemOrderLatency);
976 }
977 // Add dependence on barrier chain, if needed.
978 // There is no point to check aliasing on barrier event. Even if
979 // SU and barrier _could_ be reordered, they should not. In addition,
980 // we have lost all RejectMemNodes below barrier.
981 if (BarrierChain)
982 BarrierChain->addPred(SDep(SU, SDep::Barrier));
Evan Cheng15459b62010-10-23 02:10:46 +0000983
984 if (!ExitSU.isPred(SU))
985 // Push store's up a bit to avoid them getting in between cmp
986 // and branches.
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000987 ExitSU.addPred(SDep(SU, SDep::Artificial));
Evan Cheng7f8e5632011-12-07 07:15:52 +0000988 } else if (MI->mayLoad()) {
David Goodwina86f9192009-11-03 20:15:00 +0000989 bool MayAlias = true;
Dan Gohman87b02d52009-10-09 23:27:56 +0000990 if (MI->isInvariantLoad(AA)) {
Dan Gohman3aab10b2008-12-04 01:35:46 +0000991 // Invariant load, no chain dependencies needed!
David Goodwin28ba4f22009-11-05 00:16:44 +0000992 } else {
Benjamin Kramerfd510922013-06-29 18:41:17 +0000993 UnderlyingObjectsVector Objs;
Hal Finkel66859ae2012-12-10 18:49:16 +0000994 getUnderlyingObjectsForInstr(MI, MFI, Objs);
995
996 if (Objs.empty()) {
David Goodwind2f9c042009-11-09 19:22:17 +0000997 // A load with no underlying object. Depend on all
998 // potentially aliasing stores.
Hal Finkela228a812014-01-20 14:03:02 +0000999 for (MapVector<const Value *, std::vector<SUnit *> >::iterator I =
David Goodwind2f9c042009-11-09 19:22:17 +00001000 AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I)
Hal Finkela228a812014-01-20 14:03:02 +00001001 for (unsigned i = 0, e = I->second.size(); i != e; ++i)
1002 addChainDependency(AAForDep, MFI, SU, I->second[i],
1003 RejectMemNodes);
Andrew Trick24b1c482011-05-05 19:24:06 +00001004
David Goodwind2f9c042009-11-09 19:22:17 +00001005 PendingLoads.push_back(SU);
1006 MayAlias = true;
Hal Finkel66859ae2012-12-10 18:49:16 +00001007 } else {
1008 MayAlias = false;
1009 }
1010
Benjamin Kramerfd510922013-06-29 18:41:17 +00001011 for (UnderlyingObjectsVector::iterator
Hal Finkel66859ae2012-12-10 18:49:16 +00001012 J = Objs.begin(), JE = Objs.end(); J != JE; ++J) {
Benjamin Kramerfd510922013-06-29 18:41:17 +00001013 const Value *V = J->getPointer();
1014 bool ThisMayAlias = J->getInt();
Hal Finkel66859ae2012-12-10 18:49:16 +00001015
1016 if (ThisMayAlias)
1017 MayAlias = true;
1018
1019 // A load from a specific PseudoSourceValue. Add precise dependencies.
Hal Finkela228a812014-01-20 14:03:02 +00001020 MapVector<const Value *, std::vector<SUnit *> >::iterator I =
Hal Finkel66859ae2012-12-10 18:49:16 +00001021 ((ThisMayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
Hal Finkela228a812014-01-20 14:03:02 +00001022 MapVector<const Value *, std::vector<SUnit *> >::iterator IE =
Hal Finkel66859ae2012-12-10 18:49:16 +00001023 ((ThisMayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
1024 if (I != IE)
Hal Finkela228a812014-01-20 14:03:02 +00001025 for (unsigned i = 0, e = I->second.size(); i != e; ++i)
1026 addChainDependency(AAForDep, MFI, SU, I->second[i],
1027 RejectMemNodes, 0, true);
Hal Finkel66859ae2012-12-10 18:49:16 +00001028 if (ThisMayAlias)
1029 AliasMemUses[V].push_back(SU);
1030 else
1031 NonAliasMemUses[V].push_back(SU);
David Goodwina86f9192009-11-03 20:15:00 +00001032 }
Andrew Trickda01ba32012-05-15 18:59:41 +00001033 if (MayAlias)
Andrew Trick344fb642012-06-13 02:39:03 +00001034 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes, /*Latency=*/0);
David Goodwind2f9c042009-11-09 19:22:17 +00001035 // Add dependencies on alias and barrier chains, if needed.
1036 if (MayAlias && AliasChain)
Hal Finkelb350ffd2013-08-29 03:25:05 +00001037 addChainDependency(AAForDep, MFI, SU, AliasChain, RejectMemNodes);
David Goodwind2f9c042009-11-09 19:22:17 +00001038 if (BarrierChain)
Andrew Trickbaeaabb2012-11-06 03:13:46 +00001039 BarrierChain->addPred(SDep(SU, SDep::Barrier));
Andrew Trick24b1c482011-05-05 19:24:06 +00001040 }
Dan Gohman60cb69e2008-11-19 23:18:57 +00001041 }
Dan Gohman60cb69e2008-11-19 23:18:57 +00001042 }
Andrew Trickb767d1e2012-12-01 01:22:49 +00001043 if (DbgMI)
1044 FirstDbgValue = DbgMI;
Dan Gohman619ef482009-01-15 19:20:50 +00001045
Andrew Trickd675a4c2012-02-23 01:52:38 +00001046 Defs.clear();
1047 Uses.clear();
Andrew Trick59ac4fb2012-01-14 02:17:18 +00001048 VRegDefs.clear();
Dan Gohman619ef482009-01-15 19:20:50 +00001049 PendingLoads.clear();
Dan Gohman60cb69e2008-11-19 23:18:57 +00001050}
1051
Andrew Trick6b104f82013-12-28 21:56:55 +00001052/// \brief Initialize register live-range state for updating kills.
1053void ScheduleDAGInstrs::startBlockForKills(MachineBasicBlock *BB) {
1054 // Start with no live registers.
1055 LiveRegs.reset();
1056
1057 // Examine the live-in regs of all successors.
1058 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
1059 SE = BB->succ_end(); SI != SE; ++SI) {
1060 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
1061 E = (*SI)->livein_end(); I != E; ++I) {
1062 unsigned Reg = *I;
1063 // Repeat, for reg and all subregs.
1064 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1065 SubRegs.isValid(); ++SubRegs)
1066 LiveRegs.set(*SubRegs);
1067 }
1068 }
1069}
1070
1071bool ScheduleDAGInstrs::toggleKillFlag(MachineInstr *MI, MachineOperand &MO) {
1072 // Setting kill flag...
1073 if (!MO.isKill()) {
1074 MO.setIsKill(true);
1075 return false;
1076 }
1077
1078 // If MO itself is live, clear the kill flag...
1079 if (LiveRegs.test(MO.getReg())) {
1080 MO.setIsKill(false);
1081 return false;
1082 }
1083
1084 // If any subreg of MO is live, then create an imp-def for that
1085 // subreg and keep MO marked as killed.
1086 MO.setIsKill(false);
1087 bool AllDead = true;
1088 const unsigned SuperReg = MO.getReg();
1089 MachineInstrBuilder MIB(MF, MI);
1090 for (MCSubRegIterator SubRegs(SuperReg, TRI); SubRegs.isValid(); ++SubRegs) {
1091 if (LiveRegs.test(*SubRegs)) {
1092 MIB.addReg(*SubRegs, RegState::ImplicitDefine);
1093 AllDead = false;
1094 }
1095 }
1096
1097 if(AllDead)
1098 MO.setIsKill(true);
1099 return false;
1100}
1101
1102// FIXME: Reuse the LivePhysRegs utility for this.
1103void ScheduleDAGInstrs::fixupKills(MachineBasicBlock *MBB) {
1104 DEBUG(dbgs() << "Fixup kills for BB#" << MBB->getNumber() << '\n');
1105
1106 LiveRegs.resize(TRI->getNumRegs());
1107 BitVector killedRegs(TRI->getNumRegs());
1108
1109 startBlockForKills(MBB);
1110
1111 // Examine block from end to start...
1112 unsigned Count = MBB->size();
1113 for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
1114 I != E; --Count) {
1115 MachineInstr *MI = --I;
1116 if (MI->isDebugValue())
1117 continue;
1118
1119 // Update liveness. Registers that are defed but not used in this
1120 // instruction are now dead. Mark register and all subregs as they
1121 // are completely defined.
1122 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1123 MachineOperand &MO = MI->getOperand(i);
1124 if (MO.isRegMask())
1125 LiveRegs.clearBitsNotInMask(MO.getRegMask());
1126 if (!MO.isReg()) continue;
1127 unsigned Reg = MO.getReg();
1128 if (Reg == 0) continue;
1129 if (!MO.isDef()) continue;
1130 // Ignore two-addr defs.
1131 if (MI->isRegTiedToUseOperand(i)) continue;
1132
1133 // Repeat for reg and all subregs.
1134 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1135 SubRegs.isValid(); ++SubRegs)
1136 LiveRegs.reset(*SubRegs);
1137 }
1138
1139 // Examine all used registers and set/clear kill flag. When a
1140 // register is used multiple times we only set the kill flag on
1141 // the first use. Don't set kill flags on undef operands.
1142 killedRegs.reset();
1143 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1144 MachineOperand &MO = MI->getOperand(i);
1145 if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
1146 unsigned Reg = MO.getReg();
1147 if ((Reg == 0) || MRI.isReserved(Reg)) continue;
1148
1149 bool kill = false;
1150 if (!killedRegs.test(Reg)) {
1151 kill = true;
1152 // A register is not killed if any subregs are live...
1153 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
1154 if (LiveRegs.test(*SubRegs)) {
1155 kill = false;
1156 break;
1157 }
1158 }
1159
1160 // If subreg is not live, then register is killed if it became
1161 // live in this instruction
1162 if (kill)
1163 kill = !LiveRegs.test(Reg);
1164 }
1165
1166 if (MO.isKill() != kill) {
1167 DEBUG(dbgs() << "Fixing " << MO << " in ");
1168 // Warning: toggleKillFlag may invalidate MO.
1169 toggleKillFlag(MI, MO);
1170 DEBUG(MI->dump());
1171 }
1172
1173 killedRegs.set(Reg);
1174 }
1175
1176 // Mark any used register (that is not using undef) and subregs as
1177 // now live...
1178 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1179 MachineOperand &MO = MI->getOperand(i);
1180 if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
1181 unsigned Reg = MO.getReg();
1182 if ((Reg == 0) || MRI.isReserved(Reg)) continue;
1183
1184 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1185 SubRegs.isValid(); ++SubRegs)
1186 LiveRegs.set(*SubRegs);
1187 }
1188 }
1189}
1190
Dan Gohman60cb69e2008-11-19 23:18:57 +00001191void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
Manman Ren19f49ac2012-09-11 22:23:19 +00001192#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohman60cb69e2008-11-19 23:18:57 +00001193 SU->getInstr()->dump();
Manman Ren742534c2012-09-06 19:06:06 +00001194#endif
Dan Gohman60cb69e2008-11-19 23:18:57 +00001195}
1196
1197std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
1198 std::string s;
1199 raw_string_ostream oss(s);
Dan Gohmanb9543432009-02-10 23:27:53 +00001200 if (SU == &EntrySU)
1201 oss << "<entry>";
1202 else if (SU == &ExitSU)
1203 oss << "<exit>";
1204 else
Andrew Trickb36388a2013-01-25 07:45:25 +00001205 SU->getInstr()->print(oss, &TM, /*SkipOpers=*/true);
Dan Gohman60cb69e2008-11-19 23:18:57 +00001206 return oss.str();
1207}
1208
Andrew Trick1b2324d2012-03-07 00:18:22 +00001209/// Return the basic block label. It is not necessarilly unique because a block
1210/// contains multiple scheduling regions. But it is fine for visualization.
1211std::string ScheduleDAGInstrs::getDAGName() const {
1212 return "dag." + BB->getFullName();
1213}
Andrew Trick90f711d2012-10-15 18:02:27 +00001214
Andrew Trick48d392e2012-11-28 05:13:28 +00001215//===----------------------------------------------------------------------===//
1216// SchedDFSResult Implementation
1217//===----------------------------------------------------------------------===//
1218
1219namespace llvm {
1220/// \brief Internal state used to compute SchedDFSResult.
1221class SchedDFSImpl {
1222 SchedDFSResult &R;
1223
1224 /// Join DAG nodes into equivalence classes by their subtree.
1225 IntEqClasses SubtreeClasses;
1226 /// List PredSU, SuccSU pairs that represent data edges between subtrees.
1227 std::vector<std::pair<const SUnit*, const SUnit*> > ConnectionPairs;
1228
Andrew Trickffc80972013-01-25 06:52:27 +00001229 struct RootData {
1230 unsigned NodeID;
1231 unsigned ParentNodeID; // Parent node (member of the parent subtree).
1232 unsigned SubInstrCount; // Instr count in this tree only, not children.
1233
1234 RootData(unsigned id): NodeID(id),
1235 ParentNodeID(SchedDFSResult::InvalidSubtreeID),
1236 SubInstrCount(0) {}
1237
1238 unsigned getSparseSetIndex() const { return NodeID; }
1239 };
1240
1241 SparseSet<RootData> RootSet;
1242
Andrew Trick48d392e2012-11-28 05:13:28 +00001243public:
Andrew Trickffc80972013-01-25 06:52:27 +00001244 SchedDFSImpl(SchedDFSResult &r): R(r), SubtreeClasses(R.DFSNodeData.size()) {
1245 RootSet.setUniverse(R.DFSNodeData.size());
1246 }
Andrew Trick48d392e2012-11-28 05:13:28 +00001247
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001248 /// Return true if this node been visited by the DFS traversal.
1249 ///
1250 /// During visitPostorderNode the Node's SubtreeID is assigned to the Node
1251 /// ID. Later, SubtreeID is updated but remains valid.
Andrew Trick48d392e2012-11-28 05:13:28 +00001252 bool isVisited(const SUnit *SU) const {
Andrew Trickffc80972013-01-25 06:52:27 +00001253 return R.DFSNodeData[SU->NodeNum].SubtreeID
1254 != SchedDFSResult::InvalidSubtreeID;
Andrew Trick48d392e2012-11-28 05:13:28 +00001255 }
1256
1257 /// Initialize this node's instruction count. We don't need to flag the node
1258 /// visited until visitPostorder because the DAG cannot have cycles.
1259 void visitPreorder(const SUnit *SU) {
Andrew Trickffc80972013-01-25 06:52:27 +00001260 R.DFSNodeData[SU->NodeNum].InstrCount =
1261 SU->getInstr()->isTransient() ? 0 : 1;
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001262 }
1263
1264 /// Called once for each node after all predecessors are visited. Revisit this
1265 /// node's predecessors and potentially join them now that we know the ILP of
1266 /// the other predecessors.
1267 void visitPostorderNode(const SUnit *SU) {
1268 // Mark this node as the root of a subtree. It may be joined with its
1269 // successors later.
Andrew Trickffc80972013-01-25 06:52:27 +00001270 R.DFSNodeData[SU->NodeNum].SubtreeID = SU->NodeNum;
1271 RootData RData(SU->NodeNum);
1272 RData.SubInstrCount = SU->getInstr()->isTransient() ? 0 : 1;
Andrew Trick48d392e2012-11-28 05:13:28 +00001273
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001274 // If any predecessors are still in their own subtree, they either cannot be
1275 // joined or are large enough to remain separate. If this parent node's
1276 // total instruction count is not greater than a child subtree by at least
1277 // the subtree limit, then try to join it now since splitting subtrees is
1278 // only useful if multiple high-pressure paths are possible.
Andrew Trickffc80972013-01-25 06:52:27 +00001279 unsigned InstrCount = R.DFSNodeData[SU->NodeNum].InstrCount;
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001280 for (SUnit::const_pred_iterator
1281 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
1282 if (PI->getKind() != SDep::Data)
1283 continue;
1284 unsigned PredNum = PI->getSUnit()->NodeNum;
Andrew Trickffc80972013-01-25 06:52:27 +00001285 if ((InstrCount - R.DFSNodeData[PredNum].InstrCount) < R.SubtreeLimit)
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001286 joinPredSubtree(*PI, SU, /*CheckLimit=*/false);
Andrew Trickffc80972013-01-25 06:52:27 +00001287
1288 // Either link or merge the TreeData entry from the child to the parent.
Andrew Trick646eeb62013-01-25 06:52:30 +00001289 if (R.DFSNodeData[PredNum].SubtreeID == PredNum) {
1290 // If the predecessor's parent is invalid, this is a tree edge and the
1291 // current node is the parent.
1292 if (RootSet[PredNum].ParentNodeID == SchedDFSResult::InvalidSubtreeID)
1293 RootSet[PredNum].ParentNodeID = SU->NodeNum;
1294 }
1295 else if (RootSet.count(PredNum)) {
1296 // The predecessor is not a root, but is still in the root set. This
1297 // must be the new parent that it was just joined to. Note that
1298 // RootSet[PredNum].ParentNodeID may either be invalid or may still be
1299 // set to the original parent.
Andrew Trickffc80972013-01-25 06:52:27 +00001300 RData.SubInstrCount += RootSet[PredNum].SubInstrCount;
1301 RootSet.erase(PredNum);
1302 }
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001303 }
Andrew Trickffc80972013-01-25 06:52:27 +00001304 RootSet[SU->NodeNum] = RData;
1305 }
1306
1307 /// Called once for each tree edge after calling visitPostOrderNode on the
1308 /// predecessor. Increment the parent node's instruction count and
1309 /// preemptively join this subtree to its parent's if it is small enough.
1310 void visitPostorderEdge(const SDep &PredDep, const SUnit *Succ) {
1311 R.DFSNodeData[Succ->NodeNum].InstrCount
1312 += R.DFSNodeData[PredDep.getSUnit()->NodeNum].InstrCount;
1313 joinPredSubtree(PredDep, Succ);
Andrew Trick48d392e2012-11-28 05:13:28 +00001314 }
1315
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001316 /// Add a connection for cross edges.
1317 void visitCrossEdge(const SDep &PredDep, const SUnit *Succ) {
Andrew Trick48d392e2012-11-28 05:13:28 +00001318 ConnectionPairs.push_back(std::make_pair(PredDep.getSUnit(), Succ));
1319 }
1320
1321 /// Set each node's subtree ID to the representative ID and record connections
1322 /// between trees.
1323 void finalize() {
1324 SubtreeClasses.compress();
Andrew Trickffc80972013-01-25 06:52:27 +00001325 R.DFSTreeData.resize(SubtreeClasses.getNumClasses());
1326 assert(SubtreeClasses.getNumClasses() == RootSet.size()
1327 && "number of roots should match trees");
1328 for (SparseSet<RootData>::const_iterator
1329 RI = RootSet.begin(), RE = RootSet.end(); RI != RE; ++RI) {
1330 unsigned TreeID = SubtreeClasses[RI->NodeID];
1331 if (RI->ParentNodeID != SchedDFSResult::InvalidSubtreeID)
1332 R.DFSTreeData[TreeID].ParentTreeID = SubtreeClasses[RI->ParentNodeID];
1333 R.DFSTreeData[TreeID].SubInstrCount = RI->SubInstrCount;
Andrew Trick646eeb62013-01-25 06:52:30 +00001334 // Note that SubInstrCount may be greater than InstrCount if we joined
1335 // subtrees across a cross edge. InstrCount will be attributed to the
1336 // original parent, while SubInstrCount will be attributed to the joined
1337 // parent.
Andrew Trickffc80972013-01-25 06:52:27 +00001338 }
Andrew Trick48d392e2012-11-28 05:13:28 +00001339 R.SubtreeConnections.resize(SubtreeClasses.getNumClasses());
1340 R.SubtreeConnectLevels.resize(SubtreeClasses.getNumClasses());
1341 DEBUG(dbgs() << R.getNumSubtrees() << " subtrees:\n");
Andrew Trickffc80972013-01-25 06:52:27 +00001342 for (unsigned Idx = 0, End = R.DFSNodeData.size(); Idx != End; ++Idx) {
1343 R.DFSNodeData[Idx].SubtreeID = SubtreeClasses[Idx];
Andrew Trick48d392e2012-11-28 05:13:28 +00001344 DEBUG(dbgs() << " SU(" << Idx << ") in tree "
Andrew Trickffc80972013-01-25 06:52:27 +00001345 << R.DFSNodeData[Idx].SubtreeID << '\n');
Andrew Trick48d392e2012-11-28 05:13:28 +00001346 }
1347 for (std::vector<std::pair<const SUnit*, const SUnit*> >::const_iterator
1348 I = ConnectionPairs.begin(), E = ConnectionPairs.end();
1349 I != E; ++I) {
1350 unsigned PredTree = SubtreeClasses[I->first->NodeNum];
1351 unsigned SuccTree = SubtreeClasses[I->second->NodeNum];
1352 if (PredTree == SuccTree)
1353 continue;
1354 unsigned Depth = I->first->getDepth();
1355 addConnection(PredTree, SuccTree, Depth);
1356 addConnection(SuccTree, PredTree, Depth);
1357 }
1358 }
1359
1360protected:
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001361 /// Join the predecessor subtree with the successor that is its DFS
1362 /// parent. Apply some heuristics before joining.
1363 bool joinPredSubtree(const SDep &PredDep, const SUnit *Succ,
1364 bool CheckLimit = true) {
1365 assert(PredDep.getKind() == SDep::Data && "Subtrees are for data edges");
1366
1367 // Check if the predecessor is already joined.
1368 const SUnit *PredSU = PredDep.getSUnit();
1369 unsigned PredNum = PredSU->NodeNum;
Andrew Trickffc80972013-01-25 06:52:27 +00001370 if (R.DFSNodeData[PredNum].SubtreeID != PredNum)
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001371 return false;
Andrew Trickb52a8562013-01-25 00:12:57 +00001372
1373 // Four is the magic number of successors before a node is considered a
1374 // pinch point.
1375 unsigned NumDataSucs = 0;
Andrew Trickb52a8562013-01-25 00:12:57 +00001376 for (SUnit::const_succ_iterator SI = PredSU->Succs.begin(),
1377 SE = PredSU->Succs.end(); SI != SE; ++SI) {
1378 if (SI->getKind() == SDep::Data) {
1379 if (++NumDataSucs >= 4)
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001380 return false;
Andrew Trickb52a8562013-01-25 00:12:57 +00001381 }
1382 }
Andrew Trickffc80972013-01-25 06:52:27 +00001383 if (CheckLimit && R.DFSNodeData[PredNum].InstrCount > R.SubtreeLimit)
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001384 return false;
Andrew Trickffc80972013-01-25 06:52:27 +00001385 R.DFSNodeData[PredNum].SubtreeID = Succ->NodeNum;
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001386 SubtreeClasses.join(Succ->NodeNum, PredNum);
1387 return true;
Andrew Trickb52a8562013-01-25 00:12:57 +00001388 }
1389
Andrew Trick48d392e2012-11-28 05:13:28 +00001390 /// Called by finalize() to record a connection between trees.
1391 void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth) {
1392 if (!Depth)
1393 return;
1394
Andrew Trickffc80972013-01-25 06:52:27 +00001395 do {
1396 SmallVectorImpl<SchedDFSResult::Connection> &Connections =
1397 R.SubtreeConnections[FromTree];
1398 for (SmallVectorImpl<SchedDFSResult::Connection>::iterator
1399 I = Connections.begin(), E = Connections.end(); I != E; ++I) {
1400 if (I->TreeID == ToTree) {
1401 I->Level = std::max(I->Level, Depth);
1402 return;
1403 }
Andrew Trick48d392e2012-11-28 05:13:28 +00001404 }
Andrew Trickffc80972013-01-25 06:52:27 +00001405 Connections.push_back(SchedDFSResult::Connection(ToTree, Depth));
1406 FromTree = R.DFSTreeData[FromTree].ParentTreeID;
1407 } while (FromTree != SchedDFSResult::InvalidSubtreeID);
Andrew Trick48d392e2012-11-28 05:13:28 +00001408 }
1409};
1410} // namespace llvm
1411
Andrew Trick90f711d2012-10-15 18:02:27 +00001412namespace {
1413/// \brief Manage the stack used by a reverse depth-first search over the DAG.
1414class SchedDAGReverseDFS {
1415 std::vector<std::pair<const SUnit*, SUnit::const_pred_iterator> > DFSStack;
1416public:
1417 bool isComplete() const { return DFSStack.empty(); }
1418
1419 void follow(const SUnit *SU) {
1420 DFSStack.push_back(std::make_pair(SU, SU->Preds.begin()));
1421 }
1422 void advance() { ++DFSStack.back().second; }
1423
Andrew Trick48d392e2012-11-28 05:13:28 +00001424 const SDep *backtrack() {
1425 DFSStack.pop_back();
Craig Topperc0196b12014-04-14 00:51:57 +00001426 return DFSStack.empty() ? nullptr : std::prev(DFSStack.back().second);
Andrew Trick48d392e2012-11-28 05:13:28 +00001427 }
Andrew Trick90f711d2012-10-15 18:02:27 +00001428
1429 const SUnit *getCurr() const { return DFSStack.back().first; }
1430
1431 SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
1432
1433 SUnit::const_pred_iterator getPredEnd() const {
1434 return getCurr()->Preds.end();
1435 }
1436};
1437} // anonymous
1438
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001439static bool hasDataSucc(const SUnit *SU) {
1440 for (SUnit::const_succ_iterator
1441 SI = SU->Succs.begin(), SE = SU->Succs.end(); SI != SE; ++SI) {
Andrew Trick646eeb62013-01-25 06:52:30 +00001442 if (SI->getKind() == SDep::Data && !SI->getSUnit()->isBoundaryNode())
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001443 return true;
1444 }
1445 return false;
1446}
1447
Andrew Trick90f711d2012-10-15 18:02:27 +00001448/// Compute an ILP metric for all nodes in the subDAG reachable via depth-first
1449/// search from this root.
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001450void SchedDFSResult::compute(ArrayRef<SUnit> SUnits) {
Andrew Trick90f711d2012-10-15 18:02:27 +00001451 if (!IsBottomUp)
1452 llvm_unreachable("Top-down ILP metric is unimplemnted");
1453
Andrew Trick48d392e2012-11-28 05:13:28 +00001454 SchedDFSImpl Impl(*this);
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001455 for (ArrayRef<SUnit>::const_iterator
1456 SI = SUnits.begin(), SE = SUnits.end(); SI != SE; ++SI) {
1457 const SUnit *SU = &*SI;
1458 if (Impl.isVisited(SU) || hasDataSucc(SU))
1459 continue;
1460
Andrew Trick48d392e2012-11-28 05:13:28 +00001461 SchedDAGReverseDFS DFS;
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001462 Impl.visitPreorder(SU);
1463 DFS.follow(SU);
Andrew Trick48d392e2012-11-28 05:13:28 +00001464 for (;;) {
1465 // Traverse the leftmost path as far as possible.
1466 while (DFS.getPred() != DFS.getPredEnd()) {
1467 const SDep &PredDep = *DFS.getPred();
1468 DFS.advance();
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001469 // Ignore non-data edges.
Andrew Trick646eeb62013-01-25 06:52:30 +00001470 if (PredDep.getKind() != SDep::Data
1471 || PredDep.getSUnit()->isBoundaryNode()) {
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001472 continue;
Andrew Trick646eeb62013-01-25 06:52:30 +00001473 }
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001474 // An already visited edge is a cross edge, assuming an acyclic DAG.
Andrew Trick48d392e2012-11-28 05:13:28 +00001475 if (Impl.isVisited(PredDep.getSUnit())) {
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001476 Impl.visitCrossEdge(PredDep, DFS.getCurr());
Andrew Trick48d392e2012-11-28 05:13:28 +00001477 continue;
1478 }
1479 Impl.visitPreorder(PredDep.getSUnit());
1480 DFS.follow(PredDep.getSUnit());
1481 }
1482 // Visit the top of the stack in postorder and backtrack.
1483 const SUnit *Child = DFS.getCurr();
1484 const SDep *PredDep = DFS.backtrack();
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001485 Impl.visitPostorderNode(Child);
1486 if (PredDep)
1487 Impl.visitPostorderEdge(*PredDep, DFS.getCurr());
Andrew Trick48d392e2012-11-28 05:13:28 +00001488 if (DFS.isComplete())
1489 break;
Andrew Trick90f711d2012-10-15 18:02:27 +00001490 }
Andrew Trick48d392e2012-11-28 05:13:28 +00001491 }
1492 Impl.finalize();
1493}
1494
1495/// The root of the given SubtreeID was just scheduled. For all subtrees
1496/// connected to this tree, record the depth of the connection so that the
1497/// nearest connected subtrees can be prioritized.
1498void SchedDFSResult::scheduleTree(unsigned SubtreeID) {
1499 for (SmallVectorImpl<Connection>::const_iterator
1500 I = SubtreeConnections[SubtreeID].begin(),
1501 E = SubtreeConnections[SubtreeID].end(); I != E; ++I) {
1502 SubtreeConnectLevels[I->TreeID] =
1503 std::max(SubtreeConnectLevels[I->TreeID], I->Level);
1504 DEBUG(dbgs() << " Tree: " << I->TreeID
1505 << " @" << SubtreeConnectLevels[I->TreeID] << '\n');
Andrew Trick90f711d2012-10-15 18:02:27 +00001506 }
1507}
1508
1509#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1510void ILPValue::print(raw_ostream &OS) const {
Andrew Trick48d392e2012-11-28 05:13:28 +00001511 OS << InstrCount << " / " << Length << " = ";
1512 if (!Length)
Andrew Trick90f711d2012-10-15 18:02:27 +00001513 OS << "BADILP";
Andrew Trick48d392e2012-11-28 05:13:28 +00001514 else
1515 OS << format("%g", ((double)InstrCount / Length));
Andrew Trick90f711d2012-10-15 18:02:27 +00001516}
1517
1518void ILPValue::dump() const {
1519 dbgs() << *this << '\n';
1520}
1521
1522namespace llvm {
1523
1524raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) {
1525 Val.print(OS);
1526 return OS;
1527}
1528
1529} // namespace llvm
1530#endif // !NDEBUG || LLVM_ENABLE_DUMP