blob: 977b8f0b41dcf1d8d62c9c719dfb8f8b1eab2af3 [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"
Dan Gohman48b185d2009-09-25 20:36:54 +000024#include "llvm/CodeGen/MachineMemOperand.h"
Dan Gohmandddc1ac2008-12-16 03:25:46 +000025#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman3aab10b2008-12-04 01:35:46 +000026#include "llvm/CodeGen/PseudoSourceValue.h"
Andrew Trick88517f62012-06-06 19:47:35 +000027#include "llvm/CodeGen/RegisterPressure.h"
Andrew Trickcd1c2f92012-11-28 05:13:24 +000028#include "llvm/CodeGen/ScheduleDFS.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Operator.h"
Evan Cheng8264e272011-06-29 01:14:12 +000030#include "llvm/MC/MCInstrItineraries.h"
Andrew Trickda01ba32012-05-15 18:59:41 +000031#include "llvm/Support/CommandLine.h"
Dan Gohman60cb69e2008-11-19 23:18:57 +000032#include "llvm/Support/Debug.h"
Andrew Trick90f711d2012-10-15 18:02:27 +000033#include "llvm/Support/Format.h"
Dan Gohman60cb69e2008-11-19 23:18:57 +000034#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Target/TargetInstrInfo.h"
36#include "llvm/Target/TargetMachine.h"
37#include "llvm/Target/TargetRegisterInfo.h"
38#include "llvm/Target/TargetSubtargetInfo.h"
Andrew Trickc01b0042013-08-23 17:48:43 +000039#include <queue>
40
Dan Gohman60cb69e2008-11-19 23:18:57 +000041using namespace llvm;
42
Andrew Trickda01ba32012-05-15 18:59:41 +000043static cl::opt<bool> EnableAASchedMI("enable-aa-sched-mi", cl::Hidden,
44 cl::ZeroOrMore, cl::init(false),
45 cl::desc("Enable use of AA during MI GAD construction"));
46
Dan Gohman619ef482009-01-15 19:20:50 +000047ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
Dan Gohmandddc1ac2008-12-16 03:25:46 +000048 const MachineLoopInfo &mli,
Andrew Trick1d028a32012-01-14 02:17:12 +000049 const MachineDominatorTree &mdt,
Andrew Trick46cc9a42012-02-22 06:08:11 +000050 bool IsPostRAFlag,
51 LiveIntervals *lis)
Andrew Trickdd79f0f2012-10-10 05:43:09 +000052 : ScheduleDAG(mf), MLI(mli), MDT(mdt), MFI(mf.getFrameInfo()), LIS(lis),
Andrew Trickcaf1dc72012-10-09 23:44:23 +000053 IsPostRA(IsPostRAFlag), CanHandleTerminators(false), FirstDbgValue(0) {
Andrew Trick46cc9a42012-02-22 06:08:11 +000054 assert((IsPostRA || LIS) && "PreRA scheduling requires LiveIntervals");
Devang Patele5feef02011-06-02 20:07:12 +000055 DbgValues.clear();
Andrew Trickdb42c6f2012-02-22 06:08:13 +000056 assert(!(IsPostRA && MRI.getNumVirtRegs()) &&
Andrew Trickda84e642012-02-21 04:51:23 +000057 "Virtual registers must be removed prior to PostRA scheduling");
Andrew Trick9b635132012-09-18 18:20:00 +000058
59 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
60 SchedModel.init(*ST.getSchedModel(), &ST, TII);
Evan Chengf0236e02009-10-18 19:58:47 +000061}
Dan Gohman60cb69e2008-11-19 23:18:57 +000062
Dan Gohman1ee0d412009-01-30 02:49:14 +000063/// getUnderlyingObjectFromInt - This is the function that does the work of
64/// looking through basic ptrtoint+arithmetic+inttoptr sequences.
65static const Value *getUnderlyingObjectFromInt(const Value *V) {
66 do {
Dan Gohman58b0e712009-07-17 20:58:59 +000067 if (const Operator *U = dyn_cast<Operator>(V)) {
Dan Gohman1ee0d412009-01-30 02:49:14 +000068 // If we find a ptrtoint, we can transfer control back to the
69 // regular getUnderlyingObjectFromInt.
Dan Gohman58b0e712009-07-17 20:58:59 +000070 if (U->getOpcode() == Instruction::PtrToInt)
Dan Gohman1ee0d412009-01-30 02:49:14 +000071 return U->getOperand(0);
Andrew Trick0be19362012-11-28 03:42:49 +000072 // If we find an add of a constant, a multiplied value, or a phi, it's
Dan Gohman1ee0d412009-01-30 02:49:14 +000073 // likely that the other operand will lead us to the base
74 // object. We don't have to worry about the case where the
Dan Gohman6c0c2192009-08-07 01:26:06 +000075 // object address is somehow being computed by the multiply,
Dan Gohman1ee0d412009-01-30 02:49:14 +000076 // because our callers only care when the result is an
Nick Lewycky1a329542012-10-26 04:27:49 +000077 // identifiable object.
Dan Gohman58b0e712009-07-17 20:58:59 +000078 if (U->getOpcode() != Instruction::Add ||
Dan Gohman1ee0d412009-01-30 02:49:14 +000079 (!isa<ConstantInt>(U->getOperand(1)) &&
Andrew Trick0be19362012-11-28 03:42:49 +000080 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
81 !isa<PHINode>(U->getOperand(1))))
Dan Gohman1ee0d412009-01-30 02:49:14 +000082 return V;
83 V = U->getOperand(0);
84 } else {
85 return V;
86 }
Duncan Sands19d0b472010-02-16 11:11:14 +000087 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
Dan Gohman1ee0d412009-01-30 02:49:14 +000088 } while (1);
89}
90
Hal Finkel66859ae2012-12-10 18:49:16 +000091/// getUnderlyingObjects - This is a wrapper around GetUnderlyingObjects
Dan Gohman1ee0d412009-01-30 02:49:14 +000092/// and adds support for basic ptrtoint+arithmetic+inttoptr sequences.
Hal Finkel66859ae2012-12-10 18:49:16 +000093static void getUnderlyingObjects(const Value *V,
94 SmallVectorImpl<Value *> &Objects) {
95 SmallPtrSet<const Value*, 16> Visited;
96 SmallVector<const Value *, 4> Working(1, V);
Dan Gohman1ee0d412009-01-30 02:49:14 +000097 do {
Hal Finkel66859ae2012-12-10 18:49:16 +000098 V = Working.pop_back_val();
99
100 SmallVector<Value *, 4> Objs;
101 GetUnderlyingObjects(const_cast<Value *>(V), Objs);
102
Craig Toppere1c1d362013-07-03 05:11:49 +0000103 for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), IE = Objs.end();
Hal Finkel66859ae2012-12-10 18:49:16 +0000104 I != IE; ++I) {
105 V = *I;
106 if (!Visited.insert(V))
107 continue;
108 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
109 const Value *O =
110 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
111 if (O->getType()->isPointerTy()) {
112 Working.push_back(O);
113 continue;
114 }
115 }
116 Objects.push_back(const_cast<Value *>(V));
117 }
118 } while (!Working.empty());
Dan Gohman1ee0d412009-01-30 02:49:14 +0000119}
120
Benjamin Kramerfd510922013-06-29 18:41:17 +0000121typedef SmallVector<PointerIntPair<const Value *, 1, bool>, 4>
122UnderlyingObjectsVector;
123
Hal Finkel66859ae2012-12-10 18:49:16 +0000124/// getUnderlyingObjectsForInstr - If this machine instr has memory reference
Dan Gohman1ee0d412009-01-30 02:49:14 +0000125/// information and it can be tracked to a normal reference to a known
Hal Finkel66859ae2012-12-10 18:49:16 +0000126/// object, return the Value for that object.
127static void getUnderlyingObjectsForInstr(const MachineInstr *MI,
Benjamin Kramerfd510922013-06-29 18:41:17 +0000128 const MachineFrameInfo *MFI,
129 UnderlyingObjectsVector &Objects) {
Dan Gohman1ee0d412009-01-30 02:49:14 +0000130 if (!MI->hasOneMemOperand() ||
Dan Gohman48b185d2009-09-25 20:36:54 +0000131 !(*MI->memoperands_begin())->getValue() ||
132 (*MI->memoperands_begin())->isVolatile())
Hal Finkel66859ae2012-12-10 18:49:16 +0000133 return;
Dan Gohman1ee0d412009-01-30 02:49:14 +0000134
Dan Gohman48b185d2009-09-25 20:36:54 +0000135 const Value *V = (*MI->memoperands_begin())->getValue();
Dan Gohman1ee0d412009-01-30 02:49:14 +0000136 if (!V)
Hal Finkel66859ae2012-12-10 18:49:16 +0000137 return;
Dan Gohman1ee0d412009-01-30 02:49:14 +0000138
Hal Finkel66859ae2012-12-10 18:49:16 +0000139 SmallVector<Value *, 4> Objs;
140 getUnderlyingObjects(V, Objs);
Andrew Trick24b1c482011-05-05 19:24:06 +0000141
Craig Toppere1c1d362013-07-03 05:11:49 +0000142 for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), IE = Objs.end();
143 I != IE; ++I) {
Hal Finkel66859ae2012-12-10 18:49:16 +0000144 bool MayAlias = true;
145 V = *I;
146
147 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
148 // For now, ignore PseudoSourceValues which may alias LLVM IR values
149 // because the code that uses this function has no way to cope with
150 // such aliases.
151
152 if (PSV->isAliased(MFI)) {
153 Objects.clear();
154 return;
155 }
156
157 MayAlias = PSV->mayAlias(MFI);
158 } else if (!isIdentifiedObject(V)) {
159 Objects.clear();
160 return;
161 }
162
Benjamin Kramerfd510922013-06-29 18:41:17 +0000163 Objects.push_back(UnderlyingObjectsVector::value_type(V, MayAlias));
Evan Cheng0e9d9ca2009-10-18 18:16:27 +0000164 }
Dan Gohman1ee0d412009-01-30 02:49:14 +0000165}
166
Andrew Trick7405c6d2012-04-20 20:05:21 +0000167void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) {
168 BB = bb;
Dan Gohmanb9543432009-02-10 23:27:53 +0000169}
170
Andrew Trick52226d42012-03-07 23:00:49 +0000171void ScheduleDAGInstrs::finishBlock() {
Andrew Trick51ee9362012-04-20 20:24:33 +0000172 // Subclasses should no longer refer to the old block.
Andrew Trick7405c6d2012-04-20 20:05:21 +0000173 BB = 0;
Andrew Trick60cf03e2012-03-07 05:21:52 +0000174}
175
Andrew Trick60cf03e2012-03-07 05:21:52 +0000176/// Initialize the DAG and common scheduler state for the current scheduling
177/// region. This does not actually create the DAG, only clears it. The
178/// scheduling driver may call BuildSchedGraph multiple times per scheduling
179/// region.
180void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb,
181 MachineBasicBlock::iterator begin,
182 MachineBasicBlock::iterator end,
Andrew Tricka53e1012013-08-23 17:48:33 +0000183 unsigned regioninstrs) {
Andrew Trick7405c6d2012-04-20 20:05:21 +0000184 assert(bb == BB && "startBlock should set BB");
Andrew Trick8c207e42012-03-09 04:29:02 +0000185 RegionBegin = begin;
186 RegionEnd = end;
Andrew Tricka53e1012013-08-23 17:48:33 +0000187 NumRegionInstrs = regioninstrs;
Andrew Trick60cf03e2012-03-07 05:21:52 +0000188}
189
190/// Close the current scheduling region. Don't clear any state in case the
191/// driver wants to refer to the previous scheduling region.
192void ScheduleDAGInstrs::exitRegion() {
193 // Nothing to do.
194}
195
Andrew Trick52226d42012-03-07 23:00:49 +0000196/// addSchedBarrierDeps - Add dependencies from instructions in the current
Evan Cheng15459b62010-10-23 02:10:46 +0000197/// list of instructions being scheduled to scheduling barrier by adding
198/// the exit SU to the register defs and use list. This is because we want to
199/// make sure instructions which define registers that are either used by
200/// the terminator or are live-out are properly scheduled. This is
201/// especially important when the definition latency of the return value(s)
202/// are too high to be hidden by the branch or when the liveout registers
203/// used by instructions in the fallthrough block.
Andrew Trick52226d42012-03-07 23:00:49 +0000204void ScheduleDAGInstrs::addSchedBarrierDeps() {
Andrew Trick8c207e42012-03-09 04:29:02 +0000205 MachineInstr *ExitMI = RegionEnd != BB->end() ? &*RegionEnd : 0;
Evan Cheng15459b62010-10-23 02:10:46 +0000206 ExitSU.setInstr(ExitMI);
207 bool AllDepKnown = ExitMI &&
Evan Cheng7f8e5632011-12-07 07:15:52 +0000208 (ExitMI->isCall() || ExitMI->isBarrier());
Evan Cheng15459b62010-10-23 02:10:46 +0000209 if (ExitMI && AllDepKnown) {
210 // If it's a call or a barrier, add dependencies on the defs and uses of
211 // instruction.
212 for (unsigned i = 0, e = ExitMI->getNumOperands(); i != e; ++i) {
213 const MachineOperand &MO = ExitMI->getOperand(i);
214 if (!MO.isReg() || MO.isDef()) continue;
215 unsigned Reg = MO.getReg();
216 if (Reg == 0) continue;
217
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000218 if (TRI->isPhysicalRegister(Reg))
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000219 Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg));
Andrew Tricke6913c72012-03-16 05:04:25 +0000220 else {
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000221 assert(!IsPostRA && "Virtual register encountered after regalloc.");
Andrew Trickd5953622012-12-01 01:22:44 +0000222 if (MO.readsReg()) // ignore undef operands
223 addVRegUseDeps(&ExitSU, i);
Andrew Tricke6913c72012-03-16 05:04:25 +0000224 }
Evan Cheng15459b62010-10-23 02:10:46 +0000225 }
226 } else {
227 // For others, e.g. fallthrough, conditional branch, assume the exit
Evan Chengcbdf7e82010-10-27 23:17:17 +0000228 // uses all the registers that are livein to the successor blocks.
Benjamin Kramer411d5a22012-03-16 17:38:19 +0000229 assert(Uses.empty() && "Uses in set before adding deps?");
Evan Chengcbdf7e82010-10-27 23:17:17 +0000230 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
231 SE = BB->succ_end(); SI != SE; ++SI)
232 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
Andrew Trick24b1c482011-05-05 19:24:06 +0000233 E = (*SI)->livein_end(); I != E; ++I) {
Evan Chengcbdf7e82010-10-27 23:17:17 +0000234 unsigned Reg = *I;
Benjamin Kramer411d5a22012-03-16 17:38:19 +0000235 if (!Uses.contains(Reg))
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000236 Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg));
Evan Chengcbdf7e82010-10-27 23:17:17 +0000237 }
Evan Cheng15459b62010-10-23 02:10:46 +0000238 }
239}
240
Andrew Trickd675a4c2012-02-23 01:52:38 +0000241/// MO is an operand of SU's instruction that defines a physical register. Add
242/// data dependencies from SU to any uses of the physical register.
Andrew Trickae535612012-08-23 00:39:43 +0000243void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU, unsigned OperIdx) {
244 const MachineOperand &MO = SU->getInstr()->getOperand(OperIdx);
Andrew Trickd675a4c2012-02-23 01:52:38 +0000245 assert(MO.isDef() && "expect physreg def");
246
247 // Ask the target if address-backscheduling is desirable, and if so how much.
248 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
Andrew Trickd675a4c2012-02-23 01:52:38 +0000249
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000250 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
251 Alias.isValid(); ++Alias) {
Andrew Trick9dbbd3e2012-02-24 07:04:55 +0000252 if (!Uses.contains(*Alias))
Andrew Trickd675a4c2012-02-23 01:52:38 +0000253 continue;
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000254 for (Reg2SUnitsMap::iterator I = Uses.find(*Alias); I != Uses.end(); ++I) {
255 SUnit *UseSU = I->SU;
Andrew Trickd675a4c2012-02-23 01:52:38 +0000256 if (UseSU == SU)
257 continue;
Andrew Trick07dced62012-10-08 18:54:00 +0000258
Andrew Trick07dced62012-10-08 18:54:00 +0000259 // Adjust the dependence latency using operand def/use information,
260 // then allow the target to perform its own adjustments.
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000261 int UseOp = I->OpIdx;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000262 MachineInstr *RegUse = 0;
263 SDep Dep;
264 if (UseOp < 0)
265 Dep = SDep(SU, SDep::Artificial);
266 else {
Andrew Tricke833e1c2013-04-13 06:07:40 +0000267 // Set the hasPhysRegDefs only for physreg defs that have a use within
268 // the scheduling region.
269 SU->hasPhysRegDefs = true;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000270 Dep = SDep(SU, SDep::Data, *Alias);
271 RegUse = UseSU->getInstr();
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000272 }
273 Dep.setLatency(
Andrew Trickde2109e2013-06-15 04:49:57 +0000274 SchedModel.computeOperandLatency(SU->getInstr(), OperIdx, RegUse,
275 UseOp));
Andrew Trick45446062012-06-05 21:11:27 +0000276
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000277 ST.adjustSchedDependency(SU, UseSU, Dep);
278 UseSU->addPred(Dep);
Andrew Trickd675a4c2012-02-23 01:52:38 +0000279 }
280 }
281}
282
Andrew Trickdbee9d82012-01-14 02:17:15 +0000283/// addPhysRegDeps - Add register dependencies (data, anti, and output) from
284/// this SUnit to following instructions in the same scheduling region that
285/// depend the physical register referenced at OperIdx.
286void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
287 const MachineInstr *MI = SU->getInstr();
288 const MachineOperand &MO = MI->getOperand(OperIdx);
Andrew Trickdbee9d82012-01-14 02:17:15 +0000289
290 // Optionally add output and anti dependencies. For anti
291 // dependencies we use a latency of 0 because for a multi-issue
292 // target we want to allow the defining instruction to issue
293 // in the same cycle as the using instruction.
294 // TODO: Using a latency of 1 here for output dependencies assumes
295 // there's no cost for reusing registers.
296 SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000297 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
298 Alias.isValid(); ++Alias) {
Andrew Trick9dbbd3e2012-02-24 07:04:55 +0000299 if (!Defs.contains(*Alias))
Andrew Trickd675a4c2012-02-23 01:52:38 +0000300 continue;
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000301 for (Reg2SUnitsMap::iterator I = Defs.find(*Alias); I != Defs.end(); ++I) {
302 SUnit *DefSU = I->SU;
Andrew Trickdbee9d82012-01-14 02:17:15 +0000303 if (DefSU == &ExitSU)
304 continue;
305 if (DefSU != SU &&
306 (Kind != SDep::Output || !MO.isDead() ||
307 !DefSU->getInstr()->registerDefIsDead(*Alias))) {
308 if (Kind == SDep::Anti)
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000309 DefSU->addPred(SDep(SU, Kind, /*Reg=*/*Alias));
Andrew Trickdbee9d82012-01-14 02:17:15 +0000310 else {
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000311 SDep Dep(SU, Kind, /*Reg=*/*Alias);
Andrew Trickde2109e2013-06-15 04:49:57 +0000312 Dep.setLatency(
313 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000314 DefSU->addPred(Dep);
Andrew Trickdbee9d82012-01-14 02:17:15 +0000315 }
316 }
317 }
318 }
319
Andrew Trickd675a4c2012-02-23 01:52:38 +0000320 if (!MO.isDef()) {
Andrew Tricke833e1c2013-04-13 06:07:40 +0000321 SU->hasPhysRegUses = true;
Andrew Trickd675a4c2012-02-23 01:52:38 +0000322 // Either insert a new Reg2SUnits entry with an empty SUnits list, or
323 // retrieve the existing SUnits list for this register's uses.
324 // Push this SUnit on the use list.
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000325 Uses.insert(PhysRegSUOper(SU, OperIdx, MO.getReg()));
Andrew Trickd675a4c2012-02-23 01:52:38 +0000326 }
327 else {
Andrew Trickae535612012-08-23 00:39:43 +0000328 addPhysRegDataDeps(SU, OperIdx);
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000329 unsigned Reg = MO.getReg();
Andrew Trickdbee9d82012-01-14 02:17:15 +0000330
Andrew Trickd675a4c2012-02-23 01:52:38 +0000331 // clear this register's use list
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000332 if (Uses.contains(Reg))
333 Uses.eraseAll(Reg);
Andrew Trickd675a4c2012-02-23 01:52:38 +0000334
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000335 if (!MO.isDead()) {
336 Defs.eraseAll(Reg);
337 } else if (SU->isCall) {
338 // Calls will not be reordered because of chain dependencies (see
339 // below). Since call operands are dead, calls may continue to be added
340 // to the DefList making dependence checking quadratic in the size of
341 // the block. Instead, we leave only one call at the back of the
342 // DefList.
343 Reg2SUnitsMap::RangePair P = Defs.equal_range(Reg);
344 Reg2SUnitsMap::iterator B = P.first;
345 Reg2SUnitsMap::iterator I = P.second;
346 for (bool isBegin = I == B; !isBegin; /* empty */) {
347 isBegin = (--I) == B;
348 if (!I->SU->isCall)
349 break;
350 I = Defs.erase(I);
351 }
Andrew Trickdbee9d82012-01-14 02:17:15 +0000352 }
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000353
Andrew Trickd675a4c2012-02-23 01:52:38 +0000354 // Defs are pushed in the order they are visited and never reordered.
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000355 Defs.insert(PhysRegSUOper(SU, OperIdx, Reg));
Andrew Trickdbee9d82012-01-14 02:17:15 +0000356 }
357}
358
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000359/// addVRegDefDeps - Add register output and data dependencies from this SUnit
360/// to instructions that occur later in the same scheduling region if they read
361/// from or write to the virtual register defined at OperIdx.
362///
363/// TODO: Hoist loop induction variable increments. This has to be
364/// reevaluated. Generally, IV scheduling should be done before coalescing.
365void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
366 const MachineInstr *MI = SU->getInstr();
367 unsigned Reg = MI->getOperand(OperIdx).getReg();
368
Andrew Trick94053432012-07-28 01:48:15 +0000369 // Singly defined vregs do not have output/anti dependencies.
Andrew Trick64ca16e2012-02-22 18:34:49 +0000370 // The current operand is a def, so we have at least one.
Andrew Trick94053432012-07-28 01:48:15 +0000371 // Check here if there are any others...
Andrew Trick79795892012-07-30 23:48:17 +0000372 if (MRI.hasOneDef(Reg))
Andrew Trick94053432012-07-28 01:48:15 +0000373 return;
Andrew Trickdb42c6f2012-02-22 06:08:13 +0000374
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000375 // Add output dependence to the next nearest def of this vreg.
376 //
377 // Unless this definition is dead, the output dependence should be
378 // transitively redundant with antidependencies from this definition's
379 // uses. We're conservative for now until we have a way to guarantee the uses
380 // are not eliminated sometime during scheduling. The output dependence edge
381 // is also useful if output latency exceeds def-use latency.
Andrew Trick1eb4a0d2012-04-20 20:05:28 +0000382 VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
Andrew Trickd458e2d2012-02-22 21:59:00 +0000383 if (DefI == VRegDefs.end())
384 VRegDefs.insert(VReg2SUnit(Reg, SU));
385 else {
386 SUnit *DefSU = DefI->SU;
387 if (DefSU != SU && DefSU != &ExitSU) {
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000388 SDep Dep(SU, SDep::Output, Reg);
Andrew Trickde2109e2013-06-15 04:49:57 +0000389 Dep.setLatency(
390 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000391 DefSU->addPred(Dep);
Andrew Trickd458e2d2012-02-22 21:59:00 +0000392 }
393 DefI->SU = SU;
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000394 }
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000395}
396
Andrew Trick46cc9a42012-02-22 06:08:11 +0000397/// addVRegUseDeps - Add a register data dependency if the instruction that
398/// defines the virtual register used at OperIdx is mapped to an SUnit. Add a
399/// register antidependency from this SUnit to instructions that occur later in
400/// the same scheduling region if they write the virtual register.
401///
402/// TODO: Handle ExitSU "uses" properly.
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000403void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
Andrew Trick46cc9a42012-02-22 06:08:11 +0000404 MachineInstr *MI = SU->getInstr();
405 unsigned Reg = MI->getOperand(OperIdx).getReg();
406
Andrew Trick8dd26f02013-08-23 17:48:39 +0000407 // Record this local VReg use.
Andrew Trick2bc74c22013-08-30 04:36:57 +0000408 VReg2UseMap::iterator UI = VRegUses.find(Reg);
409 for (; UI != VRegUses.end(); ++UI) {
410 if (UI->SU == SU)
411 break;
412 }
413 if (UI == VRegUses.end())
414 VRegUses.insert(VReg2SUnit(Reg, SU));
Andrew Trick8dd26f02013-08-23 17:48:39 +0000415
Andrew Trick46cc9a42012-02-22 06:08:11 +0000416 // Lookup this operand's reaching definition.
417 assert(LIS && "vreg dependencies requires LiveIntervals");
Matthias Braun88dd0ab2013-10-10 21:28:52 +0000418 LiveQueryResult LRQ
419 = LIS->getInterval(Reg).Query(LIS->getInstructionIndex(MI));
Jakob Stoklund Olesenabc8c3d2012-05-20 02:44:38 +0000420 VNInfo *VNI = LRQ.valueIn();
Andrew Trick9e9a9f12012-04-24 18:04:41 +0000421
Andrew Trickda6a15d2012-02-23 03:16:24 +0000422 // VNI will be valid because MachineOperand::readsReg() is checked by caller.
Jakob Stoklund Olesenabc8c3d2012-05-20 02:44:38 +0000423 assert(VNI && "No value to read by operand");
Andrew Trick46cc9a42012-02-22 06:08:11 +0000424 MachineInstr *Def = LIS->getInstructionFromIndex(VNI->def);
Andrew Trickda6a15d2012-02-23 03:16:24 +0000425 // Phis and other noninstructions (after coalescing) have a NULL Def.
Andrew Trick46cc9a42012-02-22 06:08:11 +0000426 if (Def) {
427 SUnit *DefSU = getSUnit(Def);
428 if (DefSU) {
429 // The reaching Def lives within this scheduling region.
430 // Create a data dependence.
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000431 SDep dep(DefSU, SDep::Data, Reg);
Andrew Trick09650df2012-10-08 18:53:57 +0000432 // Adjust the dependence latency using operand def/use information, then
433 // allow the target to perform its own adjustments.
434 int DefOp = Def->findRegisterDefOperandIdx(Reg);
Andrew Trickde2109e2013-06-15 04:49:57 +0000435 dep.setLatency(SchedModel.computeOperandLatency(Def, DefOp, MI, OperIdx));
Andrew Trick45446062012-06-05 21:11:27 +0000436
Andrew Trick09650df2012-10-08 18:53:57 +0000437 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
438 ST.adjustSchedDependency(DefSU, SU, const_cast<SDep &>(dep));
Andrew Trick46cc9a42012-02-22 06:08:11 +0000439 SU->addPred(dep);
440 }
441 }
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000442
443 // Add antidependence to the following def of the vreg it uses.
Andrew Trick1eb4a0d2012-04-20 20:05:28 +0000444 VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
Andrew Trickd458e2d2012-02-22 21:59:00 +0000445 if (DefI != VRegDefs.end() && DefI->SU != SU)
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000446 DefI->SU->addPred(SDep(SU, SDep::Anti, Reg));
Andrew Trick46cc9a42012-02-22 06:08:11 +0000447}
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000448
Andrew Trickda01ba32012-05-15 18:59:41 +0000449/// Return true if MI is an instruction we are unable to reason about
450/// (like a call or something with unmodeled side effects).
451static inline bool isGlobalMemoryObject(AliasAnalysis *AA, MachineInstr *MI) {
452 if (MI->isCall() || MI->hasUnmodeledSideEffects() ||
Jakob Stoklund Olesencea3e772012-08-29 21:19:21 +0000453 (MI->hasOrderedMemoryRef() &&
Andrew Trickda01ba32012-05-15 18:59:41 +0000454 (!MI->mayLoad() || !MI->isInvariantLoad(AA))))
455 return true;
456 return false;
457}
458
459// This MI might have either incomplete info, or known to be unsafe
460// to deal with (i.e. volatile object).
461static inline bool isUnsafeMemoryObject(MachineInstr *MI,
462 const MachineFrameInfo *MFI) {
463 if (!MI || MI->memoperands_empty())
464 return true;
465 // We purposefully do no check for hasOneMemOperand() here
466 // in hope to trigger an assert downstream in order to
467 // finish implementation.
468 if ((*MI->memoperands_begin())->isVolatile() ||
469 MI->hasUnmodeledSideEffects())
470 return true;
Andrew Trickda01ba32012-05-15 18:59:41 +0000471 const Value *V = (*MI->memoperands_begin())->getValue();
472 if (!V)
473 return true;
474
Hal Finkel66859ae2012-12-10 18:49:16 +0000475 SmallVector<Value *, 4> Objs;
476 getUnderlyingObjects(V, Objs);
Craig Toppere1c1d362013-07-03 05:11:49 +0000477 for (SmallVectorImpl<Value *>::iterator I = Objs.begin(),
478 IE = Objs.end(); I != IE; ++I) {
Hal Finkel66859ae2012-12-10 18:49:16 +0000479 V = *I;
480
481 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
482 // Similarly to getUnderlyingObjectForInstr:
483 // For now, ignore PseudoSourceValues which may alias LLVM IR values
484 // because the code that uses this function has no way to cope with
485 // such aliases.
486 if (PSV->isAliased(MFI))
487 return true;
488 }
489
490 // Does this pointer refer to a distinct and identifiable object?
491 if (!isIdentifiedObject(V))
Andrew Trickda01ba32012-05-15 18:59:41 +0000492 return true;
493 }
Andrew Trickda01ba32012-05-15 18:59:41 +0000494
495 return false;
496}
497
498/// This returns true if the two MIs need a chain edge betwee them.
499/// If these are not even memory operations, we still may need
500/// chain deps between them. The question really is - could
501/// these two MIs be reordered during scheduling from memory dependency
502/// point of view.
503static bool MIsNeedChainEdge(AliasAnalysis *AA, const MachineFrameInfo *MFI,
504 MachineInstr *MIa,
505 MachineInstr *MIb) {
506 // Cover a trivial case - no edge is need to itself.
507 if (MIa == MIb)
508 return false;
509
510 if (isUnsafeMemoryObject(MIa, MFI) || isUnsafeMemoryObject(MIb, MFI))
511 return true;
512
513 // If we are dealing with two "normal" loads, we do not need an edge
514 // between them - they could be reordered.
515 if (!MIa->mayStore() && !MIb->mayStore())
516 return false;
517
518 // To this point analysis is generic. From here on we do need AA.
519 if (!AA)
520 return true;
521
522 MachineMemOperand *MMOa = *MIa->memoperands_begin();
523 MachineMemOperand *MMOb = *MIb->memoperands_begin();
524
525 // FIXME: Need to handle multiple memory operands to support all targets.
526 if (!MIa->hasOneMemOperand() || !MIb->hasOneMemOperand())
527 llvm_unreachable("Multiple memory operands.");
528
529 // The following interface to AA is fashioned after DAGCombiner::isAlias
530 // and operates with MachineMemOperand offset with some important
531 // assumptions:
532 // - LLVM fundamentally assumes flat address spaces.
533 // - MachineOperand offset can *only* result from legalization and
534 // cannot affect queries other than the trivial case of overlap
535 // checking.
536 // - These offsets never wrap and never step outside
537 // of allocated objects.
538 // - There should never be any negative offsets here.
539 //
540 // FIXME: Modify API to hide this math from "user"
541 // FIXME: Even before we go to AA we can reason locally about some
542 // memory objects. It can save compile time, and possibly catch some
543 // corner cases not currently covered.
544
545 assert ((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset");
546 assert ((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset");
547
548 int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset());
549 int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset;
550 int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset;
551
552 AliasAnalysis::AliasResult AAResult = AA->alias(
553 AliasAnalysis::Location(MMOa->getValue(), Overlapa,
554 MMOa->getTBAAInfo()),
555 AliasAnalysis::Location(MMOb->getValue(), Overlapb,
556 MMOb->getTBAAInfo()));
557
558 return (AAResult != AliasAnalysis::NoAlias);
559}
560
561/// This recursive function iterates over chain deps of SUb looking for
562/// "latest" node that needs a chain edge to SUa.
563static unsigned
564iterateChainSucc(AliasAnalysis *AA, const MachineFrameInfo *MFI,
565 SUnit *SUa, SUnit *SUb, SUnit *ExitSU, unsigned *Depth,
566 SmallPtrSet<const SUnit*, 16> &Visited) {
567 if (!SUa || !SUb || SUb == ExitSU)
568 return *Depth;
569
570 // Remember visited nodes.
571 if (!Visited.insert(SUb))
572 return *Depth;
573 // If there is _some_ dependency already in place, do not
574 // descend any further.
575 // TODO: Need to make sure that if that dependency got eliminated or ignored
576 // for any reason in the future, we would not violate DAG topology.
577 // Currently it does not happen, but makes an implicit assumption about
578 // future implementation.
579 //
580 // Independently, if we encounter node that is some sort of global
581 // object (like a call) we already have full set of dependencies to it
582 // and we can stop descending.
583 if (SUa->isSucc(SUb) ||
584 isGlobalMemoryObject(AA, SUb->getInstr()))
585 return *Depth;
586
587 // If we do need an edge, or we have exceeded depth budget,
588 // add that edge to the predecessors chain of SUb,
589 // and stop descending.
590 if (*Depth > 200 ||
591 MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) {
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000592 SUb->addPred(SDep(SUa, SDep::MayAliasMem));
Andrew Trickda01ba32012-05-15 18:59:41 +0000593 return *Depth;
594 }
595 // Track current depth.
596 (*Depth)++;
597 // Iterate over chain dependencies only.
598 for (SUnit::const_succ_iterator I = SUb->Succs.begin(), E = SUb->Succs.end();
599 I != E; ++I)
600 if (I->isCtrl())
601 iterateChainSucc (AA, MFI, SUa, I->getSUnit(), ExitSU, Depth, Visited);
602 return *Depth;
603}
604
605/// This function assumes that "downward" from SU there exist
606/// tail/leaf of already constructed DAG. It iterates downward and
607/// checks whether SU can be aliasing any node dominated
608/// by it.
609static void adjustChainDeps(AliasAnalysis *AA, const MachineFrameInfo *MFI,
Andrew Trick344fb642012-06-13 02:39:03 +0000610 SUnit *SU, SUnit *ExitSU, std::set<SUnit *> &CheckList,
611 unsigned LatencyToLoad) {
Andrew Trickda01ba32012-05-15 18:59:41 +0000612 if (!SU)
613 return;
614
615 SmallPtrSet<const SUnit*, 16> Visited;
616 unsigned Depth = 0;
617
618 for (std::set<SUnit *>::iterator I = CheckList.begin(), IE = CheckList.end();
619 I != IE; ++I) {
620 if (SU == *I)
621 continue;
Andrew Trick344fb642012-06-13 02:39:03 +0000622 if (MIsNeedChainEdge(AA, MFI, SU->getInstr(), (*I)->getInstr())) {
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000623 SDep Dep(SU, SDep::MayAliasMem);
624 Dep.setLatency(((*I)->getInstr()->mayLoad()) ? LatencyToLoad : 0);
625 (*I)->addPred(Dep);
Andrew Trick344fb642012-06-13 02:39:03 +0000626 }
Andrew Trickda01ba32012-05-15 18:59:41 +0000627 // Now go through all the chain successors and iterate from them.
628 // Keep track of visited nodes.
629 for (SUnit::const_succ_iterator J = (*I)->Succs.begin(),
630 JE = (*I)->Succs.end(); J != JE; ++J)
631 if (J->isCtrl())
632 iterateChainSucc (AA, MFI, SU, J->getSUnit(),
633 ExitSU, &Depth, Visited);
634 }
635}
636
637/// Check whether two objects need a chain edge, if so, add it
638/// otherwise remember the rejected SU.
639static inline
640void addChainDependency (AliasAnalysis *AA, const MachineFrameInfo *MFI,
641 SUnit *SUa, SUnit *SUb,
642 std::set<SUnit *> &RejectList,
643 unsigned TrueMemOrderLatency = 0,
644 bool isNormalMemory = false) {
645 // If this is a false dependency,
646 // do not add the edge, but rememeber the rejected node.
Hal Finkelb350ffd2013-08-29 03:25:05 +0000647 if (!AA || MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) {
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000648 SDep Dep(SUa, isNormalMemory ? SDep::MayAliasMem : SDep::Barrier);
649 Dep.setLatency(TrueMemOrderLatency);
650 SUb->addPred(Dep);
651 }
Andrew Trickda01ba32012-05-15 18:59:41 +0000652 else {
653 // Duplicate entries should be ignored.
654 RejectList.insert(SUb);
655 DEBUG(dbgs() << "\tReject chain dep between SU("
656 << SUa->NodeNum << ") and SU("
657 << SUb->NodeNum << ")\n");
658 }
659}
660
Andrew Trick46cc9a42012-02-22 06:08:11 +0000661/// Create an SUnit for each real instruction, numbered in top-down toplological
662/// order. The instruction order A < B, implies that no edge exists from B to A.
663///
664/// Map each real instruction to its SUnit.
665///
Andrew Trick8823dec2012-03-14 04:00:41 +0000666/// After initSUnits, the SUnits vector cannot be resized and the scheduler may
667/// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
668/// instead of pointers.
669///
670/// MachineScheduler relies on initSUnits numbering the nodes by their order in
671/// the original instruction list.
Andrew Trick46cc9a42012-02-22 06:08:11 +0000672void ScheduleDAGInstrs::initSUnits() {
673 // We'll be allocating one SUnit for each real instruction in the region,
674 // which is contained within a basic block.
Andrew Tricka53e1012013-08-23 17:48:33 +0000675 SUnits.reserve(NumRegionInstrs);
Andrew Trick46cc9a42012-02-22 06:08:11 +0000676
Andrew Trick8c207e42012-03-09 04:29:02 +0000677 for (MachineBasicBlock::iterator I = RegionBegin; I != RegionEnd; ++I) {
Andrew Trick46cc9a42012-02-22 06:08:11 +0000678 MachineInstr *MI = I;
679 if (MI->isDebugValue())
680 continue;
681
Andrew Trick52226d42012-03-07 23:00:49 +0000682 SUnit *SU = newSUnit(MI);
Andrew Trick46cc9a42012-02-22 06:08:11 +0000683 MISUnitMap[MI] = SU;
684
685 SU->isCall = MI->isCall();
686 SU->isCommutable = MI->isCommutable();
687
688 // Assign the Latency field of SU using target-provided information.
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000689 SU->Latency = SchedModel.computeInstrLatency(SU->getInstr());
Andrew Trick880e5732013-12-05 17:55:58 +0000690
691 // If this SUnit uses an unbuffered resource, mark it as such.
692 // These resources are used for in-order execution pipelines within an
693 // out-of-order core and are identified by BufferSize=1. BufferSize=0 is
694 // used for dispatch/issue groups and is not considered here.
695 if (SchedModel.hasInstrSchedModel()) {
696 const MCSchedClassDesc *SC = getSchedClass(SU);
697 for (TargetSchedModel::ProcResIter
698 PI = SchedModel.getWriteProcResBegin(SC),
699 PE = SchedModel.getWriteProcResEnd(SC); PI != PE; ++PI) {
Andrew Trick5a22df42013-12-05 17:56:02 +0000700 switch (SchedModel.getProcResource(PI->ProcResourceIdx)->BufferSize) {
701 case 0:
702 SU->hasReservedResource = true;
703 break;
704 case 1:
Andrew Trick880e5732013-12-05 17:55:58 +0000705 SU->isUnbuffered = true;
706 break;
Andrew Trick5a22df42013-12-05 17:56:02 +0000707 default:
708 break;
Andrew Trick880e5732013-12-05 17:55:58 +0000709 }
710 }
711 }
Andrew Trick46cc9a42012-02-22 06:08:11 +0000712 }
Andrew Trickdbee9d82012-01-14 02:17:15 +0000713}
714
Alp Tokerf907b892013-12-05 05:44:44 +0000715/// If RegPressure is non-null, compute register pressure as a side effect. The
Andrew Trick88639922012-04-24 17:56:43 +0000716/// DAG builder is an efficient place to do it because it already visits
717/// operands.
718void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA,
Andrew Trick1a831342013-08-30 03:49:48 +0000719 RegPressureTracker *RPTracker,
720 PressureDiffs *PDiffs) {
Hal Finkelb350ffd2013-08-29 03:25:05 +0000721 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
722 bool UseAA = EnableAASchedMI.getNumOccurrences() > 0 ? EnableAASchedMI
723 : ST.useAA();
724 AliasAnalysis *AAForDep = UseAA ? AA : 0;
725
Andrew Trick310190e2013-09-04 21:00:02 +0000726 MISUnitMap.clear();
727 ScheduleDAG::clearDAG();
728
Andrew Trick46cc9a42012-02-22 06:08:11 +0000729 // Create an SUnit for each real instruction.
730 initSUnits();
Dan Gohman60cb69e2008-11-19 23:18:57 +0000731
Andrew Trick1a831342013-08-30 03:49:48 +0000732 if (PDiffs)
733 PDiffs->init(SUnits.size());
734
Dan Gohman3aab10b2008-12-04 01:35:46 +0000735 // We build scheduling units by walking a block's instruction list from bottom
736 // to top.
737
David Goodwind2f9c042009-11-09 19:22:17 +0000738 // Remember where a generic side-effecting instruction is as we procede.
739 SUnit *BarrierChain = 0, *AliasChain = 0;
Dan Gohman3aab10b2008-12-04 01:35:46 +0000740
David Goodwind2f9c042009-11-09 19:22:17 +0000741 // Memory references to specific known memory locations are tracked
742 // so that they can be given more precise dependencies. We track
743 // separately the known memory locations that may alias and those
744 // that are known not to alias
Sergei Larine8221482012-11-15 17:45:50 +0000745 MapVector<const Value *, SUnit *> AliasMemDefs, NonAliasMemDefs;
746 MapVector<const Value *, std::vector<SUnit *> > AliasMemUses, NonAliasMemUses;
Andrew Trickda01ba32012-05-15 18:59:41 +0000747 std::set<SUnit*> RejectMemNodes;
Dan Gohman3aab10b2008-12-04 01:35:46 +0000748
Dale Johannesen49de0602010-03-10 22:13:47 +0000749 // Remove any stale debug info; sometimes BuildSchedGraph is called again
750 // without emitting the info from the previous call.
Devang Patele5feef02011-06-02 20:07:12 +0000751 DbgValues.clear();
752 FirstDbgValue = NULL;
Dale Johannesen49de0602010-03-10 22:13:47 +0000753
Andrew Trickd675a4c2012-02-23 01:52:38 +0000754 assert(Defs.empty() && Uses.empty() &&
755 "Only BuildGraph should update Defs/Uses");
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000756 Defs.setUniverse(TRI->getNumRegs());
757 Uses.setUniverse(TRI->getNumRegs());
Andrew Trick2e116a42011-05-06 21:52:52 +0000758
Andrew Trickd458e2d2012-02-22 21:59:00 +0000759 assert(VRegDefs.empty() && "Only BuildSchedGraph may access VRegDefs");
Andrew Trick8dd26f02013-08-23 17:48:39 +0000760 VRegUses.clear();
Andrew Trickd458e2d2012-02-22 21:59:00 +0000761 VRegDefs.setUniverse(MRI.getNumVirtRegs());
Andrew Trick8dd26f02013-08-23 17:48:39 +0000762 VRegUses.setUniverse(MRI.getNumVirtRegs());
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000763
Andrew Trickd675a4c2012-02-23 01:52:38 +0000764 // Model data dependencies between instructions being scheduled and the
765 // ExitSU.
Andrew Trick52226d42012-03-07 23:00:49 +0000766 addSchedBarrierDeps();
Andrew Trickd675a4c2012-02-23 01:52:38 +0000767
Dan Gohmanb9543432009-02-10 23:27:53 +0000768 // Walk the list of instructions, from bottom moving up.
Andrew Trickb767d1e2012-12-01 01:22:49 +0000769 MachineInstr *DbgMI = NULL;
Andrew Trick8c207e42012-03-09 04:29:02 +0000770 for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
Dan Gohman60cb69e2008-11-19 23:18:57 +0000771 MII != MIE; --MII) {
772 MachineInstr *MI = prior(MII);
Andrew Trickb767d1e2012-12-01 01:22:49 +0000773 if (MI && DbgMI) {
774 DbgValues.push_back(std::make_pair(DbgMI, MI));
775 DbgMI = NULL;
Devang Patele5feef02011-06-02 20:07:12 +0000776 }
777
Dale Johannesen49de0602010-03-10 22:13:47 +0000778 if (MI->isDebugValue()) {
Andrew Trickb767d1e2012-12-01 01:22:49 +0000779 DbgMI = MI;
Dale Johannesen49de0602010-03-10 22:13:47 +0000780 continue;
781 }
Andrew Trick1a831342013-08-30 03:49:48 +0000782 SUnit *SU = MISUnitMap[MI];
783 assert(SU && "No SUnit mapped to this MI");
784
Andrew Trick88639922012-04-24 17:56:43 +0000785 if (RPTracker) {
Andrew Trick1a831342013-08-30 03:49:48 +0000786 PressureDiff *PDiff = PDiffs ? &(*PDiffs)[SU->NodeNum] : 0;
Andrew Trick2bc74c22013-08-30 04:36:57 +0000787 RPTracker->recede(/*LiveUses=*/0, PDiff);
Andrew Trick88639922012-04-24 17:56:43 +0000788 assert(RPTracker->getPos() == prior(MII) && "RPTracker can't find MI");
789 }
Devang Patele5feef02011-06-02 20:07:12 +0000790
Sergei Larin5e76aa92013-02-12 16:36:03 +0000791 assert((CanHandleTerminators || (!MI->isTerminator() && !MI->isLabel())) &&
Dan Gohmanb9543432009-02-10 23:27:53 +0000792 "Cannot schedule terminators or labels!");
Dan Gohman60cb69e2008-11-19 23:18:57 +0000793
Dan Gohman3aab10b2008-12-04 01:35:46 +0000794 // Add register-based dependencies (data, anti, and output).
Andrew Trickec256482012-12-18 20:53:01 +0000795 bool HasVRegDef = false;
Dan Gohman60cb69e2008-11-19 23:18:57 +0000796 for (unsigned j = 0, n = MI->getNumOperands(); j != n; ++j) {
797 const MachineOperand &MO = MI->getOperand(j);
798 if (!MO.isReg()) continue;
799 unsigned Reg = MO.getReg();
800 if (Reg == 0) continue;
801
Andrew Trickdbee9d82012-01-14 02:17:15 +0000802 if (TRI->isPhysicalRegister(Reg))
803 addPhysRegDeps(SU, j);
804 else {
805 assert(!IsPostRA && "Virtual register encountered!");
Andrew Trickec256482012-12-18 20:53:01 +0000806 if (MO.isDef()) {
807 HasVRegDef = true;
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000808 addVRegDefDeps(SU, j);
Andrew Trickec256482012-12-18 20:53:01 +0000809 }
Andrew Trickda6a15d2012-02-23 03:16:24 +0000810 else if (MO.readsReg()) // ignore undef operands
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000811 addVRegUseDeps(SU, j);
Dan Gohman60cb69e2008-11-19 23:18:57 +0000812 }
813 }
Andrew Trickec256482012-12-18 20:53:01 +0000814 // If we haven't seen any uses in this scheduling region, create a
815 // dependence edge to ExitSU to model the live-out latency. This is required
816 // for vreg defs with no in-region use, and prefetches with no vreg def.
817 //
818 // FIXME: NumDataSuccs would be more precise than NumSuccs here. This
819 // check currently relies on being called before adding chain deps.
820 if (SU->NumSuccs == 0 && SU->Latency > 1
821 && (HasVRegDef || MI->mayLoad())) {
822 SDep Dep(SU, SDep::Artificial);
823 Dep.setLatency(SU->Latency - 1);
824 ExitSU.addPred(Dep);
825 }
Dan Gohman3aab10b2008-12-04 01:35:46 +0000826
827 // Add chain dependencies.
David Goodwin00822aa2009-11-02 17:06:28 +0000828 // Chain dependencies used to enforce memory order should have
829 // latency of 0 (except for true dependency of Store followed by
830 // aliased Load... we estimate that with a single cycle of latency
831 // assuming the hardware will bypass)
Dan Gohman3aab10b2008-12-04 01:35:46 +0000832 // Note that isStoreToStackSlot and isLoadFromStackSLot are not usable
833 // after stack slots are lowered to actual addresses.
834 // TODO: Use an AliasAnalysis and do real alias-analysis queries, and
835 // produce more precise dependence information.
Andrew Trick344fb642012-06-13 02:39:03 +0000836 unsigned TrueMemOrderLatency = MI->mayStore() ? 1 : 0;
Andrew Trickda01ba32012-05-15 18:59:41 +0000837 if (isGlobalMemoryObject(AA, MI)) {
David Goodwind2f9c042009-11-09 19:22:17 +0000838 // Be conservative with these and add dependencies on all memory
839 // references, even those that are known to not alias.
Sergei Larine8221482012-11-15 17:45:50 +0000840 for (MapVector<const Value *, SUnit *>::iterator I =
David Goodwind2f9c042009-11-09 19:22:17 +0000841 NonAliasMemDefs.begin(), E = NonAliasMemDefs.end(); I != E; ++I) {
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000842 I->second->addPred(SDep(SU, SDep::Barrier));
Dan Gohman3aab10b2008-12-04 01:35:46 +0000843 }
Sergei Larine8221482012-11-15 17:45:50 +0000844 for (MapVector<const Value *, std::vector<SUnit *> >::iterator I =
David Goodwind2f9c042009-11-09 19:22:17 +0000845 NonAliasMemUses.begin(), E = NonAliasMemUses.end(); I != E; ++I) {
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000846 for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
847 SDep Dep(SU, SDep::Barrier);
848 Dep.setLatency(TrueMemOrderLatency);
849 I->second[i]->addPred(Dep);
850 }
Dan Gohman3aab10b2008-12-04 01:35:46 +0000851 }
David Goodwind2f9c042009-11-09 19:22:17 +0000852 // Add SU to the barrier chain.
853 if (BarrierChain)
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000854 BarrierChain->addPred(SDep(SU, SDep::Barrier));
David Goodwind2f9c042009-11-09 19:22:17 +0000855 BarrierChain = SU;
Andrew Trickda01ba32012-05-15 18:59:41 +0000856 // This is a barrier event that acts as a pivotal node in the DAG,
857 // so it is safe to clear list of exposed nodes.
Andrew Trick344fb642012-06-13 02:39:03 +0000858 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
859 TrueMemOrderLatency);
Andrew Trickda01ba32012-05-15 18:59:41 +0000860 RejectMemNodes.clear();
861 NonAliasMemDefs.clear();
862 NonAliasMemUses.clear();
David Goodwind2f9c042009-11-09 19:22:17 +0000863
864 // fall-through
865 new_alias_chain:
866 // Chain all possibly aliasing memory references though SU.
Andrew Trick344fb642012-06-13 02:39:03 +0000867 if (AliasChain) {
868 unsigned ChainLatency = 0;
869 if (AliasChain->getInstr()->mayLoad())
870 ChainLatency = TrueMemOrderLatency;
Hal Finkelb350ffd2013-08-29 03:25:05 +0000871 addChainDependency(AAForDep, MFI, SU, AliasChain, RejectMemNodes,
Andrew Trick344fb642012-06-13 02:39:03 +0000872 ChainLatency);
873 }
David Goodwind2f9c042009-11-09 19:22:17 +0000874 AliasChain = SU;
875 for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
Hal Finkelb350ffd2013-08-29 03:25:05 +0000876 addChainDependency(AAForDep, MFI, SU, PendingLoads[k], RejectMemNodes,
Andrew Trickda01ba32012-05-15 18:59:41 +0000877 TrueMemOrderLatency);
Sergei Larine8221482012-11-15 17:45:50 +0000878 for (MapVector<const Value *, SUnit *>::iterator I = AliasMemDefs.begin(),
Andrew Trickda01ba32012-05-15 18:59:41 +0000879 E = AliasMemDefs.end(); I != E; ++I)
Hal Finkelb350ffd2013-08-29 03:25:05 +0000880 addChainDependency(AAForDep, MFI, SU, I->second, RejectMemNodes);
Sergei Larine8221482012-11-15 17:45:50 +0000881 for (MapVector<const Value *, std::vector<SUnit *> >::iterator I =
David Goodwind2f9c042009-11-09 19:22:17 +0000882 AliasMemUses.begin(), E = AliasMemUses.end(); I != E; ++I) {
883 for (unsigned i = 0, e = I->second.size(); i != e; ++i)
Hal Finkelb350ffd2013-08-29 03:25:05 +0000884 addChainDependency(AAForDep, MFI, SU, I->second[i], RejectMemNodes,
Andrew Trickda01ba32012-05-15 18:59:41 +0000885 TrueMemOrderLatency);
David Goodwind2f9c042009-11-09 19:22:17 +0000886 }
Andrew Trick344fb642012-06-13 02:39:03 +0000887 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
888 TrueMemOrderLatency);
David Goodwind2f9c042009-11-09 19:22:17 +0000889 PendingLoads.clear();
890 AliasMemDefs.clear();
891 AliasMemUses.clear();
Evan Cheng7f8e5632011-12-07 07:15:52 +0000892 } else if (MI->mayStore()) {
Benjamin Kramerfd510922013-06-29 18:41:17 +0000893 UnderlyingObjectsVector Objs;
Hal Finkel66859ae2012-12-10 18:49:16 +0000894 getUnderlyingObjectsForInstr(MI, MFI, Objs);
895
896 if (Objs.empty()) {
897 // Treat all other stores conservatively.
898 goto new_alias_chain;
899 }
900
901 bool MayAlias = false;
Benjamin Kramerfd510922013-06-29 18:41:17 +0000902 for (UnderlyingObjectsVector::iterator K = Objs.begin(), KE = Objs.end();
903 K != KE; ++K) {
904 const Value *V = K->getPointer();
905 bool ThisMayAlias = K->getInt();
Hal Finkel66859ae2012-12-10 18:49:16 +0000906 if (ThisMayAlias)
907 MayAlias = true;
908
Dan Gohman3aab10b2008-12-04 01:35:46 +0000909 // A store to a specific PseudoSourceValue. Add precise dependencies.
David Goodwind2f9c042009-11-09 19:22:17 +0000910 // Record the def in MemDefs, first adding a dep if there is
911 // an existing def.
Sergei Larine8221482012-11-15 17:45:50 +0000912 MapVector<const Value *, SUnit *>::iterator I =
Hal Finkel66859ae2012-12-10 18:49:16 +0000913 ((ThisMayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
Sergei Larine8221482012-11-15 17:45:50 +0000914 MapVector<const Value *, SUnit *>::iterator IE =
Hal Finkel66859ae2012-12-10 18:49:16 +0000915 ((ThisMayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
David Goodwind2f9c042009-11-09 19:22:17 +0000916 if (I != IE) {
Hal Finkelb350ffd2013-08-29 03:25:05 +0000917 addChainDependency(AAForDep, MFI, SU, I->second, RejectMemNodes,
918 0, true);
Dan Gohman3aab10b2008-12-04 01:35:46 +0000919 I->second = SU;
920 } else {
Hal Finkel66859ae2012-12-10 18:49:16 +0000921 if (ThisMayAlias)
David Goodwind2f9c042009-11-09 19:22:17 +0000922 AliasMemDefs[V] = SU;
923 else
924 NonAliasMemDefs[V] = SU;
Dan Gohman3aab10b2008-12-04 01:35:46 +0000925 }
926 // Handle the uses in MemUses, if there are any.
Sergei Larine8221482012-11-15 17:45:50 +0000927 MapVector<const Value *, std::vector<SUnit *> >::iterator J =
Hal Finkel66859ae2012-12-10 18:49:16 +0000928 ((ThisMayAlias) ? AliasMemUses.find(V) : NonAliasMemUses.find(V));
Sergei Larine8221482012-11-15 17:45:50 +0000929 MapVector<const Value *, std::vector<SUnit *> >::iterator JE =
Hal Finkel66859ae2012-12-10 18:49:16 +0000930 ((ThisMayAlias) ? AliasMemUses.end() : NonAliasMemUses.end());
David Goodwind2f9c042009-11-09 19:22:17 +0000931 if (J != JE) {
Dan Gohman3aab10b2008-12-04 01:35:46 +0000932 for (unsigned i = 0, e = J->second.size(); i != e; ++i)
Hal Finkelb350ffd2013-08-29 03:25:05 +0000933 addChainDependency(AAForDep, MFI, SU, J->second[i], RejectMemNodes,
Andrew Trickda01ba32012-05-15 18:59:41 +0000934 TrueMemOrderLatency, true);
Dan Gohman3aab10b2008-12-04 01:35:46 +0000935 J->second.clear();
936 }
David Goodwin00822aa2009-11-02 17:06:28 +0000937 }
Hal Finkel66859ae2012-12-10 18:49:16 +0000938 if (MayAlias) {
939 // Add dependencies from all the PendingLoads, i.e. loads
940 // with no underlying object.
941 for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
Hal Finkelb350ffd2013-08-29 03:25:05 +0000942 addChainDependency(AAForDep, MFI, SU, PendingLoads[k], RejectMemNodes,
Hal Finkel66859ae2012-12-10 18:49:16 +0000943 TrueMemOrderLatency);
944 // Add dependence on alias chain, if needed.
945 if (AliasChain)
Hal Finkelb350ffd2013-08-29 03:25:05 +0000946 addChainDependency(AAForDep, MFI, SU, AliasChain, RejectMemNodes);
Hal Finkel66859ae2012-12-10 18:49:16 +0000947 // But we also should check dependent instructions for the
948 // SU in question.
949 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
950 TrueMemOrderLatency);
951 }
952 // Add dependence on barrier chain, if needed.
953 // There is no point to check aliasing on barrier event. Even if
954 // SU and barrier _could_ be reordered, they should not. In addition,
955 // we have lost all RejectMemNodes below barrier.
956 if (BarrierChain)
957 BarrierChain->addPred(SDep(SU, SDep::Barrier));
Evan Cheng15459b62010-10-23 02:10:46 +0000958
959 if (!ExitSU.isPred(SU))
960 // Push store's up a bit to avoid them getting in between cmp
961 // and branches.
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000962 ExitSU.addPred(SDep(SU, SDep::Artificial));
Evan Cheng7f8e5632011-12-07 07:15:52 +0000963 } else if (MI->mayLoad()) {
David Goodwina86f9192009-11-03 20:15:00 +0000964 bool MayAlias = true;
Dan Gohman87b02d52009-10-09 23:27:56 +0000965 if (MI->isInvariantLoad(AA)) {
Dan Gohman3aab10b2008-12-04 01:35:46 +0000966 // Invariant load, no chain dependencies needed!
David Goodwin28ba4f22009-11-05 00:16:44 +0000967 } else {
Benjamin Kramerfd510922013-06-29 18:41:17 +0000968 UnderlyingObjectsVector Objs;
Hal Finkel66859ae2012-12-10 18:49:16 +0000969 getUnderlyingObjectsForInstr(MI, MFI, Objs);
970
971 if (Objs.empty()) {
David Goodwind2f9c042009-11-09 19:22:17 +0000972 // A load with no underlying object. Depend on all
973 // potentially aliasing stores.
Sergei Larine8221482012-11-15 17:45:50 +0000974 for (MapVector<const Value *, SUnit *>::iterator I =
David Goodwind2f9c042009-11-09 19:22:17 +0000975 AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I)
Hal Finkelb350ffd2013-08-29 03:25:05 +0000976 addChainDependency(AAForDep, MFI, SU, I->second, RejectMemNodes);
Andrew Trick24b1c482011-05-05 19:24:06 +0000977
David Goodwind2f9c042009-11-09 19:22:17 +0000978 PendingLoads.push_back(SU);
979 MayAlias = true;
Hal Finkel66859ae2012-12-10 18:49:16 +0000980 } else {
981 MayAlias = false;
982 }
983
Benjamin Kramerfd510922013-06-29 18:41:17 +0000984 for (UnderlyingObjectsVector::iterator
Hal Finkel66859ae2012-12-10 18:49:16 +0000985 J = Objs.begin(), JE = Objs.end(); J != JE; ++J) {
Benjamin Kramerfd510922013-06-29 18:41:17 +0000986 const Value *V = J->getPointer();
987 bool ThisMayAlias = J->getInt();
Hal Finkel66859ae2012-12-10 18:49:16 +0000988
989 if (ThisMayAlias)
990 MayAlias = true;
991
992 // A load from a specific PseudoSourceValue. Add precise dependencies.
993 MapVector<const Value *, SUnit *>::iterator I =
994 ((ThisMayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
995 MapVector<const Value *, SUnit *>::iterator IE =
996 ((ThisMayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
997 if (I != IE)
Hal Finkelb350ffd2013-08-29 03:25:05 +0000998 addChainDependency(AAForDep, MFI, SU, I->second, RejectMemNodes,
999 0, true);
Hal Finkel66859ae2012-12-10 18:49:16 +00001000 if (ThisMayAlias)
1001 AliasMemUses[V].push_back(SU);
1002 else
1003 NonAliasMemUses[V].push_back(SU);
David Goodwina86f9192009-11-03 20:15:00 +00001004 }
Andrew Trickda01ba32012-05-15 18:59:41 +00001005 if (MayAlias)
Andrew Trick344fb642012-06-13 02:39:03 +00001006 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes, /*Latency=*/0);
David Goodwind2f9c042009-11-09 19:22:17 +00001007 // Add dependencies on alias and barrier chains, if needed.
1008 if (MayAlias && AliasChain)
Hal Finkelb350ffd2013-08-29 03:25:05 +00001009 addChainDependency(AAForDep, MFI, SU, AliasChain, RejectMemNodes);
David Goodwind2f9c042009-11-09 19:22:17 +00001010 if (BarrierChain)
Andrew Trickbaeaabb2012-11-06 03:13:46 +00001011 BarrierChain->addPred(SDep(SU, SDep::Barrier));
Andrew Trick24b1c482011-05-05 19:24:06 +00001012 }
Dan Gohman60cb69e2008-11-19 23:18:57 +00001013 }
Dan Gohman60cb69e2008-11-19 23:18:57 +00001014 }
Andrew Trickb767d1e2012-12-01 01:22:49 +00001015 if (DbgMI)
1016 FirstDbgValue = DbgMI;
Dan Gohman619ef482009-01-15 19:20:50 +00001017
Andrew Trickd675a4c2012-02-23 01:52:38 +00001018 Defs.clear();
1019 Uses.clear();
Andrew Trick59ac4fb2012-01-14 02:17:18 +00001020 VRegDefs.clear();
Dan Gohman619ef482009-01-15 19:20:50 +00001021 PendingLoads.clear();
Dan Gohman60cb69e2008-11-19 23:18:57 +00001022}
1023
Dan Gohman60cb69e2008-11-19 23:18:57 +00001024void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
Manman Ren19f49ac2012-09-11 22:23:19 +00001025#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohman60cb69e2008-11-19 23:18:57 +00001026 SU->getInstr()->dump();
Manman Ren742534c2012-09-06 19:06:06 +00001027#endif
Dan Gohman60cb69e2008-11-19 23:18:57 +00001028}
1029
1030std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
1031 std::string s;
1032 raw_string_ostream oss(s);
Dan Gohmanb9543432009-02-10 23:27:53 +00001033 if (SU == &EntrySU)
1034 oss << "<entry>";
1035 else if (SU == &ExitSU)
1036 oss << "<exit>";
1037 else
Andrew Trickb36388a2013-01-25 07:45:25 +00001038 SU->getInstr()->print(oss, &TM, /*SkipOpers=*/true);
Dan Gohman60cb69e2008-11-19 23:18:57 +00001039 return oss.str();
1040}
1041
Andrew Trick1b2324d2012-03-07 00:18:22 +00001042/// Return the basic block label. It is not necessarilly unique because a block
1043/// contains multiple scheduling regions. But it is fine for visualization.
1044std::string ScheduleDAGInstrs::getDAGName() const {
1045 return "dag." + BB->getFullName();
1046}
Andrew Trick90f711d2012-10-15 18:02:27 +00001047
Andrew Trick48d392e2012-11-28 05:13:28 +00001048//===----------------------------------------------------------------------===//
1049// SchedDFSResult Implementation
1050//===----------------------------------------------------------------------===//
1051
1052namespace llvm {
1053/// \brief Internal state used to compute SchedDFSResult.
1054class SchedDFSImpl {
1055 SchedDFSResult &R;
1056
1057 /// Join DAG nodes into equivalence classes by their subtree.
1058 IntEqClasses SubtreeClasses;
1059 /// List PredSU, SuccSU pairs that represent data edges between subtrees.
1060 std::vector<std::pair<const SUnit*, const SUnit*> > ConnectionPairs;
1061
Andrew Trickffc80972013-01-25 06:52:27 +00001062 struct RootData {
1063 unsigned NodeID;
1064 unsigned ParentNodeID; // Parent node (member of the parent subtree).
1065 unsigned SubInstrCount; // Instr count in this tree only, not children.
1066
1067 RootData(unsigned id): NodeID(id),
1068 ParentNodeID(SchedDFSResult::InvalidSubtreeID),
1069 SubInstrCount(0) {}
1070
1071 unsigned getSparseSetIndex() const { return NodeID; }
1072 };
1073
1074 SparseSet<RootData> RootSet;
1075
Andrew Trick48d392e2012-11-28 05:13:28 +00001076public:
Andrew Trickffc80972013-01-25 06:52:27 +00001077 SchedDFSImpl(SchedDFSResult &r): R(r), SubtreeClasses(R.DFSNodeData.size()) {
1078 RootSet.setUniverse(R.DFSNodeData.size());
1079 }
Andrew Trick48d392e2012-11-28 05:13:28 +00001080
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001081 /// Return true if this node been visited by the DFS traversal.
1082 ///
1083 /// During visitPostorderNode the Node's SubtreeID is assigned to the Node
1084 /// ID. Later, SubtreeID is updated but remains valid.
Andrew Trick48d392e2012-11-28 05:13:28 +00001085 bool isVisited(const SUnit *SU) const {
Andrew Trickffc80972013-01-25 06:52:27 +00001086 return R.DFSNodeData[SU->NodeNum].SubtreeID
1087 != SchedDFSResult::InvalidSubtreeID;
Andrew Trick48d392e2012-11-28 05:13:28 +00001088 }
1089
1090 /// Initialize this node's instruction count. We don't need to flag the node
1091 /// visited until visitPostorder because the DAG cannot have cycles.
1092 void visitPreorder(const SUnit *SU) {
Andrew Trickffc80972013-01-25 06:52:27 +00001093 R.DFSNodeData[SU->NodeNum].InstrCount =
1094 SU->getInstr()->isTransient() ? 0 : 1;
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001095 }
1096
1097 /// Called once for each node after all predecessors are visited. Revisit this
1098 /// node's predecessors and potentially join them now that we know the ILP of
1099 /// the other predecessors.
1100 void visitPostorderNode(const SUnit *SU) {
1101 // Mark this node as the root of a subtree. It may be joined with its
1102 // successors later.
Andrew Trickffc80972013-01-25 06:52:27 +00001103 R.DFSNodeData[SU->NodeNum].SubtreeID = SU->NodeNum;
1104 RootData RData(SU->NodeNum);
1105 RData.SubInstrCount = SU->getInstr()->isTransient() ? 0 : 1;
Andrew Trick48d392e2012-11-28 05:13:28 +00001106
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001107 // If any predecessors are still in their own subtree, they either cannot be
1108 // joined or are large enough to remain separate. If this parent node's
1109 // total instruction count is not greater than a child subtree by at least
1110 // the subtree limit, then try to join it now since splitting subtrees is
1111 // only useful if multiple high-pressure paths are possible.
Andrew Trickffc80972013-01-25 06:52:27 +00001112 unsigned InstrCount = R.DFSNodeData[SU->NodeNum].InstrCount;
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001113 for (SUnit::const_pred_iterator
1114 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
1115 if (PI->getKind() != SDep::Data)
1116 continue;
1117 unsigned PredNum = PI->getSUnit()->NodeNum;
Andrew Trickffc80972013-01-25 06:52:27 +00001118 if ((InstrCount - R.DFSNodeData[PredNum].InstrCount) < R.SubtreeLimit)
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001119 joinPredSubtree(*PI, SU, /*CheckLimit=*/false);
Andrew Trickffc80972013-01-25 06:52:27 +00001120
1121 // Either link or merge the TreeData entry from the child to the parent.
Andrew Trick646eeb62013-01-25 06:52:30 +00001122 if (R.DFSNodeData[PredNum].SubtreeID == PredNum) {
1123 // If the predecessor's parent is invalid, this is a tree edge and the
1124 // current node is the parent.
1125 if (RootSet[PredNum].ParentNodeID == SchedDFSResult::InvalidSubtreeID)
1126 RootSet[PredNum].ParentNodeID = SU->NodeNum;
1127 }
1128 else if (RootSet.count(PredNum)) {
1129 // The predecessor is not a root, but is still in the root set. This
1130 // must be the new parent that it was just joined to. Note that
1131 // RootSet[PredNum].ParentNodeID may either be invalid or may still be
1132 // set to the original parent.
Andrew Trickffc80972013-01-25 06:52:27 +00001133 RData.SubInstrCount += RootSet[PredNum].SubInstrCount;
1134 RootSet.erase(PredNum);
1135 }
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001136 }
Andrew Trickffc80972013-01-25 06:52:27 +00001137 RootSet[SU->NodeNum] = RData;
1138 }
1139
1140 /// Called once for each tree edge after calling visitPostOrderNode on the
1141 /// predecessor. Increment the parent node's instruction count and
1142 /// preemptively join this subtree to its parent's if it is small enough.
1143 void visitPostorderEdge(const SDep &PredDep, const SUnit *Succ) {
1144 R.DFSNodeData[Succ->NodeNum].InstrCount
1145 += R.DFSNodeData[PredDep.getSUnit()->NodeNum].InstrCount;
1146 joinPredSubtree(PredDep, Succ);
Andrew Trick48d392e2012-11-28 05:13:28 +00001147 }
1148
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001149 /// Add a connection for cross edges.
1150 void visitCrossEdge(const SDep &PredDep, const SUnit *Succ) {
Andrew Trick48d392e2012-11-28 05:13:28 +00001151 ConnectionPairs.push_back(std::make_pair(PredDep.getSUnit(), Succ));
1152 }
1153
1154 /// Set each node's subtree ID to the representative ID and record connections
1155 /// between trees.
1156 void finalize() {
1157 SubtreeClasses.compress();
Andrew Trickffc80972013-01-25 06:52:27 +00001158 R.DFSTreeData.resize(SubtreeClasses.getNumClasses());
1159 assert(SubtreeClasses.getNumClasses() == RootSet.size()
1160 && "number of roots should match trees");
1161 for (SparseSet<RootData>::const_iterator
1162 RI = RootSet.begin(), RE = RootSet.end(); RI != RE; ++RI) {
1163 unsigned TreeID = SubtreeClasses[RI->NodeID];
1164 if (RI->ParentNodeID != SchedDFSResult::InvalidSubtreeID)
1165 R.DFSTreeData[TreeID].ParentTreeID = SubtreeClasses[RI->ParentNodeID];
1166 R.DFSTreeData[TreeID].SubInstrCount = RI->SubInstrCount;
Andrew Trick646eeb62013-01-25 06:52:30 +00001167 // Note that SubInstrCount may be greater than InstrCount if we joined
1168 // subtrees across a cross edge. InstrCount will be attributed to the
1169 // original parent, while SubInstrCount will be attributed to the joined
1170 // parent.
Andrew Trickffc80972013-01-25 06:52:27 +00001171 }
Andrew Trick48d392e2012-11-28 05:13:28 +00001172 R.SubtreeConnections.resize(SubtreeClasses.getNumClasses());
1173 R.SubtreeConnectLevels.resize(SubtreeClasses.getNumClasses());
1174 DEBUG(dbgs() << R.getNumSubtrees() << " subtrees:\n");
Andrew Trickffc80972013-01-25 06:52:27 +00001175 for (unsigned Idx = 0, End = R.DFSNodeData.size(); Idx != End; ++Idx) {
1176 R.DFSNodeData[Idx].SubtreeID = SubtreeClasses[Idx];
Andrew Trick48d392e2012-11-28 05:13:28 +00001177 DEBUG(dbgs() << " SU(" << Idx << ") in tree "
Andrew Trickffc80972013-01-25 06:52:27 +00001178 << R.DFSNodeData[Idx].SubtreeID << '\n');
Andrew Trick48d392e2012-11-28 05:13:28 +00001179 }
1180 for (std::vector<std::pair<const SUnit*, const SUnit*> >::const_iterator
1181 I = ConnectionPairs.begin(), E = ConnectionPairs.end();
1182 I != E; ++I) {
1183 unsigned PredTree = SubtreeClasses[I->first->NodeNum];
1184 unsigned SuccTree = SubtreeClasses[I->second->NodeNum];
1185 if (PredTree == SuccTree)
1186 continue;
1187 unsigned Depth = I->first->getDepth();
1188 addConnection(PredTree, SuccTree, Depth);
1189 addConnection(SuccTree, PredTree, Depth);
1190 }
1191 }
1192
1193protected:
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001194 /// Join the predecessor subtree with the successor that is its DFS
1195 /// parent. Apply some heuristics before joining.
1196 bool joinPredSubtree(const SDep &PredDep, const SUnit *Succ,
1197 bool CheckLimit = true) {
1198 assert(PredDep.getKind() == SDep::Data && "Subtrees are for data edges");
1199
1200 // Check if the predecessor is already joined.
1201 const SUnit *PredSU = PredDep.getSUnit();
1202 unsigned PredNum = PredSU->NodeNum;
Andrew Trickffc80972013-01-25 06:52:27 +00001203 if (R.DFSNodeData[PredNum].SubtreeID != PredNum)
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001204 return false;
Andrew Trickb52a8562013-01-25 00:12:57 +00001205
1206 // Four is the magic number of successors before a node is considered a
1207 // pinch point.
1208 unsigned NumDataSucs = 0;
Andrew Trickb52a8562013-01-25 00:12:57 +00001209 for (SUnit::const_succ_iterator SI = PredSU->Succs.begin(),
1210 SE = PredSU->Succs.end(); SI != SE; ++SI) {
1211 if (SI->getKind() == SDep::Data) {
1212 if (++NumDataSucs >= 4)
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001213 return false;
Andrew Trickb52a8562013-01-25 00:12:57 +00001214 }
1215 }
Andrew Trickffc80972013-01-25 06:52:27 +00001216 if (CheckLimit && R.DFSNodeData[PredNum].InstrCount > R.SubtreeLimit)
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001217 return false;
Andrew Trickffc80972013-01-25 06:52:27 +00001218 R.DFSNodeData[PredNum].SubtreeID = Succ->NodeNum;
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001219 SubtreeClasses.join(Succ->NodeNum, PredNum);
1220 return true;
Andrew Trickb52a8562013-01-25 00:12:57 +00001221 }
1222
Andrew Trick48d392e2012-11-28 05:13:28 +00001223 /// Called by finalize() to record a connection between trees.
1224 void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth) {
1225 if (!Depth)
1226 return;
1227
Andrew Trickffc80972013-01-25 06:52:27 +00001228 do {
1229 SmallVectorImpl<SchedDFSResult::Connection> &Connections =
1230 R.SubtreeConnections[FromTree];
1231 for (SmallVectorImpl<SchedDFSResult::Connection>::iterator
1232 I = Connections.begin(), E = Connections.end(); I != E; ++I) {
1233 if (I->TreeID == ToTree) {
1234 I->Level = std::max(I->Level, Depth);
1235 return;
1236 }
Andrew Trick48d392e2012-11-28 05:13:28 +00001237 }
Andrew Trickffc80972013-01-25 06:52:27 +00001238 Connections.push_back(SchedDFSResult::Connection(ToTree, Depth));
1239 FromTree = R.DFSTreeData[FromTree].ParentTreeID;
1240 } while (FromTree != SchedDFSResult::InvalidSubtreeID);
Andrew Trick48d392e2012-11-28 05:13:28 +00001241 }
1242};
1243} // namespace llvm
1244
Andrew Trick90f711d2012-10-15 18:02:27 +00001245namespace {
1246/// \brief Manage the stack used by a reverse depth-first search over the DAG.
1247class SchedDAGReverseDFS {
1248 std::vector<std::pair<const SUnit*, SUnit::const_pred_iterator> > DFSStack;
1249public:
1250 bool isComplete() const { return DFSStack.empty(); }
1251
1252 void follow(const SUnit *SU) {
1253 DFSStack.push_back(std::make_pair(SU, SU->Preds.begin()));
1254 }
1255 void advance() { ++DFSStack.back().second; }
1256
Andrew Trick48d392e2012-11-28 05:13:28 +00001257 const SDep *backtrack() {
1258 DFSStack.pop_back();
1259 return DFSStack.empty() ? 0 : llvm::prior(DFSStack.back().second);
1260 }
Andrew Trick90f711d2012-10-15 18:02:27 +00001261
1262 const SUnit *getCurr() const { return DFSStack.back().first; }
1263
1264 SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
1265
1266 SUnit::const_pred_iterator getPredEnd() const {
1267 return getCurr()->Preds.end();
1268 }
1269};
1270} // anonymous
1271
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001272static bool hasDataSucc(const SUnit *SU) {
1273 for (SUnit::const_succ_iterator
1274 SI = SU->Succs.begin(), SE = SU->Succs.end(); SI != SE; ++SI) {
Andrew Trick646eeb62013-01-25 06:52:30 +00001275 if (SI->getKind() == SDep::Data && !SI->getSUnit()->isBoundaryNode())
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001276 return true;
1277 }
1278 return false;
1279}
1280
Andrew Trick90f711d2012-10-15 18:02:27 +00001281/// Compute an ILP metric for all nodes in the subDAG reachable via depth-first
1282/// search from this root.
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001283void SchedDFSResult::compute(ArrayRef<SUnit> SUnits) {
Andrew Trick90f711d2012-10-15 18:02:27 +00001284 if (!IsBottomUp)
1285 llvm_unreachable("Top-down ILP metric is unimplemnted");
1286
Andrew Trick48d392e2012-11-28 05:13:28 +00001287 SchedDFSImpl Impl(*this);
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001288 for (ArrayRef<SUnit>::const_iterator
1289 SI = SUnits.begin(), SE = SUnits.end(); SI != SE; ++SI) {
1290 const SUnit *SU = &*SI;
1291 if (Impl.isVisited(SU) || hasDataSucc(SU))
1292 continue;
1293
Andrew Trick48d392e2012-11-28 05:13:28 +00001294 SchedDAGReverseDFS DFS;
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001295 Impl.visitPreorder(SU);
1296 DFS.follow(SU);
Andrew Trick48d392e2012-11-28 05:13:28 +00001297 for (;;) {
1298 // Traverse the leftmost path as far as possible.
1299 while (DFS.getPred() != DFS.getPredEnd()) {
1300 const SDep &PredDep = *DFS.getPred();
1301 DFS.advance();
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001302 // Ignore non-data edges.
Andrew Trick646eeb62013-01-25 06:52:30 +00001303 if (PredDep.getKind() != SDep::Data
1304 || PredDep.getSUnit()->isBoundaryNode()) {
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001305 continue;
Andrew Trick646eeb62013-01-25 06:52:30 +00001306 }
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001307 // An already visited edge is a cross edge, assuming an acyclic DAG.
Andrew Trick48d392e2012-11-28 05:13:28 +00001308 if (Impl.isVisited(PredDep.getSUnit())) {
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001309 Impl.visitCrossEdge(PredDep, DFS.getCurr());
Andrew Trick48d392e2012-11-28 05:13:28 +00001310 continue;
1311 }
1312 Impl.visitPreorder(PredDep.getSUnit());
1313 DFS.follow(PredDep.getSUnit());
1314 }
1315 // Visit the top of the stack in postorder and backtrack.
1316 const SUnit *Child = DFS.getCurr();
1317 const SDep *PredDep = DFS.backtrack();
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001318 Impl.visitPostorderNode(Child);
1319 if (PredDep)
1320 Impl.visitPostorderEdge(*PredDep, DFS.getCurr());
Andrew Trick48d392e2012-11-28 05:13:28 +00001321 if (DFS.isComplete())
1322 break;
Andrew Trick90f711d2012-10-15 18:02:27 +00001323 }
Andrew Trick48d392e2012-11-28 05:13:28 +00001324 }
1325 Impl.finalize();
1326}
1327
1328/// The root of the given SubtreeID was just scheduled. For all subtrees
1329/// connected to this tree, record the depth of the connection so that the
1330/// nearest connected subtrees can be prioritized.
1331void SchedDFSResult::scheduleTree(unsigned SubtreeID) {
1332 for (SmallVectorImpl<Connection>::const_iterator
1333 I = SubtreeConnections[SubtreeID].begin(),
1334 E = SubtreeConnections[SubtreeID].end(); I != E; ++I) {
1335 SubtreeConnectLevels[I->TreeID] =
1336 std::max(SubtreeConnectLevels[I->TreeID], I->Level);
1337 DEBUG(dbgs() << " Tree: " << I->TreeID
1338 << " @" << SubtreeConnectLevels[I->TreeID] << '\n');
Andrew Trick90f711d2012-10-15 18:02:27 +00001339 }
1340}
1341
1342#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1343void ILPValue::print(raw_ostream &OS) const {
Andrew Trick48d392e2012-11-28 05:13:28 +00001344 OS << InstrCount << " / " << Length << " = ";
1345 if (!Length)
Andrew Trick90f711d2012-10-15 18:02:27 +00001346 OS << "BADILP";
Andrew Trick48d392e2012-11-28 05:13:28 +00001347 else
1348 OS << format("%g", ((double)InstrCount / Length));
Andrew Trick90f711d2012-10-15 18:02:27 +00001349}
1350
1351void ILPValue::dump() const {
1352 dbgs() << *this << '\n';
1353}
1354
1355namespace llvm {
1356
1357raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) {
1358 Val.print(OS);
1359 return OS;
1360}
1361
1362} // namespace llvm
1363#endif // !NDEBUG || LLVM_ENABLE_DUMP