LLVM API Documentation
00001 //===---- ScheduleDAGInstrs.cpp - MachineInstr Rescheduling ---------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This implements the ScheduleDAGInstrs class, which implements re-scheduling 00011 // of MachineInstrs. 00012 // 00013 //===----------------------------------------------------------------------===// 00014 00015 #define DEBUG_TYPE "misched" 00016 #include "llvm/CodeGen/ScheduleDAGInstrs.h" 00017 #include "llvm/ADT/MapVector.h" 00018 #include "llvm/ADT/SmallPtrSet.h" 00019 #include "llvm/ADT/SmallSet.h" 00020 #include "llvm/Analysis/AliasAnalysis.h" 00021 #include "llvm/Analysis/ValueTracking.h" 00022 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 00023 #include "llvm/CodeGen/MachineFunctionPass.h" 00024 #include "llvm/CodeGen/MachineMemOperand.h" 00025 #include "llvm/CodeGen/MachineRegisterInfo.h" 00026 #include "llvm/CodeGen/PseudoSourceValue.h" 00027 #include "llvm/CodeGen/RegisterPressure.h" 00028 #include "llvm/CodeGen/ScheduleDFS.h" 00029 #include "llvm/IR/Operator.h" 00030 #include "llvm/MC/MCInstrItineraries.h" 00031 #include "llvm/Support/CommandLine.h" 00032 #include "llvm/Support/Debug.h" 00033 #include "llvm/Support/Format.h" 00034 #include "llvm/Support/raw_ostream.h" 00035 #include "llvm/Target/TargetInstrInfo.h" 00036 #include "llvm/Target/TargetMachine.h" 00037 #include "llvm/Target/TargetRegisterInfo.h" 00038 #include "llvm/Target/TargetSubtargetInfo.h" 00039 using namespace llvm; 00040 00041 static cl::opt<bool> EnableAASchedMI("enable-aa-sched-mi", cl::Hidden, 00042 cl::ZeroOrMore, cl::init(false), 00043 cl::desc("Enable use of AA during MI GAD construction")); 00044 00045 ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf, 00046 const MachineLoopInfo &mli, 00047 const MachineDominatorTree &mdt, 00048 bool IsPostRAFlag, 00049 LiveIntervals *lis) 00050 : ScheduleDAG(mf), MLI(mli), MDT(mdt), MFI(mf.getFrameInfo()), LIS(lis), 00051 IsPostRA(IsPostRAFlag), CanHandleTerminators(false), FirstDbgValue(0) { 00052 assert((IsPostRA || LIS) && "PreRA scheduling requires LiveIntervals"); 00053 DbgValues.clear(); 00054 assert(!(IsPostRA && MRI.getNumVirtRegs()) && 00055 "Virtual registers must be removed prior to PostRA scheduling"); 00056 00057 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>(); 00058 SchedModel.init(*ST.getSchedModel(), &ST, TII); 00059 } 00060 00061 /// getUnderlyingObjectFromInt - This is the function that does the work of 00062 /// looking through basic ptrtoint+arithmetic+inttoptr sequences. 00063 static const Value *getUnderlyingObjectFromInt(const Value *V) { 00064 do { 00065 if (const Operator *U = dyn_cast<Operator>(V)) { 00066 // If we find a ptrtoint, we can transfer control back to the 00067 // regular getUnderlyingObjectFromInt. 00068 if (U->getOpcode() == Instruction::PtrToInt) 00069 return U->getOperand(0); 00070 // If we find an add of a constant, a multiplied value, or a phi, it's 00071 // likely that the other operand will lead us to the base 00072 // object. We don't have to worry about the case where the 00073 // object address is somehow being computed by the multiply, 00074 // because our callers only care when the result is an 00075 // identifiable object. 00076 if (U->getOpcode() != Instruction::Add || 00077 (!isa<ConstantInt>(U->getOperand(1)) && 00078 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul && 00079 !isa<PHINode>(U->getOperand(1)))) 00080 return V; 00081 V = U->getOperand(0); 00082 } else { 00083 return V; 00084 } 00085 assert(V->getType()->isIntegerTy() && "Unexpected operand type!"); 00086 } while (1); 00087 } 00088 00089 /// getUnderlyingObjects - This is a wrapper around GetUnderlyingObjects 00090 /// and adds support for basic ptrtoint+arithmetic+inttoptr sequences. 00091 static void getUnderlyingObjects(const Value *V, 00092 SmallVectorImpl<Value *> &Objects) { 00093 SmallPtrSet<const Value*, 16> Visited; 00094 SmallVector<const Value *, 4> Working(1, V); 00095 do { 00096 V = Working.pop_back_val(); 00097 00098 SmallVector<Value *, 4> Objs; 00099 GetUnderlyingObjects(const_cast<Value *>(V), Objs); 00100 00101 for (SmallVector<Value *, 4>::iterator I = Objs.begin(), IE = Objs.end(); 00102 I != IE; ++I) { 00103 V = *I; 00104 if (!Visited.insert(V)) 00105 continue; 00106 if (Operator::getOpcode(V) == Instruction::IntToPtr) { 00107 const Value *O = 00108 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0)); 00109 if (O->getType()->isPointerTy()) { 00110 Working.push_back(O); 00111 continue; 00112 } 00113 } 00114 Objects.push_back(const_cast<Value *>(V)); 00115 } 00116 } while (!Working.empty()); 00117 } 00118 00119 /// getUnderlyingObjectsForInstr - If this machine instr has memory reference 00120 /// information and it can be tracked to a normal reference to a known 00121 /// object, return the Value for that object. 00122 static void getUnderlyingObjectsForInstr(const MachineInstr *MI, 00123 const MachineFrameInfo *MFI, 00124 SmallVectorImpl<std::pair<const Value *, bool> > &Objects) { 00125 if (!MI->hasOneMemOperand() || 00126 !(*MI->memoperands_begin())->getValue() || 00127 (*MI->memoperands_begin())->isVolatile()) 00128 return; 00129 00130 const Value *V = (*MI->memoperands_begin())->getValue(); 00131 if (!V) 00132 return; 00133 00134 SmallVector<Value *, 4> Objs; 00135 getUnderlyingObjects(V, Objs); 00136 00137 for (SmallVector<Value *, 4>::iterator I = Objs.begin(), IE = Objs.end(); 00138 I != IE; ++I) { 00139 bool MayAlias = true; 00140 V = *I; 00141 00142 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) { 00143 // For now, ignore PseudoSourceValues which may alias LLVM IR values 00144 // because the code that uses this function has no way to cope with 00145 // such aliases. 00146 00147 if (PSV->isAliased(MFI)) { 00148 Objects.clear(); 00149 return; 00150 } 00151 00152 MayAlias = PSV->mayAlias(MFI); 00153 } else if (!isIdentifiedObject(V)) { 00154 Objects.clear(); 00155 return; 00156 } 00157 00158 Objects.push_back(std::make_pair(V, MayAlias)); 00159 } 00160 } 00161 00162 void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) { 00163 BB = bb; 00164 } 00165 00166 void ScheduleDAGInstrs::finishBlock() { 00167 // Subclasses should no longer refer to the old block. 00168 BB = 0; 00169 } 00170 00171 /// Initialize the DAG and common scheduler state for the current scheduling 00172 /// region. This does not actually create the DAG, only clears it. The 00173 /// scheduling driver may call BuildSchedGraph multiple times per scheduling 00174 /// region. 00175 void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb, 00176 MachineBasicBlock::iterator begin, 00177 MachineBasicBlock::iterator end, 00178 unsigned endcount) { 00179 assert(bb == BB && "startBlock should set BB"); 00180 RegionBegin = begin; 00181 RegionEnd = end; 00182 EndIndex = endcount; 00183 MISUnitMap.clear(); 00184 00185 ScheduleDAG::clearDAG(); 00186 } 00187 00188 /// Close the current scheduling region. Don't clear any state in case the 00189 /// driver wants to refer to the previous scheduling region. 00190 void ScheduleDAGInstrs::exitRegion() { 00191 // Nothing to do. 00192 } 00193 00194 /// addSchedBarrierDeps - Add dependencies from instructions in the current 00195 /// list of instructions being scheduled to scheduling barrier by adding 00196 /// the exit SU to the register defs and use list. This is because we want to 00197 /// make sure instructions which define registers that are either used by 00198 /// the terminator or are live-out are properly scheduled. This is 00199 /// especially important when the definition latency of the return value(s) 00200 /// are too high to be hidden by the branch or when the liveout registers 00201 /// used by instructions in the fallthrough block. 00202 void ScheduleDAGInstrs::addSchedBarrierDeps() { 00203 MachineInstr *ExitMI = RegionEnd != BB->end() ? &*RegionEnd : 0; 00204 ExitSU.setInstr(ExitMI); 00205 bool AllDepKnown = ExitMI && 00206 (ExitMI->isCall() || ExitMI->isBarrier()); 00207 if (ExitMI && AllDepKnown) { 00208 // If it's a call or a barrier, add dependencies on the defs and uses of 00209 // instruction. 00210 for (unsigned i = 0, e = ExitMI->getNumOperands(); i != e; ++i) { 00211 const MachineOperand &MO = ExitMI->getOperand(i); 00212 if (!MO.isReg() || MO.isDef()) continue; 00213 unsigned Reg = MO.getReg(); 00214 if (Reg == 0) continue; 00215 00216 if (TRI->isPhysicalRegister(Reg)) 00217 Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg)); 00218 else { 00219 assert(!IsPostRA && "Virtual register encountered after regalloc."); 00220 if (MO.readsReg()) // ignore undef operands 00221 addVRegUseDeps(&ExitSU, i); 00222 } 00223 } 00224 } else { 00225 // For others, e.g. fallthrough, conditional branch, assume the exit 00226 // uses all the registers that are livein to the successor blocks. 00227 assert(Uses.empty() && "Uses in set before adding deps?"); 00228 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(), 00229 SE = BB->succ_end(); SI != SE; ++SI) 00230 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(), 00231 E = (*SI)->livein_end(); I != E; ++I) { 00232 unsigned Reg = *I; 00233 if (!Uses.contains(Reg)) 00234 Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg)); 00235 } 00236 } 00237 } 00238 00239 /// MO is an operand of SU's instruction that defines a physical register. Add 00240 /// data dependencies from SU to any uses of the physical register. 00241 void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU, unsigned OperIdx) { 00242 const MachineOperand &MO = SU->getInstr()->getOperand(OperIdx); 00243 assert(MO.isDef() && "expect physreg def"); 00244 00245 // Ask the target if address-backscheduling is desirable, and if so how much. 00246 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>(); 00247 00248 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true); 00249 Alias.isValid(); ++Alias) { 00250 if (!Uses.contains(*Alias)) 00251 continue; 00252 for (Reg2SUnitsMap::iterator I = Uses.find(*Alias); I != Uses.end(); ++I) { 00253 SUnit *UseSU = I->SU; 00254 if (UseSU == SU) 00255 continue; 00256 00257 // Adjust the dependence latency using operand def/use information, 00258 // then allow the target to perform its own adjustments. 00259 int UseOp = I->OpIdx; 00260 MachineInstr *RegUse = 0; 00261 SDep Dep; 00262 if (UseOp < 0) 00263 Dep = SDep(SU, SDep::Artificial); 00264 else { 00265 // Set the hasPhysRegDefs only for physreg defs that have a use within 00266 // the scheduling region. 00267 SU->hasPhysRegDefs = true; 00268 Dep = SDep(SU, SDep::Data, *Alias); 00269 RegUse = UseSU->getInstr(); 00270 Dep.setMinLatency( 00271 SchedModel.computeOperandLatency(SU->getInstr(), OperIdx, 00272 RegUse, UseOp, /*FindMin=*/true)); 00273 } 00274 Dep.setLatency( 00275 SchedModel.computeOperandLatency(SU->getInstr(), OperIdx, 00276 RegUse, UseOp, /*FindMin=*/false)); 00277 00278 ST.adjustSchedDependency(SU, UseSU, Dep); 00279 UseSU->addPred(Dep); 00280 } 00281 } 00282 } 00283 00284 /// addPhysRegDeps - Add register dependencies (data, anti, and output) from 00285 /// this SUnit to following instructions in the same scheduling region that 00286 /// depend the physical register referenced at OperIdx. 00287 void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) { 00288 const MachineInstr *MI = SU->getInstr(); 00289 const MachineOperand &MO = MI->getOperand(OperIdx); 00290 00291 // Optionally add output and anti dependencies. For anti 00292 // dependencies we use a latency of 0 because for a multi-issue 00293 // target we want to allow the defining instruction to issue 00294 // in the same cycle as the using instruction. 00295 // TODO: Using a latency of 1 here for output dependencies assumes 00296 // there's no cost for reusing registers. 00297 SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output; 00298 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true); 00299 Alias.isValid(); ++Alias) { 00300 if (!Defs.contains(*Alias)) 00301 continue; 00302 for (Reg2SUnitsMap::iterator I = Defs.find(*Alias); I != Defs.end(); ++I) { 00303 SUnit *DefSU = I->SU; 00304 if (DefSU == &ExitSU) 00305 continue; 00306 if (DefSU != SU && 00307 (Kind != SDep::Output || !MO.isDead() || 00308 !DefSU->getInstr()->registerDefIsDead(*Alias))) { 00309 if (Kind == SDep::Anti) 00310 DefSU->addPred(SDep(SU, Kind, /*Reg=*/*Alias)); 00311 else { 00312 SDep Dep(SU, Kind, /*Reg=*/*Alias); 00313 unsigned OutLatency = 00314 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()); 00315 Dep.setMinLatency(OutLatency); 00316 Dep.setLatency(OutLatency); 00317 DefSU->addPred(Dep); 00318 } 00319 } 00320 } 00321 } 00322 00323 if (!MO.isDef()) { 00324 SU->hasPhysRegUses = true; 00325 // Either insert a new Reg2SUnits entry with an empty SUnits list, or 00326 // retrieve the existing SUnits list for this register's uses. 00327 // Push this SUnit on the use list. 00328 Uses.insert(PhysRegSUOper(SU, OperIdx, MO.getReg())); 00329 } 00330 else { 00331 addPhysRegDataDeps(SU, OperIdx); 00332 unsigned Reg = MO.getReg(); 00333 00334 // clear this register's use list 00335 if (Uses.contains(Reg)) 00336 Uses.eraseAll(Reg); 00337 00338 if (!MO.isDead()) { 00339 Defs.eraseAll(Reg); 00340 } else if (SU->isCall) { 00341 // Calls will not be reordered because of chain dependencies (see 00342 // below). Since call operands are dead, calls may continue to be added 00343 // to the DefList making dependence checking quadratic in the size of 00344 // the block. Instead, we leave only one call at the back of the 00345 // DefList. 00346 Reg2SUnitsMap::RangePair P = Defs.equal_range(Reg); 00347 Reg2SUnitsMap::iterator B = P.first; 00348 Reg2SUnitsMap::iterator I = P.second; 00349 for (bool isBegin = I == B; !isBegin; /* empty */) { 00350 isBegin = (--I) == B; 00351 if (!I->SU->isCall) 00352 break; 00353 I = Defs.erase(I); 00354 } 00355 } 00356 00357 // Defs are pushed in the order they are visited and never reordered. 00358 Defs.insert(PhysRegSUOper(SU, OperIdx, Reg)); 00359 } 00360 } 00361 00362 /// addVRegDefDeps - Add register output and data dependencies from this SUnit 00363 /// to instructions that occur later in the same scheduling region if they read 00364 /// from or write to the virtual register defined at OperIdx. 00365 /// 00366 /// TODO: Hoist loop induction variable increments. This has to be 00367 /// reevaluated. Generally, IV scheduling should be done before coalescing. 00368 void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) { 00369 const MachineInstr *MI = SU->getInstr(); 00370 unsigned Reg = MI->getOperand(OperIdx).getReg(); 00371 00372 // Singly defined vregs do not have output/anti dependencies. 00373 // The current operand is a def, so we have at least one. 00374 // Check here if there are any others... 00375 if (MRI.hasOneDef(Reg)) 00376 return; 00377 00378 // Add output dependence to the next nearest def of this vreg. 00379 // 00380 // Unless this definition is dead, the output dependence should be 00381 // transitively redundant with antidependencies from this definition's 00382 // uses. We're conservative for now until we have a way to guarantee the uses 00383 // are not eliminated sometime during scheduling. The output dependence edge 00384 // is also useful if output latency exceeds def-use latency. 00385 VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg); 00386 if (DefI == VRegDefs.end()) 00387 VRegDefs.insert(VReg2SUnit(Reg, SU)); 00388 else { 00389 SUnit *DefSU = DefI->SU; 00390 if (DefSU != SU && DefSU != &ExitSU) { 00391 SDep Dep(SU, SDep::Output, Reg); 00392 unsigned OutLatency = 00393 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()); 00394 Dep.setMinLatency(OutLatency); 00395 Dep.setLatency(OutLatency); 00396 DefSU->addPred(Dep); 00397 } 00398 DefI->SU = SU; 00399 } 00400 } 00401 00402 /// addVRegUseDeps - Add a register data dependency if the instruction that 00403 /// defines the virtual register used at OperIdx is mapped to an SUnit. Add a 00404 /// register antidependency from this SUnit to instructions that occur later in 00405 /// the same scheduling region if they write the virtual register. 00406 /// 00407 /// TODO: Handle ExitSU "uses" properly. 00408 void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) { 00409 MachineInstr *MI = SU->getInstr(); 00410 unsigned Reg = MI->getOperand(OperIdx).getReg(); 00411 00412 // Lookup this operand's reaching definition. 00413 assert(LIS && "vreg dependencies requires LiveIntervals"); 00414 LiveRangeQuery LRQ(LIS->getInterval(Reg), LIS->getInstructionIndex(MI)); 00415 VNInfo *VNI = LRQ.valueIn(); 00416 00417 // VNI will be valid because MachineOperand::readsReg() is checked by caller. 00418 assert(VNI && "No value to read by operand"); 00419 MachineInstr *Def = LIS->getInstructionFromIndex(VNI->def); 00420 // Phis and other noninstructions (after coalescing) have a NULL Def. 00421 if (Def) { 00422 SUnit *DefSU = getSUnit(Def); 00423 if (DefSU) { 00424 // The reaching Def lives within this scheduling region. 00425 // Create a data dependence. 00426 SDep dep(DefSU, SDep::Data, Reg); 00427 // Adjust the dependence latency using operand def/use information, then 00428 // allow the target to perform its own adjustments. 00429 int DefOp = Def->findRegisterDefOperandIdx(Reg); 00430 dep.setLatency( 00431 SchedModel.computeOperandLatency(Def, DefOp, MI, OperIdx, false)); 00432 dep.setMinLatency( 00433 SchedModel.computeOperandLatency(Def, DefOp, MI, OperIdx, true)); 00434 00435 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>(); 00436 ST.adjustSchedDependency(DefSU, SU, const_cast<SDep &>(dep)); 00437 SU->addPred(dep); 00438 } 00439 } 00440 00441 // Add antidependence to the following def of the vreg it uses. 00442 VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg); 00443 if (DefI != VRegDefs.end() && DefI->SU != SU) 00444 DefI->SU->addPred(SDep(SU, SDep::Anti, Reg)); 00445 } 00446 00447 /// Return true if MI is an instruction we are unable to reason about 00448 /// (like a call or something with unmodeled side effects). 00449 static inline bool isGlobalMemoryObject(AliasAnalysis *AA, MachineInstr *MI) { 00450 if (MI->isCall() || MI->hasUnmodeledSideEffects() || 00451 (MI->hasOrderedMemoryRef() && 00452 (!MI->mayLoad() || !MI->isInvariantLoad(AA)))) 00453 return true; 00454 return false; 00455 } 00456 00457 // This MI might have either incomplete info, or known to be unsafe 00458 // to deal with (i.e. volatile object). 00459 static inline bool isUnsafeMemoryObject(MachineInstr *MI, 00460 const MachineFrameInfo *MFI) { 00461 if (!MI || MI->memoperands_empty()) 00462 return true; 00463 // We purposefully do no check for hasOneMemOperand() here 00464 // in hope to trigger an assert downstream in order to 00465 // finish implementation. 00466 if ((*MI->memoperands_begin())->isVolatile() || 00467 MI->hasUnmodeledSideEffects()) 00468 return true; 00469 const Value *V = (*MI->memoperands_begin())->getValue(); 00470 if (!V) 00471 return true; 00472 00473 SmallVector<Value *, 4> Objs; 00474 getUnderlyingObjects(V, Objs); 00475 for (SmallVector<Value *, 4>::iterator I = Objs.begin(), 00476 IE = Objs.end(); I != IE; ++I) { 00477 V = *I; 00478 00479 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) { 00480 // Similarly to getUnderlyingObjectForInstr: 00481 // For now, ignore PseudoSourceValues which may alias LLVM IR values 00482 // because the code that uses this function has no way to cope with 00483 // such aliases. 00484 if (PSV->isAliased(MFI)) 00485 return true; 00486 } 00487 00488 // Does this pointer refer to a distinct and identifiable object? 00489 if (!isIdentifiedObject(V)) 00490 return true; 00491 } 00492 00493 return false; 00494 } 00495 00496 /// This returns true if the two MIs need a chain edge betwee them. 00497 /// If these are not even memory operations, we still may need 00498 /// chain deps between them. The question really is - could 00499 /// these two MIs be reordered during scheduling from memory dependency 00500 /// point of view. 00501 static bool MIsNeedChainEdge(AliasAnalysis *AA, const MachineFrameInfo *MFI, 00502 MachineInstr *MIa, 00503 MachineInstr *MIb) { 00504 // Cover a trivial case - no edge is need to itself. 00505 if (MIa == MIb) 00506 return false; 00507 00508 if (isUnsafeMemoryObject(MIa, MFI) || isUnsafeMemoryObject(MIb, MFI)) 00509 return true; 00510 00511 // If we are dealing with two "normal" loads, we do not need an edge 00512 // between them - they could be reordered. 00513 if (!MIa->mayStore() && !MIb->mayStore()) 00514 return false; 00515 00516 // To this point analysis is generic. From here on we do need AA. 00517 if (!AA) 00518 return true; 00519 00520 MachineMemOperand *MMOa = *MIa->memoperands_begin(); 00521 MachineMemOperand *MMOb = *MIb->memoperands_begin(); 00522 00523 // FIXME: Need to handle multiple memory operands to support all targets. 00524 if (!MIa->hasOneMemOperand() || !MIb->hasOneMemOperand()) 00525 llvm_unreachable("Multiple memory operands."); 00526 00527 // The following interface to AA is fashioned after DAGCombiner::isAlias 00528 // and operates with MachineMemOperand offset with some important 00529 // assumptions: 00530 // - LLVM fundamentally assumes flat address spaces. 00531 // - MachineOperand offset can *only* result from legalization and 00532 // cannot affect queries other than the trivial case of overlap 00533 // checking. 00534 // - These offsets never wrap and never step outside 00535 // of allocated objects. 00536 // - There should never be any negative offsets here. 00537 // 00538 // FIXME: Modify API to hide this math from "user" 00539 // FIXME: Even before we go to AA we can reason locally about some 00540 // memory objects. It can save compile time, and possibly catch some 00541 // corner cases not currently covered. 00542 00543 assert ((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset"); 00544 assert ((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset"); 00545 00546 int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset()); 00547 int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset; 00548 int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset; 00549 00550 AliasAnalysis::AliasResult AAResult = AA->alias( 00551 AliasAnalysis::Location(MMOa->getValue(), Overlapa, 00552 MMOa->getTBAAInfo()), 00553 AliasAnalysis::Location(MMOb->getValue(), Overlapb, 00554 MMOb->getTBAAInfo())); 00555 00556 return (AAResult != AliasAnalysis::NoAlias); 00557 } 00558 00559 /// This recursive function iterates over chain deps of SUb looking for 00560 /// "latest" node that needs a chain edge to SUa. 00561 static unsigned 00562 iterateChainSucc(AliasAnalysis *AA, const MachineFrameInfo *MFI, 00563 SUnit *SUa, SUnit *SUb, SUnit *ExitSU, unsigned *Depth, 00564 SmallPtrSet<const SUnit*, 16> &Visited) { 00565 if (!SUa || !SUb || SUb == ExitSU) 00566 return *Depth; 00567 00568 // Remember visited nodes. 00569 if (!Visited.insert(SUb)) 00570 return *Depth; 00571 // If there is _some_ dependency already in place, do not 00572 // descend any further. 00573 // TODO: Need to make sure that if that dependency got eliminated or ignored 00574 // for any reason in the future, we would not violate DAG topology. 00575 // Currently it does not happen, but makes an implicit assumption about 00576 // future implementation. 00577 // 00578 // Independently, if we encounter node that is some sort of global 00579 // object (like a call) we already have full set of dependencies to it 00580 // and we can stop descending. 00581 if (SUa->isSucc(SUb) || 00582 isGlobalMemoryObject(AA, SUb->getInstr())) 00583 return *Depth; 00584 00585 // If we do need an edge, or we have exceeded depth budget, 00586 // add that edge to the predecessors chain of SUb, 00587 // and stop descending. 00588 if (*Depth > 200 || 00589 MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) { 00590 SUb->addPred(SDep(SUa, SDep::MayAliasMem)); 00591 return *Depth; 00592 } 00593 // Track current depth. 00594 (*Depth)++; 00595 // Iterate over chain dependencies only. 00596 for (SUnit::const_succ_iterator I = SUb->Succs.begin(), E = SUb->Succs.end(); 00597 I != E; ++I) 00598 if (I->isCtrl()) 00599 iterateChainSucc (AA, MFI, SUa, I->getSUnit(), ExitSU, Depth, Visited); 00600 return *Depth; 00601 } 00602 00603 /// This function assumes that "downward" from SU there exist 00604 /// tail/leaf of already constructed DAG. It iterates downward and 00605 /// checks whether SU can be aliasing any node dominated 00606 /// by it. 00607 static void adjustChainDeps(AliasAnalysis *AA, const MachineFrameInfo *MFI, 00608 SUnit *SU, SUnit *ExitSU, std::set<SUnit *> &CheckList, 00609 unsigned LatencyToLoad) { 00610 if (!SU) 00611 return; 00612 00613 SmallPtrSet<const SUnit*, 16> Visited; 00614 unsigned Depth = 0; 00615 00616 for (std::set<SUnit *>::iterator I = CheckList.begin(), IE = CheckList.end(); 00617 I != IE; ++I) { 00618 if (SU == *I) 00619 continue; 00620 if (MIsNeedChainEdge(AA, MFI, SU->getInstr(), (*I)->getInstr())) { 00621 SDep Dep(SU, SDep::MayAliasMem); 00622 Dep.setLatency(((*I)->getInstr()->mayLoad()) ? LatencyToLoad : 0); 00623 (*I)->addPred(Dep); 00624 } 00625 // Now go through all the chain successors and iterate from them. 00626 // Keep track of visited nodes. 00627 for (SUnit::const_succ_iterator J = (*I)->Succs.begin(), 00628 JE = (*I)->Succs.end(); J != JE; ++J) 00629 if (J->isCtrl()) 00630 iterateChainSucc (AA, MFI, SU, J->getSUnit(), 00631 ExitSU, &Depth, Visited); 00632 } 00633 } 00634 00635 /// Check whether two objects need a chain edge, if so, add it 00636 /// otherwise remember the rejected SU. 00637 static inline 00638 void addChainDependency (AliasAnalysis *AA, const MachineFrameInfo *MFI, 00639 SUnit *SUa, SUnit *SUb, 00640 std::set<SUnit *> &RejectList, 00641 unsigned TrueMemOrderLatency = 0, 00642 bool isNormalMemory = false) { 00643 // If this is a false dependency, 00644 // do not add the edge, but rememeber the rejected node. 00645 if (!EnableAASchedMI || 00646 MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) { 00647 SDep Dep(SUa, isNormalMemory ? SDep::MayAliasMem : SDep::Barrier); 00648 Dep.setLatency(TrueMemOrderLatency); 00649 SUb->addPred(Dep); 00650 } 00651 else { 00652 // Duplicate entries should be ignored. 00653 RejectList.insert(SUb); 00654 DEBUG(dbgs() << "\tReject chain dep between SU(" 00655 << SUa->NodeNum << ") and SU(" 00656 << SUb->NodeNum << ")\n"); 00657 } 00658 } 00659 00660 /// Create an SUnit for each real instruction, numbered in top-down toplological 00661 /// order. The instruction order A < B, implies that no edge exists from B to A. 00662 /// 00663 /// Map each real instruction to its SUnit. 00664 /// 00665 /// After initSUnits, the SUnits vector cannot be resized and the scheduler may 00666 /// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs 00667 /// instead of pointers. 00668 /// 00669 /// MachineScheduler relies on initSUnits numbering the nodes by their order in 00670 /// the original instruction list. 00671 void ScheduleDAGInstrs::initSUnits() { 00672 // We'll be allocating one SUnit for each real instruction in the region, 00673 // which is contained within a basic block. 00674 SUnits.reserve(BB->size()); 00675 00676 for (MachineBasicBlock::iterator I = RegionBegin; I != RegionEnd; ++I) { 00677 MachineInstr *MI = I; 00678 if (MI->isDebugValue()) 00679 continue; 00680 00681 SUnit *SU = newSUnit(MI); 00682 MISUnitMap[MI] = SU; 00683 00684 SU->isCall = MI->isCall(); 00685 SU->isCommutable = MI->isCommutable(); 00686 00687 // Assign the Latency field of SU using target-provided information. 00688 SU->Latency = SchedModel.computeInstrLatency(SU->getInstr()); 00689 } 00690 } 00691 00692 /// If RegPressure is non null, compute register pressure as a side effect. The 00693 /// DAG builder is an efficient place to do it because it already visits 00694 /// operands. 00695 void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA, 00696 RegPressureTracker *RPTracker) { 00697 // Create an SUnit for each real instruction. 00698 initSUnits(); 00699 00700 // We build scheduling units by walking a block's instruction list from bottom 00701 // to top. 00702 00703 // Remember where a generic side-effecting instruction is as we procede. 00704 SUnit *BarrierChain = 0, *AliasChain = 0; 00705 00706 // Memory references to specific known memory locations are tracked 00707 // so that they can be given more precise dependencies. We track 00708 // separately the known memory locations that may alias and those 00709 // that are known not to alias 00710 MapVector<const Value *, SUnit *> AliasMemDefs, NonAliasMemDefs; 00711 MapVector<const Value *, std::vector<SUnit *> > AliasMemUses, NonAliasMemUses; 00712 std::set<SUnit*> RejectMemNodes; 00713 00714 // Remove any stale debug info; sometimes BuildSchedGraph is called again 00715 // without emitting the info from the previous call. 00716 DbgValues.clear(); 00717 FirstDbgValue = NULL; 00718 00719 assert(Defs.empty() && Uses.empty() && 00720 "Only BuildGraph should update Defs/Uses"); 00721 Defs.setUniverse(TRI->getNumRegs()); 00722 Uses.setUniverse(TRI->getNumRegs()); 00723 00724 assert(VRegDefs.empty() && "Only BuildSchedGraph may access VRegDefs"); 00725 // FIXME: Allow SparseSet to reserve space for the creation of virtual 00726 // registers during scheduling. Don't artificially inflate the Universe 00727 // because we want to assert that vregs are not created during DAG building. 00728 VRegDefs.setUniverse(MRI.getNumVirtRegs()); 00729 00730 // Model data dependencies between instructions being scheduled and the 00731 // ExitSU. 00732 addSchedBarrierDeps(); 00733 00734 // Walk the list of instructions, from bottom moving up. 00735 MachineInstr *DbgMI = NULL; 00736 for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin; 00737 MII != MIE; --MII) { 00738 MachineInstr *MI = prior(MII); 00739 if (MI && DbgMI) { 00740 DbgValues.push_back(std::make_pair(DbgMI, MI)); 00741 DbgMI = NULL; 00742 } 00743 00744 if (MI->isDebugValue()) { 00745 DbgMI = MI; 00746 continue; 00747 } 00748 if (RPTracker) { 00749 RPTracker->recede(); 00750 assert(RPTracker->getPos() == prior(MII) && "RPTracker can't find MI"); 00751 } 00752 00753 assert((CanHandleTerminators || (!MI->isTerminator() && !MI->isLabel())) && 00754 "Cannot schedule terminators or labels!"); 00755 00756 SUnit *SU = MISUnitMap[MI]; 00757 assert(SU && "No SUnit mapped to this MI"); 00758 00759 // Add register-based dependencies (data, anti, and output). 00760 bool HasVRegDef = false; 00761 for (unsigned j = 0, n = MI->getNumOperands(); j != n; ++j) { 00762 const MachineOperand &MO = MI->getOperand(j); 00763 if (!MO.isReg()) continue; 00764 unsigned Reg = MO.getReg(); 00765 if (Reg == 0) continue; 00766 00767 if (TRI->isPhysicalRegister(Reg)) 00768 addPhysRegDeps(SU, j); 00769 else { 00770 assert(!IsPostRA && "Virtual register encountered!"); 00771 if (MO.isDef()) { 00772 HasVRegDef = true; 00773 addVRegDefDeps(SU, j); 00774 } 00775 else if (MO.readsReg()) // ignore undef operands 00776 addVRegUseDeps(SU, j); 00777 } 00778 } 00779 // If we haven't seen any uses in this scheduling region, create a 00780 // dependence edge to ExitSU to model the live-out latency. This is required 00781 // for vreg defs with no in-region use, and prefetches with no vreg def. 00782 // 00783 // FIXME: NumDataSuccs would be more precise than NumSuccs here. This 00784 // check currently relies on being called before adding chain deps. 00785 if (SU->NumSuccs == 0 && SU->Latency > 1 00786 && (HasVRegDef || MI->mayLoad())) { 00787 SDep Dep(SU, SDep::Artificial); 00788 Dep.setLatency(SU->Latency - 1); 00789 ExitSU.addPred(Dep); 00790 } 00791 00792 // Add chain dependencies. 00793 // Chain dependencies used to enforce memory order should have 00794 // latency of 0 (except for true dependency of Store followed by 00795 // aliased Load... we estimate that with a single cycle of latency 00796 // assuming the hardware will bypass) 00797 // Note that isStoreToStackSlot and isLoadFromStackSLot are not usable 00798 // after stack slots are lowered to actual addresses. 00799 // TODO: Use an AliasAnalysis and do real alias-analysis queries, and 00800 // produce more precise dependence information. 00801 unsigned TrueMemOrderLatency = MI->mayStore() ? 1 : 0; 00802 if (isGlobalMemoryObject(AA, MI)) { 00803 // Be conservative with these and add dependencies on all memory 00804 // references, even those that are known to not alias. 00805 for (MapVector<const Value *, SUnit *>::iterator I = 00806 NonAliasMemDefs.begin(), E = NonAliasMemDefs.end(); I != E; ++I) { 00807 I->second->addPred(SDep(SU, SDep::Barrier)); 00808 } 00809 for (MapVector<const Value *, std::vector<SUnit *> >::iterator I = 00810 NonAliasMemUses.begin(), E = NonAliasMemUses.end(); I != E; ++I) { 00811 for (unsigned i = 0, e = I->second.size(); i != e; ++i) { 00812 SDep Dep(SU, SDep::Barrier); 00813 Dep.setLatency(TrueMemOrderLatency); 00814 I->second[i]->addPred(Dep); 00815 } 00816 } 00817 // Add SU to the barrier chain. 00818 if (BarrierChain) 00819 BarrierChain->addPred(SDep(SU, SDep::Barrier)); 00820 BarrierChain = SU; 00821 // This is a barrier event that acts as a pivotal node in the DAG, 00822 // so it is safe to clear list of exposed nodes. 00823 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes, 00824 TrueMemOrderLatency); 00825 RejectMemNodes.clear(); 00826 NonAliasMemDefs.clear(); 00827 NonAliasMemUses.clear(); 00828 00829 // fall-through 00830 new_alias_chain: 00831 // Chain all possibly aliasing memory references though SU. 00832 if (AliasChain) { 00833 unsigned ChainLatency = 0; 00834 if (AliasChain->getInstr()->mayLoad()) 00835 ChainLatency = TrueMemOrderLatency; 00836 addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes, 00837 ChainLatency); 00838 } 00839 AliasChain = SU; 00840 for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k) 00841 addChainDependency(AA, MFI, SU, PendingLoads[k], RejectMemNodes, 00842 TrueMemOrderLatency); 00843 for (MapVector<const Value *, SUnit *>::iterator I = AliasMemDefs.begin(), 00844 E = AliasMemDefs.end(); I != E; ++I) 00845 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes); 00846 for (MapVector<const Value *, std::vector<SUnit *> >::iterator I = 00847 AliasMemUses.begin(), E = AliasMemUses.end(); I != E; ++I) { 00848 for (unsigned i = 0, e = I->second.size(); i != e; ++i) 00849 addChainDependency(AA, MFI, SU, I->second[i], RejectMemNodes, 00850 TrueMemOrderLatency); 00851 } 00852 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes, 00853 TrueMemOrderLatency); 00854 PendingLoads.clear(); 00855 AliasMemDefs.clear(); 00856 AliasMemUses.clear(); 00857 } else if (MI->mayStore()) { 00858 SmallVector<std::pair<const Value *, bool>, 4> Objs; 00859 getUnderlyingObjectsForInstr(MI, MFI, Objs); 00860 00861 if (Objs.empty()) { 00862 // Treat all other stores conservatively. 00863 goto new_alias_chain; 00864 } 00865 00866 bool MayAlias = false; 00867 for (SmallVector<std::pair<const Value *, bool>, 4>::iterator 00868 K = Objs.begin(), KE = Objs.end(); K != KE; ++K) { 00869 const Value *V = K->first; 00870 bool ThisMayAlias = K->second; 00871 if (ThisMayAlias) 00872 MayAlias = true; 00873 00874 // A store to a specific PseudoSourceValue. Add precise dependencies. 00875 // Record the def in MemDefs, first adding a dep if there is 00876 // an existing def. 00877 MapVector<const Value *, SUnit *>::iterator I = 00878 ((ThisMayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V)); 00879 MapVector<const Value *, SUnit *>::iterator IE = 00880 ((ThisMayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end()); 00881 if (I != IE) { 00882 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes, 0, true); 00883 I->second = SU; 00884 } else { 00885 if (ThisMayAlias) 00886 AliasMemDefs[V] = SU; 00887 else 00888 NonAliasMemDefs[V] = SU; 00889 } 00890 // Handle the uses in MemUses, if there are any. 00891 MapVector<const Value *, std::vector<SUnit *> >::iterator J = 00892 ((ThisMayAlias) ? AliasMemUses.find(V) : NonAliasMemUses.find(V)); 00893 MapVector<const Value *, std::vector<SUnit *> >::iterator JE = 00894 ((ThisMayAlias) ? AliasMemUses.end() : NonAliasMemUses.end()); 00895 if (J != JE) { 00896 for (unsigned i = 0, e = J->second.size(); i != e; ++i) 00897 addChainDependency(AA, MFI, SU, J->second[i], RejectMemNodes, 00898 TrueMemOrderLatency, true); 00899 J->second.clear(); 00900 } 00901 } 00902 if (MayAlias) { 00903 // Add dependencies from all the PendingLoads, i.e. loads 00904 // with no underlying object. 00905 for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k) 00906 addChainDependency(AA, MFI, SU, PendingLoads[k], RejectMemNodes, 00907 TrueMemOrderLatency); 00908 // Add dependence on alias chain, if needed. 00909 if (AliasChain) 00910 addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes); 00911 // But we also should check dependent instructions for the 00912 // SU in question. 00913 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes, 00914 TrueMemOrderLatency); 00915 } 00916 // Add dependence on barrier chain, if needed. 00917 // There is no point to check aliasing on barrier event. Even if 00918 // SU and barrier _could_ be reordered, they should not. In addition, 00919 // we have lost all RejectMemNodes below barrier. 00920 if (BarrierChain) 00921 BarrierChain->addPred(SDep(SU, SDep::Barrier)); 00922 00923 if (!ExitSU.isPred(SU)) 00924 // Push store's up a bit to avoid them getting in between cmp 00925 // and branches. 00926 ExitSU.addPred(SDep(SU, SDep::Artificial)); 00927 } else if (MI->mayLoad()) { 00928 bool MayAlias = true; 00929 if (MI->isInvariantLoad(AA)) { 00930 // Invariant load, no chain dependencies needed! 00931 } else { 00932 SmallVector<std::pair<const Value *, bool>, 4> Objs; 00933 getUnderlyingObjectsForInstr(MI, MFI, Objs); 00934 00935 if (Objs.empty()) { 00936 // A load with no underlying object. Depend on all 00937 // potentially aliasing stores. 00938 for (MapVector<const Value *, SUnit *>::iterator I = 00939 AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I) 00940 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes); 00941 00942 PendingLoads.push_back(SU); 00943 MayAlias = true; 00944 } else { 00945 MayAlias = false; 00946 } 00947 00948 for (SmallVector<std::pair<const Value *, bool>, 4>::iterator 00949 J = Objs.begin(), JE = Objs.end(); J != JE; ++J) { 00950 const Value *V = J->first; 00951 bool ThisMayAlias = J->second; 00952 00953 if (ThisMayAlias) 00954 MayAlias = true; 00955 00956 // A load from a specific PseudoSourceValue. Add precise dependencies. 00957 MapVector<const Value *, SUnit *>::iterator I = 00958 ((ThisMayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V)); 00959 MapVector<const Value *, SUnit *>::iterator IE = 00960 ((ThisMayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end()); 00961 if (I != IE) 00962 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes, 0, true); 00963 if (ThisMayAlias) 00964 AliasMemUses[V].push_back(SU); 00965 else 00966 NonAliasMemUses[V].push_back(SU); 00967 } 00968 if (MayAlias) 00969 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes, /*Latency=*/0); 00970 // Add dependencies on alias and barrier chains, if needed. 00971 if (MayAlias && AliasChain) 00972 addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes); 00973 if (BarrierChain) 00974 BarrierChain->addPred(SDep(SU, SDep::Barrier)); 00975 } 00976 } 00977 } 00978 if (DbgMI) 00979 FirstDbgValue = DbgMI; 00980 00981 Defs.clear(); 00982 Uses.clear(); 00983 VRegDefs.clear(); 00984 PendingLoads.clear(); 00985 } 00986 00987 void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const { 00988 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 00989 SU->getInstr()->dump(); 00990 #endif 00991 } 00992 00993 std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const { 00994 std::string s; 00995 raw_string_ostream oss(s); 00996 if (SU == &EntrySU) 00997 oss << "<entry>"; 00998 else if (SU == &ExitSU) 00999 oss << "<exit>"; 01000 else 01001 SU->getInstr()->print(oss, &TM, /*SkipOpers=*/true); 01002 return oss.str(); 01003 } 01004 01005 /// Return the basic block label. It is not necessarilly unique because a block 01006 /// contains multiple scheduling regions. But it is fine for visualization. 01007 std::string ScheduleDAGInstrs::getDAGName() const { 01008 return "dag." + BB->getFullName(); 01009 } 01010 01011 //===----------------------------------------------------------------------===// 01012 // SchedDFSResult Implementation 01013 //===----------------------------------------------------------------------===// 01014 01015 namespace llvm { 01016 /// \brief Internal state used to compute SchedDFSResult. 01017 class SchedDFSImpl { 01018 SchedDFSResult &R; 01019 01020 /// Join DAG nodes into equivalence classes by their subtree. 01021 IntEqClasses SubtreeClasses; 01022 /// List PredSU, SuccSU pairs that represent data edges between subtrees. 01023 std::vector<std::pair<const SUnit*, const SUnit*> > ConnectionPairs; 01024 01025 struct RootData { 01026 unsigned NodeID; 01027 unsigned ParentNodeID; // Parent node (member of the parent subtree). 01028 unsigned SubInstrCount; // Instr count in this tree only, not children. 01029 01030 RootData(unsigned id): NodeID(id), 01031 ParentNodeID(SchedDFSResult::InvalidSubtreeID), 01032 SubInstrCount(0) {} 01033 01034 unsigned getSparseSetIndex() const { return NodeID; } 01035 }; 01036 01037 SparseSet<RootData> RootSet; 01038 01039 public: 01040 SchedDFSImpl(SchedDFSResult &r): R(r), SubtreeClasses(R.DFSNodeData.size()) { 01041 RootSet.setUniverse(R.DFSNodeData.size()); 01042 } 01043 01044 /// Return true if this node been visited by the DFS traversal. 01045 /// 01046 /// During visitPostorderNode the Node's SubtreeID is assigned to the Node 01047 /// ID. Later, SubtreeID is updated but remains valid. 01048 bool isVisited(const SUnit *SU) const { 01049 return R.DFSNodeData[SU->NodeNum].SubtreeID 01050 != SchedDFSResult::InvalidSubtreeID; 01051 } 01052 01053 /// Initialize this node's instruction count. We don't need to flag the node 01054 /// visited until visitPostorder because the DAG cannot have cycles. 01055 void visitPreorder(const SUnit *SU) { 01056 R.DFSNodeData[SU->NodeNum].InstrCount = 01057 SU->getInstr()->isTransient() ? 0 : 1; 01058 } 01059 01060 /// Called once for each node after all predecessors are visited. Revisit this 01061 /// node's predecessors and potentially join them now that we know the ILP of 01062 /// the other predecessors. 01063 void visitPostorderNode(const SUnit *SU) { 01064 // Mark this node as the root of a subtree. It may be joined with its 01065 // successors later. 01066 R.DFSNodeData[SU->NodeNum].SubtreeID = SU->NodeNum; 01067 RootData RData(SU->NodeNum); 01068 RData.SubInstrCount = SU->getInstr()->isTransient() ? 0 : 1; 01069 01070 // If any predecessors are still in their own subtree, they either cannot be 01071 // joined or are large enough to remain separate. If this parent node's 01072 // total instruction count is not greater than a child subtree by at least 01073 // the subtree limit, then try to join it now since splitting subtrees is 01074 // only useful if multiple high-pressure paths are possible. 01075 unsigned InstrCount = R.DFSNodeData[SU->NodeNum].InstrCount; 01076 for (SUnit::const_pred_iterator 01077 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) { 01078 if (PI->getKind() != SDep::Data) 01079 continue; 01080 unsigned PredNum = PI->getSUnit()->NodeNum; 01081 if ((InstrCount - R.DFSNodeData[PredNum].InstrCount) < R.SubtreeLimit) 01082 joinPredSubtree(*PI, SU, /*CheckLimit=*/false); 01083 01084 // Either link or merge the TreeData entry from the child to the parent. 01085 if (R.DFSNodeData[PredNum].SubtreeID == PredNum) { 01086 // If the predecessor's parent is invalid, this is a tree edge and the 01087 // current node is the parent. 01088 if (RootSet[PredNum].ParentNodeID == SchedDFSResult::InvalidSubtreeID) 01089 RootSet[PredNum].ParentNodeID = SU->NodeNum; 01090 } 01091 else if (RootSet.count(PredNum)) { 01092 // The predecessor is not a root, but is still in the root set. This 01093 // must be the new parent that it was just joined to. Note that 01094 // RootSet[PredNum].ParentNodeID may either be invalid or may still be 01095 // set to the original parent. 01096 RData.SubInstrCount += RootSet[PredNum].SubInstrCount; 01097 RootSet.erase(PredNum); 01098 } 01099 } 01100 RootSet[SU->NodeNum] = RData; 01101 } 01102 01103 /// Called once for each tree edge after calling visitPostOrderNode on the 01104 /// predecessor. Increment the parent node's instruction count and 01105 /// preemptively join this subtree to its parent's if it is small enough. 01106 void visitPostorderEdge(const SDep &PredDep, const SUnit *Succ) { 01107 R.DFSNodeData[Succ->NodeNum].InstrCount 01108 += R.DFSNodeData[PredDep.getSUnit()->NodeNum].InstrCount; 01109 joinPredSubtree(PredDep, Succ); 01110 } 01111 01112 /// Add a connection for cross edges. 01113 void visitCrossEdge(const SDep &PredDep, const SUnit *Succ) { 01114 ConnectionPairs.push_back(std::make_pair(PredDep.getSUnit(), Succ)); 01115 } 01116 01117 /// Set each node's subtree ID to the representative ID and record connections 01118 /// between trees. 01119 void finalize() { 01120 SubtreeClasses.compress(); 01121 R.DFSTreeData.resize(SubtreeClasses.getNumClasses()); 01122 assert(SubtreeClasses.getNumClasses() == RootSet.size() 01123 && "number of roots should match trees"); 01124 for (SparseSet<RootData>::const_iterator 01125 RI = RootSet.begin(), RE = RootSet.end(); RI != RE; ++RI) { 01126 unsigned TreeID = SubtreeClasses[RI->NodeID]; 01127 if (RI->ParentNodeID != SchedDFSResult::InvalidSubtreeID) 01128 R.DFSTreeData[TreeID].ParentTreeID = SubtreeClasses[RI->ParentNodeID]; 01129 R.DFSTreeData[TreeID].SubInstrCount = RI->SubInstrCount; 01130 // Note that SubInstrCount may be greater than InstrCount if we joined 01131 // subtrees across a cross edge. InstrCount will be attributed to the 01132 // original parent, while SubInstrCount will be attributed to the joined 01133 // parent. 01134 } 01135 R.SubtreeConnections.resize(SubtreeClasses.getNumClasses()); 01136 R.SubtreeConnectLevels.resize(SubtreeClasses.getNumClasses()); 01137 DEBUG(dbgs() << R.getNumSubtrees() << " subtrees:\n"); 01138 for (unsigned Idx = 0, End = R.DFSNodeData.size(); Idx != End; ++Idx) { 01139 R.DFSNodeData[Idx].SubtreeID = SubtreeClasses[Idx]; 01140 DEBUG(dbgs() << " SU(" << Idx << ") in tree " 01141 << R.DFSNodeData[Idx].SubtreeID << '\n'); 01142 } 01143 for (std::vector<std::pair<const SUnit*, const SUnit*> >::const_iterator 01144 I = ConnectionPairs.begin(), E = ConnectionPairs.end(); 01145 I != E; ++I) { 01146 unsigned PredTree = SubtreeClasses[I->first->NodeNum]; 01147 unsigned SuccTree = SubtreeClasses[I->second->NodeNum]; 01148 if (PredTree == SuccTree) 01149 continue; 01150 unsigned Depth = I->first->getDepth(); 01151 addConnection(PredTree, SuccTree, Depth); 01152 addConnection(SuccTree, PredTree, Depth); 01153 } 01154 } 01155 01156 protected: 01157 /// Join the predecessor subtree with the successor that is its DFS 01158 /// parent. Apply some heuristics before joining. 01159 bool joinPredSubtree(const SDep &PredDep, const SUnit *Succ, 01160 bool CheckLimit = true) { 01161 assert(PredDep.getKind() == SDep::Data && "Subtrees are for data edges"); 01162 01163 // Check if the predecessor is already joined. 01164 const SUnit *PredSU = PredDep.getSUnit(); 01165 unsigned PredNum = PredSU->NodeNum; 01166 if (R.DFSNodeData[PredNum].SubtreeID != PredNum) 01167 return false; 01168 01169 // Four is the magic number of successors before a node is considered a 01170 // pinch point. 01171 unsigned NumDataSucs = 0; 01172 for (SUnit::const_succ_iterator SI = PredSU->Succs.begin(), 01173 SE = PredSU->Succs.end(); SI != SE; ++SI) { 01174 if (SI->getKind() == SDep::Data) { 01175 if (++NumDataSucs >= 4) 01176 return false; 01177 } 01178 } 01179 if (CheckLimit && R.DFSNodeData[PredNum].InstrCount > R.SubtreeLimit) 01180 return false; 01181 R.DFSNodeData[PredNum].SubtreeID = Succ->NodeNum; 01182 SubtreeClasses.join(Succ->NodeNum, PredNum); 01183 return true; 01184 } 01185 01186 /// Called by finalize() to record a connection between trees. 01187 void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth) { 01188 if (!Depth) 01189 return; 01190 01191 do { 01192 SmallVectorImpl<SchedDFSResult::Connection> &Connections = 01193 R.SubtreeConnections[FromTree]; 01194 for (SmallVectorImpl<SchedDFSResult::Connection>::iterator 01195 I = Connections.begin(), E = Connections.end(); I != E; ++I) { 01196 if (I->TreeID == ToTree) { 01197 I->Level = std::max(I->Level, Depth); 01198 return; 01199 } 01200 } 01201 Connections.push_back(SchedDFSResult::Connection(ToTree, Depth)); 01202 FromTree = R.DFSTreeData[FromTree].ParentTreeID; 01203 } while (FromTree != SchedDFSResult::InvalidSubtreeID); 01204 } 01205 }; 01206 } // namespace llvm 01207 01208 namespace { 01209 /// \brief Manage the stack used by a reverse depth-first search over the DAG. 01210 class SchedDAGReverseDFS { 01211 std::vector<std::pair<const SUnit*, SUnit::const_pred_iterator> > DFSStack; 01212 public: 01213 bool isComplete() const { return DFSStack.empty(); } 01214 01215 void follow(const SUnit *SU) { 01216 DFSStack.push_back(std::make_pair(SU, SU->Preds.begin())); 01217 } 01218 void advance() { ++DFSStack.back().second; } 01219 01220 const SDep *backtrack() { 01221 DFSStack.pop_back(); 01222 return DFSStack.empty() ? 0 : llvm::prior(DFSStack.back().second); 01223 } 01224 01225 const SUnit *getCurr() const { return DFSStack.back().first; } 01226 01227 SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; } 01228 01229 SUnit::const_pred_iterator getPredEnd() const { 01230 return getCurr()->Preds.end(); 01231 } 01232 }; 01233 } // anonymous 01234 01235 static bool hasDataSucc(const SUnit *SU) { 01236 for (SUnit::const_succ_iterator 01237 SI = SU->Succs.begin(), SE = SU->Succs.end(); SI != SE; ++SI) { 01238 if (SI->getKind() == SDep::Data && !SI->getSUnit()->isBoundaryNode()) 01239 return true; 01240 } 01241 return false; 01242 } 01243 01244 /// Compute an ILP metric for all nodes in the subDAG reachable via depth-first 01245 /// search from this root. 01246 void SchedDFSResult::compute(ArrayRef<SUnit> SUnits) { 01247 if (!IsBottomUp) 01248 llvm_unreachable("Top-down ILP metric is unimplemnted"); 01249 01250 SchedDFSImpl Impl(*this); 01251 for (ArrayRef<SUnit>::const_iterator 01252 SI = SUnits.begin(), SE = SUnits.end(); SI != SE; ++SI) { 01253 const SUnit *SU = &*SI; 01254 if (Impl.isVisited(SU) || hasDataSucc(SU)) 01255 continue; 01256 01257 SchedDAGReverseDFS DFS; 01258 Impl.visitPreorder(SU); 01259 DFS.follow(SU); 01260 for (;;) { 01261 // Traverse the leftmost path as far as possible. 01262 while (DFS.getPred() != DFS.getPredEnd()) { 01263 const SDep &PredDep = *DFS.getPred(); 01264 DFS.advance(); 01265 // Ignore non-data edges. 01266 if (PredDep.getKind() != SDep::Data 01267 || PredDep.getSUnit()->isBoundaryNode()) { 01268 continue; 01269 } 01270 // An already visited edge is a cross edge, assuming an acyclic DAG. 01271 if (Impl.isVisited(PredDep.getSUnit())) { 01272 Impl.visitCrossEdge(PredDep, DFS.getCurr()); 01273 continue; 01274 } 01275 Impl.visitPreorder(PredDep.getSUnit()); 01276 DFS.follow(PredDep.getSUnit()); 01277 } 01278 // Visit the top of the stack in postorder and backtrack. 01279 const SUnit *Child = DFS.getCurr(); 01280 const SDep *PredDep = DFS.backtrack(); 01281 Impl.visitPostorderNode(Child); 01282 if (PredDep) 01283 Impl.visitPostorderEdge(*PredDep, DFS.getCurr()); 01284 if (DFS.isComplete()) 01285 break; 01286 } 01287 } 01288 Impl.finalize(); 01289 } 01290 01291 /// The root of the given SubtreeID was just scheduled. For all subtrees 01292 /// connected to this tree, record the depth of the connection so that the 01293 /// nearest connected subtrees can be prioritized. 01294 void SchedDFSResult::scheduleTree(unsigned SubtreeID) { 01295 for (SmallVectorImpl<Connection>::const_iterator 01296 I = SubtreeConnections[SubtreeID].begin(), 01297 E = SubtreeConnections[SubtreeID].end(); I != E; ++I) { 01298 SubtreeConnectLevels[I->TreeID] = 01299 std::max(SubtreeConnectLevels[I->TreeID], I->Level); 01300 DEBUG(dbgs() << " Tree: " << I->TreeID 01301 << " @" << SubtreeConnectLevels[I->TreeID] << '\n'); 01302 } 01303 } 01304 01305 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 01306 void ILPValue::print(raw_ostream &OS) const { 01307 OS << InstrCount << " / " << Length << " = "; 01308 if (!Length) 01309 OS << "BADILP"; 01310 else 01311 OS << format("%g", ((double)InstrCount / Length)); 01312 } 01313 01314 void ILPValue::dump() const { 01315 dbgs() << *this << '\n'; 01316 } 01317 01318 namespace llvm { 01319 01320 raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) { 01321 Val.print(OS); 01322 return OS; 01323 } 01324 01325 } // namespace llvm 01326 #endif // !NDEBUG || LLVM_ENABLE_DUMP