blob: 773a29d0c23e5054810ce08a12beeed4aea9c18e [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"
Andrew Trick006e1ab2012-04-24 17:56:43 +000016#include "RegisterPressure.h"
Dan Gohman8906f952009-07-17 20:58:59 +000017#include "llvm/Operator.h"
Dan Gohman3311a1f2009-01-30 02:49:14 +000018#include "llvm/Analysis/AliasAnalysis.h"
Dan Gohman5034dd32010-12-15 20:02:24 +000019#include "llvm/Analysis/ValueTracking.h"
Andrew Trickb4566a92012-02-22 06:08:11 +000020#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Dan Gohman3f237442008-12-16 03:25:46 +000021#include "llvm/CodeGen/MachineFunctionPass.h"
Dan Gohmanc76909a2009-09-25 20:36:54 +000022#include "llvm/CodeGen/MachineMemOperand.h"
Dan Gohman3f237442008-12-16 03:25:46 +000023#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman6a9041e2008-12-04 01:35:46 +000024#include "llvm/CodeGen/PseudoSourceValue.h"
Andrew Tricked395c82012-03-07 23:01:06 +000025#include "llvm/CodeGen/ScheduleDAGInstrs.h"
Evan Chengab8be962011-06-29 01:14:12 +000026#include "llvm/MC/MCInstrItineraries.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000027#include "llvm/Target/TargetMachine.h"
28#include "llvm/Target/TargetInstrInfo.h"
29#include "llvm/Target/TargetRegisterInfo.h"
Evan Cheng5b1b44892011-07-01 21:01:15 +000030#include "llvm/Target/TargetSubtargetInfo.h"
Andrew Trickeb05b972012-05-15 18:59:41 +000031#include "llvm/Support/CommandLine.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000032#include "llvm/Support/Debug.h"
33#include "llvm/Support/raw_ostream.h"
Dan Gohman3f237442008-12-16 03:25:46 +000034#include "llvm/ADT/SmallSet.h"
Andrew Trickeb05b972012-05-15 18:59:41 +000035#include "llvm/ADT/SmallPtrSet.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000036using namespace llvm;
37
Andrew Trickeb05b972012-05-15 18:59:41 +000038static cl::opt<bool> EnableAASchedMI("enable-aa-sched-mi", cl::Hidden,
39 cl::ZeroOrMore, cl::init(false),
40 cl::desc("Enable use of AA during MI GAD construction"));
41
Dan Gohman79ce2762009-01-15 19:20:50 +000042ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
Dan Gohman3f237442008-12-16 03:25:46 +000043 const MachineLoopInfo &mli,
Andrew Trick5e920d72012-01-14 02:17:12 +000044 const MachineDominatorTree &mdt,
Andrew Trickb4566a92012-02-22 06:08:11 +000045 bool IsPostRAFlag,
46 LiveIntervals *lis)
Evan Cheng3ef1c872010-09-10 01:29:16 +000047 : ScheduleDAG(mf), MLI(mli), MDT(mdt), MFI(mf.getFrameInfo()),
Andrew Trickd790cad2012-03-07 23:00:59 +000048 InstrItins(mf.getTarget().getInstrItineraryData()), LIS(lis),
Andrew Trick00707922012-04-13 23:29:54 +000049 IsPostRA(IsPostRAFlag), UnitLatencies(false), CanHandleTerminators(false),
50 LoopRegs(MLI, MDT), 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");
Evan Cheng38bdfc62009-10-18 19:58:47 +000055}
Dan Gohman343f0c02008-11-19 23:18:57 +000056
Dan Gohman3311a1f2009-01-30 02:49:14 +000057/// getUnderlyingObjectFromInt - This is the function that does the work of
58/// looking through basic ptrtoint+arithmetic+inttoptr sequences.
59static const Value *getUnderlyingObjectFromInt(const Value *V) {
60 do {
Dan Gohman8906f952009-07-17 20:58:59 +000061 if (const Operator *U = dyn_cast<Operator>(V)) {
Dan Gohman3311a1f2009-01-30 02:49:14 +000062 // If we find a ptrtoint, we can transfer control back to the
63 // regular getUnderlyingObjectFromInt.
Dan Gohman8906f952009-07-17 20:58:59 +000064 if (U->getOpcode() == Instruction::PtrToInt)
Dan Gohman3311a1f2009-01-30 02:49:14 +000065 return U->getOperand(0);
66 // If we find an add of a constant or a multiplied value, it's
67 // likely that the other operand will lead us to the base
68 // object. We don't have to worry about the case where the
Dan Gohman748f98f2009-08-07 01:26:06 +000069 // object address is somehow being computed by the multiply,
Dan Gohman3311a1f2009-01-30 02:49:14 +000070 // because our callers only care when the result is an
71 // identifibale object.
Dan Gohman8906f952009-07-17 20:58:59 +000072 if (U->getOpcode() != Instruction::Add ||
Dan Gohman3311a1f2009-01-30 02:49:14 +000073 (!isa<ConstantInt>(U->getOperand(1)) &&
Dan Gohman8906f952009-07-17 20:58:59 +000074 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul))
Dan Gohman3311a1f2009-01-30 02:49:14 +000075 return V;
76 V = U->getOperand(0);
77 } else {
78 return V;
79 }
Duncan Sands1df98592010-02-16 11:11:14 +000080 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
Dan Gohman3311a1f2009-01-30 02:49:14 +000081 } while (1);
82}
83
Dan Gohman5034dd32010-12-15 20:02:24 +000084/// getUnderlyingObject - This is a wrapper around GetUnderlyingObject
Dan Gohman3311a1f2009-01-30 02:49:14 +000085/// and adds support for basic ptrtoint+arithmetic+inttoptr sequences.
86static const Value *getUnderlyingObject(const Value *V) {
87 // First just call Value::getUnderlyingObject to let it do what it does.
88 do {
Dan Gohman5034dd32010-12-15 20:02:24 +000089 V = GetUnderlyingObject(V);
Dan Gohman3311a1f2009-01-30 02:49:14 +000090 // If it found an inttoptr, use special code to continue climing.
Dan Gohman8906f952009-07-17 20:58:59 +000091 if (Operator::getOpcode(V) != Instruction::IntToPtr)
Dan Gohman3311a1f2009-01-30 02:49:14 +000092 break;
93 const Value *O = getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
94 // If that succeeded in finding a pointer, continue the search.
Duncan Sands1df98592010-02-16 11:11:14 +000095 if (!O->getType()->isPointerTy())
Dan Gohman3311a1f2009-01-30 02:49:14 +000096 break;
97 V = O;
98 } while (1);
99 return V;
100}
101
102/// getUnderlyingObjectForInstr - If this machine instr has memory reference
103/// information and it can be tracked to a normal reference to a known
104/// object, return the Value for that object. Otherwise return null.
Evan Cheng38bdfc62009-10-18 19:58:47 +0000105static const Value *getUnderlyingObjectForInstr(const MachineInstr *MI,
David Goodwina9e61072009-11-03 20:15:00 +0000106 const MachineFrameInfo *MFI,
107 bool &MayAlias) {
108 MayAlias = true;
Dan Gohman3311a1f2009-01-30 02:49:14 +0000109 if (!MI->hasOneMemOperand() ||
Dan Gohmanc76909a2009-09-25 20:36:54 +0000110 !(*MI->memoperands_begin())->getValue() ||
111 (*MI->memoperands_begin())->isVolatile())
Dan Gohman3311a1f2009-01-30 02:49:14 +0000112 return 0;
113
Dan Gohmanc76909a2009-09-25 20:36:54 +0000114 const Value *V = (*MI->memoperands_begin())->getValue();
Dan Gohman3311a1f2009-01-30 02:49:14 +0000115 if (!V)
116 return 0;
117
118 V = getUnderlyingObject(V);
Evan Chengff89dcb2009-10-18 18:16:27 +0000119 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
120 // For now, ignore PseudoSourceValues which may alias LLVM IR values
121 // because the code that uses this function has no way to cope with
122 // such aliases.
Evan Cheng38bdfc62009-10-18 19:58:47 +0000123 if (PSV->isAliased(MFI))
Evan Chengff89dcb2009-10-18 18:16:27 +0000124 return 0;
Andrew Trickf405b1a2011-05-05 19:24:06 +0000125
David Goodwin980d4942009-11-09 19:22:17 +0000126 MayAlias = PSV->mayAlias(MFI);
Evan Chengff89dcb2009-10-18 18:16:27 +0000127 return V;
128 }
Dan Gohman3311a1f2009-01-30 02:49:14 +0000129
Evan Chengff89dcb2009-10-18 18:16:27 +0000130 if (isIdentifiedObject(V))
131 return V;
132
133 return 0;
Dan Gohman3311a1f2009-01-30 02:49:14 +0000134}
135
Andrew Trick918f38a2012-04-20 20:05:21 +0000136void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) {
137 BB = bb;
Andrew Tricke8deca82011-10-07 06:33:09 +0000138 LoopRegs.Deps.clear();
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000139 if (MachineLoop *ML = MLI.getLoopFor(BB))
Evan Cheng977679d2012-01-07 03:02:36 +0000140 if (BB == ML->getLoopLatch())
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000141 LoopRegs.VisitLoop(ML);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000142}
143
Andrew Trick953be892012-03-07 23:00:49 +0000144void ScheduleDAGInstrs::finishBlock() {
Andrew Tricka30444a2012-04-20 20:24:33 +0000145 // Subclasses should no longer refer to the old block.
Andrew Trick918f38a2012-04-20 20:05:21 +0000146 BB = 0;
Andrew Trick47c14452012-03-07 05:21:52 +0000147}
148
Andrew Trick702d4892012-02-24 07:04:55 +0000149/// Initialize the map with the number of registers.
Andrew Trick035ec402012-03-07 23:00:57 +0000150void Reg2SUnitsMap::setRegLimit(unsigned Limit) {
Andrew Trick702d4892012-02-24 07:04:55 +0000151 PhysRegSet.setUniverse(Limit);
152 SUnits.resize(Limit);
153}
154
155/// Clear the map without deallocating storage.
Andrew Trick035ec402012-03-07 23:00:57 +0000156void Reg2SUnitsMap::clear() {
Andrew Trick702d4892012-02-24 07:04:55 +0000157 for (const_iterator I = reg_begin(), E = reg_end(); I != E; ++I) {
158 SUnits[*I].clear();
159 }
160 PhysRegSet.clear();
161}
162
Andrew Trick47c14452012-03-07 05:21:52 +0000163/// Initialize the DAG and common scheduler state for the current scheduling
164/// region. This does not actually create the DAG, only clears it. The
165/// scheduling driver may call BuildSchedGraph multiple times per scheduling
166/// region.
167void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb,
168 MachineBasicBlock::iterator begin,
169 MachineBasicBlock::iterator end,
170 unsigned endcount) {
Andrew Trick918f38a2012-04-20 20:05:21 +0000171 assert(bb == BB && "startBlock should set BB");
Andrew Trick68675c62012-03-09 04:29:02 +0000172 RegionBegin = begin;
173 RegionEnd = end;
Andrew Trickcf46b5a2012-03-07 23:00:52 +0000174 EndIndex = endcount;
Andrew Trick17d35e52012-03-14 04:00:41 +0000175 MISUnitMap.clear();
Andrew Trick47c14452012-03-07 05:21:52 +0000176
177 // Check to see if the scheduler cares about latencies.
Andrew Trick953be892012-03-07 23:00:49 +0000178 UnitLatencies = forceUnitLatencies();
Andrew Trick47c14452012-03-07 05:21:52 +0000179
180 ScheduleDAG::clearDAG();
181}
182
183/// Close the current scheduling region. Don't clear any state in case the
184/// driver wants to refer to the previous scheduling region.
185void ScheduleDAGInstrs::exitRegion() {
186 // Nothing to do.
187}
188
Andrew Trick953be892012-03-07 23:00:49 +0000189/// addSchedBarrierDeps - Add dependencies from instructions in the current
Evan Chengec6906b2010-10-23 02:10:46 +0000190/// list of instructions being scheduled to scheduling barrier by adding
191/// the exit SU to the register defs and use list. This is because we want to
192/// make sure instructions which define registers that are either used by
193/// the terminator or are live-out are properly scheduled. This is
194/// especially important when the definition latency of the return value(s)
195/// are too high to be hidden by the branch or when the liveout registers
196/// used by instructions in the fallthrough block.
Andrew Trick953be892012-03-07 23:00:49 +0000197void ScheduleDAGInstrs::addSchedBarrierDeps() {
Andrew Trick68675c62012-03-09 04:29:02 +0000198 MachineInstr *ExitMI = RegionEnd != BB->end() ? &*RegionEnd : 0;
Evan Chengec6906b2010-10-23 02:10:46 +0000199 ExitSU.setInstr(ExitMI);
200 bool AllDepKnown = ExitMI &&
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000201 (ExitMI->isCall() || ExitMI->isBarrier());
Evan Chengec6906b2010-10-23 02:10:46 +0000202 if (ExitMI && AllDepKnown) {
203 // If it's a call or a barrier, add dependencies on the defs and uses of
204 // instruction.
205 for (unsigned i = 0, e = ExitMI->getNumOperands(); i != e; ++i) {
206 const MachineOperand &MO = ExitMI->getOperand(i);
207 if (!MO.isReg() || MO.isDef()) continue;
208 unsigned Reg = MO.getReg();
209 if (Reg == 0) continue;
210
Andrew Trick3c58ba82012-01-14 02:17:18 +0000211 if (TRI->isPhysicalRegister(Reg))
Andrew Trick702d4892012-02-24 07:04:55 +0000212 Uses[Reg].push_back(&ExitSU);
Andrew Trickd3a74862012-03-16 05:04:25 +0000213 else {
Andrew Trick3c58ba82012-01-14 02:17:18 +0000214 assert(!IsPostRA && "Virtual register encountered after regalloc.");
Andrew Trickd3a74862012-03-16 05:04:25 +0000215 addVRegUseDeps(&ExitSU, i);
216 }
Evan Chengec6906b2010-10-23 02:10:46 +0000217 }
218 } else {
219 // For others, e.g. fallthrough, conditional branch, assume the exit
Evan Chengde5fa932010-10-27 23:17:17 +0000220 // uses all the registers that are livein to the successor blocks.
Benjamin Kramera82d5262012-03-16 17:38:19 +0000221 assert(Uses.empty() && "Uses in set before adding deps?");
Evan Chengde5fa932010-10-27 23:17:17 +0000222 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
223 SE = BB->succ_end(); SI != SE; ++SI)
224 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
Andrew Trickf405b1a2011-05-05 19:24:06 +0000225 E = (*SI)->livein_end(); I != E; ++I) {
Evan Chengde5fa932010-10-27 23:17:17 +0000226 unsigned Reg = *I;
Benjamin Kramera82d5262012-03-16 17:38:19 +0000227 if (!Uses.contains(Reg))
Andrew Trick702d4892012-02-24 07:04:55 +0000228 Uses[Reg].push_back(&ExitSU);
Evan Chengde5fa932010-10-27 23:17:17 +0000229 }
Evan Chengec6906b2010-10-23 02:10:46 +0000230 }
231}
232
Andrew Trick81a682a2012-02-23 01:52:38 +0000233/// MO is an operand of SU's instruction that defines a physical register. Add
234/// data dependencies from SU to any uses of the physical register.
235void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU,
236 const MachineOperand &MO) {
237 assert(MO.isDef() && "expect physreg def");
238
239 // Ask the target if address-backscheduling is desirable, and if so how much.
240 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
241 unsigned SpecialAddressLatency = ST.getSpecialAddressLatency();
242 unsigned DataLatency = SU->Latency;
243
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000244 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
245 Alias.isValid(); ++Alias) {
Andrew Trick702d4892012-02-24 07:04:55 +0000246 if (!Uses.contains(*Alias))
Andrew Trick81a682a2012-02-23 01:52:38 +0000247 continue;
Andrew Trick702d4892012-02-24 07:04:55 +0000248 std::vector<SUnit*> &UseList = Uses[*Alias];
Andrew Trick81a682a2012-02-23 01:52:38 +0000249 for (unsigned i = 0, e = UseList.size(); i != e; ++i) {
250 SUnit *UseSU = UseList[i];
251 if (UseSU == SU)
252 continue;
253 unsigned LDataLatency = DataLatency;
254 // Optionally add in a special extra latency for nodes that
255 // feed addresses.
256 // TODO: Perhaps we should get rid of
257 // SpecialAddressLatency and just move this into
258 // adjustSchedDependency for the targets that care about it.
259 if (SpecialAddressLatency != 0 && !UnitLatencies &&
260 UseSU != &ExitSU) {
261 MachineInstr *UseMI = UseSU->getInstr();
262 const MCInstrDesc &UseMCID = UseMI->getDesc();
263 int RegUseIndex = UseMI->findRegisterUseOperandIdx(*Alias);
264 assert(RegUseIndex >= 0 && "UseMI doesn't use register!");
265 if (RegUseIndex >= 0 &&
266 (UseMI->mayLoad() || UseMI->mayStore()) &&
267 (unsigned)RegUseIndex < UseMCID.getNumOperands() &&
268 UseMCID.OpInfo[RegUseIndex].isLookupPtrRegClass())
269 LDataLatency += SpecialAddressLatency;
270 }
271 // Adjust the dependence latency using operand def/use
272 // information (if any), and then allow the target to
273 // perform its own adjustments.
274 const SDep& dep = SDep(SU, SDep::Data, LDataLatency, *Alias);
275 if (!UnitLatencies) {
Andrew Trick953be892012-03-07 23:00:49 +0000276 computeOperandLatency(SU, UseSU, const_cast<SDep &>(dep));
Andrew Trick81a682a2012-02-23 01:52:38 +0000277 ST.adjustSchedDependency(SU, UseSU, const_cast<SDep &>(dep));
278 }
279 UseSU->addPred(dep);
280 }
281 }
282}
283
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000284/// addPhysRegDeps - Add register dependencies (data, anti, and output) from
285/// this SUnit to following instructions in the same scheduling region that
286/// depend the physical register referenced at OperIdx.
287void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
288 const MachineInstr *MI = SU->getInstr();
289 const MachineOperand &MO = MI->getOperand(OperIdx);
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000290
291 // Optionally add output and anti dependencies. For anti
292 // dependencies we use a latency of 0 because for a multi-issue
293 // target we want to allow the defining instruction to issue
294 // in the same cycle as the using instruction.
295 // TODO: Using a latency of 1 here for output dependencies assumes
296 // there's no cost for reusing registers.
297 SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000298 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
299 Alias.isValid(); ++Alias) {
Andrew Trick702d4892012-02-24 07:04:55 +0000300 if (!Defs.contains(*Alias))
Andrew Trick81a682a2012-02-23 01:52:38 +0000301 continue;
Andrew Trick702d4892012-02-24 07:04:55 +0000302 std::vector<SUnit *> &DefList = Defs[*Alias];
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000303 for (unsigned i = 0, e = DefList.size(); i != e; ++i) {
304 SUnit *DefSU = DefList[i];
305 if (DefSU == &ExitSU)
306 continue;
307 if (DefSU != SU &&
308 (Kind != SDep::Output || !MO.isDead() ||
309 !DefSU->getInstr()->registerDefIsDead(*Alias))) {
310 if (Kind == SDep::Anti)
311 DefSU->addPred(SDep(SU, Kind, 0, /*Reg=*/*Alias));
312 else {
313 unsigned AOLat = TII->getOutputLatency(InstrItins, MI, OperIdx,
314 DefSU->getInstr());
315 DefSU->addPred(SDep(SU, Kind, AOLat, /*Reg=*/*Alias));
316 }
317 }
318 }
319 }
320
Andrew Trick81a682a2012-02-23 01:52:38 +0000321 if (!MO.isDef()) {
322 // 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.
Andrew Trick702d4892012-02-24 07:04:55 +0000325 Uses[MO.getReg()].push_back(SU);
Andrew Trick81a682a2012-02-23 01:52:38 +0000326 }
327 else {
328 addPhysRegDataDeps(SU, MO);
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000329
Andrew Trick81a682a2012-02-23 01:52:38 +0000330 // Either insert a new Reg2SUnits entry with an empty SUnits list, or
331 // retrieve the existing SUnits list for this register's defs.
Andrew Trick702d4892012-02-24 07:04:55 +0000332 std::vector<SUnit *> &DefList = Defs[MO.getReg()];
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000333
334 // If a def is going to wrap back around to the top of the loop,
335 // backschedule it.
336 if (!UnitLatencies && DefList.empty()) {
Andrew Trick81a682a2012-02-23 01:52:38 +0000337 LoopDependencies::LoopDeps::iterator I = LoopRegs.Deps.find(MO.getReg());
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000338 if (I != LoopRegs.Deps.end()) {
339 const MachineOperand *UseMO = I->second.first;
340 unsigned Count = I->second.second;
341 const MachineInstr *UseMI = UseMO->getParent();
342 unsigned UseMOIdx = UseMO - &UseMI->getOperand(0);
343 const MCInstrDesc &UseMCID = UseMI->getDesc();
Andrew Trick81a682a2012-02-23 01:52:38 +0000344 const TargetSubtargetInfo &ST =
345 TM.getSubtarget<TargetSubtargetInfo>();
346 unsigned SpecialAddressLatency = ST.getSpecialAddressLatency();
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000347 // TODO: If we knew the total depth of the region here, we could
348 // handle the case where the whole loop is inside the region but
349 // is large enough that the isScheduleHigh trick isn't needed.
350 if (UseMOIdx < UseMCID.getNumOperands()) {
351 // Currently, we only support scheduling regions consisting of
352 // single basic blocks. Check to see if the instruction is in
353 // the same region by checking to see if it has the same parent.
354 if (UseMI->getParent() != MI->getParent()) {
355 unsigned Latency = SU->Latency;
356 if (UseMCID.OpInfo[UseMOIdx].isLookupPtrRegClass())
357 Latency += SpecialAddressLatency;
358 // This is a wild guess as to the portion of the latency which
359 // will be overlapped by work done outside the current
360 // scheduling region.
361 Latency -= std::min(Latency, Count);
362 // Add the artificial edge.
363 ExitSU.addPred(SDep(SU, SDep::Order, Latency,
364 /*Reg=*/0, /*isNormalMemory=*/false,
365 /*isMustAlias=*/false,
366 /*isArtificial=*/true));
367 } else if (SpecialAddressLatency > 0 &&
368 UseMCID.OpInfo[UseMOIdx].isLookupPtrRegClass()) {
369 // The entire loop body is within the current scheduling region
370 // and the latency of this operation is assumed to be greater
371 // than the latency of the loop.
372 // TODO: Recursively mark data-edge predecessors as
373 // isScheduleHigh too.
374 SU->isScheduleHigh = true;
375 }
376 }
377 LoopRegs.Deps.erase(I);
378 }
379 }
380
Andrew Trick81a682a2012-02-23 01:52:38 +0000381 // clear this register's use list
Andrew Trick702d4892012-02-24 07:04:55 +0000382 if (Uses.contains(MO.getReg()))
383 Uses[MO.getReg()].clear();
Andrew Trick81a682a2012-02-23 01:52:38 +0000384
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000385 if (!MO.isDead())
386 DefList.clear();
387
388 // Calls will not be reordered because of chain dependencies (see
389 // below). Since call operands are dead, calls may continue to be added
390 // to the DefList making dependence checking quadratic in the size of
391 // the block. Instead, we leave only one call at the back of the
392 // DefList.
393 if (SU->isCall) {
394 while (!DefList.empty() && DefList.back()->isCall)
395 DefList.pop_back();
396 }
Andrew Trick81a682a2012-02-23 01:52:38 +0000397 // Defs are pushed in the order they are visited and never reordered.
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000398 DefList.push_back(SU);
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000399 }
400}
401
Andrew Trick3c58ba82012-01-14 02:17:18 +0000402/// addVRegDefDeps - Add register output and data dependencies from this SUnit
403/// to instructions that occur later in the same scheduling region if they read
404/// from or write to the virtual register defined at OperIdx.
405///
406/// TODO: Hoist loop induction variable increments. This has to be
407/// reevaluated. Generally, IV scheduling should be done before coalescing.
408void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
409 const MachineInstr *MI = SU->getInstr();
410 unsigned Reg = MI->getOperand(OperIdx).getReg();
411
Andrew Trickcc77b542012-02-22 06:08:13 +0000412 // SSA defs do not have output/anti dependencies.
Andrew Trick2fc09772012-02-22 18:34:49 +0000413 // The current operand is a def, so we have at least one.
Andrew Trickcc77b542012-02-22 06:08:13 +0000414 if (llvm::next(MRI.def_begin(Reg)) == MRI.def_end())
415 return;
416
Andrew Trick3c58ba82012-01-14 02:17:18 +0000417 // Add output dependence to the next nearest def of this vreg.
418 //
419 // Unless this definition is dead, the output dependence should be
420 // transitively redundant with antidependencies from this definition's
421 // uses. We're conservative for now until we have a way to guarantee the uses
422 // are not eliminated sometime during scheduling. The output dependence edge
423 // is also useful if output latency exceeds def-use latency.
Andrew Trickc0ccb8b2012-04-20 20:05:28 +0000424 VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
Andrew Trick8ae3ac72012-02-22 21:59:00 +0000425 if (DefI == VRegDefs.end())
426 VRegDefs.insert(VReg2SUnit(Reg, SU));
427 else {
428 SUnit *DefSU = DefI->SU;
429 if (DefSU != SU && DefSU != &ExitSU) {
430 unsigned OutLatency = TII->getOutputLatency(InstrItins, MI, OperIdx,
431 DefSU->getInstr());
432 DefSU->addPred(SDep(SU, SDep::Output, OutLatency, Reg));
433 }
434 DefI->SU = SU;
Andrew Trick3c58ba82012-01-14 02:17:18 +0000435 }
Andrew Trick3c58ba82012-01-14 02:17:18 +0000436}
437
Andrew Trickb4566a92012-02-22 06:08:11 +0000438/// addVRegUseDeps - Add a register data dependency if the instruction that
439/// defines the virtual register used at OperIdx is mapped to an SUnit. Add a
440/// register antidependency from this SUnit to instructions that occur later in
441/// the same scheduling region if they write the virtual register.
442///
443/// TODO: Handle ExitSU "uses" properly.
Andrew Trick3c58ba82012-01-14 02:17:18 +0000444void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
Andrew Trickb4566a92012-02-22 06:08:11 +0000445 MachineInstr *MI = SU->getInstr();
446 unsigned Reg = MI->getOperand(OperIdx).getReg();
447
448 // Lookup this operand's reaching definition.
449 assert(LIS && "vreg dependencies requires LiveIntervals");
Jakob Stoklund Olesen93e29ce2012-05-20 02:44:38 +0000450 LiveRangeQuery LRQ(LIS->getInterval(Reg), LIS->getInstructionIndex(MI));
451 VNInfo *VNI = LRQ.valueIn();
Andrew Trickc3ad8852012-04-24 18:04:41 +0000452
Andrew Trick63d578b2012-02-23 03:16:24 +0000453 // VNI will be valid because MachineOperand::readsReg() is checked by caller.
Jakob Stoklund Olesen93e29ce2012-05-20 02:44:38 +0000454 assert(VNI && "No value to read by operand");
Andrew Trickb4566a92012-02-22 06:08:11 +0000455 MachineInstr *Def = LIS->getInstructionFromIndex(VNI->def);
Andrew Trick63d578b2012-02-23 03:16:24 +0000456 // Phis and other noninstructions (after coalescing) have a NULL Def.
Andrew Trickb4566a92012-02-22 06:08:11 +0000457 if (Def) {
458 SUnit *DefSU = getSUnit(Def);
459 if (DefSU) {
460 // The reaching Def lives within this scheduling region.
461 // Create a data dependence.
462 //
463 // TODO: Handle "special" address latencies cleanly.
464 const SDep &dep = SDep(DefSU, SDep::Data, DefSU->Latency, Reg);
465 if (!UnitLatencies) {
466 // Adjust the dependence latency using operand def/use information, then
467 // allow the target to perform its own adjustments.
Andrew Trick953be892012-03-07 23:00:49 +0000468 computeOperandLatency(DefSU, SU, const_cast<SDep &>(dep));
Andrew Trickb4566a92012-02-22 06:08:11 +0000469 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
470 ST.adjustSchedDependency(DefSU, SU, const_cast<SDep &>(dep));
471 }
472 SU->addPred(dep);
473 }
474 }
Andrew Trick3c58ba82012-01-14 02:17:18 +0000475
476 // Add antidependence to the following def of the vreg it uses.
Andrew Trickc0ccb8b2012-04-20 20:05:28 +0000477 VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
Andrew Trick8ae3ac72012-02-22 21:59:00 +0000478 if (DefI != VRegDefs.end() && DefI->SU != SU)
479 DefI->SU->addPred(SDep(SU, SDep::Anti, 0, Reg));
Andrew Trickb4566a92012-02-22 06:08:11 +0000480}
Andrew Trick3c58ba82012-01-14 02:17:18 +0000481
Andrew Trickeb05b972012-05-15 18:59:41 +0000482/// Return true if MI is an instruction we are unable to reason about
483/// (like a call or something with unmodeled side effects).
484static inline bool isGlobalMemoryObject(AliasAnalysis *AA, MachineInstr *MI) {
485 if (MI->isCall() || MI->hasUnmodeledSideEffects() ||
486 (MI->hasVolatileMemoryRef() &&
487 (!MI->mayLoad() || !MI->isInvariantLoad(AA))))
488 return true;
489 return false;
490}
491
492// This MI might have either incomplete info, or known to be unsafe
493// to deal with (i.e. volatile object).
494static inline bool isUnsafeMemoryObject(MachineInstr *MI,
495 const MachineFrameInfo *MFI) {
496 if (!MI || MI->memoperands_empty())
497 return true;
498 // We purposefully do no check for hasOneMemOperand() here
499 // in hope to trigger an assert downstream in order to
500 // finish implementation.
501 if ((*MI->memoperands_begin())->isVolatile() ||
502 MI->hasUnmodeledSideEffects())
503 return true;
504
505 const Value *V = (*MI->memoperands_begin())->getValue();
506 if (!V)
507 return true;
508
509 V = getUnderlyingObject(V);
510 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
511 // Similarly to getUnderlyingObjectForInstr:
512 // For now, ignore PseudoSourceValues which may alias LLVM IR values
513 // because the code that uses this function has no way to cope with
514 // such aliases.
515 if (PSV->isAliased(MFI))
516 return true;
517 }
518 // Does this pointer refer to a distinct and identifiable object?
519 if (!isIdentifiedObject(V))
520 return true;
521
522 return false;
523}
524
525/// This returns true if the two MIs need a chain edge betwee them.
526/// If these are not even memory operations, we still may need
527/// chain deps between them. The question really is - could
528/// these two MIs be reordered during scheduling from memory dependency
529/// point of view.
530static bool MIsNeedChainEdge(AliasAnalysis *AA, const MachineFrameInfo *MFI,
531 MachineInstr *MIa,
532 MachineInstr *MIb) {
533 // Cover a trivial case - no edge is need to itself.
534 if (MIa == MIb)
535 return false;
536
537 if (isUnsafeMemoryObject(MIa, MFI) || isUnsafeMemoryObject(MIb, MFI))
538 return true;
539
540 // If we are dealing with two "normal" loads, we do not need an edge
541 // between them - they could be reordered.
542 if (!MIa->mayStore() && !MIb->mayStore())
543 return false;
544
545 // To this point analysis is generic. From here on we do need AA.
546 if (!AA)
547 return true;
548
549 MachineMemOperand *MMOa = *MIa->memoperands_begin();
550 MachineMemOperand *MMOb = *MIb->memoperands_begin();
551
552 // FIXME: Need to handle multiple memory operands to support all targets.
553 if (!MIa->hasOneMemOperand() || !MIb->hasOneMemOperand())
554 llvm_unreachable("Multiple memory operands.");
555
556 // The following interface to AA is fashioned after DAGCombiner::isAlias
557 // and operates with MachineMemOperand offset with some important
558 // assumptions:
559 // - LLVM fundamentally assumes flat address spaces.
560 // - MachineOperand offset can *only* result from legalization and
561 // cannot affect queries other than the trivial case of overlap
562 // checking.
563 // - These offsets never wrap and never step outside
564 // of allocated objects.
565 // - There should never be any negative offsets here.
566 //
567 // FIXME: Modify API to hide this math from "user"
568 // FIXME: Even before we go to AA we can reason locally about some
569 // memory objects. It can save compile time, and possibly catch some
570 // corner cases not currently covered.
571
572 assert ((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset");
573 assert ((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset");
574
575 int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset());
576 int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset;
577 int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset;
578
579 AliasAnalysis::AliasResult AAResult = AA->alias(
580 AliasAnalysis::Location(MMOa->getValue(), Overlapa,
581 MMOa->getTBAAInfo()),
582 AliasAnalysis::Location(MMOb->getValue(), Overlapb,
583 MMOb->getTBAAInfo()));
584
585 return (AAResult != AliasAnalysis::NoAlias);
586}
587
588/// This recursive function iterates over chain deps of SUb looking for
589/// "latest" node that needs a chain edge to SUa.
590static unsigned
591iterateChainSucc(AliasAnalysis *AA, const MachineFrameInfo *MFI,
592 SUnit *SUa, SUnit *SUb, SUnit *ExitSU, unsigned *Depth,
593 SmallPtrSet<const SUnit*, 16> &Visited) {
594 if (!SUa || !SUb || SUb == ExitSU)
595 return *Depth;
596
597 // Remember visited nodes.
598 if (!Visited.insert(SUb))
599 return *Depth;
600 // If there is _some_ dependency already in place, do not
601 // descend any further.
602 // TODO: Need to make sure that if that dependency got eliminated or ignored
603 // for any reason in the future, we would not violate DAG topology.
604 // Currently it does not happen, but makes an implicit assumption about
605 // future implementation.
606 //
607 // Independently, if we encounter node that is some sort of global
608 // object (like a call) we already have full set of dependencies to it
609 // and we can stop descending.
610 if (SUa->isSucc(SUb) ||
611 isGlobalMemoryObject(AA, SUb->getInstr()))
612 return *Depth;
613
614 // If we do need an edge, or we have exceeded depth budget,
615 // add that edge to the predecessors chain of SUb,
616 // and stop descending.
617 if (*Depth > 200 ||
618 MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) {
619 SUb->addPred(SDep(SUa, SDep::Order, /*Latency=*/0, /*Reg=*/0,
620 /*isNormalMemory=*/true));
621 return *Depth;
622 }
623 // Track current depth.
624 (*Depth)++;
625 // Iterate over chain dependencies only.
626 for (SUnit::const_succ_iterator I = SUb->Succs.begin(), E = SUb->Succs.end();
627 I != E; ++I)
628 if (I->isCtrl())
629 iterateChainSucc (AA, MFI, SUa, I->getSUnit(), ExitSU, Depth, Visited);
630 return *Depth;
631}
632
633/// This function assumes that "downward" from SU there exist
634/// tail/leaf of already constructed DAG. It iterates downward and
635/// checks whether SU can be aliasing any node dominated
636/// by it.
637static void adjustChainDeps(AliasAnalysis *AA, const MachineFrameInfo *MFI,
638 SUnit *SU, SUnit *ExitSU, std::set<SUnit *> &CheckList) {
639 if (!SU)
640 return;
641
642 SmallPtrSet<const SUnit*, 16> Visited;
643 unsigned Depth = 0;
644
645 for (std::set<SUnit *>::iterator I = CheckList.begin(), IE = CheckList.end();
646 I != IE; ++I) {
647 if (SU == *I)
648 continue;
649 if (MIsNeedChainEdge(AA, MFI, SU->getInstr(), (*I)->getInstr()))
650 (*I)->addPred(SDep(SU, SDep::Order, /*Latency=*/0, /*Reg=*/0,
651 /*isNormalMemory=*/true));
652 // Now go through all the chain successors and iterate from them.
653 // Keep track of visited nodes.
654 for (SUnit::const_succ_iterator J = (*I)->Succs.begin(),
655 JE = (*I)->Succs.end(); J != JE; ++J)
656 if (J->isCtrl())
657 iterateChainSucc (AA, MFI, SU, J->getSUnit(),
658 ExitSU, &Depth, Visited);
659 }
660}
661
662/// Check whether two objects need a chain edge, if so, add it
663/// otherwise remember the rejected SU.
664static inline
665void addChainDependency (AliasAnalysis *AA, const MachineFrameInfo *MFI,
666 SUnit *SUa, SUnit *SUb,
667 std::set<SUnit *> &RejectList,
668 unsigned TrueMemOrderLatency = 0,
669 bool isNormalMemory = false) {
670 // If this is a false dependency,
671 // do not add the edge, but rememeber the rejected node.
672 if (!EnableAASchedMI ||
673 MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr()))
674 SUb->addPred(SDep(SUa, SDep::Order, TrueMemOrderLatency, /*Reg=*/0,
675 isNormalMemory));
676 else {
677 // Duplicate entries should be ignored.
678 RejectList.insert(SUb);
679 DEBUG(dbgs() << "\tReject chain dep between SU("
680 << SUa->NodeNum << ") and SU("
681 << SUb->NodeNum << ")\n");
682 }
683}
684
Andrew Trickb4566a92012-02-22 06:08:11 +0000685/// Create an SUnit for each real instruction, numbered in top-down toplological
686/// order. The instruction order A < B, implies that no edge exists from B to A.
687///
688/// Map each real instruction to its SUnit.
689///
Andrew Trick17d35e52012-03-14 04:00:41 +0000690/// After initSUnits, the SUnits vector cannot be resized and the scheduler may
691/// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
692/// instead of pointers.
693///
694/// MachineScheduler relies on initSUnits numbering the nodes by their order in
695/// the original instruction list.
Andrew Trickb4566a92012-02-22 06:08:11 +0000696void ScheduleDAGInstrs::initSUnits() {
697 // We'll be allocating one SUnit for each real instruction in the region,
698 // which is contained within a basic block.
699 SUnits.reserve(BB->size());
700
Andrew Trick68675c62012-03-09 04:29:02 +0000701 for (MachineBasicBlock::iterator I = RegionBegin; I != RegionEnd; ++I) {
Andrew Trickb4566a92012-02-22 06:08:11 +0000702 MachineInstr *MI = I;
703 if (MI->isDebugValue())
704 continue;
705
Andrew Trick953be892012-03-07 23:00:49 +0000706 SUnit *SU = newSUnit(MI);
Andrew Trickb4566a92012-02-22 06:08:11 +0000707 MISUnitMap[MI] = SU;
708
709 SU->isCall = MI->isCall();
710 SU->isCommutable = MI->isCommutable();
711
712 // Assign the Latency field of SU using target-provided information.
713 if (UnitLatencies)
714 SU->Latency = 1;
715 else
Andrew Trick953be892012-03-07 23:00:49 +0000716 computeLatency(SU);
Andrew Trickb4566a92012-02-22 06:08:11 +0000717 }
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000718}
719
Andrew Trick006e1ab2012-04-24 17:56:43 +0000720/// If RegPressure is non null, compute register pressure as a side effect. The
721/// DAG builder is an efficient place to do it because it already visits
722/// operands.
723void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA,
724 RegPressureTracker *RPTracker) {
Andrew Trickb4566a92012-02-22 06:08:11 +0000725 // Create an SUnit for each real instruction.
726 initSUnits();
Dan Gohman343f0c02008-11-19 23:18:57 +0000727
Dan Gohman6a9041e2008-12-04 01:35:46 +0000728 // We build scheduling units by walking a block's instruction list from bottom
729 // to top.
730
David Goodwin980d4942009-11-09 19:22:17 +0000731 // Remember where a generic side-effecting instruction is as we procede.
732 SUnit *BarrierChain = 0, *AliasChain = 0;
Dan Gohman6a9041e2008-12-04 01:35:46 +0000733
David Goodwin980d4942009-11-09 19:22:17 +0000734 // Memory references to specific known memory locations are tracked
735 // so that they can be given more precise dependencies. We track
736 // separately the known memory locations that may alias and those
737 // that are known not to alias
738 std::map<const Value *, SUnit *> AliasMemDefs, NonAliasMemDefs;
739 std::map<const Value *, std::vector<SUnit *> > AliasMemUses, NonAliasMemUses;
Andrew Trickeb05b972012-05-15 18:59:41 +0000740 std::set<SUnit*> RejectMemNodes;
Dan Gohman6a9041e2008-12-04 01:35:46 +0000741
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000742 // Remove any stale debug info; sometimes BuildSchedGraph is called again
743 // without emitting the info from the previous call.
Devang Patelcf4cc842011-06-02 20:07:12 +0000744 DbgValues.clear();
745 FirstDbgValue = NULL;
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000746
Andrew Trick81a682a2012-02-23 01:52:38 +0000747 assert(Defs.empty() && Uses.empty() &&
748 "Only BuildGraph should update Defs/Uses");
Andrew Trick702d4892012-02-24 07:04:55 +0000749 Defs.setRegLimit(TRI->getNumRegs());
750 Uses.setRegLimit(TRI->getNumRegs());
Andrew Trick9b668532011-05-06 21:52:52 +0000751
Andrew Trick8ae3ac72012-02-22 21:59:00 +0000752 assert(VRegDefs.empty() && "Only BuildSchedGraph may access VRegDefs");
753 // FIXME: Allow SparseSet to reserve space for the creation of virtual
754 // registers during scheduling. Don't artificially inflate the Universe
755 // because we want to assert that vregs are not created during DAG building.
756 VRegDefs.setUniverse(MRI.getNumVirtRegs());
Andrew Trick3c58ba82012-01-14 02:17:18 +0000757
Andrew Trick81a682a2012-02-23 01:52:38 +0000758 // Model data dependencies between instructions being scheduled and the
759 // ExitSU.
Andrew Trick953be892012-03-07 23:00:49 +0000760 addSchedBarrierDeps();
Andrew Trick81a682a2012-02-23 01:52:38 +0000761
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000762 // Walk the list of instructions, from bottom moving up.
Devang Patelcf4cc842011-06-02 20:07:12 +0000763 MachineInstr *PrevMI = NULL;
Andrew Trick68675c62012-03-09 04:29:02 +0000764 for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
Dan Gohman343f0c02008-11-19 23:18:57 +0000765 MII != MIE; --MII) {
766 MachineInstr *MI = prior(MII);
Devang Patelcf4cc842011-06-02 20:07:12 +0000767 if (MI && PrevMI) {
768 DbgValues.push_back(std::make_pair(PrevMI, MI));
769 PrevMI = NULL;
770 }
771
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000772 if (MI->isDebugValue()) {
Devang Patelcf4cc842011-06-02 20:07:12 +0000773 PrevMI = MI;
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000774 continue;
775 }
Andrew Trick006e1ab2012-04-24 17:56:43 +0000776 if (RPTracker) {
777 RPTracker->recede();
778 assert(RPTracker->getPos() == prior(MII) && "RPTracker can't find MI");
779 }
Devang Patelcf4cc842011-06-02 20:07:12 +0000780
Andrew Trick00707922012-04-13 23:29:54 +0000781 assert((!MI->isTerminator() || CanHandleTerminators) && !MI->isLabel() &&
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000782 "Cannot schedule terminators or labels!");
Dan Gohman343f0c02008-11-19 23:18:57 +0000783
Andrew Trickb4566a92012-02-22 06:08:11 +0000784 SUnit *SU = MISUnitMap[MI];
785 assert(SU && "No SUnit mapped to this MI");
Dan Gohman54e4c362008-12-09 22:54:47 +0000786
Dan Gohman6a9041e2008-12-04 01:35:46 +0000787 // Add register-based dependencies (data, anti, and output).
Dan Gohman343f0c02008-11-19 23:18:57 +0000788 for (unsigned j = 0, n = MI->getNumOperands(); j != n; ++j) {
789 const MachineOperand &MO = MI->getOperand(j);
790 if (!MO.isReg()) continue;
791 unsigned Reg = MO.getReg();
792 if (Reg == 0) continue;
793
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000794 if (TRI->isPhysicalRegister(Reg))
795 addPhysRegDeps(SU, j);
796 else {
797 assert(!IsPostRA && "Virtual register encountered!");
Andrew Trick3c58ba82012-01-14 02:17:18 +0000798 if (MO.isDef())
799 addVRegDefDeps(SU, j);
Andrew Trick63d578b2012-02-23 03:16:24 +0000800 else if (MO.readsReg()) // ignore undef operands
Andrew Trick3c58ba82012-01-14 02:17:18 +0000801 addVRegUseDeps(SU, j);
Dan Gohman343f0c02008-11-19 23:18:57 +0000802 }
803 }
Dan Gohman6a9041e2008-12-04 01:35:46 +0000804
805 // Add chain dependencies.
David Goodwin7c9b1ac2009-11-02 17:06:28 +0000806 // Chain dependencies used to enforce memory order should have
807 // latency of 0 (except for true dependency of Store followed by
808 // aliased Load... we estimate that with a single cycle of latency
809 // assuming the hardware will bypass)
Dan Gohman6a9041e2008-12-04 01:35:46 +0000810 // Note that isStoreToStackSlot and isLoadFromStackSLot are not usable
811 // after stack slots are lowered to actual addresses.
812 // TODO: Use an AliasAnalysis and do real alias-analysis queries, and
813 // produce more precise dependence information.
David Goodwin7c9b1ac2009-11-02 17:06:28 +0000814#define STORE_LOAD_LATENCY 1
815 unsigned TrueMemOrderLatency = 0;
Andrew Trickeb05b972012-05-15 18:59:41 +0000816 if (isGlobalMemoryObject(AA, MI)) {
David Goodwin980d4942009-11-09 19:22:17 +0000817 // Be conservative with these and add dependencies on all memory
818 // references, even those that are known to not alias.
Andrew Trickf405b1a2011-05-05 19:24:06 +0000819 for (std::map<const Value *, SUnit *>::iterator I =
David Goodwin980d4942009-11-09 19:22:17 +0000820 NonAliasMemDefs.begin(), E = NonAliasMemDefs.end(); I != E; ++I) {
David Goodwin7c9b1ac2009-11-02 17:06:28 +0000821 I->second->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
Dan Gohman6a9041e2008-12-04 01:35:46 +0000822 }
823 for (std::map<const Value *, std::vector<SUnit *> >::iterator I =
David Goodwin980d4942009-11-09 19:22:17 +0000824 NonAliasMemUses.begin(), E = NonAliasMemUses.end(); I != E; ++I) {
Dan Gohman6a9041e2008-12-04 01:35:46 +0000825 for (unsigned i = 0, e = I->second.size(); i != e; ++i)
David Goodwin7c9b1ac2009-11-02 17:06:28 +0000826 I->second[i]->addPred(SDep(SU, SDep::Order, TrueMemOrderLatency));
Dan Gohman6a9041e2008-12-04 01:35:46 +0000827 }
David Goodwin980d4942009-11-09 19:22:17 +0000828 // Add SU to the barrier chain.
829 if (BarrierChain)
830 BarrierChain->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
831 BarrierChain = SU;
Andrew Trickeb05b972012-05-15 18:59:41 +0000832 // This is a barrier event that acts as a pivotal node in the DAG,
833 // so it is safe to clear list of exposed nodes.
834 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes);
835 RejectMemNodes.clear();
836 NonAliasMemDefs.clear();
837 NonAliasMemUses.clear();
David Goodwin980d4942009-11-09 19:22:17 +0000838
839 // fall-through
840 new_alias_chain:
841 // Chain all possibly aliasing memory references though SU.
842 if (AliasChain)
Andrew Trickeb05b972012-05-15 18:59:41 +0000843 addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes);
David Goodwin980d4942009-11-09 19:22:17 +0000844 AliasChain = SU;
845 for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
Andrew Trickeb05b972012-05-15 18:59:41 +0000846 addChainDependency(AA, MFI, SU, PendingLoads[k], RejectMemNodes,
847 TrueMemOrderLatency);
David Goodwin980d4942009-11-09 19:22:17 +0000848 for (std::map<const Value *, SUnit *>::iterator I = AliasMemDefs.begin(),
Andrew Trickeb05b972012-05-15 18:59:41 +0000849 E = AliasMemDefs.end(); I != E; ++I)
850 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes);
David Goodwin980d4942009-11-09 19:22:17 +0000851 for (std::map<const Value *, std::vector<SUnit *> >::iterator I =
852 AliasMemUses.begin(), E = AliasMemUses.end(); I != E; ++I) {
853 for (unsigned i = 0, e = I->second.size(); i != e; ++i)
Andrew Trickeb05b972012-05-15 18:59:41 +0000854 addChainDependency(AA, MFI, SU, I->second[i], RejectMemNodes,
855 TrueMemOrderLatency);
David Goodwin980d4942009-11-09 19:22:17 +0000856 }
Andrew Trickeb05b972012-05-15 18:59:41 +0000857 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes);
David Goodwin980d4942009-11-09 19:22:17 +0000858 PendingLoads.clear();
859 AliasMemDefs.clear();
860 AliasMemUses.clear();
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000861 } else if (MI->mayStore()) {
David Goodwina9e61072009-11-03 20:15:00 +0000862 bool MayAlias = true;
David Goodwin7c9b1ac2009-11-02 17:06:28 +0000863 TrueMemOrderLatency = STORE_LOAD_LATENCY;
David Goodwina9e61072009-11-03 20:15:00 +0000864 if (const Value *V = getUnderlyingObjectForInstr(MI, MFI, MayAlias)) {
Dan Gohman6a9041e2008-12-04 01:35:46 +0000865 // A store to a specific PseudoSourceValue. Add precise dependencies.
David Goodwin980d4942009-11-09 19:22:17 +0000866 // Record the def in MemDefs, first adding a dep if there is
867 // an existing def.
Andrew Trickf405b1a2011-05-05 19:24:06 +0000868 std::map<const Value *, SUnit *>::iterator I =
David Goodwin980d4942009-11-09 19:22:17 +0000869 ((MayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
Andrew Trickf405b1a2011-05-05 19:24:06 +0000870 std::map<const Value *, SUnit *>::iterator IE =
David Goodwin980d4942009-11-09 19:22:17 +0000871 ((MayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
872 if (I != IE) {
Andrew Trickeb05b972012-05-15 18:59:41 +0000873 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes,
874 0, true);
Dan Gohman6a9041e2008-12-04 01:35:46 +0000875 I->second = SU;
876 } else {
David Goodwin980d4942009-11-09 19:22:17 +0000877 if (MayAlias)
878 AliasMemDefs[V] = SU;
879 else
880 NonAliasMemDefs[V] = SU;
Dan Gohman6a9041e2008-12-04 01:35:46 +0000881 }
882 // Handle the uses in MemUses, if there are any.
Dan Gohmana629b482008-12-08 17:50:35 +0000883 std::map<const Value *, std::vector<SUnit *> >::iterator J =
David Goodwin980d4942009-11-09 19:22:17 +0000884 ((MayAlias) ? AliasMemUses.find(V) : NonAliasMemUses.find(V));
885 std::map<const Value *, std::vector<SUnit *> >::iterator JE =
886 ((MayAlias) ? AliasMemUses.end() : NonAliasMemUses.end());
887 if (J != JE) {
Dan Gohman6a9041e2008-12-04 01:35:46 +0000888 for (unsigned i = 0, e = J->second.size(); i != e; ++i)
Andrew Trickeb05b972012-05-15 18:59:41 +0000889 addChainDependency(AA, MFI, SU, J->second[i], RejectMemNodes,
890 TrueMemOrderLatency, true);
Dan Gohman6a9041e2008-12-04 01:35:46 +0000891 J->second.clear();
892 }
David Goodwina9e61072009-11-03 20:15:00 +0000893 if (MayAlias) {
David Goodwin980d4942009-11-09 19:22:17 +0000894 // Add dependencies from all the PendingLoads, i.e. loads
895 // with no underlying object.
David Goodwina9e61072009-11-03 20:15:00 +0000896 for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
Andrew Trickeb05b972012-05-15 18:59:41 +0000897 addChainDependency(AA, MFI, SU, PendingLoads[k], RejectMemNodes,
898 TrueMemOrderLatency);
David Goodwin980d4942009-11-09 19:22:17 +0000899 // Add dependence on alias chain, if needed.
900 if (AliasChain)
Andrew Trickeb05b972012-05-15 18:59:41 +0000901 addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes);
902 // But we also should check dependent instructions for the
903 // SU in question.
904 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes);
David Goodwina9e61072009-11-03 20:15:00 +0000905 }
David Goodwin980d4942009-11-09 19:22:17 +0000906 // Add dependence on barrier chain, if needed.
Andrew Trickeb05b972012-05-15 18:59:41 +0000907 // There is no point to check aliasing on barrier event. Even if
908 // SU and barrier _could_ be reordered, they should not. In addition,
909 // we have lost all RejectMemNodes below barrier.
David Goodwin980d4942009-11-09 19:22:17 +0000910 if (BarrierChain)
911 BarrierChain->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
David Goodwin5be870a2009-11-05 00:16:44 +0000912 } else {
Dan Gohman6a9041e2008-12-04 01:35:46 +0000913 // Treat all other stores conservatively.
David Goodwin980d4942009-11-09 19:22:17 +0000914 goto new_alias_chain;
David Goodwin7c9b1ac2009-11-02 17:06:28 +0000915 }
Evan Chengec6906b2010-10-23 02:10:46 +0000916
917 if (!ExitSU.isPred(SU))
918 // Push store's up a bit to avoid them getting in between cmp
919 // and branches.
920 ExitSU.addPred(SDep(SU, SDep::Order, 0,
921 /*Reg=*/0, /*isNormalMemory=*/false,
922 /*isMustAlias=*/false,
923 /*isArtificial=*/true));
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000924 } else if (MI->mayLoad()) {
David Goodwina9e61072009-11-03 20:15:00 +0000925 bool MayAlias = true;
David Goodwin7c9b1ac2009-11-02 17:06:28 +0000926 TrueMemOrderLatency = 0;
Dan Gohmana70dca12009-10-09 23:27:56 +0000927 if (MI->isInvariantLoad(AA)) {
Dan Gohman6a9041e2008-12-04 01:35:46 +0000928 // Invariant load, no chain dependencies needed!
David Goodwin5be870a2009-11-05 00:16:44 +0000929 } else {
Andrew Trickf405b1a2011-05-05 19:24:06 +0000930 if (const Value *V =
David Goodwin980d4942009-11-09 19:22:17 +0000931 getUnderlyingObjectForInstr(MI, MFI, MayAlias)) {
932 // A load from a specific PseudoSourceValue. Add precise dependencies.
Andrew Trickf405b1a2011-05-05 19:24:06 +0000933 std::map<const Value *, SUnit *>::iterator I =
David Goodwin980d4942009-11-09 19:22:17 +0000934 ((MayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
Andrew Trickf405b1a2011-05-05 19:24:06 +0000935 std::map<const Value *, SUnit *>::iterator IE =
David Goodwin980d4942009-11-09 19:22:17 +0000936 ((MayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
937 if (I != IE)
Andrew Trickeb05b972012-05-15 18:59:41 +0000938 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes, 0, true);
David Goodwin980d4942009-11-09 19:22:17 +0000939 if (MayAlias)
940 AliasMemUses[V].push_back(SU);
Andrew Trickf405b1a2011-05-05 19:24:06 +0000941 else
David Goodwin980d4942009-11-09 19:22:17 +0000942 NonAliasMemUses[V].push_back(SU);
943 } else {
944 // A load with no underlying object. Depend on all
945 // potentially aliasing stores.
Andrew Trickf405b1a2011-05-05 19:24:06 +0000946 for (std::map<const Value *, SUnit *>::iterator I =
David Goodwin980d4942009-11-09 19:22:17 +0000947 AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I)
Andrew Trickeb05b972012-05-15 18:59:41 +0000948 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes);
Andrew Trickf405b1a2011-05-05 19:24:06 +0000949
David Goodwin980d4942009-11-09 19:22:17 +0000950 PendingLoads.push_back(SU);
951 MayAlias = true;
David Goodwina9e61072009-11-03 20:15:00 +0000952 }
Andrew Trickeb05b972012-05-15 18:59:41 +0000953 if (MayAlias)
954 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes);
David Goodwin980d4942009-11-09 19:22:17 +0000955 // Add dependencies on alias and barrier chains, if needed.
956 if (MayAlias && AliasChain)
Andrew Trickeb05b972012-05-15 18:59:41 +0000957 addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes);
David Goodwin980d4942009-11-09 19:22:17 +0000958 if (BarrierChain)
959 BarrierChain->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
Andrew Trickf405b1a2011-05-05 19:24:06 +0000960 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000961 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000962 }
Devang Patelcf4cc842011-06-02 20:07:12 +0000963 if (PrevMI)
964 FirstDbgValue = PrevMI;
Dan Gohman79ce2762009-01-15 19:20:50 +0000965
Andrew Trick81a682a2012-02-23 01:52:38 +0000966 Defs.clear();
967 Uses.clear();
Andrew Trick3c58ba82012-01-14 02:17:18 +0000968 VRegDefs.clear();
Dan Gohman79ce2762009-01-15 19:20:50 +0000969 PendingLoads.clear();
Dan Gohman343f0c02008-11-19 23:18:57 +0000970}
971
Andrew Trick953be892012-03-07 23:00:49 +0000972void ScheduleDAGInstrs::computeLatency(SUnit *SU) {
David Goodwind94a4e52009-08-10 15:55:25 +0000973 // Compute the latency for the node.
Evan Cheng3ef1c872010-09-10 01:29:16 +0000974 if (!InstrItins || InstrItins->isEmpty()) {
975 SU->Latency = 1;
Dan Gohman4ea8e852008-12-16 02:38:22 +0000976
Evan Cheng3ef1c872010-09-10 01:29:16 +0000977 // Simplistic target-independent heuristic: assume that loads take
978 // extra time.
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000979 if (SU->getInstr()->mayLoad())
Dan Gohman4ea8e852008-12-16 02:38:22 +0000980 SU->Latency += 2;
Evan Cheng8239daf2010-11-03 00:45:17 +0000981 } else {
982 SU->Latency = TII->getInstrLatency(InstrItins, SU->getInstr());
983 }
Dan Gohmanc8c28272008-11-21 00:12:10 +0000984}
985
Andrew Trick953be892012-03-07 23:00:49 +0000986void ScheduleDAGInstrs::computeOperandLatency(SUnit *Def, SUnit *Use,
David Goodwindc4bdcd2009-08-19 16:08:58 +0000987 SDep& dep) const {
Evan Cheng3ef1c872010-09-10 01:29:16 +0000988 if (!InstrItins || InstrItins->isEmpty())
David Goodwindc4bdcd2009-08-19 16:08:58 +0000989 return;
Andrew Trickf405b1a2011-05-05 19:24:06 +0000990
David Goodwindc4bdcd2009-08-19 16:08:58 +0000991 // For a data dependency with a known register...
992 if ((dep.getKind() != SDep::Data) || (dep.getReg() == 0))
993 return;
994
995 const unsigned Reg = dep.getReg();
996
997 // ... find the definition of the register in the defining
998 // instruction
999 MachineInstr *DefMI = Def->getInstr();
1000 int DefIdx = DefMI->findRegisterDefOperandIdx(Reg);
1001 if (DefIdx != -1) {
Evan Cheng1aca5bc2010-10-08 18:42:25 +00001002 const MachineOperand &MO = DefMI->getOperand(DefIdx);
1003 if (MO.isReg() && MO.isImplicit() &&
Evan Chengd82de832010-10-08 23:01:57 +00001004 DefIdx >= (int)DefMI->getDesc().getNumOperands()) {
Evan Cheng1aca5bc2010-10-08 18:42:25 +00001005 // This is an implicit def, getOperandLatency() won't return the correct
1006 // latency. e.g.
1007 // %D6<def>, %D7<def> = VLD1q16 %R2<kill>, 0, ..., %Q3<imp-def>
1008 // %Q1<def> = VMULv8i16 %Q1<kill>, %Q3<kill>, ...
1009 // What we want is to compute latency between def of %D6/%D7 and use of
1010 // %Q3 instead.
Jakob Stoklund Olesen02634be2012-02-22 22:52:52 +00001011 unsigned Op2 = DefMI->findRegisterDefOperandIdx(Reg, false, true, TRI);
1012 if (DefMI->getOperand(Op2).isReg())
1013 DefIdx = Op2;
Evan Cheng1aca5bc2010-10-08 18:42:25 +00001014 }
Evan Chenga0792de2010-10-06 06:27:31 +00001015 MachineInstr *UseMI = Use->getInstr();
Evan Cheng3881cb72010-09-29 22:42:35 +00001016 // For all uses of the register, calculate the maxmimum latency
1017 int Latency = -1;
Evan Chengec6906b2010-10-23 02:10:46 +00001018 if (UseMI) {
1019 for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
1020 const MachineOperand &MO = UseMI->getOperand(i);
1021 if (!MO.isReg() || !MO.isUse())
1022 continue;
1023 unsigned MOReg = MO.getReg();
1024 if (MOReg != Reg)
1025 continue;
David Goodwindc4bdcd2009-08-19 16:08:58 +00001026
Evan Chengec6906b2010-10-23 02:10:46 +00001027 int UseCycle = TII->getOperandLatency(InstrItins, DefMI, DefIdx,
1028 UseMI, i);
1029 Latency = std::max(Latency, UseCycle);
1030 }
1031 } else {
1032 // UseMI is null, then it must be a scheduling barrier.
1033 if (!InstrItins || InstrItins->isEmpty())
1034 return;
1035 unsigned DefClass = DefMI->getDesc().getSchedClass();
1036 Latency = InstrItins->getOperandCycle(DefClass, DefIdx);
David Goodwindc4bdcd2009-08-19 16:08:58 +00001037 }
Evan Chengec6906b2010-10-23 02:10:46 +00001038
1039 // If we found a latency, then replace the existing dependence latency.
1040 if (Latency >= 0)
1041 dep.setLatency(Latency);
David Goodwindc4bdcd2009-08-19 16:08:58 +00001042 }
1043}
1044
Dan Gohman343f0c02008-11-19 23:18:57 +00001045void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
1046 SU->getInstr()->dump();
1047}
1048
1049std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
1050 std::string s;
1051 raw_string_ostream oss(s);
Dan Gohman9e64bbb2009-02-10 23:27:53 +00001052 if (SU == &EntrySU)
1053 oss << "<entry>";
1054 else if (SU == &ExitSU)
1055 oss << "<exit>";
1056 else
1057 SU->getInstr()->print(oss);
Dan Gohman343f0c02008-11-19 23:18:57 +00001058 return oss.str();
1059}
1060
Andrew Trick56b94c52012-03-07 00:18:22 +00001061/// Return the basic block label. It is not necessarilly unique because a block
1062/// contains multiple scheduling regions. But it is fine for visualization.
1063std::string ScheduleDAGInstrs::getDAGName() const {
1064 return "dag." + BB->getFullName();
1065}