blob: a4d4a93e6dd5bed36bb8362735b89344d913b5be [file] [log] [blame]
Dan Gohmana629b482008-12-08 17:50:35 +00001//===---- ScheduleDAGInstrs.cpp - MachineInstr Rescheduling ---------------===//
Dan Gohman343f0c02008-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 Gohmana629b482008-12-08 17:50:35 +000010// This implements the ScheduleDAGInstrs class, which implements re-scheduling
11// of MachineInstrs.
Dan Gohman343f0c02008-11-19 23:18:57 +000012//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "sched-instrs"
Dan Gohman8906f952009-07-17 20:58:59 +000016#include "llvm/Operator.h"
Dan Gohman3311a1f2009-01-30 02:49:14 +000017#include "llvm/Analysis/AliasAnalysis.h"
Dan Gohman5034dd32010-12-15 20:02:24 +000018#include "llvm/Analysis/ValueTracking.h"
Andrew Trickb4566a92012-02-22 06:08:11 +000019#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Dan Gohman3f237442008-12-16 03:25:46 +000020#include "llvm/CodeGen/MachineFunctionPass.h"
Dan Gohmanc76909a2009-09-25 20:36:54 +000021#include "llvm/CodeGen/MachineMemOperand.h"
Dan Gohman3f237442008-12-16 03:25:46 +000022#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman6a9041e2008-12-04 01:35:46 +000023#include "llvm/CodeGen/PseudoSourceValue.h"
Andrew Trickafc26572012-06-06 19:47:35 +000024#include "llvm/CodeGen/RegisterPressure.h"
Andrew Trick1e94e982012-10-15 18:02:27 +000025#include "llvm/CodeGen/ScheduleDAGILP.h"
Andrew Tricked395c82012-03-07 23:01:06 +000026#include "llvm/CodeGen/ScheduleDAGInstrs.h"
Evan Chengab8be962011-06-29 01:14:12 +000027#include "llvm/MC/MCInstrItineraries.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000028#include "llvm/Target/TargetMachine.h"
29#include "llvm/Target/TargetInstrInfo.h"
30#include "llvm/Target/TargetRegisterInfo.h"
Evan Cheng5b1b44892011-07-01 21:01:15 +000031#include "llvm/Target/TargetSubtargetInfo.h"
Andrew Trickeb05b972012-05-15 18:59:41 +000032#include "llvm/Support/CommandLine.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000033#include "llvm/Support/Debug.h"
Andrew Trick1e94e982012-10-15 18:02:27 +000034#include "llvm/Support/Format.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000035#include "llvm/Support/raw_ostream.h"
Dan Gohman3f237442008-12-16 03:25:46 +000036#include "llvm/ADT/SmallSet.h"
Andrew Trickeb05b972012-05-15 18:59:41 +000037#include "llvm/ADT/SmallPtrSet.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000038using namespace llvm;
39
Andrew Trickeb05b972012-05-15 18:59:41 +000040static cl::opt<bool> EnableAASchedMI("enable-aa-sched-mi", cl::Hidden,
41 cl::ZeroOrMore, cl::init(false),
42 cl::desc("Enable use of AA during MI GAD construction"));
43
Dan Gohman79ce2762009-01-15 19:20:50 +000044ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
Dan Gohman3f237442008-12-16 03:25:46 +000045 const MachineLoopInfo &mli,
Andrew Trick5e920d72012-01-14 02:17:12 +000046 const MachineDominatorTree &mdt,
Andrew Trickb4566a92012-02-22 06:08:11 +000047 bool IsPostRAFlag,
48 LiveIntervals *lis)
Andrew Trick412cd2f2012-10-10 05:43:09 +000049 : ScheduleDAG(mf), MLI(mli), MDT(mdt), MFI(mf.getFrameInfo()), LIS(lis),
Andrew Trick714973e2012-10-09 23:44:23 +000050 IsPostRA(IsPostRAFlag), CanHandleTerminators(false), FirstDbgValue(0) {
Andrew Trickb4566a92012-02-22 06:08:11 +000051 assert((IsPostRA || LIS) && "PreRA scheduling requires LiveIntervals");
Devang Patelcf4cc842011-06-02 20:07:12 +000052 DbgValues.clear();
Andrew Trickcc77b542012-02-22 06:08:13 +000053 assert(!(IsPostRA && MRI.getNumVirtRegs()) &&
Andrew Trick19273ae2012-02-21 04:51:23 +000054 "Virtual registers must be removed prior to PostRA scheduling");
Andrew Trick781ab472012-09-18 18:20:00 +000055
56 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
57 SchedModel.init(*ST.getSchedModel(), &ST, TII);
Evan Cheng38bdfc62009-10-18 19:58:47 +000058}
Dan Gohman343f0c02008-11-19 23:18:57 +000059
Dan Gohman3311a1f2009-01-30 02:49:14 +000060/// getUnderlyingObjectFromInt - This is the function that does the work of
61/// looking through basic ptrtoint+arithmetic+inttoptr sequences.
62static const Value *getUnderlyingObjectFromInt(const Value *V) {
63 do {
Dan Gohman8906f952009-07-17 20:58:59 +000064 if (const Operator *U = dyn_cast<Operator>(V)) {
Dan Gohman3311a1f2009-01-30 02:49:14 +000065 // If we find a ptrtoint, we can transfer control back to the
66 // regular getUnderlyingObjectFromInt.
Dan Gohman8906f952009-07-17 20:58:59 +000067 if (U->getOpcode() == Instruction::PtrToInt)
Dan Gohman3311a1f2009-01-30 02:49:14 +000068 return U->getOperand(0);
69 // If we find an add of a constant or a multiplied value, it's
70 // likely that the other operand will lead us to the base
71 // object. We don't have to worry about the case where the
Dan Gohman748f98f2009-08-07 01:26:06 +000072 // object address is somehow being computed by the multiply,
Dan Gohman3311a1f2009-01-30 02:49:14 +000073 // because our callers only care when the result is an
Nick Lewycky6b0db5f2012-10-26 04:27:49 +000074 // identifiable object.
Dan Gohman8906f952009-07-17 20:58:59 +000075 if (U->getOpcode() != Instruction::Add ||
Dan Gohman3311a1f2009-01-30 02:49:14 +000076 (!isa<ConstantInt>(U->getOperand(1)) &&
Dan Gohman8906f952009-07-17 20:58:59 +000077 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul))
Dan Gohman3311a1f2009-01-30 02:49:14 +000078 return V;
79 V = U->getOperand(0);
80 } else {
81 return V;
82 }
Duncan Sands1df98592010-02-16 11:11:14 +000083 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
Dan Gohman3311a1f2009-01-30 02:49:14 +000084 } while (1);
85}
86
Dan Gohman5034dd32010-12-15 20:02:24 +000087/// getUnderlyingObject - This is a wrapper around GetUnderlyingObject
Dan Gohman3311a1f2009-01-30 02:49:14 +000088/// and adds support for basic ptrtoint+arithmetic+inttoptr sequences.
89static const Value *getUnderlyingObject(const Value *V) {
90 // First just call Value::getUnderlyingObject to let it do what it does.
91 do {
Dan Gohman5034dd32010-12-15 20:02:24 +000092 V = GetUnderlyingObject(V);
Dan Gohman3311a1f2009-01-30 02:49:14 +000093 // If it found an inttoptr, use special code to continue climing.
Dan Gohman8906f952009-07-17 20:58:59 +000094 if (Operator::getOpcode(V) != Instruction::IntToPtr)
Dan Gohman3311a1f2009-01-30 02:49:14 +000095 break;
96 const Value *O = getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
97 // If that succeeded in finding a pointer, continue the search.
Duncan Sands1df98592010-02-16 11:11:14 +000098 if (!O->getType()->isPointerTy())
Dan Gohman3311a1f2009-01-30 02:49:14 +000099 break;
100 V = O;
101 } while (1);
102 return V;
103}
104
105/// getUnderlyingObjectForInstr - If this machine instr has memory reference
106/// information and it can be tracked to a normal reference to a known
107/// object, return the Value for that object. Otherwise return null.
Evan Cheng38bdfc62009-10-18 19:58:47 +0000108static const Value *getUnderlyingObjectForInstr(const MachineInstr *MI,
David Goodwina9e61072009-11-03 20:15:00 +0000109 const MachineFrameInfo *MFI,
110 bool &MayAlias) {
111 MayAlias = true;
Dan Gohman3311a1f2009-01-30 02:49:14 +0000112 if (!MI->hasOneMemOperand() ||
Dan Gohmanc76909a2009-09-25 20:36:54 +0000113 !(*MI->memoperands_begin())->getValue() ||
114 (*MI->memoperands_begin())->isVolatile())
Dan Gohman3311a1f2009-01-30 02:49:14 +0000115 return 0;
116
Dan Gohmanc76909a2009-09-25 20:36:54 +0000117 const Value *V = (*MI->memoperands_begin())->getValue();
Dan Gohman3311a1f2009-01-30 02:49:14 +0000118 if (!V)
119 return 0;
120
121 V = getUnderlyingObject(V);
Evan Chengff89dcb2009-10-18 18:16:27 +0000122 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
123 // For now, ignore PseudoSourceValues which may alias LLVM IR values
124 // because the code that uses this function has no way to cope with
125 // such aliases.
Evan Cheng38bdfc62009-10-18 19:58:47 +0000126 if (PSV->isAliased(MFI))
Evan Chengff89dcb2009-10-18 18:16:27 +0000127 return 0;
Andrew Trickf405b1a2011-05-05 19:24:06 +0000128
David Goodwin980d4942009-11-09 19:22:17 +0000129 MayAlias = PSV->mayAlias(MFI);
Evan Chengff89dcb2009-10-18 18:16:27 +0000130 return V;
131 }
Dan Gohman3311a1f2009-01-30 02:49:14 +0000132
Evan Chengff89dcb2009-10-18 18:16:27 +0000133 if (isIdentifiedObject(V))
134 return V;
135
136 return 0;
Dan Gohman3311a1f2009-01-30 02:49:14 +0000137}
138
Andrew Trick918f38a2012-04-20 20:05:21 +0000139void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) {
140 BB = bb;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000141}
142
Andrew Trick953be892012-03-07 23:00:49 +0000143void ScheduleDAGInstrs::finishBlock() {
Andrew Tricka30444a2012-04-20 20:24:33 +0000144 // Subclasses should no longer refer to the old block.
Andrew Trick918f38a2012-04-20 20:05:21 +0000145 BB = 0;
Andrew Trick47c14452012-03-07 05:21:52 +0000146}
147
Andrew Trick702d4892012-02-24 07:04:55 +0000148/// Initialize the map with the number of registers.
Andrew Trick035ec402012-03-07 23:00:57 +0000149void Reg2SUnitsMap::setRegLimit(unsigned Limit) {
Andrew Trick702d4892012-02-24 07:04:55 +0000150 PhysRegSet.setUniverse(Limit);
151 SUnits.resize(Limit);
152}
153
154/// Clear the map without deallocating storage.
Andrew Trick035ec402012-03-07 23:00:57 +0000155void Reg2SUnitsMap::clear() {
Andrew Trick702d4892012-02-24 07:04:55 +0000156 for (const_iterator I = reg_begin(), E = reg_end(); I != E; ++I) {
157 SUnits[*I].clear();
158 }
159 PhysRegSet.clear();
160}
161
Andrew Trick47c14452012-03-07 05:21:52 +0000162/// Initialize the DAG and common scheduler state for the current scheduling
163/// region. This does not actually create the DAG, only clears it. The
164/// scheduling driver may call BuildSchedGraph multiple times per scheduling
165/// region.
166void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb,
167 MachineBasicBlock::iterator begin,
168 MachineBasicBlock::iterator end,
169 unsigned endcount) {
Andrew Trick918f38a2012-04-20 20:05:21 +0000170 assert(bb == BB && "startBlock should set BB");
Andrew Trick68675c62012-03-09 04:29:02 +0000171 RegionBegin = begin;
172 RegionEnd = end;
Andrew Trickcf46b5a2012-03-07 23:00:52 +0000173 EndIndex = endcount;
Andrew Trick17d35e52012-03-14 04:00:41 +0000174 MISUnitMap.clear();
Andrew Trick47c14452012-03-07 05:21:52 +0000175
Andrew Trick47c14452012-03-07 05:21:52 +0000176 ScheduleDAG::clearDAG();
177}
178
179/// Close the current scheduling region. Don't clear any state in case the
180/// driver wants to refer to the previous scheduling region.
181void ScheduleDAGInstrs::exitRegion() {
182 // Nothing to do.
183}
184
Andrew Trick953be892012-03-07 23:00:49 +0000185/// addSchedBarrierDeps - Add dependencies from instructions in the current
Evan Chengec6906b2010-10-23 02:10:46 +0000186/// list of instructions being scheduled to scheduling barrier by adding
187/// the exit SU to the register defs and use list. This is because we want to
188/// make sure instructions which define registers that are either used by
189/// the terminator or are live-out are properly scheduled. This is
190/// especially important when the definition latency of the return value(s)
191/// are too high to be hidden by the branch or when the liveout registers
192/// used by instructions in the fallthrough block.
Andrew Trick953be892012-03-07 23:00:49 +0000193void ScheduleDAGInstrs::addSchedBarrierDeps() {
Andrew Trick68675c62012-03-09 04:29:02 +0000194 MachineInstr *ExitMI = RegionEnd != BB->end() ? &*RegionEnd : 0;
Evan Chengec6906b2010-10-23 02:10:46 +0000195 ExitSU.setInstr(ExitMI);
196 bool AllDepKnown = ExitMI &&
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000197 (ExitMI->isCall() || ExitMI->isBarrier());
Evan Chengec6906b2010-10-23 02:10:46 +0000198 if (ExitMI && AllDepKnown) {
199 // If it's a call or a barrier, add dependencies on the defs and uses of
200 // instruction.
201 for (unsigned i = 0, e = ExitMI->getNumOperands(); i != e; ++i) {
202 const MachineOperand &MO = ExitMI->getOperand(i);
203 if (!MO.isReg() || MO.isDef()) continue;
204 unsigned Reg = MO.getReg();
205 if (Reg == 0) continue;
206
Andrew Trick3c58ba82012-01-14 02:17:18 +0000207 if (TRI->isPhysicalRegister(Reg))
Andrew Trickffd25262012-08-23 00:39:43 +0000208 Uses[Reg].push_back(PhysRegSUOper(&ExitSU, -1));
Andrew Trickd3a74862012-03-16 05:04:25 +0000209 else {
Andrew Trick3c58ba82012-01-14 02:17:18 +0000210 assert(!IsPostRA && "Virtual register encountered after regalloc.");
Andrew Trickd3a74862012-03-16 05:04:25 +0000211 addVRegUseDeps(&ExitSU, i);
212 }
Evan Chengec6906b2010-10-23 02:10:46 +0000213 }
214 } else {
215 // For others, e.g. fallthrough, conditional branch, assume the exit
Evan Chengde5fa932010-10-27 23:17:17 +0000216 // uses all the registers that are livein to the successor blocks.
Benjamin Kramera82d5262012-03-16 17:38:19 +0000217 assert(Uses.empty() && "Uses in set before adding deps?");
Evan Chengde5fa932010-10-27 23:17:17 +0000218 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
219 SE = BB->succ_end(); SI != SE; ++SI)
220 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
Andrew Trickf405b1a2011-05-05 19:24:06 +0000221 E = (*SI)->livein_end(); I != E; ++I) {
Evan Chengde5fa932010-10-27 23:17:17 +0000222 unsigned Reg = *I;
Benjamin Kramera82d5262012-03-16 17:38:19 +0000223 if (!Uses.contains(Reg))
Andrew Trickffd25262012-08-23 00:39:43 +0000224 Uses[Reg].push_back(PhysRegSUOper(&ExitSU, -1));
Evan Chengde5fa932010-10-27 23:17:17 +0000225 }
Evan Chengec6906b2010-10-23 02:10:46 +0000226 }
227}
228
Andrew Trick81a682a2012-02-23 01:52:38 +0000229/// MO is an operand of SU's instruction that defines a physical register. Add
230/// data dependencies from SU to any uses of the physical register.
Andrew Trickffd25262012-08-23 00:39:43 +0000231void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU, unsigned OperIdx) {
232 const MachineOperand &MO = SU->getInstr()->getOperand(OperIdx);
Andrew Trick81a682a2012-02-23 01:52:38 +0000233 assert(MO.isDef() && "expect physreg def");
234
235 // Ask the target if address-backscheduling is desirable, and if so how much.
236 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
Andrew Trick81a682a2012-02-23 01:52:38 +0000237
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000238 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
239 Alias.isValid(); ++Alias) {
Andrew Trick702d4892012-02-24 07:04:55 +0000240 if (!Uses.contains(*Alias))
Andrew Trick81a682a2012-02-23 01:52:38 +0000241 continue;
Andrew Trickffd25262012-08-23 00:39:43 +0000242 std::vector<PhysRegSUOper> &UseList = Uses[*Alias];
Andrew Trick81a682a2012-02-23 01:52:38 +0000243 for (unsigned i = 0, e = UseList.size(); i != e; ++i) {
Andrew Trickffd25262012-08-23 00:39:43 +0000244 SUnit *UseSU = UseList[i].SU;
Andrew Trick81a682a2012-02-23 01:52:38 +0000245 if (UseSU == SU)
246 continue;
Andrew Trick39817f92012-10-08 18:54:00 +0000247
Andrew Tricka78d3222012-11-06 03:13:46 +0000248 SDep dep(SU, SDep::Data, *Alias);
Andrew Trick39817f92012-10-08 18:54:00 +0000249
250 // Adjust the dependence latency using operand def/use information,
251 // then allow the target to perform its own adjustments.
Andrew Trickffd25262012-08-23 00:39:43 +0000252 int UseOp = UseList[i].OpIdx;
Andrew Trick39817f92012-10-08 18:54:00 +0000253 MachineInstr *RegUse = UseOp < 0 ? 0 : UseSU->getInstr();
Andrew Tricka98f6002012-10-08 18:53:57 +0000254 dep.setLatency(
255 SchedModel.computeOperandLatency(SU->getInstr(), OperIdx,
256 RegUse, UseOp, /*FindMin=*/false));
257 dep.setMinLatency(
258 SchedModel.computeOperandLatency(SU->getInstr(), OperIdx,
259 RegUse, UseOp, /*FindMin=*/true));
Andrew Trickb7e02892012-06-05 21:11:27 +0000260
Andrew Tricka98f6002012-10-08 18:53:57 +0000261 ST.adjustSchedDependency(SU, UseSU, dep);
Andrew Trick81a682a2012-02-23 01:52:38 +0000262 UseSU->addPred(dep);
263 }
264 }
265}
266
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000267/// addPhysRegDeps - Add register dependencies (data, anti, and output) from
268/// this SUnit to following instructions in the same scheduling region that
269/// depend the physical register referenced at OperIdx.
270void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
271 const MachineInstr *MI = SU->getInstr();
272 const MachineOperand &MO = MI->getOperand(OperIdx);
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000273
274 // Optionally add output and anti dependencies. For anti
275 // dependencies we use a latency of 0 because for a multi-issue
276 // target we want to allow the defining instruction to issue
277 // in the same cycle as the using instruction.
278 // TODO: Using a latency of 1 here for output dependencies assumes
279 // there's no cost for reusing registers.
280 SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000281 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
282 Alias.isValid(); ++Alias) {
Andrew Trick702d4892012-02-24 07:04:55 +0000283 if (!Defs.contains(*Alias))
Andrew Trick81a682a2012-02-23 01:52:38 +0000284 continue;
Andrew Trickffd25262012-08-23 00:39:43 +0000285 std::vector<PhysRegSUOper> &DefList = Defs[*Alias];
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000286 for (unsigned i = 0, e = DefList.size(); i != e; ++i) {
Andrew Trickffd25262012-08-23 00:39:43 +0000287 SUnit *DefSU = DefList[i].SU;
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000288 if (DefSU == &ExitSU)
289 continue;
290 if (DefSU != SU &&
291 (Kind != SDep::Output || !MO.isDead() ||
292 !DefSU->getInstr()->registerDefIsDead(*Alias))) {
293 if (Kind == SDep::Anti)
Andrew Tricka78d3222012-11-06 03:13:46 +0000294 DefSU->addPred(SDep(SU, Kind, /*Reg=*/*Alias));
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000295 else {
Andrew Tricka78d3222012-11-06 03:13:46 +0000296 SDep Dep(SU, Kind, /*Reg=*/*Alias);
297 unsigned OutLatency =
Andrew Trick412cd2f2012-10-10 05:43:09 +0000298 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr());
Andrew Tricka78d3222012-11-06 03:13:46 +0000299 Dep.setMinLatency(OutLatency);
300 Dep.setLatency(OutLatency);
301 DefSU->addPred(Dep);
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000302 }
303 }
304 }
305 }
306
Andrew Trick81a682a2012-02-23 01:52:38 +0000307 if (!MO.isDef()) {
308 // Either insert a new Reg2SUnits entry with an empty SUnits list, or
309 // retrieve the existing SUnits list for this register's uses.
310 // Push this SUnit on the use list.
Andrew Trickffd25262012-08-23 00:39:43 +0000311 Uses[MO.getReg()].push_back(PhysRegSUOper(SU, OperIdx));
Andrew Trick81a682a2012-02-23 01:52:38 +0000312 }
313 else {
Andrew Trickffd25262012-08-23 00:39:43 +0000314 addPhysRegDataDeps(SU, OperIdx);
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000315
Andrew Trick81a682a2012-02-23 01:52:38 +0000316 // Either insert a new Reg2SUnits entry with an empty SUnits list, or
317 // retrieve the existing SUnits list for this register's defs.
Andrew Trickffd25262012-08-23 00:39:43 +0000318 std::vector<PhysRegSUOper> &DefList = Defs[MO.getReg()];
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000319
Andrew Trick81a682a2012-02-23 01:52:38 +0000320 // clear this register's use list
Andrew Trick702d4892012-02-24 07:04:55 +0000321 if (Uses.contains(MO.getReg()))
322 Uses[MO.getReg()].clear();
Andrew Trick81a682a2012-02-23 01:52:38 +0000323
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000324 if (!MO.isDead())
325 DefList.clear();
326
327 // Calls will not be reordered because of chain dependencies (see
328 // below). Since call operands are dead, calls may continue to be added
329 // to the DefList making dependence checking quadratic in the size of
330 // the block. Instead, we leave only one call at the back of the
331 // DefList.
332 if (SU->isCall) {
Andrew Trickffd25262012-08-23 00:39:43 +0000333 while (!DefList.empty() && DefList.back().SU->isCall)
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000334 DefList.pop_back();
335 }
Andrew Trick81a682a2012-02-23 01:52:38 +0000336 // Defs are pushed in the order they are visited and never reordered.
Andrew Trickffd25262012-08-23 00:39:43 +0000337 DefList.push_back(PhysRegSUOper(SU, OperIdx));
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000338 }
339}
340
Andrew Trick3c58ba82012-01-14 02:17:18 +0000341/// addVRegDefDeps - Add register output and data dependencies from this SUnit
342/// to instructions that occur later in the same scheduling region if they read
343/// from or write to the virtual register defined at OperIdx.
344///
345/// TODO: Hoist loop induction variable increments. This has to be
346/// reevaluated. Generally, IV scheduling should be done before coalescing.
347void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
348 const MachineInstr *MI = SU->getInstr();
349 unsigned Reg = MI->getOperand(OperIdx).getReg();
350
Andrew Trick4b72ada2012-07-28 01:48:15 +0000351 // Singly defined vregs do not have output/anti dependencies.
Andrew Trick2fc09772012-02-22 18:34:49 +0000352 // The current operand is a def, so we have at least one.
Andrew Trick4b72ada2012-07-28 01:48:15 +0000353 // Check here if there are any others...
Andrew Trick8b5704f2012-07-30 23:48:17 +0000354 if (MRI.hasOneDef(Reg))
Andrew Trick4b72ada2012-07-28 01:48:15 +0000355 return;
Andrew Trickcc77b542012-02-22 06:08:13 +0000356
Andrew Trick3c58ba82012-01-14 02:17:18 +0000357 // Add output dependence to the next nearest def of this vreg.
358 //
359 // Unless this definition is dead, the output dependence should be
360 // transitively redundant with antidependencies from this definition's
361 // uses. We're conservative for now until we have a way to guarantee the uses
362 // are not eliminated sometime during scheduling. The output dependence edge
363 // is also useful if output latency exceeds def-use latency.
Andrew Trickc0ccb8b2012-04-20 20:05:28 +0000364 VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
Andrew Trick8ae3ac72012-02-22 21:59:00 +0000365 if (DefI == VRegDefs.end())
366 VRegDefs.insert(VReg2SUnit(Reg, SU));
367 else {
368 SUnit *DefSU = DefI->SU;
369 if (DefSU != SU && DefSU != &ExitSU) {
Andrew Tricka78d3222012-11-06 03:13:46 +0000370 SDep Dep(SU, SDep::Output, Reg);
Andrew Trick412cd2f2012-10-10 05:43:09 +0000371 unsigned OutLatency =
372 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr());
Andrew Tricka78d3222012-11-06 03:13:46 +0000373 Dep.setMinLatency(OutLatency);
374 Dep.setLatency(OutLatency);
375 DefSU->addPred(Dep);
Andrew Trick8ae3ac72012-02-22 21:59:00 +0000376 }
377 DefI->SU = SU;
Andrew Trick3c58ba82012-01-14 02:17:18 +0000378 }
Andrew Trick3c58ba82012-01-14 02:17:18 +0000379}
380
Andrew Trickb4566a92012-02-22 06:08:11 +0000381/// addVRegUseDeps - Add a register data dependency if the instruction that
382/// defines the virtual register used at OperIdx is mapped to an SUnit. Add a
383/// register antidependency from this SUnit to instructions that occur later in
384/// the same scheduling region if they write the virtual register.
385///
386/// TODO: Handle ExitSU "uses" properly.
Andrew Trick3c58ba82012-01-14 02:17:18 +0000387void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
Andrew Trickb4566a92012-02-22 06:08:11 +0000388 MachineInstr *MI = SU->getInstr();
389 unsigned Reg = MI->getOperand(OperIdx).getReg();
390
391 // Lookup this operand's reaching definition.
392 assert(LIS && "vreg dependencies requires LiveIntervals");
Jakob Stoklund Olesen93e29ce2012-05-20 02:44:38 +0000393 LiveRangeQuery LRQ(LIS->getInterval(Reg), LIS->getInstructionIndex(MI));
394 VNInfo *VNI = LRQ.valueIn();
Andrew Trickc3ad8852012-04-24 18:04:41 +0000395
Andrew Trick63d578b2012-02-23 03:16:24 +0000396 // VNI will be valid because MachineOperand::readsReg() is checked by caller.
Jakob Stoklund Olesen93e29ce2012-05-20 02:44:38 +0000397 assert(VNI && "No value to read by operand");
Andrew Trickb4566a92012-02-22 06:08:11 +0000398 MachineInstr *Def = LIS->getInstructionFromIndex(VNI->def);
Andrew Trick63d578b2012-02-23 03:16:24 +0000399 // Phis and other noninstructions (after coalescing) have a NULL Def.
Andrew Trickb4566a92012-02-22 06:08:11 +0000400 if (Def) {
401 SUnit *DefSU = getSUnit(Def);
402 if (DefSU) {
403 // The reaching Def lives within this scheduling region.
404 // Create a data dependence.
Andrew Tricka78d3222012-11-06 03:13:46 +0000405 SDep dep(DefSU, SDep::Data, Reg);
Andrew Tricka98f6002012-10-08 18:53:57 +0000406 // Adjust the dependence latency using operand def/use information, then
407 // allow the target to perform its own adjustments.
408 int DefOp = Def->findRegisterDefOperandIdx(Reg);
409 dep.setLatency(
410 SchedModel.computeOperandLatency(Def, DefOp, MI, OperIdx, false));
411 dep.setMinLatency(
412 SchedModel.computeOperandLatency(Def, DefOp, MI, OperIdx, true));
Andrew Trickb7e02892012-06-05 21:11:27 +0000413
Andrew Tricka98f6002012-10-08 18:53:57 +0000414 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
415 ST.adjustSchedDependency(DefSU, SU, const_cast<SDep &>(dep));
Andrew Trickb4566a92012-02-22 06:08:11 +0000416 SU->addPred(dep);
417 }
418 }
Andrew Trick3c58ba82012-01-14 02:17:18 +0000419
420 // Add antidependence to the following def of the vreg it uses.
Andrew Trickc0ccb8b2012-04-20 20:05:28 +0000421 VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
Andrew Trick8ae3ac72012-02-22 21:59:00 +0000422 if (DefI != VRegDefs.end() && DefI->SU != SU)
Andrew Tricka78d3222012-11-06 03:13:46 +0000423 DefI->SU->addPred(SDep(SU, SDep::Anti, Reg));
Andrew Trickb4566a92012-02-22 06:08:11 +0000424}
Andrew Trick3c58ba82012-01-14 02:17:18 +0000425
Andrew Trickeb05b972012-05-15 18:59:41 +0000426/// Return true if MI is an instruction we are unable to reason about
427/// (like a call or something with unmodeled side effects).
428static inline bool isGlobalMemoryObject(AliasAnalysis *AA, MachineInstr *MI) {
429 if (MI->isCall() || MI->hasUnmodeledSideEffects() ||
Jakob Stoklund Olesenf036f7a2012-08-29 21:19:21 +0000430 (MI->hasOrderedMemoryRef() &&
Andrew Trickeb05b972012-05-15 18:59:41 +0000431 (!MI->mayLoad() || !MI->isInvariantLoad(AA))))
432 return true;
433 return false;
434}
435
436// This MI might have either incomplete info, or known to be unsafe
437// to deal with (i.e. volatile object).
438static inline bool isUnsafeMemoryObject(MachineInstr *MI,
439 const MachineFrameInfo *MFI) {
440 if (!MI || MI->memoperands_empty())
441 return true;
442 // We purposefully do no check for hasOneMemOperand() here
443 // in hope to trigger an assert downstream in order to
444 // finish implementation.
445 if ((*MI->memoperands_begin())->isVolatile() ||
446 MI->hasUnmodeledSideEffects())
447 return true;
448
449 const Value *V = (*MI->memoperands_begin())->getValue();
450 if (!V)
451 return true;
452
453 V = getUnderlyingObject(V);
454 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
455 // Similarly to getUnderlyingObjectForInstr:
456 // For now, ignore PseudoSourceValues which may alias LLVM IR values
457 // because the code that uses this function has no way to cope with
458 // such aliases.
459 if (PSV->isAliased(MFI))
460 return true;
461 }
462 // Does this pointer refer to a distinct and identifiable object?
463 if (!isIdentifiedObject(V))
464 return true;
465
466 return false;
467}
468
469/// This returns true if the two MIs need a chain edge betwee them.
470/// If these are not even memory operations, we still may need
471/// chain deps between them. The question really is - could
472/// these two MIs be reordered during scheduling from memory dependency
473/// point of view.
474static bool MIsNeedChainEdge(AliasAnalysis *AA, const MachineFrameInfo *MFI,
475 MachineInstr *MIa,
476 MachineInstr *MIb) {
477 // Cover a trivial case - no edge is need to itself.
478 if (MIa == MIb)
479 return false;
480
481 if (isUnsafeMemoryObject(MIa, MFI) || isUnsafeMemoryObject(MIb, MFI))
482 return true;
483
484 // If we are dealing with two "normal" loads, we do not need an edge
485 // between them - they could be reordered.
486 if (!MIa->mayStore() && !MIb->mayStore())
487 return false;
488
489 // To this point analysis is generic. From here on we do need AA.
490 if (!AA)
491 return true;
492
493 MachineMemOperand *MMOa = *MIa->memoperands_begin();
494 MachineMemOperand *MMOb = *MIb->memoperands_begin();
495
496 // FIXME: Need to handle multiple memory operands to support all targets.
497 if (!MIa->hasOneMemOperand() || !MIb->hasOneMemOperand())
498 llvm_unreachable("Multiple memory operands.");
499
500 // The following interface to AA is fashioned after DAGCombiner::isAlias
501 // and operates with MachineMemOperand offset with some important
502 // assumptions:
503 // - LLVM fundamentally assumes flat address spaces.
504 // - MachineOperand offset can *only* result from legalization and
505 // cannot affect queries other than the trivial case of overlap
506 // checking.
507 // - These offsets never wrap and never step outside
508 // of allocated objects.
509 // - There should never be any negative offsets here.
510 //
511 // FIXME: Modify API to hide this math from "user"
512 // FIXME: Even before we go to AA we can reason locally about some
513 // memory objects. It can save compile time, and possibly catch some
514 // corner cases not currently covered.
515
516 assert ((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset");
517 assert ((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset");
518
519 int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset());
520 int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset;
521 int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset;
522
523 AliasAnalysis::AliasResult AAResult = AA->alias(
524 AliasAnalysis::Location(MMOa->getValue(), Overlapa,
525 MMOa->getTBAAInfo()),
526 AliasAnalysis::Location(MMOb->getValue(), Overlapb,
527 MMOb->getTBAAInfo()));
528
529 return (AAResult != AliasAnalysis::NoAlias);
530}
531
532/// This recursive function iterates over chain deps of SUb looking for
533/// "latest" node that needs a chain edge to SUa.
534static unsigned
535iterateChainSucc(AliasAnalysis *AA, const MachineFrameInfo *MFI,
536 SUnit *SUa, SUnit *SUb, SUnit *ExitSU, unsigned *Depth,
537 SmallPtrSet<const SUnit*, 16> &Visited) {
538 if (!SUa || !SUb || SUb == ExitSU)
539 return *Depth;
540
541 // Remember visited nodes.
542 if (!Visited.insert(SUb))
543 return *Depth;
544 // If there is _some_ dependency already in place, do not
545 // descend any further.
546 // TODO: Need to make sure that if that dependency got eliminated or ignored
547 // for any reason in the future, we would not violate DAG topology.
548 // Currently it does not happen, but makes an implicit assumption about
549 // future implementation.
550 //
551 // Independently, if we encounter node that is some sort of global
552 // object (like a call) we already have full set of dependencies to it
553 // and we can stop descending.
554 if (SUa->isSucc(SUb) ||
555 isGlobalMemoryObject(AA, SUb->getInstr()))
556 return *Depth;
557
558 // If we do need an edge, or we have exceeded depth budget,
559 // add that edge to the predecessors chain of SUb,
560 // and stop descending.
561 if (*Depth > 200 ||
562 MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) {
Andrew Tricka78d3222012-11-06 03:13:46 +0000563 SUb->addPred(SDep(SUa, SDep::MayAliasMem));
Andrew Trickeb05b972012-05-15 18:59:41 +0000564 return *Depth;
565 }
566 // Track current depth.
567 (*Depth)++;
568 // Iterate over chain dependencies only.
569 for (SUnit::const_succ_iterator I = SUb->Succs.begin(), E = SUb->Succs.end();
570 I != E; ++I)
571 if (I->isCtrl())
572 iterateChainSucc (AA, MFI, SUa, I->getSUnit(), ExitSU, Depth, Visited);
573 return *Depth;
574}
575
576/// This function assumes that "downward" from SU there exist
577/// tail/leaf of already constructed DAG. It iterates downward and
578/// checks whether SU can be aliasing any node dominated
579/// by it.
580static void adjustChainDeps(AliasAnalysis *AA, const MachineFrameInfo *MFI,
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000581 SUnit *SU, SUnit *ExitSU, std::set<SUnit *> &CheckList,
582 unsigned LatencyToLoad) {
Andrew Trickeb05b972012-05-15 18:59:41 +0000583 if (!SU)
584 return;
585
586 SmallPtrSet<const SUnit*, 16> Visited;
587 unsigned Depth = 0;
588
589 for (std::set<SUnit *>::iterator I = CheckList.begin(), IE = CheckList.end();
590 I != IE; ++I) {
591 if (SU == *I)
592 continue;
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000593 if (MIsNeedChainEdge(AA, MFI, SU->getInstr(), (*I)->getInstr())) {
Andrew Tricka78d3222012-11-06 03:13:46 +0000594 SDep Dep(SU, SDep::MayAliasMem);
595 Dep.setLatency(((*I)->getInstr()->mayLoad()) ? LatencyToLoad : 0);
596 (*I)->addPred(Dep);
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000597 }
Andrew Trickeb05b972012-05-15 18:59:41 +0000598 // Now go through all the chain successors and iterate from them.
599 // Keep track of visited nodes.
600 for (SUnit::const_succ_iterator J = (*I)->Succs.begin(),
601 JE = (*I)->Succs.end(); J != JE; ++J)
602 if (J->isCtrl())
603 iterateChainSucc (AA, MFI, SU, J->getSUnit(),
604 ExitSU, &Depth, Visited);
605 }
606}
607
608/// Check whether two objects need a chain edge, if so, add it
609/// otherwise remember the rejected SU.
610static inline
611void addChainDependency (AliasAnalysis *AA, const MachineFrameInfo *MFI,
612 SUnit *SUa, SUnit *SUb,
613 std::set<SUnit *> &RejectList,
614 unsigned TrueMemOrderLatency = 0,
615 bool isNormalMemory = false) {
616 // If this is a false dependency,
617 // do not add the edge, but rememeber the rejected node.
618 if (!EnableAASchedMI ||
Andrew Tricka78d3222012-11-06 03:13:46 +0000619 MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) {
620 SDep Dep(SUa, isNormalMemory ? SDep::MayAliasMem : SDep::Barrier);
621 Dep.setLatency(TrueMemOrderLatency);
622 SUb->addPred(Dep);
623 }
Andrew Trickeb05b972012-05-15 18:59:41 +0000624 else {
625 // Duplicate entries should be ignored.
626 RejectList.insert(SUb);
627 DEBUG(dbgs() << "\tReject chain dep between SU("
628 << SUa->NodeNum << ") and SU("
629 << SUb->NodeNum << ")\n");
630 }
631}
632
Andrew Trickb4566a92012-02-22 06:08:11 +0000633/// Create an SUnit for each real instruction, numbered in top-down toplological
634/// order. The instruction order A < B, implies that no edge exists from B to A.
635///
636/// Map each real instruction to its SUnit.
637///
Andrew Trick17d35e52012-03-14 04:00:41 +0000638/// After initSUnits, the SUnits vector cannot be resized and the scheduler may
639/// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
640/// instead of pointers.
641///
642/// MachineScheduler relies on initSUnits numbering the nodes by their order in
643/// the original instruction list.
Andrew Trickb4566a92012-02-22 06:08:11 +0000644void ScheduleDAGInstrs::initSUnits() {
645 // We'll be allocating one SUnit for each real instruction in the region,
646 // which is contained within a basic block.
647 SUnits.reserve(BB->size());
648
Andrew Trick68675c62012-03-09 04:29:02 +0000649 for (MachineBasicBlock::iterator I = RegionBegin; I != RegionEnd; ++I) {
Andrew Trickb4566a92012-02-22 06:08:11 +0000650 MachineInstr *MI = I;
651 if (MI->isDebugValue())
652 continue;
653
Andrew Trick953be892012-03-07 23:00:49 +0000654 SUnit *SU = newSUnit(MI);
Andrew Trickb4566a92012-02-22 06:08:11 +0000655 MISUnitMap[MI] = SU;
656
657 SU->isCall = MI->isCall();
658 SU->isCommutable = MI->isCommutable();
659
660 // Assign the Latency field of SU using target-provided information.
Andrew Trick412cd2f2012-10-10 05:43:09 +0000661 SU->Latency = SchedModel.computeInstrLatency(SU->getInstr());
Andrew Trickb4566a92012-02-22 06:08:11 +0000662 }
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000663}
664
Andrew Trick006e1ab2012-04-24 17:56:43 +0000665/// If RegPressure is non null, compute register pressure as a side effect. The
666/// DAG builder is an efficient place to do it because it already visits
667/// operands.
668void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA,
669 RegPressureTracker *RPTracker) {
Andrew Trickb4566a92012-02-22 06:08:11 +0000670 // Create an SUnit for each real instruction.
671 initSUnits();
Dan Gohman343f0c02008-11-19 23:18:57 +0000672
Dan Gohman6a9041e2008-12-04 01:35:46 +0000673 // We build scheduling units by walking a block's instruction list from bottom
674 // to top.
675
David Goodwin980d4942009-11-09 19:22:17 +0000676 // Remember where a generic side-effecting instruction is as we procede.
677 SUnit *BarrierChain = 0, *AliasChain = 0;
Dan Gohman6a9041e2008-12-04 01:35:46 +0000678
David Goodwin980d4942009-11-09 19:22:17 +0000679 // Memory references to specific known memory locations are tracked
680 // so that they can be given more precise dependencies. We track
681 // separately the known memory locations that may alias and those
682 // that are known not to alias
683 std::map<const Value *, SUnit *> AliasMemDefs, NonAliasMemDefs;
684 std::map<const Value *, std::vector<SUnit *> > AliasMemUses, NonAliasMemUses;
Andrew Trickeb05b972012-05-15 18:59:41 +0000685 std::set<SUnit*> RejectMemNodes;
Dan Gohman6a9041e2008-12-04 01:35:46 +0000686
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000687 // Remove any stale debug info; sometimes BuildSchedGraph is called again
688 // without emitting the info from the previous call.
Devang Patelcf4cc842011-06-02 20:07:12 +0000689 DbgValues.clear();
690 FirstDbgValue = NULL;
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000691
Andrew Trick81a682a2012-02-23 01:52:38 +0000692 assert(Defs.empty() && Uses.empty() &&
693 "Only BuildGraph should update Defs/Uses");
Andrew Trick702d4892012-02-24 07:04:55 +0000694 Defs.setRegLimit(TRI->getNumRegs());
695 Uses.setRegLimit(TRI->getNumRegs());
Andrew Trick9b668532011-05-06 21:52:52 +0000696
Andrew Trick8ae3ac72012-02-22 21:59:00 +0000697 assert(VRegDefs.empty() && "Only BuildSchedGraph may access VRegDefs");
698 // FIXME: Allow SparseSet to reserve space for the creation of virtual
699 // registers during scheduling. Don't artificially inflate the Universe
700 // because we want to assert that vregs are not created during DAG building.
701 VRegDefs.setUniverse(MRI.getNumVirtRegs());
Andrew Trick3c58ba82012-01-14 02:17:18 +0000702
Andrew Trick81a682a2012-02-23 01:52:38 +0000703 // Model data dependencies between instructions being scheduled and the
704 // ExitSU.
Andrew Trick953be892012-03-07 23:00:49 +0000705 addSchedBarrierDeps();
Andrew Trick81a682a2012-02-23 01:52:38 +0000706
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000707 // Walk the list of instructions, from bottom moving up.
Devang Patelcf4cc842011-06-02 20:07:12 +0000708 MachineInstr *PrevMI = NULL;
Andrew Trick68675c62012-03-09 04:29:02 +0000709 for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
Dan Gohman343f0c02008-11-19 23:18:57 +0000710 MII != MIE; --MII) {
711 MachineInstr *MI = prior(MII);
Devang Patelcf4cc842011-06-02 20:07:12 +0000712 if (MI && PrevMI) {
713 DbgValues.push_back(std::make_pair(PrevMI, MI));
714 PrevMI = NULL;
715 }
716
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000717 if (MI->isDebugValue()) {
Devang Patelcf4cc842011-06-02 20:07:12 +0000718 PrevMI = MI;
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000719 continue;
720 }
Andrew Trick006e1ab2012-04-24 17:56:43 +0000721 if (RPTracker) {
722 RPTracker->recede();
723 assert(RPTracker->getPos() == prior(MII) && "RPTracker can't find MI");
724 }
Devang Patelcf4cc842011-06-02 20:07:12 +0000725
Andrew Trick00707922012-04-13 23:29:54 +0000726 assert((!MI->isTerminator() || CanHandleTerminators) && !MI->isLabel() &&
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000727 "Cannot schedule terminators or labels!");
Dan Gohman343f0c02008-11-19 23:18:57 +0000728
Andrew Trickb4566a92012-02-22 06:08:11 +0000729 SUnit *SU = MISUnitMap[MI];
730 assert(SU && "No SUnit mapped to this MI");
Dan Gohman54e4c362008-12-09 22:54:47 +0000731
Dan Gohman6a9041e2008-12-04 01:35:46 +0000732 // Add register-based dependencies (data, anti, and output).
Dan Gohman343f0c02008-11-19 23:18:57 +0000733 for (unsigned j = 0, n = MI->getNumOperands(); j != n; ++j) {
734 const MachineOperand &MO = MI->getOperand(j);
735 if (!MO.isReg()) continue;
736 unsigned Reg = MO.getReg();
737 if (Reg == 0) continue;
738
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000739 if (TRI->isPhysicalRegister(Reg))
740 addPhysRegDeps(SU, j);
741 else {
742 assert(!IsPostRA && "Virtual register encountered!");
Andrew Trick3c58ba82012-01-14 02:17:18 +0000743 if (MO.isDef())
744 addVRegDefDeps(SU, j);
Andrew Trick63d578b2012-02-23 03:16:24 +0000745 else if (MO.readsReg()) // ignore undef operands
Andrew Trick3c58ba82012-01-14 02:17:18 +0000746 addVRegUseDeps(SU, j);
Dan Gohman343f0c02008-11-19 23:18:57 +0000747 }
748 }
Dan Gohman6a9041e2008-12-04 01:35:46 +0000749
750 // Add chain dependencies.
David Goodwin7c9b1ac2009-11-02 17:06:28 +0000751 // Chain dependencies used to enforce memory order should have
752 // latency of 0 (except for true dependency of Store followed by
753 // aliased Load... we estimate that with a single cycle of latency
754 // assuming the hardware will bypass)
Dan Gohman6a9041e2008-12-04 01:35:46 +0000755 // Note that isStoreToStackSlot and isLoadFromStackSLot are not usable
756 // after stack slots are lowered to actual addresses.
757 // TODO: Use an AliasAnalysis and do real alias-analysis queries, and
758 // produce more precise dependence information.
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000759 unsigned TrueMemOrderLatency = MI->mayStore() ? 1 : 0;
Andrew Trickeb05b972012-05-15 18:59:41 +0000760 if (isGlobalMemoryObject(AA, MI)) {
David Goodwin980d4942009-11-09 19:22:17 +0000761 // Be conservative with these and add dependencies on all memory
762 // references, even those that are known to not alias.
Andrew Trickf405b1a2011-05-05 19:24:06 +0000763 for (std::map<const Value *, SUnit *>::iterator I =
David Goodwin980d4942009-11-09 19:22:17 +0000764 NonAliasMemDefs.begin(), E = NonAliasMemDefs.end(); I != E; ++I) {
Andrew Tricka78d3222012-11-06 03:13:46 +0000765 I->second->addPred(SDep(SU, SDep::Barrier));
Dan Gohman6a9041e2008-12-04 01:35:46 +0000766 }
767 for (std::map<const Value *, std::vector<SUnit *> >::iterator I =
David Goodwin980d4942009-11-09 19:22:17 +0000768 NonAliasMemUses.begin(), E = NonAliasMemUses.end(); I != E; ++I) {
Andrew Tricka78d3222012-11-06 03:13:46 +0000769 for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
770 SDep Dep(SU, SDep::Barrier);
771 Dep.setLatency(TrueMemOrderLatency);
772 I->second[i]->addPred(Dep);
773 }
Dan Gohman6a9041e2008-12-04 01:35:46 +0000774 }
David Goodwin980d4942009-11-09 19:22:17 +0000775 // Add SU to the barrier chain.
776 if (BarrierChain)
Andrew Tricka78d3222012-11-06 03:13:46 +0000777 BarrierChain->addPred(SDep(SU, SDep::Barrier));
David Goodwin980d4942009-11-09 19:22:17 +0000778 BarrierChain = SU;
Andrew Trickeb05b972012-05-15 18:59:41 +0000779 // This is a barrier event that acts as a pivotal node in the DAG,
780 // so it is safe to clear list of exposed nodes.
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000781 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
782 TrueMemOrderLatency);
Andrew Trickeb05b972012-05-15 18:59:41 +0000783 RejectMemNodes.clear();
784 NonAliasMemDefs.clear();
785 NonAliasMemUses.clear();
David Goodwin980d4942009-11-09 19:22:17 +0000786
787 // fall-through
788 new_alias_chain:
789 // Chain all possibly aliasing memory references though SU.
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000790 if (AliasChain) {
791 unsigned ChainLatency = 0;
792 if (AliasChain->getInstr()->mayLoad())
793 ChainLatency = TrueMemOrderLatency;
794 addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes,
795 ChainLatency);
796 }
David Goodwin980d4942009-11-09 19:22:17 +0000797 AliasChain = SU;
798 for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
Andrew Trickeb05b972012-05-15 18:59:41 +0000799 addChainDependency(AA, MFI, SU, PendingLoads[k], RejectMemNodes,
800 TrueMemOrderLatency);
David Goodwin980d4942009-11-09 19:22:17 +0000801 for (std::map<const Value *, SUnit *>::iterator I = AliasMemDefs.begin(),
Andrew Trickeb05b972012-05-15 18:59:41 +0000802 E = AliasMemDefs.end(); I != E; ++I)
803 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes);
David Goodwin980d4942009-11-09 19:22:17 +0000804 for (std::map<const Value *, std::vector<SUnit *> >::iterator I =
805 AliasMemUses.begin(), E = AliasMemUses.end(); I != E; ++I) {
806 for (unsigned i = 0, e = I->second.size(); i != e; ++i)
Andrew Trickeb05b972012-05-15 18:59:41 +0000807 addChainDependency(AA, MFI, SU, I->second[i], RejectMemNodes,
808 TrueMemOrderLatency);
David Goodwin980d4942009-11-09 19:22:17 +0000809 }
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000810 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
811 TrueMemOrderLatency);
David Goodwin980d4942009-11-09 19:22:17 +0000812 PendingLoads.clear();
813 AliasMemDefs.clear();
814 AliasMemUses.clear();
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000815 } else if (MI->mayStore()) {
David Goodwina9e61072009-11-03 20:15:00 +0000816 bool MayAlias = true;
David Goodwina9e61072009-11-03 20:15:00 +0000817 if (const Value *V = getUnderlyingObjectForInstr(MI, MFI, MayAlias)) {
Dan Gohman6a9041e2008-12-04 01:35:46 +0000818 // A store to a specific PseudoSourceValue. Add precise dependencies.
David Goodwin980d4942009-11-09 19:22:17 +0000819 // Record the def in MemDefs, first adding a dep if there is
820 // an existing def.
Andrew Trickf405b1a2011-05-05 19:24:06 +0000821 std::map<const Value *, SUnit *>::iterator I =
David Goodwin980d4942009-11-09 19:22:17 +0000822 ((MayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
Andrew Trickf405b1a2011-05-05 19:24:06 +0000823 std::map<const Value *, SUnit *>::iterator IE =
David Goodwin980d4942009-11-09 19:22:17 +0000824 ((MayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
825 if (I != IE) {
Andrew Trickeb05b972012-05-15 18:59:41 +0000826 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes,
827 0, true);
Dan Gohman6a9041e2008-12-04 01:35:46 +0000828 I->second = SU;
829 } else {
David Goodwin980d4942009-11-09 19:22:17 +0000830 if (MayAlias)
831 AliasMemDefs[V] = SU;
832 else
833 NonAliasMemDefs[V] = SU;
Dan Gohman6a9041e2008-12-04 01:35:46 +0000834 }
835 // Handle the uses in MemUses, if there are any.
Dan Gohmana629b482008-12-08 17:50:35 +0000836 std::map<const Value *, std::vector<SUnit *> >::iterator J =
David Goodwin980d4942009-11-09 19:22:17 +0000837 ((MayAlias) ? AliasMemUses.find(V) : NonAliasMemUses.find(V));
838 std::map<const Value *, std::vector<SUnit *> >::iterator JE =
839 ((MayAlias) ? AliasMemUses.end() : NonAliasMemUses.end());
840 if (J != JE) {
Dan Gohman6a9041e2008-12-04 01:35:46 +0000841 for (unsigned i = 0, e = J->second.size(); i != e; ++i)
Andrew Trickeb05b972012-05-15 18:59:41 +0000842 addChainDependency(AA, MFI, SU, J->second[i], RejectMemNodes,
843 TrueMemOrderLatency, true);
Dan Gohman6a9041e2008-12-04 01:35:46 +0000844 J->second.clear();
845 }
David Goodwina9e61072009-11-03 20:15:00 +0000846 if (MayAlias) {
David Goodwin980d4942009-11-09 19:22:17 +0000847 // Add dependencies from all the PendingLoads, i.e. loads
848 // with no underlying object.
David Goodwina9e61072009-11-03 20:15:00 +0000849 for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
Andrew Trickeb05b972012-05-15 18:59:41 +0000850 addChainDependency(AA, MFI, SU, PendingLoads[k], RejectMemNodes,
851 TrueMemOrderLatency);
David Goodwin980d4942009-11-09 19:22:17 +0000852 // Add dependence on alias chain, if needed.
853 if (AliasChain)
Andrew Trickeb05b972012-05-15 18:59:41 +0000854 addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes);
855 // But we also should check dependent instructions for the
856 // SU in question.
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000857 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
858 TrueMemOrderLatency);
David Goodwina9e61072009-11-03 20:15:00 +0000859 }
David Goodwin980d4942009-11-09 19:22:17 +0000860 // Add dependence on barrier chain, if needed.
Andrew Trickeb05b972012-05-15 18:59:41 +0000861 // There is no point to check aliasing on barrier event. Even if
862 // SU and barrier _could_ be reordered, they should not. In addition,
863 // we have lost all RejectMemNodes below barrier.
David Goodwin980d4942009-11-09 19:22:17 +0000864 if (BarrierChain)
Andrew Tricka78d3222012-11-06 03:13:46 +0000865 BarrierChain->addPred(SDep(SU, SDep::Barrier));
David Goodwin5be870a2009-11-05 00:16:44 +0000866 } else {
Dan Gohman6a9041e2008-12-04 01:35:46 +0000867 // Treat all other stores conservatively.
David Goodwin980d4942009-11-09 19:22:17 +0000868 goto new_alias_chain;
David Goodwin7c9b1ac2009-11-02 17:06:28 +0000869 }
Evan Chengec6906b2010-10-23 02:10:46 +0000870
871 if (!ExitSU.isPred(SU))
872 // Push store's up a bit to avoid them getting in between cmp
873 // and branches.
Andrew Tricka78d3222012-11-06 03:13:46 +0000874 ExitSU.addPred(SDep(SU, SDep::Artificial));
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000875 } else if (MI->mayLoad()) {
David Goodwina9e61072009-11-03 20:15:00 +0000876 bool MayAlias = true;
Dan Gohmana70dca12009-10-09 23:27:56 +0000877 if (MI->isInvariantLoad(AA)) {
Dan Gohman6a9041e2008-12-04 01:35:46 +0000878 // Invariant load, no chain dependencies needed!
David Goodwin5be870a2009-11-05 00:16:44 +0000879 } else {
Andrew Trickf405b1a2011-05-05 19:24:06 +0000880 if (const Value *V =
David Goodwin980d4942009-11-09 19:22:17 +0000881 getUnderlyingObjectForInstr(MI, MFI, MayAlias)) {
882 // A load from a specific PseudoSourceValue. Add precise dependencies.
Andrew Trickf405b1a2011-05-05 19:24:06 +0000883 std::map<const Value *, SUnit *>::iterator I =
David Goodwin980d4942009-11-09 19:22:17 +0000884 ((MayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
Andrew Trickf405b1a2011-05-05 19:24:06 +0000885 std::map<const Value *, SUnit *>::iterator IE =
David Goodwin980d4942009-11-09 19:22:17 +0000886 ((MayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
887 if (I != IE)
Andrew Trickeb05b972012-05-15 18:59:41 +0000888 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes, 0, true);
David Goodwin980d4942009-11-09 19:22:17 +0000889 if (MayAlias)
890 AliasMemUses[V].push_back(SU);
Andrew Trickf405b1a2011-05-05 19:24:06 +0000891 else
David Goodwin980d4942009-11-09 19:22:17 +0000892 NonAliasMemUses[V].push_back(SU);
893 } else {
894 // A load with no underlying object. Depend on all
895 // potentially aliasing stores.
Andrew Trickf405b1a2011-05-05 19:24:06 +0000896 for (std::map<const Value *, SUnit *>::iterator I =
David Goodwin980d4942009-11-09 19:22:17 +0000897 AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I)
Andrew Trickeb05b972012-05-15 18:59:41 +0000898 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes);
Andrew Trickf405b1a2011-05-05 19:24:06 +0000899
David Goodwin980d4942009-11-09 19:22:17 +0000900 PendingLoads.push_back(SU);
901 MayAlias = true;
David Goodwina9e61072009-11-03 20:15:00 +0000902 }
Andrew Trickeb05b972012-05-15 18:59:41 +0000903 if (MayAlias)
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000904 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes, /*Latency=*/0);
David Goodwin980d4942009-11-09 19:22:17 +0000905 // Add dependencies on alias and barrier chains, if needed.
906 if (MayAlias && AliasChain)
Andrew Trickeb05b972012-05-15 18:59:41 +0000907 addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes);
David Goodwin980d4942009-11-09 19:22:17 +0000908 if (BarrierChain)
Andrew Tricka78d3222012-11-06 03:13:46 +0000909 BarrierChain->addPred(SDep(SU, SDep::Barrier));
Andrew Trickf405b1a2011-05-05 19:24:06 +0000910 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000911 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000912 }
Devang Patelcf4cc842011-06-02 20:07:12 +0000913 if (PrevMI)
914 FirstDbgValue = PrevMI;
Dan Gohman79ce2762009-01-15 19:20:50 +0000915
Andrew Trick81a682a2012-02-23 01:52:38 +0000916 Defs.clear();
917 Uses.clear();
Andrew Trick3c58ba82012-01-14 02:17:18 +0000918 VRegDefs.clear();
Dan Gohman79ce2762009-01-15 19:20:50 +0000919 PendingLoads.clear();
Dan Gohman343f0c02008-11-19 23:18:57 +0000920}
921
Dan Gohman343f0c02008-11-19 23:18:57 +0000922void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
Manman Renb720be62012-09-11 22:23:19 +0000923#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohman343f0c02008-11-19 23:18:57 +0000924 SU->getInstr()->dump();
Manman Ren77e300e2012-09-06 19:06:06 +0000925#endif
Dan Gohman343f0c02008-11-19 23:18:57 +0000926}
927
928std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
929 std::string s;
930 raw_string_ostream oss(s);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000931 if (SU == &EntrySU)
932 oss << "<entry>";
933 else if (SU == &ExitSU)
934 oss << "<exit>";
935 else
936 SU->getInstr()->print(oss);
Dan Gohman343f0c02008-11-19 23:18:57 +0000937 return oss.str();
938}
939
Andrew Trick56b94c52012-03-07 00:18:22 +0000940/// Return the basic block label. It is not necessarilly unique because a block
941/// contains multiple scheduling regions. But it is fine for visualization.
942std::string ScheduleDAGInstrs::getDAGName() const {
943 return "dag." + BB->getFullName();
944}
Andrew Trick1e94e982012-10-15 18:02:27 +0000945
946namespace {
947/// \brief Manage the stack used by a reverse depth-first search over the DAG.
948class SchedDAGReverseDFS {
949 std::vector<std::pair<const SUnit*, SUnit::const_pred_iterator> > DFSStack;
950public:
951 bool isComplete() const { return DFSStack.empty(); }
952
953 void follow(const SUnit *SU) {
954 DFSStack.push_back(std::make_pair(SU, SU->Preds.begin()));
955 }
956 void advance() { ++DFSStack.back().second; }
957
958 void backtrack() { DFSStack.pop_back(); }
959
960 const SUnit *getCurr() const { return DFSStack.back().first; }
961
962 SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
963
964 SUnit::const_pred_iterator getPredEnd() const {
965 return getCurr()->Preds.end();
966 }
967};
968} // anonymous
969
970void ScheduleDAGILP::resize(unsigned NumSUnits) {
971 ILPValues.resize(NumSUnits);
972}
973
974ILPValue ScheduleDAGILP::getILP(const SUnit *SU) {
975 return ILPValues[SU->NodeNum];
976}
977
978// A leaf node has an ILP of 1/1.
979static ILPValue initILP(const SUnit *SU) {
980 unsigned Cnt = SU->getInstr()->isTransient() ? 0 : 1;
981 return ILPValue(Cnt, 1 + SU->getDepth());
982}
983
984/// Compute an ILP metric for all nodes in the subDAG reachable via depth-first
985/// search from this root.
986void ScheduleDAGILP::computeILP(const SUnit *Root) {
987 if (!IsBottomUp)
988 llvm_unreachable("Top-down ILP metric is unimplemnted");
989
990 SchedDAGReverseDFS DFS;
991 // Mark a node visited by validating it.
992 ILPValues[Root->NodeNum] = initILP(Root);
993 DFS.follow(Root);
994 for (;;) {
995 // Traverse the leftmost path as far as possible.
996 while (DFS.getPred() != DFS.getPredEnd()) {
997 const SUnit *PredSU = DFS.getPred()->getSUnit();
998 DFS.advance();
999 // If the pred is already valid, skip it.
1000 if (ILPValues[PredSU->NodeNum].isValid())
1001 continue;
1002 ILPValues[PredSU->NodeNum] = initILP(PredSU);
1003 DFS.follow(PredSU);
1004 }
1005 // Visit the top of the stack in postorder and backtrack.
1006 unsigned PredCount = ILPValues[DFS.getCurr()->NodeNum].InstrCount;
1007 DFS.backtrack();
1008 if (DFS.isComplete())
1009 break;
1010 // Add the recently finished predecessor's bottom-up descendent count.
1011 ILPValues[DFS.getCurr()->NodeNum].InstrCount += PredCount;
1012 }
1013}
1014
1015#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1016void ILPValue::print(raw_ostream &OS) const {
1017 if (!isValid())
1018 OS << "BADILP";
1019 OS << InstrCount << " / " << Cycles << " = "
1020 << format("%g", ((double)InstrCount / Cycles));
1021}
1022
1023void ILPValue::dump() const {
1024 dbgs() << *this << '\n';
1025}
1026
1027namespace llvm {
1028
1029raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) {
1030 Val.print(OS);
1031 return OS;
1032}
1033
1034} // namespace llvm
1035#endif // !NDEBUG || LLVM_ENABLE_DUMP