LLVM 24.0.0git
HexagonGlobalSchedulerV2.cpp
Go to the documentation of this file.
1//===----- HexagonGlobalSchedulerV2.cpp - Global Scheduler ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Basic infrastructure for the global scheduling + Hexagon pull-up pass.
10// Currently run at the very end of code generation for Hexagon, cleans
11// up lost scheduling opportunities. Liveness is preserved after this pass,
12// and we should not run a liveness analysis after this pass because compound
13// instructions might be formed which do not fit into the usual model of
14// use-after-def of regs.
15//
16// @note: Local pullup runs after global scheduling because global pullup
17// leaves room in packets that local instructions can fill.
18//
19// @note: Local push-down moves instructions into the immediate successor
20// packet only.
21//
22// Brief overview of working of this global scheduler.
23// This version of Hexagon Global Scheduler is basically a greedy scheduler.
24// The main purpose of this VLIW global scheduler is to increase the packet
25// density (= #instructions/#packets). Since the VLIW packetizer works on a
26// local scope, it cannot fill up the packets very efficiently.
27// Having a global scheduler post-SSA makes it a complicated infrastructure
28// because it has to deal with liveness+dependencies of physical registers.
29// As a result, many strict measures have been taken to ensure correctness.
30// There are assertions put at places where some assumptions were implicit.
31// This also means that many optimization opportunities are not explored.
32//
33// The global scheduler heavily relies on HexagonLiveVariables.cpp and
34// HexagonVLIWPacketizer.cpp.
35// There is one function isLegalToPacketizeTogetherMI() which copies little
36// bit of code from HexagonPacketizerList::isLegalToPacketizeTogether, because
37// this the packetizer version takes in SchedulingUnits as arguments and
38// it wasn't easy to refactor it completely. Please update both the functions
39// in a coherent way. Or better, instead, add code to one
40// of the following three functions:
41//
42// HexagonPacketizerList::hasDeadDependence
43// HexagonPacketizerList::hasControlDependence
44// HexagonPacketizerList::hasDualStoreDependence
45//
46//
47// Step by step explanation of the process of global scheduling.
48//
49// Step1: Correct the CFG.
50// The packetizer/other-pass may leave MBB in a state where there are
51// non-branching instructions after the branches. This pass corrects the CFG
52// so that branches are the only instructions at the very end. This helps
53// reuse analyzeBranch even after packetizer.
54//
55// Step2: Form Scheduling regions.
56// Scheduling regions are sets of basic blocks which have only one entry point
57// but, possibly, multiple exit points. This is essentially a super-block.
58//
59// Step3: Sort Scheduling regions.
60// Sort scheduling regions based on profile/branch-probability. This gives
61// priority to instructions from branch targets with higher probability. In the
62// case where both branches have same probability, it biases one successor by
63// increasing the weight of TBB (see analyzeBranch).
64// - During this pass, AnalyzeBranchInfo of all the MBBs are
65// calculated and stored to be reused later. Care must be taken to update
66// the branch-info when a branch is modified (mostly post-pullup opts)
67//
68// Step4: Perform global+local scheduling of instructions.
69// Global scheduling is done first followed by local.
70// Global scheduling: globalPullup(SchedulingRegion_t &SR)
71// Speculative scheduling is done first followed by predicated scheduling.
72// for each scheduling region
73// for each MBB in a scheduling region
74// for each MI in leaf MBB
75// find a MI candidate by calling canMIBeSpeculated
76// YES=>speculate.
77// YES means it has to be speculated. There is no coming back.
78// These strict checks are necessary to ensure correctness in this
79// complicated infrastructure.
80// NO=>Try to squeeze the bundle by making a compound instruction
81// and hence, freeing up one slot. Only in special cases where
82// `bool preciousToSpeculate' returns true, the opportunities for
83// compound instructions are explored. If it is possible to create
84// a compound then the compound instruction
85// (generateCompoundIfPossible()) is created and again
86// decomposed into individual instructions. This is done because
87// it is not possible to analyzeBranch a BB with compounds (for now).
88//
89// And then try again by calling canMIBeSpeculated
90// YES=>speculate. The bundle now contains five instructions. Since
91// the bundle contains five instructions, care must be taken to
92// avoid doing too much around that packet, because there is no
93// available infrastructure to support five-instruction bundles.
94// NO=>move on to the next MI.
95//
96// for each MI in leaf MBB
97// find a MI candidate by calling canMIBePredicated
98// YES=>predicate.
99// YES means it has to be predicated. There is no coming back.
100// NO=>Try to squeeze the bundle by making a compound instruction
101// and hence, freeing up one slot. Only in special cases where
102// `bool preciousToPredicate' returns true, the opportunities for
103// compound instructions are explored.
104//
105// And then try again by calling canMIBePredicated.
106// This is identical to the case of speculative scheduling.
107//
108//
109// Local scheduling: localPullup
110// Reuses some functionalities of speculative pullup.
111// The function findInsertPtSpec has been designed to be reused for both
112// local+global `speculative' scheduling. Similarly, srcDependence() and
113// dstDependence() are reused.
114//
115// Step5: Packetize
116// When post-sched-packet is enabled (by default), repacketize the MBBs from
117// where pull up moved instructions.
118//
119// Step6: Post scheduling optimizations
120// These are branch optimizations and they modify the CFG. During this stage
121// MBBs having compounds are skipped because analyzeBranch cannot handle
122// compound branches.
123// During this stage AnalyzeBranchInfo is updated whenever a branch
124// optimization was successful.
125//
126// Step7: Generate compound instructions.
127// The function `generateCompoundsPostSched' re-generates compound instructions
128// at places where 5-instruction packets were formed during scheduling.
129//
130// Important functions which are used at multiple places:
131//
132// MII is already a bundle. This will initialize the packetizer and update
133// the DFA with existing resources so that the DFA can be queried for more
134// information e.g. can we put another MI in the bundle?
135// void getResourcesReadyForBundle(MIInstIterType MII, bool Squeeze = false);
136//
137// Returns true if resources are available for MII in the current packet
138// after getResourcesReadyForBundle has been called to initialize the DFA.
139// Takes into account const-extenders as well.
140// bool canReserveResources(MIInstIterType MII) const;
141//
142// When the resources are available, as checked by canReserveResources(),
143// we need to check for compatibility between MI and the destination bundle.
144// This function returns true if MI is compatible. This also takes care of
145// a special case when a branch and its target are too far, and
146// the branch might be constant extended.
147// bool isLegalToPacketizeWith(MIIterType DestPack, MachineInstr *MI);
148//
149// While global scheduling there are two parts.
150// 1. The instruction should be able to execute as the first instruction
151// within its Home/Src MBB. This is handled in findInsertionPtSpecLocal.
152//
153// 2. The instruction should be able to execute in parent/dominating MBB
154// without causing side-effects. This is handled in findInsertPtSpec()
155// while speculating and findInsertPtPred() while predicating.
156//
157// This function will return MBB->begin() if it is possible to move this
158// instruction to the beginning of MBB.
159// MIIterType findInsertionPtSpecLocal(MachineInstr *MI);
160//
161// The function findInsertionPtSpecLocal calls srcDependence which tells if
162// it is possible to `detach' the MI from its Home/Src BUNDLE. For example
163// when there is a .new/duplex etc. dependency we don't want to detach the MI.
164// Dependence within the same packet [SrcBeg, SrcEnd).
165// int srcDependence(MIInstIterType SrcBeg, MIInstIterType SrcEnd,
166// MIInstIterType RMII,
167// SmallPtrSetImpl<MachineInstr *> *DepSet)
168// const;
169//
170// This function checks for dependencies between a range of MIIs
171// in the destination/target MBB (where MII will end up). Obviously, in the
172// case of predication we first create a dummy predicate instruction
173// in canMIBePredicated() which calls findInsertPtPred() which then
174// calls dstDependence() to check for dependencies.
175// int dstDependence(MICInstIterType DestBeg, MICInstIterType DestEnd,
176// MICInstIterType MII, MICInstIterType &DepTrue,
177// MICInstIterType &DepAnti, unsigned HLXUseReg = 0,
178// bool isPullDown = false) const;
179//
180//===----------------------------------------------------------------------===//
181#include "Hexagon.h"
182#include "HexagonGlobalRegion.h"
183#include "HexagonInstrInfo.h"
184#include "HexagonLiveVariables.h"
185#include "HexagonRegisterInfo.h"
186#include "HexagonSubtarget.h"
187#include "HexagonTargetMachine.h"
189#include "llvm/ADT/SmallVector.h"
190#include "llvm/ADT/Statistic.h"
201#include "llvm/Support/Debug.h"
202
203#include <map>
204#include <unordered_map>
205
206#define DEBUG_TYPE "global_schedV2"
207
208using namespace llvm;
209
210STATISTIC(HexagonGSLocalPullups, "Number of instructions pull-ups locally");
211STATISTIC(HexagonGSGlobalPullups, "Number of instructions pull-ups globally");
212
213static cl::opt<bool>
214 EnableGlobalSched("enable-global-sched", cl::Hidden, cl::init(false),
215 cl::desc("Enable global scheduler optimizer"));
216
217static cl::opt<bool> EnablePullupPred("enable-pullup-pred", cl::Hidden,
218 cl::init(true),
219 cl::desc("Use pullup predication"));
220
221static cl::opt<bool>
222 EnableLocalPullup("enable-local-pullup", cl::Hidden, cl::init(true),
223 cl::desc("Speculate local MIs in parent BUNDLEs"));
224
226 "enable-local-merge-packets", cl::Hidden, cl::init(true),
227 cl::desc("Push down local MIs into the next packet"));
228
229static cl::opt<bool> PostSchedOpt("post-sched-opt", cl::Hidden, cl::init(true),
230 cl::desc("Optimize after global scheduling"));
231
232static cl::opt<bool>
233 PostSchedPack("post-sched-packet", cl::Hidden, cl::init(true),
234 cl::desc("Packetize unbundled MIs after global scheduling"));
235
236static cl::opt<bool>
237 NoPredInBundle("nopred-sched-bundle", cl::Hidden,
238 cl::desc("Do not put predicated instructions in bundle"));
239
240static cl::opt<bool>
241 NoSpecInBundle("nospec-sched-bundle", cl::Hidden,
242 cl::desc("Do not put speculated instructions in bundle"));
243
244static cl::opt<bool>
245 EnableSqueeze("try-squeeze-bundle", cl::Hidden, cl::init(true),
246 cl::desc("Try putting 5 instructions in bundle"));
247
248// Defaults to true up to -O2 and to false above it.
250 "prevent-duplex-sep-v2", cl::Hidden, cl::init(true),
251 cl::desc(
252 "Prevent separation of duplex while pullup in global scheduler V2"));
253
254static cl::opt<bool>
255 PullUnsafeMemops("pull-unsafe-memops", cl::Hidden, cl::init(true),
256 cl::desc("Pull up loads which have no memoperands"));
257
258// Run the machine verifier at several stages of the pass (assert builds).
260 "verify-global-sched", cl::Hidden, cl::init(false),
261 cl::desc("Run the machine verifier at several stages of global scheduler"));
262
263static cl::opt<bool>
264 PredicateAllInst("predicate-all-inst", cl::Hidden,
265 cl::desc("Try predicating all possible instructions."));
266
267static cl::opt<bool>
268 SpeculateAllInst("speculate-all-inst", cl::Hidden,
269 cl::desc("Try speculating all possible instructions."));
270
272 "hexagon-pullup-distance", cl::Hidden, cl::init(10),
273 cl::desc("Maximum number of bundles to check for local pull-up"));
274
276 "enable-single-loop-superblock", cl::Hidden, cl::init(true),
277 cl::desc("Enable superblocks consisting of single block loops."));
278
280 "enable-hvx-local-pullup-load-bypass", cl::Hidden, cl::init(true),
281 cl::desc("Enable the HVX local pull-up pass (load bypass only)."));
282
284 "enable-lcgp-for-load-bypass-only", cl::Hidden, cl::init(true),
285 cl::desc("Enable the HVX last chance global pull-up for load-bypass-only"));
286
287// Enables tryTwoLoadCurBypass: a .cur load bypass for a consumer with up to
288// two producers in one packet; the producer that is not the load is moved
289// away by lastChanceGlobalPullup to free a slot. Off by default.
291 "enable-hvx-two-load-cur-bypass", cl::Hidden, cl::init(false),
292 cl::desc("Enable the two-load .cur load-bypass case in local pull-up."));
293
294static cl::opt<bool>
295 EnableHVXLocalPullup("enable-hvx-local-pullup", cl::Hidden, cl::init(true),
296 cl::desc("Enable the HVX local pull-up pass."));
297
299 "enable-hvx-local-pullup-innermost", cl::Hidden, cl::init(false),
300 cl::desc("Enable the HVX local pull-up pass on single block innermost "
301 "loops only."));
302
304 "disable-hvx-sched-superblock", cl::Hidden, cl::init(false),
305 cl::desc("Disable single block loops in superblocks and the HVX local "
306 "pull-up pass."));
307
308static cl::opt<bool>
309 EnableHVXLCGP("enable-hvx-lcgp", cl::Hidden, cl::init(true),
310 cl::desc("Enable the HVX last chance global pull-up pass."));
311
313 "enable-hvx-superblock-heuristic", cl::Hidden, cl::init(true),
314 cl::desc("Run HVX scheduling only on blocks whose ratio of HVX "
315 "instructions exceeds -hvx-sched-profit-ratio."));
316
317static cl::opt<float>
318 HVXSchedProfitRatio("hvx-sched-profit-ratio", cl::Hidden, cl::init(0.80),
319 cl::desc("Ratio of HVX instruction/Total instructions "
320 "for the profitability check."));
321
323 "enable-hlx-load-store-pullup", cl::Hidden, cl::init(true),
324 cl::desc("Pull up HLX .tmp load uses and .new HLX stores to remove the "
325 "copies inserted by HLX load/store expansion"));
326
327static cl::opt<bool>
328 EnableSparsePullup("enable-sparse-pullup", cl::Hidden, cl::init(true),
329 cl::desc("Enable pullup to/from sparse packets"));
330
331/// Enable cluster pullup optimization.
332/// Cluster pullup allows pulling up groups of dependent instructions together,
333/// rather than just individual instructions. This is particularly important for
334/// HVX/HLX instructions where .tmp and .cur dependencies create instruction
335/// chains that must be moved atomically to maintain correctness.
337 "enable-cluster-pullup", cl::Hidden, cl::init(true),
338 cl::desc("Enable pullup for dependent instruction groups"));
339
341
344
345namespace {
346
347typedef MachineBasicBlock::iterator MIIterType;
348typedef MachineBasicBlock::const_iterator MICIterType;
349typedef MachineBasicBlock::instr_iterator MIInstIterType;
350typedef MachineBasicBlock::const_instr_iterator MICInstIterType;
351typedef MachineBasicBlock::reverse_iterator MIRIterType;
352
353// The Scheduler Class.
354class GlobalScheduler : public HexagonPacketizerList {
355public:
356 // Data structure to store the analyzeBranch.
357 // ABI => Analyze Branch Info.
358 struct ABI {
359 MachineBasicBlock *TBB, *FBB;
360 MachineInstr *FirstTerm, *SecondTerm;
362 bool AnalysisValid;
363 ABI()
364 : TBB(NULL), FBB(NULL), FirstTerm(NULL), SecondTerm(NULL),
365 AnalysisValid(false) {}
366 bool analyzeBranch(MachineBasicBlock *MBB, const HexagonInstrInfo *QII,
367 bool PostSched);
368 void dump() {
369 LLVM_DEBUG(if (TBB) dbgs() << "\nTBB: " << TBB->getNumber();
370 if (FBB) dbgs() << ", FBB: " << FBB->getNumber();
371 if (FirstTerm) dbgs() << ", FirstTerm: " << *FirstTerm;
372 if (SecondTerm) dbgs() << ", SecondTerm: " << *SecondTerm);
373 }
374 };
375 struct AnalyzeBranchInfo_t {
376 typedef std::map<MachineBasicBlock *, ABI> BranchAnalyses_t;
377 BranchAnalyses_t BranchAnalyses;
378
379 // It always returns an ABI so the caller should check if the
380 // branch analysis was valid or not.
381 ABI &getOrCreate(MachineBasicBlock *MBB, const HexagonInstrInfo *QII,
382 bool PostSched = false) {
383 ABI &abi = BranchAnalyses[MBB];
384 if (!abi.AnalysisValid)
385 abi.analyzeBranch(MBB, QII, PostSched);
386 return abi;
387 }
388 void invalidate(MachineBasicBlock *MBB) {
389 iterator it = BranchAnalyses.find(MBB);
390 assert((it != BranchAnalyses.end()) &&
391 "Cannot invalidate un-analyzed branch.");
392 BranchAnalyses.erase(it);
393 }
394 bool hasABInfo(MachineBasicBlock *MBB) const {
395 return BranchAnalyses.find(MBB) != BranchAnalyses.end();
396 }
397
398 typedef BranchAnalyses_t::iterator iterator;
399 typedef BranchAnalyses_t::const_iterator const_iterator;
400 typedef BranchAnalyses_t::size_type size_type;
401
402 iterator begin() { return BranchAnalyses.begin(); }
403 const_iterator begin() const { return BranchAnalyses.begin(); }
404 iterator end() { return BranchAnalyses.end(); }
405 const_iterator end() const { return BranchAnalyses.end(); }
406 bool empty() const { return BranchAnalyses.empty(); }
407 void clear() { BranchAnalyses.clear(); }
408 size_type size() const { return BranchAnalyses.size(); }
409 };
410
411 // Data structure to store a scheduling region.
412 struct SchedulingRegion_t {
413 typedef SmallVector<MachineBasicBlock *, 2> SRMembers_t;
414 typedef MachineBasicBlock SRAtom_t;
415 BranchProbability EdgeProb;
416 SRMembers_t Members;
417 SchedulingRegion_t() : EdgeProb(BranchProbability::getZero()) {}
418
419 void addSRMember(MachineBasicBlock *MBB) { Members.push_back(MBB); }
420
421 void dump() {
422 SmallVector<MachineBasicBlock *, 2>::iterator MBBI = Members.begin();
423 while (MBBI != Members.end()) {
424 LLVM_DEBUG(dbgs() << "\tBB#" << (*MBBI)->getNumber(););
425 ++MBBI;
426 }
427 }
428 typedef SRMembers_t::iterator iterator;
429 typedef SRMembers_t::reverse_iterator reverse_iterator;
430 typedef SRMembers_t::const_iterator const_iterator;
431 typedef SRMembers_t::const_reverse_iterator const_reverse_iterator;
432 typedef SRMembers_t::size_type size_type;
433
434 iterator begin() { return Members.begin(); }
435 const_iterator begin() const { return Members.begin(); }
436 reverse_iterator rbegin() { return Members.rbegin(); }
437 const_reverse_iterator rbegin() const { return Members.rbegin(); }
438 iterator end() { return Members.end(); }
439 const_iterator end() const { return Members.end(); }
440 reverse_iterator rend() { return Members.rend(); }
441 const_reverse_iterator rend() const { return Members.rend(); }
442 bool empty() const { return Members.empty(); }
443 void clear() { Members.clear(); }
444 size_type size() const { return Members.size(); }
445 bool operator<(const SchedulingRegion_t &RHS) {
446 return EdgeProb < RHS.EdgeProb;
447 }
448 bool operator<=(const SchedulingRegion_t &RHS) const {
449 return EdgeProb <= RHS.EdgeProb;
450 }
451 bool operator>(const SchedulingRegion_t &RHS) const {
452 return EdgeProb > RHS.EdgeProb;
453 }
454 bool operator>=(const SchedulingRegion_t &RHS) const {
455 return EdgeProb >= RHS.EdgeProb;
456 }
457 };
458
459 using Dependency = HexagonInstrInfo::Dependency;
460
461 // Typedefs.
462 typedef SmallVector<SchedulingRegion_t, 2> SchedulingRegions_t;
463 typedef DenseMap<SchedulingRegion_t::SRAtom_t *,
465 PulledUpII;
466
467 // Constructor.
468 GlobalScheduler(const HexagonTargetMachine *tm, const HexagonInstrInfo *qii,
469 const HexagonRegisterInfo *tri, MachineFunction &mf,
470 MachineLoopInfo &mli, AliasAnalysis *aa,
471 const MachineBranchProbabilityInfo *mbpi,
472 HexagonLiveVariables *hlv)
473 : HexagonPacketizerList(mf, mli, aa, mbpi, false), TM(tm), QII(qii),
474 TRI(tri), HLV(hlv), MF(mf), MLI(mli), GlobalSpeculatedIns(0),
475 GlobalPredicatedIns(0), LocalPullups(0), SafetyBuffer(200),
476 SafetyBufferDelta(50) {
477 useHVXOps = mf.getSubtarget<HexagonSubtarget>().useHVXOps();
478 useHLXOps = mf.getSubtarget<HexagonSubtarget>().useHLXOps();
479 // TinyCore has different scheduling constraints and resource limits.
480 // Track this to adjust scheduling heuristics accordingly.
481 IsTinyCore = mf.getSubtarget<HexagonSubtarget>().isTinyCore();
482 }
483
484 // Dummy addtoPacket to emulate packetization.
485 MachineBasicBlock::iterator addToPacketPseudo(MachineInstr *MI);
486 void initPacketizerStateLoc();
487 // Is it legal to packetize \p MI with instructions in DestPack.
488 bool isLegalToPacketizeWith(MIIterType DestPack, MachineInstr *MI);
489 // Mimics Packetizers isLegalToPacketizeTogether, plus some more checks.
490 inline bool isLegalToPacketizeTogetherMI(MachineInstr *BI, MachineInstr *MI);
491 // Instructions for which pulled up is disabled
492 inline bool shouldNotBePulledUp(const MachineInstr *MI) const;
493
494 /// Check if it is legal to pull up ToMove across MI during scheduling.
495 /// This function determines if MI is a "barrier" instruction that ToMove
496 /// cannot be moved past.
497 /// \param MI The instruction that might block the move
498 /// \param ToMove The instruction being considered for pullup (optional)
499 /// \param IsMIInDestBundle True if MI is in the destination bundle where
500 /// ToMove will be inserted
501 /// \return true if ToMove should NOT cross MI (i.e., MI is a barrier)
502 inline bool shouldNotBeCrossed(const MachineInstr *MI,
503 const MachineInstr *ToMove,
504 bool IsMIInDestBundle = false) const;
505 // Reserve the resources for Bundle in the resource tracker.
506 // Make compound/duplex instructions when \p Squeeze=true.
507 void getResourcesReadyForBundle(MIInstIterType MII, bool Squeeze = false,
508 MachineInstr *InstrToSkip = nullptr);
509 MachineInstr *generateCompoundIfPossible(MIInstIterType MII,
510 MIInstIterType &GA,
511 MIInstIterType &GB);
512 // TODO: Once MCShuffler can accept bundles with five instructions remove
513 // this function.
514 void generateCompoundsPostSched();
515
516 // Functions to optimize for auto-and predicates
517 bool failsSpecialConditions(MachineInstr *BundleMI, Register DestReg);
518 bool canNewifyPredReg(unsigned Reg, MICInstIterType Producer,
519 MICInstIterType Sentinel) const;
520 bool getDefinitions(MachineInstr *MI, MachineInstr *&Def1,
521 MachineInstr *&Def2, MachineInstr *&Def3);
522 void generateAutoAndPredicates(MachineFunction &MF);
523
524 void packetize();
525 // Returns true if resources are available for MII in the current packet.
526 // Takes into account const-extenders as well.
527 bool canReserveResources(MIInstIterType MII) const;
528 // The usage of \p Reg is replaced by \p ScratchReg.
529 void replaceUsageOfReg(unsigned Reg, unsigned ScratchReg,
530 MachineBasicBlock *MBB,
531 const MachineInstr *ExceptMI = NULL) const;
532 inline void markLiveInsAsUsed(std::unique_ptr<RegScavenger> &RS,
533 MachineBasicBlock *MBB) const;
534 inline void markLiveOutsAsUsed(std::unique_ptr<RegScavenger> &RS,
535 MachineBasicBlock *MBB) const;
536 void markAllRegsAsUsed(std::unique_ptr<RegScavenger> &RS,
537 const MachineBasicBlock *MBB) const;
538 MachineBasicBlock *splitCriticalEdge(MachineBasicBlock *FromBB,
539 MachineBasicBlock *ToBB,
540 MachineBasicBlock *LP);
541 bool hasOneDef(const MachineInstr *MI, unsigned &DefR) const;
542 bool hasOneUse(const MachineInstr *MI, unsigned &UseR) const;
543 bool hasOneDefAndUse(const MachineInstr *MI, unsigned &Def,
544 unsigned &Use) const;
545 MICInstIterType laterOfTheTwo(MICInstIterType I1, MICInstIterType I2,
546 MICInstIterType Sentinel) const;
547 // Supporting API to figure out if the branching instruction MII,
548 // is followed by non-branching instruction.
549 bool branchesInBetweenMBB(MIInstIterType MII, MachineBasicBlock *MBB);
550
551 bool splitMBBAt(MIInstIterType MII, MachineBasicBlock *MBB);
552
553 // Generates control flow by removing 3 way branching.
554 void generateCFG(MachineFunction &MF);
555
556 virtual void schedule() = 0;
557
558 // Mostly branch related optimizations.
559 void performExposedOptimizations();
560 void removeEmptyMBB(MachineBasicBlock *MBB);
561 bool makeAsLayoutSuccessor(MachineBasicBlock *BB1, MachineBasicBlock *BB2);
562 bool removeRedundantBranches(MachineBasicBlock *MBB, MachineBasicBlock *TBB,
563 MachineInstr *FirstTerm, MachineBasicBlock *FBB,
564 MachineInstr *SecondTerm);
565 bool optimizeDualJumps(MachineBasicBlock *MBB, MachineBasicBlock *TBB,
566 MachineInstr *FirstTerm, MachineBasicBlock *FBB,
567 MachineInstr *SecondTerm);
568 MachineBasicBlock *optimizeBranches(MachineBasicBlock *MBB,
569 MachineBasicBlock *TBB,
570 MachineInstr *FirstTerm,
571 MachineBasicBlock *FBB);
572 // A region could be a set of MBBs (Hyperblocks)
573 // where scheduling algorithms could work. Default scheduling region
574 // consists of MBBs where there is a single entry point i.e., the head
575 // of scheduling region. It has at least one exit point i.e., the tail
576 // of the scheduling region.
577 // Criteria of HEAD of a scheduling region (Superblock).
578 // 1. MF.begin()
579 // 2. MBB with more than one successor:
580 // - Can be part of multiple scheduling regions.
581 // For simplicity we'll make this as HEAD as well. This lets us not
582 // worry about the loop as a special case.
583 // 3. MBB with more than one predecessor:
584 // - Will always be (if at all) the HEAD of the scheduling region.
585 virtual void formSchedulingRegions(MachineFunction &MF);
586
587 void printSchedulingRegions() {
589 SchedulingRegions.begin();
590 SRI != SchedulingRegions.end(); ++SRI) {
591 dbgs() << "\nScheduling Region: ";
592 SRI->dump();
593 } dbgs() << "\nTotal Scheduling Regions: "
594 << SchedulingRegions.size() << "\n";);
595 }
596
597 // PruneCriteria returns true if that scheduling region can be removed.
598 typedef bool (GlobalScheduler::*PruneCriteriaFP)(SchedulingRegion_t &) const;
599
600 // Decides whether a scheduling region is to be kept for scheduling.
601 // Returns true when it is okay to remove that region.
602 bool pruneCriteria(SchedulingRegion_t &SR) const {
603 assert(!SR.Members.empty() && "Empty Scheduling region.");
604 if (SR.Members.size() == 1)
605 return true;
606 // If the members are not in the same loop then remove the SR.
607 // We do not want to speculate from outside of loop into the loop body,
608 // unless in a very special case which we deal with in speculateMI.
609 MachineLoop *HeadLI = MLI.getLoopFor(SR.Members[0]);
610 MachineLoop *LeafLI = MLI.getLoopFor(SR.Members[1]);
611
612 bool speculateInnerToOuter = false;
613 if (EnableSingleLoopSuperblock && useHVXOps &&
615 if (HeadLI != nullptr && LeafLI != nullptr) {
616 if (HeadLI->getLoopDepth() < LeafLI->getLoopDepth())
617 speculateInnerToOuter = true;
618 }
619 }
620
621 if (HeadLI != LeafLI && !speculateInnerToOuter)
622 return true;
623 return false;
624 }
625
626 // Removes scheduling regions which cannot/need-not be scheduled.
627 virtual void pruneSchedulingRegions(PruneCriteriaFP PC);
628
629 // Prefers scheduling regions with high branch probability.
630 virtual void sortSchedulingRegions();
631
632 bool isSuperblockLoop(MachineLoop *L);
633 virtual bool isProfitableToScheduleHVX(MachineLoop *L);
634 virtual bool isProfitableToScheduleHVX(MachineBasicBlock *MBB);
635
636protected:
637 // Member variables.
638 const HexagonTargetMachine *TM;
639 const HexagonInstrInfo *QII;
640 const HexagonRegisterInfo *TRI;
641 HexagonLiveVariables *HLV;
642 MachineFunction &MF;
643 MachineLoopInfo &MLI;
644
645 // Since we need to use analyze branch a lot. It is better to save the
646 // analyzeBranch information. Care, however, must be taken to update
647 // this object whenever a basic block is changed.
648 AnalyzeBranchInfo_t AnalyzeBranchInfo;
649 SchedulingRegions_t SchedulingRegions;
650 // Locations where more opportunities of packetization are possible.
651 SmallVector<MachineInstr *, 4> SpecPacketOpp;
652 // Set of bundles which have compound instructions. We need to generate
653 // compound because MCShuffler rejects bundles with five instructions.
654 DenseSet<MachineInstr *> ToBeSqueezed;
655 // Ignore any post-sched opts on these MBBs.
656 SmallVector<MachineBasicBlock *, 1> IgnorePostSchedOpt;
657 // List of Speculated instructions inside each MBB (MBB is the destination)
658 PulledUpII SpeculatedIns;
659 // Global pull up from an MBB creates scope for local push-down.
660 // LocalMergePackCand keeps the list of MBBs from where MI was pulled-up.
661 std::set<MachineBasicBlock *> LocalMergePackCand;
662 // Single block loops for HVX local pullup pass.
663 std::unordered_map<MachineBasicBlock *, float> ProfitableHVXBlocks;
664 unsigned GlobalSpeculatedIns;
665 unsigned GlobalPredicatedIns;
666 unsigned LocalPullups;
667 const unsigned SafetyBuffer;
668 // In case when MBBs are moved in between Jump and their targets.
669 int SafetyBufferDelta;
670 // Is HVX support enabled?
671 bool useHVXOps = false;
672 // Is HLX support enabled?
673 bool useHLXOps = false;
674 // Is target CPU TinyCore? TinyCore has reduced resources and different
675 // scheduling constraints compared to full Hexagon cores.
676 bool IsTinyCore = false;
677};
678
679class GreedyPullup : public GlobalScheduler {
680public:
681 GreedyPullup(const HexagonTargetMachine *tm, const HexagonInstrInfo *qii,
682 const HexagonRegisterInfo *tri, MachineFunction &mf,
683 MachineLoopInfo &mli, AliasAnalysis *aa,
684 const MachineBranchProbabilityInfo *mbpi,
685 HexagonLiveVariables *hlv)
686 : GlobalScheduler(tm, qii, tri, mf, mli, aa, mbpi, hlv) {}
687
688 void schedule() override {
689 for (SchedulingRegions_t::iterator SRI = SchedulingRegions.begin();
690 SRI != SchedulingRegions.end(); ++SRI) {
691 unsigned currSpec = GlobalSpeculatedIns;
692 unsigned currPred = GlobalPredicatedIns;
693 globalPullup(*SRI);
694 LLVM_DEBUG(SRI->dump(););
695 (void)currSpec;
696 (void)currPred;
698 dbgs() << "\n\nCurrent BB Global Pullup stats: Speculated Ins: "
699 << GlobalSpeculatedIns - currSpec
700 << ", Predicated Ins: " << GlobalPredicatedIns - currPred;);
701 }
702
704
706 while (MBBI != MF.end()) {
707 LocalPullups = 0;
708 if (!MBBI->empty() && // Empty elements in a scheduling region.
709 std::find(IgnorePostSchedOpt.begin(), IgnorePostSchedOpt.end(),
710 &*MBBI) == IgnorePostSchedOpt.end()) { // Ignorable MBB?
711 localPullupHLX(&*MBBI);
712 localPullup(&*MBBI);
713 localPullupHVX(&*MBBI);
714 }
715
716 ++MBBI;
718 dbgs() << "\n\nCurrent BB Local Pullup stats: Speculated Ins: "
719 << LocalPullups;);
720 // TODO: Keep track of MBBs where LocalPullup > 0. Then we can do
721 // global scheduling in the regions having this MBB as more
722 // opportunities might have arisen.
723 HexagonGSLocalPullups += LocalPullups;
724 }
725
726 // Merge an instruction into adjacent packet.
728 mergePackets();
729
730 HexagonGSGlobalPullups = GlobalPredicatedIns + GlobalSpeculatedIns;
731
733 dbgs() << "\n\n**********Total Greedy Pullup stats**********"
734 << "\nGlobal speculated instructions: " << GlobalSpeculatedIns
735 << "\nGlobal predicated instructions: " << GlobalPredicatedIns
736 << "\nLocal speculated instruction: " << HexagonGSLocalPullups
737 << "\n";);
738 }
739
740 // Check if moving SrcMI to DestBundle will cause an interlock stall.
741 bool canCauseInterlockStall(MIInstIterType DestBundle, MachineInstr *SrcMI,
742 const InstrItineraryData *II);
743 // Generate the load-bypass (.cur) after moving InstrToMove after LoadInstr.
744 void genLoadBypass(MachineInstr *LoadInstr, MachineInstr *InstrToMove);
745 // Returns true if a single RAW dependence on \p DepTrue (a .cur-able HVX
746 // load in DestBundle) can be satisfied via a .cur load bypass when pulling
747 // up a consumer. \p PktEnd bounds the destination packet for the
748 // no-other-consumer safety check.
749 bool canGenCurBypass(MIInstIterType DestBundle, MachineInstr *DepTrue,
750 MIInstIterType PktEnd, int DstDep,
751 MachineInstr *Consumer,
752 const MachineInstr *Exempt = nullptr);
753 // Two-load .cur bypass: try to pull \p SrcMI (a single consumer with two
754 // RAW producers sharing a packet, one a .cur-able load) into \p DestBundle,
755 // relocating the other producer via lastChanceGlobalPullup. Returns true if
756 // the candidate was handled (moved); iterators are updated in place.
757 bool tryTwoLoadCurBypass(MIIterType &BI, SchedulingRegion_t::SRAtom_t *SR,
758 MIInstIterType &DestBundle, MIIterType &SrcBundle,
759 MIIterType &NextBI, bool isNextBISrc,
760 MIIterType &Next, MachineInstr *SrcMI,
761 SmallPtrSetImpl<MachineInstr *> &PulledUpSet);
762 void localPullupHVX(SchedulingRegion_t::SRAtom_t *SR);
763 // Shared local pullup engine used by localPullup (HVXMode=false) and
764 // localPullupHVX (HVXMode=true).
765 void localPullupImpl(SchedulingRegion_t::SRAtom_t *SR, bool HVXMode);
766 // Pullup HLX instructions to eliminate copies inserted for
767 // .new HLX store and .tmp HLX load
768 void localPullupHLX(SchedulingRegion_t::SRAtom_t *SR);
769 void localPullupHLXLoadUses(SchedulingRegion_t::SRAtom_t *SR,
770 MachineInstr *HLXLoadMI, MachineInstr *HLXCopyMI);
771 void localPullupHLXStore(SchedulingRegion_t::SRAtom_t *SR,
772 MachineInstr *HLXStoreMI, MachineInstr *HLXCopyMI);
773 // Within an MBB
774 void localPullup(SchedulingRegion_t::SRAtom_t *SR);
775 // Local push-down of MI into adjacent packets.
776 bool mergePacketsAround(const SmallVectorImpl<MachineInstr *> &Candidates);
777 bool mergePackets();
778 // Across MBBs
779 void globalPullup(SchedulingRegion_t &SR);
780 // Returns true if MI can be speculated (without predication)
781 // from \p SrcBB to \p DstBB
782 bool canMIBeSpeculated(MachineInstr *MI, MachineBasicBlock *SrcBB,
783 MachineBasicBlock *DstBB, MIIterType &TargetPacket);
784 // Safety checks for instructions e.g., load, store etc.
785 bool safeToSpeculate(MachineInstr *MI, MachineBasicBlock *DstBB) const;
786
787 bool preciousMICanBeSpeculated(MachineInstr *MI, MachineBasicBlock *SrcBB,
788 MachineBasicBlock *DstBB,
789 MachineBasicBlock *OtherBB,
790 MIIterType &TargetPacket,
791 unsigned ApproachNum);
792 inline bool preciousToSpeculate(const MachineInstr *MI,
793 const MachineBasicBlock *SrcBB,
794 const MachineBasicBlock *DstBB,
795 const MachineBasicBlock *OtherBB) const;
796 inline bool preciousToPredicate(const MachineInstr *MI,
797 const MachineBasicBlock *SrcBB,
798 const MachineBasicBlock *DstBB,
799 const MachineBasicBlock *OtherBB) const;
800
801 // Returns true if MI can be speculatively executed (with predication)
802 // from \p SrcBB to \p DstBB
803 bool canMIBePredicated(MachineInstr *MI, MachineBasicBlock *SrcBB,
804 MachineBasicBlock *DstBB, MIIterType &TargetPacket,
805 MICInstIterType &WithinPacket, bool &NeedToNewify,
806 bool &Precious);
807 // Returns the position *before* which \p MI could be inserted.
808 // In case of BUNDLE the \p MI can be inserted within that BUNDLE.
809 // It will try to take an extra step in accommodating the \p SrcMI when
810 // \p SpecPreciousMI=true.
811 MIIterType findInsertPtSpec(MachineInstr *SrcMI, MachineBasicBlock *DstBB,
812 bool SpecPreciousMI, bool SpecPreciousMIComp,
813 bool GlobalPrecious = false);
814 // Returns the position *before* which \p MI could be inserted.
815 // In case of BUNDLE the \p MI can be inserted within that BUNDLE.
816 // @note: The SrcMI can be modified by this function.
817 MIIterType findInsertPtPred(MachineInstr *SrcMI, MachineBasicBlock *DstBB,
818 bool &NeedToNewify, MICInstIterType &WithinPacket,
819 bool PredPreciousMI = false);
820 // Returns true if MI was successfully speculated.
821 bool speculateMI(MachineInstr *MI, MachineBasicBlock *SrcBB,
822 MachineBasicBlock *DstBB, MIIterType DstPos);
823 // Returns true if MI was successfully speculated.
824 bool predicateMI(MachineInstr *MI, MachineBasicBlock *SrcBB,
825 MachineBasicBlock *DstBB, MIIterType DstPack,
826 MICInstIterType WithinPacket, bool NeedToNewify,
827 bool Precious);
828 // Is it okay to execute MI as the first instruction in the MBB.
829 MIIterType findInsertionPtSpecLocal(MachineInstr *MI);
830
831 /// Check dependencies between MII and instructions in range [DestBeg,
832 /// DestEnd). This is used during pullup to ensure moving MII to the
833 /// destination doesn't violate dependencies. [DestBeg, DestEnd) can
834 /// span multiple bundles.
835 /// \param DestBeg Start of destination range
836 /// \param DestEnd End of destination range
837 /// \param MII Instruction being checked for dependencies
838 /// \param DepTrue Output: iterator to true (RAW) dependency if found
839 /// \param DepAnti Output: iterator to anti (WAR) dependency if found
840 /// \param HLXUseReg Optional: specific register to check for HLX
841 /// dependencies
842 /// \param isPullDown True if checking for pulldown (vs pullup) operation
843 /// \return Dependency flags indicating type of dependencies found
844 int dstDependence(MICInstIterType DestBeg, MICInstIterType DestEnd,
845 MICInstIterType MII, MICInstIterType &DepTrue,
846 MICInstIterType &DepAnti, unsigned HLXUseReg = 0,
847 bool IsPullDown = false) const;
848 // A more exhaustive dependence analysis for load bypass, more aggressive
849 // moves, etc. Used from the HVX local pullup.
850 int dstDependence(MICInstIterType DestBeg, MICInstIterType DestEnd,
851 MICInstIterType MII,
852 std::vector<const MachineInstr *> &DepTrueVec,
853 std::vector<const MachineInstr *> &DepAntiVec,
854 std::vector<const MachineInstr *> &DepOutputVec,
855 std::vector<unsigned> *Regs = nullptr) const;
856 // Dependence within the same packet [SrcBeg, SrcEnd).
857 int srcDependence(MIInstIterType SrcBeg, MIInstIterType SrcEnd,
858 MIInstIterType RMII,
859 SmallPtrSetImpl<MachineInstr *> *DepSet = nullptr) const;
860 bool singleTrueDep(MICInstIterType SrcBeg, MICInstIterType SrcEnd,
861 MICInstIterType MII, unsigned &Reg) const;
862 bool lastChanceGlobalPullup(MIInstIterType &BundleHead,
863 MIInstIterType InstrToMove,
864 const MachineInstr *LoadBypassCand = nullptr);
865 bool isLoopInvariant(MachineInstr &MI);
866 MachineInstr *isLastChanceGlobalPullupCand(const MachineInstr *MI);
867};
868
869class HexagonGlobalSchedulerV2 : public MachineFunctionPass {
870public:
871 static char ID;
872
873 HexagonGlobalSchedulerV2() : MachineFunctionPass(ID), GS(nullptr) {
875 }
876
877 StringRef getPassName() const override {
878 return "Hexagon Global Scheduler V2";
879 }
880
881 void getAnalysisUsage(AnalysisUsage &AU) const override {
882 AU.addRequired<AAResultsWrapperPass>();
883 AU.addRequired<HexagonLiveVariables>();
884 AU.addRequired<MachineBranchProbabilityInfoWrapperPass>();
885 AU.addRequired<MachineLoopInfoWrapperPass>();
887 }
888
889 bool runOnMachineFunction(MachineFunction &MF) override;
890
891private:
892 // Generates control flow by removing 3 way branching.
893 inline void generateCFG(MachineFunction &MF);
894
895 // Run the machine verifier when -verify-global-sched is set.
896 bool verifyMachineFunction(MachineFunction &MF, StringRef msg) {
898 MF.verify(this, msg.data());
899 return true;
900 }
901
902 // Member variables.
903 const HexagonTargetMachine *TM;
904 const HexagonInstrInfo *QII;
905 const HexagonRegisterInfo *TRI;
906 std::unique_ptr<GlobalScheduler> GS;
907};
908
909char HexagonGlobalSchedulerV2::ID = 0;
910
911} // namespace
912
913INITIALIZE_PASS(HexagonGlobalSchedulerV2, "global-schedV2",
914 "Hexagon Global Scheduler V2", false, false)
915
916//===----------------------------------------------------------------------===//
917// static/inline Functions
918//===----------------------------------------------------------------------===//
920 return MI->getOpcode() == Hexagon::Y2_barrier;
921}
922
923// Heuristic to determine whether to run the HVX local pull-up pass.
924bool GlobalScheduler::isProfitableToScheduleHVX(MachineBasicBlock *MBB) {
926 return true;
927 auto [It, Inserted] = ProfitableHVXBlocks.try_emplace(MBB);
928 if (!Inserted)
929 return It->second > HVXSchedProfitRatio;
930
931 unsigned NumHVXInst = 0, NumTotalInst = 0;
932 for (MIInstIterType II = MBB->instr_begin(), End = MBB->instr_end();
933 II != End; ++II) {
934 if (II->isBundle())
935 continue;
936 if (QII->isHVXVec(*II))
937 ++NumHVXInst;
938 ++NumTotalInst;
939 }
940 if (NumTotalInst == 0)
941 It->second = 0;
942 else
943 It->second = (float)NumHVXInst / (float)NumTotalInst;
944 return It->second > HVXSchedProfitRatio;
945}
946
947// This heuristic can be tuned to allow/disallow formation of superblocks
948// containing single block innermost loops. Currently, it's a simple ratio
949// of HVX vs non-HVX instructions.
950bool GlobalScheduler::isProfitableToScheduleHVX(MachineLoop *L) {
951 assert(L->getNumBlocks() == 1 && "Expecting a single block loop");
953 return true;
954 auto *BB = L->getBlocks()[0];
955 return isProfitableToScheduleHVX(BB);
956}
957
958// We allow single block innermost loops to be a part of the superblock to
959// attempt to schedule them,
960bool GlobalScheduler::isSuperblockLoop(MachineLoop *L) {
961 if (!EnableSingleLoopSuperblock || !useHVXOps ||
963 return false;
964 if (!L || L->getNumBlocks() != 1 || !L->isInnermost())
965 return false;
966 if (L->getBlocks()[0]->succ_size() < 2)
967 return false;
968 if (L->getBlocks()[0]->pred_size() != 2)
969 return false;
970
971 return isProfitableToScheduleHVX(L);
972}
973
974bool GlobalScheduler::shouldNotBePulledUp(const MachineInstr *MI) const {
975 // Allow .new HLX store to be pulled up
976 if (MI->getOpcode() == Hexagon::LX_S16b_new)
977 return false;
978 if (MI->mayStore() || MI->isCall() || MI->isBarrier() || MI->isInlineAsm() ||
979 MI->hasUnmodeledSideEffects() || MI->isEHLabel() || isSchedBarrier(MI))
980 return true;
981 if (MI->isBundle() || MI->isDebugInstr())
982 return true;
983 // Loads with ordered (volatile) memoperands. Assuming loads with empty
984 // memoperands are safe to pull unlike MachineInstr::hasOrderedMemoryRef.
985 if (PullUnsafeMemops && MI->memoperands_empty())
986 return false;
987 return MI->hasOrderedMemoryRef();
988}
989
990/// Determines if MI is a barrier that prevents ToMove from being pulled up past
991/// it. This function implements the core safety checks for instruction
992/// reordering.
993///
994/// Key rules:
995/// - Returns, calls, inline asm, EH labels, Y2_barrier and instructions with
996/// unmodeled side effects are always barriers.
997/// - A load or store is a barrier when ToMove is unknown.
998/// - MI does not block ToMove when both may load.
999/// - A .tmp or .cur load in the destination bundle (IsMIInDestBundle) does not
1000/// block a store, because it executes early in the packet.
1001/// - Otherwise, a memory access blocks ToMove when areMemAccessesDependent
1002/// says they may alias.
1003bool GlobalScheduler::shouldNotBeCrossed(const MachineInstr *MI,
1004 const MachineInstr *ToMove,
1005 bool IsMIInDestBundle) const {
1006 if (MI->isBundle() || MI->isDebugInstr())
1007 return false;
1008
1009 if (MI->isReturn() || MI->isCall() || MI->hasUnmodeledSideEffects() ||
1010 MI->isInlineAsm() || MI->isEHLabel() || isSchedBarrier(MI))
1011 return true;
1012
1013 // MI is not a load or store
1014 if (!MI->mayLoadOrStore())
1015 return false;
1016
1017 // MI is load or store, but we do not know what is ToMove
1018 if (!ToMove)
1019 return true;
1020
1021 // MI is load or store, ToMove is not a load or store
1022 if (!ToMove->mayLoadOrStore())
1023 return false;
1024
1025 if (MI->mayLoad()) {
1026 // If MI is a load and ToMove are loads, MI and ToMove can be reordered
1027 if (ToMove->mayLoad())
1028 return false;
1029
1030 // MI is a load and ToMove is a store
1031 // If MI is in DestBundle, ignore dependence if the load is a .tmp or .cur
1032 // .tmp and .cur loads execute early
1033 if (IsMIInDestBundle && (QII->isDotTmpInst(*MI) || QII->isDotCurInst(*MI)))
1034 return false;
1035 }
1036 return QII->areMemAccessesDependent(AA, MI, ToMove);
1037}
1038
1039static std::vector<const MachineOperand *>
1041 std::vector<const MachineOperand *> regmaskMOs;
1042 for (MICInstIterType II = MBB.instr_begin(), End = MBB.instr_end(); II != End;
1043 ++II) {
1044 if (II->isBundle() || II->isDebugInstr())
1045 continue;
1046 for (auto &MO : II->operands())
1047 if (MO.isRegMask())
1048 regmaskMOs.push_back(&MO);
1049 }
1050 return regmaskMOs;
1051}
1052
1053// Check if MI is invariant in a single-block loop.
1054// 1) All its uses are loop invariant
1055// 2) It's not redefined
1056// Call-clobbered registers are found from the regmask operands in the block.
1057bool GreedyPullup::isLoopInvariant(MachineInstr &MI) {
1058 auto *MBB = MI.getParent();
1059 MachineLoop *Loop = MLI.getLoopFor(MBB);
1060 if (!Loop)
1061 return true;
1062 if (!isSuperblockLoop(Loop))
1063 return false;
1064 MICInstIterType DefUseR = MBB->instr_end();
1065
1066 for (const MachineOperand &MO : MI.operands()) {
1067 if (!MO.isReg())
1068 continue;
1069 unsigned Op = MO.getReg();
1070 if (MO.isUse()) {
1071 if (HLV->isDefinedWithin(MBB->instr_begin(), MBB->instr_end(), Op,
1072 DefUseR))
1073 return false;
1074 } else if (MO.isDef()) {
1075 if (!MO.isDead()) {
1076 if (HLV->isDefinedWithin(std::next(MI.getIterator()), MBB->instr_end(),
1077 Op, DefUseR) ||
1078 HLV->isDefinedWithin(MBB->instr_begin(), MI.getIterator(), Op,
1079 DefUseR))
1080 return false;
1081
1082 // Not a candidate if it's live out
1083 for (MCRegAliasIterator AI(Op, TRI, true); AI.isValid(); ++AI)
1084 if (HLV->isLiveOut(MBB, *AI))
1085 return false;
1086 }
1087 }
1088 auto regmaskMOs = collectRegmaskMOs(*MBB);
1089 for (auto *MO : regmaskMOs)
1090 if (MO->clobbersPhysReg(Op))
1091 return false;
1092 }
1093 return true;
1094}
1095
1096// Get the iterators corresponding to the BUNDLE enclosing MI.
1097// If MI is not inside the bundle it returns MI as the first element
1098// and the MI+1, as the second element.
1099static std::pair<MIInstIterType, MIInstIterType>
1101 MIInstIterType BundleStart = getBundleStart(MI->getIterator());
1102 MIInstIterType BundleEnd = getBundleEnd(MI->getIterator());
1103 return std::make_pair(BundleStart, BundleEnd);
1104}
1105
1106// Checks if the bundle has at least 2 instructions.
1107// If not then unbundles the instructions and save in SpecScope (if provided).
1108static MachineInstr *
1110 SmallVectorImpl<MachineInstr *> *SpecScope = nullptr) {
1111 unsigned Size = QII->nonDbgBundleSize(BundleHead);
1112 if (Size >= 2)
1113 return nullptr;
1114 MachineInstr *MI = nullptr;
1115 if (Size == 1) {
1116 // Since bundle may have debug instructions.
1117 MIInstIterType BundleEnd = getBundleEnd(BundleHead->getIterator());
1118 MIInstIterType MIter = BundleHead->getIterator();
1119 ++MIter; // Skip the bundle header.
1120 while (MIter != BundleEnd) {
1121 MI = &*(MIter++);
1122 MI->unbundleFromPred();
1123 if (SpecScope)
1124 SpecScope->push_back(MI);
1125 }
1126 }
1127 // In case a bundle full of debug instructions get here.
1128 assert(BundleHead->getBundleSize() == 0);
1129 BundleHead->eraseFromParent();
1130 return MI; // if non-nullptr, point to the instruction
1131}
1132
1133// When MI is removed from a two-instruction bundle, the other instruction
1134// becomes unbundled. Return it in singleInstr.
1135static MachineInstr *
1137 SmallVectorImpl<MachineInstr *> *SpecPacketOpp = nullptr,
1138 MachineInstr **singleInstr = nullptr) {
1139 MachineInstr *NewSingleInstr = nullptr;
1140 MachineInstr *MIP = nullptr;
1141 if (MI->isBundled()) {
1142 MachineInstr *Bundle = &*getBundleStart(MI->getIterator());
1143 MIP = MI->removeFromBundle();
1144 NewSingleInstr = updateBundle(Bundle, QII, SpecPacketOpp);
1145 } else
1146 MIP = MI->removeFromParent();
1147
1148 if (singleInstr)
1149 *singleInstr = NewSingleInstr;
1150 return MIP;
1151}
1152
1153// TODO: Preprocess the MachineFunction to collect these
1154// information so that we don't have to loop over and over again.
1155// Use analyzebranch data (the cond vector)
1158 while (MII != MBB->instr_end()) {
1159 if ((MII->getOpcode() == Hexagon::ENDLOOP0) ||
1160 (MII->getOpcode() == Hexagon::ENDLOOP1))
1161 return true;
1162 ++MII;
1163 }
1164 return false;
1165}
1166
1167static void transferLiveIns(const MachineBasicBlock *From,
1168 MachineBasicBlock *To) {
1169 // Update liveins all at once.
1171 it != From->livein_end(); ++it) {
1172 if (!To->isLiveIn((*it).PhysReg))
1173 To->addLiveIn(*it);
1174 }
1175}
1176
1177// Returns true if Iter is a barrier and if there are other barriers
1178// 'after' Iter.
1179static bool inBetweenBarriers(MICIterType Iter,
1180 const MachineBasicBlock *DstBB) {
1181 MICIterType TestIt = DstBB->begin();
1182 // If Iter is after a Barrier.
1183 while (TestIt != Iter) {
1184 if (Iter->isBarrier())
1185 return true;
1186 ++TestIt;
1187 }
1188 // No barrier before Iter and Iter is not a barrier => okay.
1189 if (!Iter->isBarrier())
1190 return false;
1191 // Iter is a barrier, there should not be a barrier after Iter.
1192 while (Iter != DstBB->end()) {
1193 if (Iter->isBarrier())
1194 return true;
1195 ++Iter;
1196 }
1197 return false;
1198}
1199
1200// Blocks should be considered empty if they contain only debug info;
1201// else the debug info would affect codegen.
1203 if (MBB->isEHPad() || MBB->hasAddressTaken() || MBB->pred_size() != 1 ||
1204 MBB->succ_empty())
1205 return false;
1206 for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
1207 MBBI != MBBE; ++MBBI) {
1208 if (!MBBI->isDebugInstr())
1209 return false;
1210 }
1211 return true;
1212}
1213
1214// When the DstBB does not contain SrcMI, start from the end.
1215// Otherwise start from the bundle_iterator just before SrcMI.
1216static MIRIterType getSpeculationBeginPoint(MachineInstr *SrcMI,
1217 MachineBasicBlock *DstBB) {
1218 MIRIterType Rb = DstBB->rbegin();
1219 MIRIterType Re = DstBB->rend();
1220
1221 if (SrcMI->getParent() != DstBB)
1222 return Rb;
1223
1224 std::pair<MICInstIterType, MICInstIterType> B = getParentBundle(SrcMI);
1225 // TODO: Is there an advance function for reverse instr iterators?
1226 while ((&*Rb != &*B.first) && (Rb != Re))
1227 ++Rb;
1228 return ++Rb;
1229}
1230
1231//===----------------------------------------------------------------------===//
1232// GlobalScheduler::ABI Functions
1233//===----------------------------------------------------------------------===//
1234// TODO: Modify this to handle cases where succ_size=1.
1235bool GlobalScheduler::ABI::analyzeBranch(MachineBasicBlock *MBB,
1236 const HexagonInstrInfo *QII,
1237 bool PostSched) {
1238 AnalysisValid = !QII->analyzeBranch(*MBB, TBB, FBB, Cond, false);
1239 if (AnalysisValid) {
1240 // According to the HexagonInstrInfo::getBranchingInstrs
1241 // Only the last element can be a conditional branching instruction.
1242 SmallVector<MachineInstr *, 2> Jumpers = QII->getBranchingInstrs(*MBB);
1243 if (!Jumpers.empty() && ((MBB->succ_size() == 2) || PostSched)) {
1244 unsigned jumpers_size = Jumpers.size();
1245 assert((jumpers_size == 1) || (jumpers_size == 2));
1246 FirstTerm = Jumpers.back();
1247 if (jumpers_size == 2)
1248 SecondTerm = Jumpers[0];
1249 if (MBB->succ_size() == 2) {
1250 FBB = *MBB->succ_begin();
1251 if (FBB == TBB)
1252 FBB = *MBB->succ_rbegin(); // Since only two successors.
1253 }
1254 } else {
1255 AnalysisValid = false;
1256 }
1257 }
1258 return AnalysisValid;
1259}
1260
1261//===----------------------------------------------------------------------===//
1262// GlobalScheduler Functions
1263//===----------------------------------------------------------------------===//
1264bool GlobalScheduler::branchesInBetweenMBB(MIInstIterType MII,
1265 MachineBasicBlock *MBB) {
1266 if (!MII->isBranch())
1267 return false;
1268 // Get the beginning of the bundle containing MII.
1269 while (MII->isInsideBundle())
1270 --MII;
1271 // Now, skip to the next bundle.
1272 MII = std::next(MachineBasicBlock::iterator(MII)).getInstrIterator();
1273 if (MII == MBB->instr_end())
1274 return false;
1275
1276 if (endloopAfterMI(MII, MBB))
1277 return false;
1278 if (MII->isReturn())
1279 return false;
1280 // Anything other than a direct jump => branches in between or, > 2 succs.
1281 // MII may be a bundle => > 2 following instructions.
1282 if (MII->isBranch())
1283 return false;
1284 return true;
1285}
1286
1287bool GlobalScheduler::splitMBBAt(MIInstIterType MII, MachineBasicBlock *MBB) {
1288 MachineBasicBlock *OrigTBB = NULL, *OrigFBB = NULL;
1289 SmallVector<MachineOperand, 4> OrigCond;
1290
1291 // Not storing analyzeBranch info here because this will be stale soon.
1292 if (QII->analyzeBranch(*MBB, OrigTBB, OrigFBB, OrigCond, false) ||
1293 (MBB->succ_size() != 2))
1294 return false;
1295
1296 MachineBasicBlock *Succ1 = *MBB->succ_begin();
1297 MachineBasicBlock *Succ2 = *MBB->succ_rbegin();
1298
1299 if (!OrigFBB) {
1300 if (OrigTBB == Succ1)
1301 OrigFBB = Succ2;
1302 OrigFBB = Succ1;
1303 }
1304
1305 const BasicBlock *IR_Block = MBB->getBasicBlock();
1306 MachineFunction *MF = MBB->getParent();
1307 MachineBasicBlock *NewBlock = MF->CreateMachineBasicBlock(IR_Block);
1309
1310 MF->insert(++MBBI, NewBlock);
1311 NewBlock->splice(NewBlock->end(), MBB, MII, MBB->end());
1312
1313 MachineBasicBlock *FirstTBB = NULL, *FirstFBB = NULL;
1314 SmallVector<MachineOperand, 4> FirstCond;
1315
1316 (void)FirstTBB;
1317 (void)FirstFBB;
1318 (void)FirstCond;
1319 assert(!QII->analyzeBranch(*MBB, FirstTBB, FirstFBB, FirstCond, false));
1320
1321 MBB->removeSuccessor(OrigFBB);
1322 MBB->addSuccessor(NewBlock);
1323 NewBlock->addSuccessor(OrigFBB);
1324 // transfer liveins from MBB to NewBlock, just copy the parent's livein.
1325 transferLiveIns(MBB, NewBlock);
1326 return true;
1327}
1328
1329// Ensures that there are no more than 2 successors of a MBB
1330// with direct branching instructions.
1331// Also, performs a small optimization of removing branches to immediate succ.
1332// TODO: Some useful CFG optimizations can be done here to aid in scheduling.
1333void GlobalScheduler::generateCFG(MachineFunction &MF) {
1335 while (MBBI != MF.end()) {
1336 MachineBasicBlock *MBB = &*MBBI;
1337 MIInstIterType MII = MBBI->instr_begin();
1338 while (MII != MBBI->instr_end()) {
1339 MachineInstr *MI = &*MII;
1340 ++MII; // As MI might be removed.
1341 if (branchesInBetweenMBB(MI->getIterator(), MBB)) {
1342 // Splitting the MBB at MII.
1343 LLVM_DEBUG(dbgs() << "\nSplitting the MBB#" << MBB->getNumber()
1344 << " at: ";
1345 MI->dump());
1346 if (!splitMBBAt(std::next(MI->getIterator()), MBB))
1347 assert(MBB->succ_size() > 2);
1348 LLVM_DEBUG(dbgs() << "\nResulting BB: "; MBB->dump(););
1349 } else if (MI->getOpcode() == Hexagon::J2_jump &&
1350 MI->getOperand(0).isMBB()) {
1351 // If it jumps to the layout successor, remove the J2_jump instruction.
1352 MachineBasicBlock *Target = MI->getOperand(0).getMBB();
1353 if (MBB->isLayoutSuccessor(Target)) {
1354 LLVM_DEBUG(dbgs() << "\nRemoving branch to layout succ." << *MI);
1355 if (MI->isBundled()) {
1356 MachineInstr *Head = &*getBundleStart(MI->getIterator());
1357 MI->eraseFromBundle();
1358 updateBundle(Head, QII);
1359 } else
1360 MI->eraseFromParent();
1361 }
1362 }
1363 }
1364 ++MBBI;
1365 }
1366}
1367
1368// TODO: This needs to be improved. Is there a way to just 'copy'
1369// \p BB2 and emplace just after BB1?
1370// @brief Make BB2 as layout successor of BB1.
1371bool GlobalScheduler::makeAsLayoutSuccessor(MachineBasicBlock *BB1,
1372 MachineBasicBlock *BB2) {
1373 assert(!BB1->isLayoutSuccessor(BB2));
1374 // We can only deal with returning MBBs and MBBs with a direct jump.
1375 if (BB2->pred_size() != 1 || (BB2->succ_size() > 1))
1376 return false;
1377 // We don't want to move in MBBs if they change the CFG too much.
1378 // Passing same BB2 in both params to get the num_instrs*instr_size
1379 int InsSize = HLV->getDistanceBetween(BB2, BB2);
1380 if (SafetyBufferDelta < InsSize)
1381 return false;
1382 SafetyBufferDelta -= InsSize;
1383
1384 SmallVector<MachineInstr *, 2> Jumpers = QII->getBranchingInstrs(*BB2);
1385 if (Jumpers.size() > 1 || Jumpers.empty())
1386 return false;
1387 if (QII->isPredicated(*Jumpers[0]))
1388 return false;
1389 LLVM_DEBUG(dbgs() << "\nMaking MBB#" << BB2->getNumber()
1390 << " as LayoutSuccessor of " << BB1->getNumber(););
1392 ++BB1LS; // Current layout successor of BB1
1393 if (BB1LS != MF.end()) {
1394 MF.splice(BB1LS, BB2);
1395 return true;
1396 }
1397 return false;
1398}
1399
1400void GlobalScheduler::removeEmptyMBB(MachineBasicBlock *MBB) {
1401 assert((MBB->succ_size() == 1) && (MBB->pred_size() == 1));
1402 LLVM_DEBUG(dbgs() << "\nRemoving:" << *MBB);
1403 MachineBasicBlock *Pred = *MBB->pred_begin();
1404 LLVM_DEBUG(dbgs() << "\nPred:" << *Pred);
1405 LLVM_DEBUG(dbgs() << "\nSucc:" << **MBB->succ_begin());
1406 Pred->ReplaceUsesOfBlockWith(MBB, *MBB->succ_begin());
1407 LLVM_DEBUG(dbgs() << "\nPred after update:" << *Pred);
1408 MachineJumpTableInfo *MJTI = MBB->getParent()->getJumpTableInfo();
1409 if (MJTI) {
1411 }
1413 LLVM_DEBUG(dbgs() << "Removing BB(" << MBB->getNumber()
1414 << ") from parent.\n");
1416}
1417
1418// 1. Remove jump to the layout successor.
1419// 2. Remove multiple (dual) jump to the same target.
1420bool GlobalScheduler::removeRedundantBranches(MachineBasicBlock *MBB,
1421 MachineBasicBlock *TBB,
1422 MachineInstr *FirstTerm,
1423 MachineBasicBlock *FBB,
1424 MachineInstr *SecondTerm) {
1425 bool Analyzed = false;
1426 LLVM_DEBUG(dbgs() << "\n[removeRedundantBranches]");
1427 MachineInstr *Head = NULL, *ToErase = NULL;
1428 if (!FBB && (FirstTerm->getOpcode() == Hexagon::J2_jump) &&
1430 // Jmp layout_succ_basic_block <-- Remove
1431 LLVM_DEBUG(
1432 dbgs() << "\nRemoving Uncond. jump to the layout successor in BB#"
1433 << MBB->getNumber());
1434 ToErase = FirstTerm;
1435 } else if (SecondTerm && (TBB == FBB) &&
1436 (SecondTerm->getOpcode() == Hexagon::J2_jump)) {
1437 // If both branching instructions in same packet or are consecutive.
1438 // Jmp_c t1 <-- Remove
1439 // Jmp t1
1440 // @Note: If they are in different packets or if they are separated
1441 // by packet(s), this opt. cannot be done.
1442 MachineBasicBlock::instr_iterator FirstTermIter = FirstTerm->getIterator();
1443 MachineBasicBlock::instr_iterator SecondTermIter =
1444 SecondTerm->getIterator();
1445 if (++FirstTermIter == SecondTermIter &&
1446 !QII->isCompoundBranchInstr(*FirstTerm)) {
1447 LLVM_DEBUG(dbgs() << "\nRemoving multiple branching to same target in BB#"
1448 << MBB->getNumber());
1449 // TODO: This might make the `p' register assignment instruction dead.
1450 // and can be removed.
1451 ToErase = FirstTerm;
1452 }
1453 } else if (SecondTerm && (SecondTerm->getOpcode() == Hexagon::J2_jump) &&
1454 FBB && MBB->isLayoutSuccessor(FBB)) {
1455 // Jmp_c t1
1456 // Jmp layout_succ_basic_block <-- Remove
1457 LLVM_DEBUG(dbgs() << "\nRemoving fall through branch in BB#"
1458 << MBB->getNumber());
1459 ToErase = SecondTerm;
1460 } else if (!SecondTerm && !FirstTerm->isUnconditionalBranch() &&
1462 // Branching+Fallthrough to the layout successor.
1463 // Jmp_c layout_succ_basic_block <-- Remove
1464 assert(MBB->succ_size() == 1 && "Malformed CFG");
1465 ToErase = FirstTerm;
1466 }
1467 // Remove the instruction from the BB
1468 if (ToErase) {
1469 if (ToErase->isBundled()) {
1470 Head = &*getBundleStart(ToErase->getIterator());
1471 ToErase->eraseFromBundle();
1472 updateBundle(Head, QII);
1473 } else
1474 ToErase->eraseFromParent();
1475 Analyzed = true;
1476 }
1477 return Analyzed;
1478}
1479
1480// ----- convert
1481// p = <expr>
1482// if(p) jump layout_succ_basic_block
1483// jump t
1484// ----- to
1485// p = <expr>
1486// if(!p) jump t
1487// for now only looking at the dual jump
1488bool GlobalScheduler::optimizeDualJumps(MachineBasicBlock *MBB,
1489 MachineBasicBlock *TBB,
1490 MachineInstr *FirstTerm,
1491 MachineBasicBlock *FBB,
1492 MachineInstr *SecondTerm) {
1493 LLVM_DEBUG(dbgs() << "\n[optimizeDualJumps]");
1494
1495 bool Analyzed = false;
1496
1497 if (QII->PredOpcodeHasJMP_c(FirstTerm->getOpcode()) &&
1498 (SecondTerm->getOpcode() == Hexagon::J2_jump)) {
1499
1500 if (TBB == FBB) {
1501 LLVM_DEBUG(dbgs() << "\nBoth successors are the same.");
1502 return Analyzed;
1503 }
1504
1505 LLVM_DEBUG(dbgs() << "\nCandidate for jump optimization in BB("
1506 << MBB->getNumber() << ").\n";);
1507
1508 // Predicated jump to layout successor followed by an unconditional jump.
1509 if (MBB->isLayoutSuccessor(TBB)) {
1510 // Check if the jump in the last instruction is within range.
1511 unsigned Distance = HLV->getDistanceBetween(MBB, FBB) + SafetyBuffer;
1512 if (!QII->isJumpWithinBranchRange(*FirstTerm, Distance)) {
1513 LLVM_DEBUG(dbgs() << "\nUnconditional jump target:" << Distance
1514 << " out of range.");
1515 return Analyzed;
1516 }
1517
1518 // modify the second last -predicated- instruction (sense and target)
1519 LLVM_DEBUG(dbgs() << "\nFirst Instr:" << *FirstTerm;);
1520 LLVM_DEBUG(dbgs() << "\nSecond Instr:" << *SecondTerm;);
1521 LLVM_DEBUG(dbgs() << "\nOld Succ BB(" << TBB->getNumber() << ").";);
1522
1523 QII->invertAndChangeJumpTarget(*FirstTerm, FBB);
1524
1525 LLVM_DEBUG(dbgs() << "\nNew First Instruction:" << *FirstTerm;);
1526
1527 // unbundle if there is only one instruction left
1528 MachineInstr *SecondHead, *FirstHead;
1529 FirstHead = FirstTerm->isBundled()
1530 ? &*getBundleStart(FirstTerm->getIterator())
1531 : nullptr;
1532 SecondHead = SecondTerm->isBundled()
1533 ? &*getBundleStart(SecondTerm->getIterator())
1534 : nullptr;
1535
1536 // 1. Both unbundled, 2. FirstTerm inside bundle, second outside.
1537 if (!SecondHead)
1538 SecondTerm->eraseFromParent();
1539 else if (!FirstHead) {
1540 // 3. FirstHead outside, SecondHead inside.
1541 SecondTerm->eraseFromBundle();
1542 updateBundle(SecondHead, QII);
1543 } else if (FirstHead == SecondHead) {
1544 // 4. Both are in the same bundle
1545 assert((FirstHead && SecondHead) && "Unbundled Instruction");
1546 SecondTerm->eraseFromBundle();
1547 updateBundle(SecondHead, QII);
1548 } else {
1549 // 5. Both are in different bundles
1550 SecondTerm->eraseFromBundle();
1551 updateBundle(SecondHead, QII);
1552 }
1553 Analyzed = true;
1554 }
1555 }
1556 return Analyzed;
1557}
1558
1559// optimizeBranching -
1560// 1. A conditional-jump transfers control to a BB with
1561// jump as the only instruction.
1562// if(p0) jump t1
1563// // ...
1564// t1: jump t2
1565// 2. When a BB with a single conditional jump, jumps to succ-of-succ and
1566// falls-through BB with only jump instruction.
1567// { if(p0) jump t1 }
1568// { jump t2 }
1569// t1: { ... }
1570MachineBasicBlock *GlobalScheduler::optimizeBranches(MachineBasicBlock *MBB,
1571 MachineBasicBlock *TBB,
1572 MachineInstr *FirstTerm,
1573 MachineBasicBlock *FBB) {
1574 LLVM_DEBUG(dbgs() << "\n[optimizeBranches]");
1575 if ((TBB == MBB) || (FBB == MBB))
1576 LLVM_DEBUG(dbgs() << "Cannot deal with loops in BB#" << MBB->getNumber(););
1577
1578 // { if(p) jump t1; }
1579 // t1: { jump t2; }
1580 // --> { if(p) jump t2
1581 // remove t1: { jump t2; }, if it's address is not taken/not a landing pad.
1582 if (QII->nonDbgBBSize(TBB) == 1) {
1583 MachineInstr *TBBMIb = &*TBB->getFirstNonDebugInstr();
1584 if (TBBMIb->getOpcode() == Hexagon::J2_jump &&
1585 TBBMIb->getOperand(0).isMBB()) {
1586 MachineBasicBlock *NewTarget = TBBMIb->getOperand(0).getMBB();
1587 if (TBB->hasAddressTaken() || TBB->isEHPad() ||
1588 TBB == NewTarget /*Infinite loop*/ || (TBB->pred_size() != 1))
1589 return NULL;
1590
1591 LLVM_DEBUG(dbgs() << "\nSuboptimal branching in TBB");
1592 // Check if the jump in the last instruction is within range.
1593 unsigned Distance =
1594 HLV->getDistanceBetween(MBB, NewTarget) + SafetyBuffer;
1595 if (!QII->isJumpWithinBranchRange(*FirstTerm, Distance)) {
1596 LLVM_DEBUG(dbgs() << "\nUnconditional jump target:" << Distance
1597 << " out of range.");
1598 return NULL;
1599 }
1600 MBB->ReplaceUsesOfBlockWith(TBB, NewTarget);
1601 // TBB has only one successor since only one J2_jump instr.
1602 TBB->removeSuccessor(TBB->succ_begin());
1603 TBBMIb->eraseFromParent();
1604 return TBB;
1605 }
1606 if (TBBMIb->isReturn() && QII->isPredicable(*TBBMIb)) {
1607 SmallVector<MachineOperand, 4> PredCond;
1608 QII->findInstrPredicate(FirstTerm, PredCond);
1609 if (PredCond.empty())
1610 return NULL;
1611 unsigned Opcode = TBBMIb->getOpcode();
1612 if ((Opcode != Hexagon::PS_jmpret) && (Opcode != Hexagon::L4_return))
1613 return NULL;
1614 MachineInstr *NewMI = FirstTerm;
1615 bool NeedToNewify = QII->isPredicatedNew(*NewMI);
1616 // Since return instructions execute only in slot 0.
1617 // TODO: For bs > 2 we have to do resource tracking etc.
1618 if (NewMI->isBundled()) {
1619 if (!NeedToNewify)
1620 return nullptr;
1622 if (QII->nonDbgBundleSize(*getBundleStart(It)) > 2)
1623 return nullptr;
1624 }
1625 int rem = NewMI->getNumOperands() - 1;
1626 while (rem >= 0) // Removing from back is faster.
1627 NewMI->removeOperand(rem--);
1628 const MachineInstr *MI2Clone = TBBMIb;
1629 NewMI->setDesc(QII->get(MI2Clone->getOpcode()));
1630 unsigned NumOps = MI2Clone->getNumOperands();
1631 unsigned add = 0;
1632 while (add < NumOps)
1633 NewMI->addOperand(MI2Clone->getOperand(add++));
1634 if (!QII->PredicateInstruction(*NewMI, PredCond))
1635 llvm_unreachable("Instruction should have been predicable");
1636 if (NeedToNewify) {
1637 int NewOpcode = QII->getDotNewPredOp(*NewMI, MBPI);
1638 NewMI->setDesc(QII->get(NewOpcode));
1639 }
1641 LLVM_DEBUG(dbgs() << "ModifiedInstr:"; NewMI->dump(););
1642 if ((TBB != &*MBB->getParent()->begin()) && !TBB->isEHPad() &&
1643 !TBB->hasAddressTaken() && TBB->pred_empty() && TBB->succ_empty())
1644 return TBB;
1645 }
1646 return NULL;
1647 }
1648 // { if(p) jump t1; } may contain more instructions
1649 // { jump t2; } --only one instruction
1650 // t1: {...}
1651 // TBB is layout successor of FBB, then we can change the branch target
1652 // for conditional jump and invert the predicate to remove jump t2.
1653 // { if(!p) jump t2; }
1654 // t1: {...}
1655 if (QII->nonDbgBBSize(FBB) == 1) {
1656 MachineInstr *FBBMIb = &*FBB->getFirstNonDebugInstr();
1657 if (FBBMIb->getOpcode() == Hexagon::J2_jump &&
1658 FBBMIb->getOperand(0).isMBB()) {
1659 MachineBasicBlock *NewTarget = FBBMIb->getOperand(0).getMBB();
1660 if (FBB->hasAddressTaken() || FBB->isEHPad() ||
1661 (FBB == NewTarget /*Infinite loop*/) || (FBB->pred_size() != 1))
1662 return NULL;
1663 if (!FBB->isLayoutSuccessor(TBB) && !makeAsLayoutSuccessor(FBB, TBB))
1664 return NULL;
1666 LLVM_DEBUG(dbgs() << "\nSuboptimal branching in FBB");
1667 // Check if the jump in the last instruction is within range.
1668 unsigned Distance =
1669 HLV->getDistanceBetween(MBB, NewTarget) + SafetyBuffer;
1670
1671 if (!QII->isJumpWithinBranchRange(*FirstTerm, Distance)) {
1672 LLVM_DEBUG(dbgs() << "\nUnconditional jump target:" << Distance
1673 << " out of range.");
1674 return NULL;
1675 }
1676 if (!QII->invertAndChangeJumpTarget(*FirstTerm, NewTarget))
1677 return NULL;
1678 LLVM_DEBUG(dbgs() << "\nNew instruction:"; FirstTerm->dump(););
1679 MBB->ReplaceUsesOfBlockWith(FBB, NewTarget);
1680 FBB->removeSuccessor(FBB->succ_begin());
1681 FBBMIb->eraseFromParent();
1682 return FBB;
1683 }
1684 }
1685 return NULL;
1686}
1687
1688void GlobalScheduler::performExposedOptimizations() {
1689 LLVM_DEBUG(dbgs() << "\n[PerformExposedOptimizations]";);
1691 for (; MBBI != MF.end();) {
1692 MachineBasicBlock *MBB = &*MBBI;
1693 ++MBBI; // MBB might be removed so incrementing early.
1694 // Empty BBs.
1695 if (isEmptyBlock(MBB)) {
1697 pe = MBB->pred_end();
1698 pi != pe; ++pi)
1699 if (AnalyzeBranchInfo.hasABInfo(*pi))
1700 AnalyzeBranchInfo.invalidate(*pi);
1701
1702 if (AnalyzeBranchInfo.hasABInfo(MBB))
1703 AnalyzeBranchInfo.invalidate(MBB);
1704 removeEmptyMBB(MBB);
1705 }
1706 }
1707 for (MBBI = MF.begin(); MBBI != MF.end();) {
1708 MachineBasicBlock *MBB = &*MBBI;
1709 ++MBBI; // MBB might be removed so incrementing early.
1710 LLVM_DEBUG(dbgs() << "\nOptimizing Branches in MBB#" << MBB->getNumber(););
1711 // Don't perform optimizations on these MBBs.
1712 if (std::find(IgnorePostSchedOpt.begin(), IgnorePostSchedOpt.end(), MBB) !=
1713 IgnorePostSchedOpt.end())
1714 continue;
1715 // Branch Optimizations.
1716 ABI &abi = AnalyzeBranchInfo.getOrCreate(MBB, QII, true);
1717 if (!abi.AnalysisValid)
1718 continue;
1719 MachineBasicBlock *TBB = abi.TBB, *FBB = abi.FBB;
1720 MachineInstr *FirstTerm = abi.FirstTerm, *SecondTerm = abi.SecondTerm;
1721
1722 // If there are two jump instructions then see if one can be removed.
1723 if (TBB && FirstTerm &&
1724 removeRedundantBranches(MBB, TBB, FirstTerm, FBB, SecondTerm)) {
1725 LLVM_DEBUG(dbgs() << "\nRemoved redundant branches in BB#"
1726 << MBB->getNumber(););
1727 } else if (FirstTerm && SecondTerm &&
1728 optimizeDualJumps(MBB, TBB, FirstTerm, FBB, SecondTerm)) {
1729 LLVM_DEBUG(dbgs() << "\nRemoved dual jumps in BB#" << MBB->getNumber(););
1730 } else if (TBB && FBB && FirstTerm && !SecondTerm) {
1731 MachineBasicBlock *BBToErase = optimizeBranches(MBB, TBB, FirstTerm, FBB);
1732 if (BBToErase) {
1733 if (AnalyzeBranchInfo.hasABInfo(BBToErase))
1734 AnalyzeBranchInfo.invalidate(BBToErase);
1735 assert(BBToErase->succ_empty() && BBToErase->pred_empty());
1736 BBToErase->eraseFromParent();
1737 // Since we don't know from where this MBB got deleted, restart.
1738 // Also, this enables removal of branches which might
1739 // be redundant as a result of removing BBToErase.
1740 MBBI = MF.begin();
1741 LLVM_DEBUG(dbgs() << "\nOptimized jump from BB#" << MBB->getNumber());
1742 }
1743 }
1744 // We know that MBB was analyzed.
1745 AnalyzeBranchInfo.invalidate(MBB);
1746 }
1747}
1748
1749// Criteria of HEAD of a scheduling region (Superblock).
1750// 1. MF.begin()
1751// 2. MBB with more than one successor:
1752// - Can be part of multiple scheduling regions.
1753// For simplicity we'll make this as HEAD as well. This lets us not
1754// worry about the loop as a special case.
1755// 3. MBB with more than one predecessor:
1756// - Will always be (if at all) the HEAD of the scheduling region.
1757// TODO: Use the dominator tree to construct regions.
1758void GlobalScheduler::formSchedulingRegions(MachineFunction &MF) {
1760 // Populate the HEADs of scheduling regions.
1761 // We don't want to handle MBBs with >2 successors. This lets us
1762 // focus on most common cases and simplifies the analysis.
1763 while (MBBI != MF.end()) {
1764 unsigned MBBPredSize = MBBI->pred_size();
1765 unsigned MBBSuccSize = MBBI->succ_size();
1766 if (((MBBPredSize > 1) && ((MBBSuccSize == 1) || (MBBSuccSize == 2))) ||
1767 (MBBSuccSize == 2)) {
1768 SchedulingRegion_t SR;
1769 SR.addSRMember(&*MBBI);
1770 SchedulingRegions.push_back(SR);
1771 // Push two HEADs so that two scheduling regions can be created.
1772 if (MBBI->succ_size() == 2) {
1773 SchedulingRegions.push_back(SR);
1774 }
1775 }
1776 ++MBBI;
1777 }
1778 // For each HEAD, populate corresponding scheduling region.
1779 SchedulingRegions_t::iterator SRI = SchedulingRegions.begin();
1780 SchedulingRegions_t::iterator SRIPrev = SchedulingRegions.end();
1781 LLVM_DEBUG(dbgs() << "\nConstructing Scheduling Region for HEADs at";);
1782 while (SRI != SchedulingRegions.end()) {
1783 MachineBasicBlock *RegHead = SRI->Members[0];
1784 assert(RegHead);
1785 LLVM_DEBUG(dbgs() << " BB#" << RegHead->getNumber(););
1786 MachineBasicBlock::succ_iterator MBBSucc = RegHead->succ_begin();
1787 // In case of multiple entries, the first HEAD will have the first succ.
1788 // in its region.
1789 // Look at the other successor to construct the region, if the first branch
1790 // of Region HEAD is already included in the previous region.
1791 if ((SRIPrev != SchedulingRegions.end()) &&
1792 (SRIPrev->Members[0] == SRI->Members[0]))
1793 ++MBBSucc;
1794 assert(RegHead->succ_size() < 3);
1795 MachineFunction::iterator RegMBB = (*MBBSucc)->getIterator();
1796 while (1) {
1797 auto *L = MLI.getLoopFor(&*RegMBB);
1798 bool SuccIsSingleBlockLoop =
1799 isSuperblockLoop(L) && RegMBB->getNumber() != RegHead->getNumber();
1800 // pred_size > 1 => HEAD, cannot be included in this region.
1801 // Leaf MBBs should have at least one MI.
1802 if ((RegMBB->pred_size() > 1 && !SuccIsSingleBlockLoop) ||
1803 (RegMBB->succ_empty() && RegMBB->empty()))
1804 break;
1805 SRI->addSRMember(&*RegMBB);
1806 // succ_size = 0 => done!, =2 => HEAD
1807 if (RegMBB->succ_size() != 1) {
1808 break;
1809 }
1810 RegMBB = (*RegMBB->succ_begin())->getIterator();
1811 }
1812 SRIPrev = SRI;
1813 ++SRI;
1814 }
1815}
1816
1817void GlobalScheduler::pruneSchedulingRegions(PruneCriteriaFP PC) {
1818 LLVM_DEBUG(dbgs() << "\nErasing Scheduling Region with HEAD at";);
1819 for (SchedulingRegions_t::iterator SRI = SchedulingRegions.begin();
1820 SRI != SchedulingRegions.end();) {
1821 if ((this->*PC)(*SRI)) {
1822 LLVM_DEBUG(dbgs() << "\tBB#" << SRI->Members[0]->getNumber());
1823 SRI = SchedulingRegions.erase(SRI);
1824 } else {
1825 ++SRI;
1826 }
1827 }
1828}
1829
1830void GlobalScheduler::sortSchedulingRegions() {
1831 for (SchedulingRegions_t::iterator SRI = SchedulingRegions.begin();
1832 SRI != SchedulingRegions.end(); ++SRI) {
1833 SchedulingRegion_t &SR = *SRI;
1834 // The EdgeProb of a scheduling region is the same as the edge prob.
1835 // of the first two MBBs.
1836 SR.EdgeProb = MBPI->getEdgeProbability(SR.Members[0], SR.Members[1]);
1837 if (SR.EdgeProb.getCompl() == SR.EdgeProb) { // N = D/2;
1838 ABI &abi = AnalyzeBranchInfo.getOrCreate(SR.Members[0], QII);
1839 if (!abi.AnalysisValid)
1840 continue;
1841 // Increase the probability of TBB.
1842 if (abi.TBB == SR.Members[1])
1843 SR.EdgeProb = BranchProbability(2, 3); // N = 2D/3
1844 else
1845 SR.EdgeProb = BranchProbability(1, 3); // N = D/3
1846 }
1847 LLVM_DEBUG(dbgs() << "Edge Probability of: "; SR.dump(); dbgs() << ":\t";
1848 SR.EdgeProb.dump(););
1849 }
1850 // Sort in the decreasing order of edge probabilities.
1851 std::sort(SchedulingRegions.begin(), SchedulingRegions.end(),
1852 std::greater<SchedulingRegions_t::value_type>());
1853}
1854
1856GlobalScheduler::addToPacketPseudo(MachineInstr *MI) {
1858 // We don't want to reserve a resource for CFI_INSTRUCTION (it has zero
1859 // cost).
1860 if (!TII->isZeroCost(MI->getOpcode()))
1861 ResourceTracker->reserveResources(*MI);
1862 if (QII->isConstExtended(*MI)) {
1863 assert(canReserveResourcesForConstExt());
1864 reserveResourcesForConstExt();
1865 }
1866 CurrentPacketMIs.push_back(MI);
1867 return MII;
1868}
1869
1870void GlobalScheduler::initPacketizerStateLoc() {
1872 CurrentPacketMIs.clear();
1873}
1874
1875// Uses the packetizer checks to ensure correctness.
1876bool GlobalScheduler::isLegalToPacketizeWith(MIIterType DestPack,
1877 MachineInstr *MI) {
1878 LLVM_DEBUG(dbgs() << "\n[isLegalToPacketizeWith]";);
1879 assert(DestPack->isBundle());
1880 // Never packetize a solo instruction.
1881 if (isSoloInstruction(*MI))
1882 return false;
1883
1884 // The implementation should be inline with isLegalToPacketizeTogether.
1885 // For all MIs in DestPack call isLegalToPacketizeTogetherMI.
1886 MIInstIterType BI = (&*DestPack)->getIterator();
1887 MachineBasicBlock *MBB = BI->getParent();
1888 const MachineInstr *BranchMI = NULL;
1889 // skipping the bundle header.
1890 for (++BI; (BI != MBB->instr_end()) && BI->isInsideBundle(); ++BI) {
1891 // Remember the branch; its target may need a constant extender (below).
1892 if (BI->isBranch())
1893 BranchMI = &*BI;
1894 if (!isLegalToPacketizeTogetherMI(&*BI, MI))
1895 return false;
1896 }
1897
1898 unsigned NumI = QII->nonDbgBundleSize(*DestPack);
1899 // When there is only one slot left we want to check if there's a
1900 // scope for const-extender.
1901 if ((NumI >= (HEXAGON_PACKET_SIZE - 1)) && BranchMI &&
1902 (DisableHVXLocalPullupAndSuperblock || !useHVXOps ||
1903 !QII->isEndLoopN(BranchMI->getOpcode()))) {
1904 for (unsigned i = 0; i < BranchMI->getNumOperands(); ++i) {
1905 const MachineOperand &MO = BranchMI->getOperand(i);
1906 if (MO.isMBB()) {
1907 unsigned dist = HLV->getDistanceBetween(MBB, MO.getMBB());
1908 if (!QII->isJumpWithinBranchRange(*BranchMI, dist + SafetyBuffer)) {
1909 LLVM_DEBUG(dbgs() << "\nBranch might be constant extended later";);
1910 return false;
1911 }
1912 }
1913 }
1914 }
1915 return true;
1916}
1917
1918// BI is the destination packet where MI may be placed.
1919bool GlobalScheduler::isLegalToPacketizeTogetherMI(MachineInstr *BI,
1920 MachineInstr *MI) {
1921 if (cannotCoexist(*BI, *MI))
1922 return false;
1923
1924 if (hasDeadDependence(*BI, *MI))
1925 return false;
1926 if (hasControlDependence(*BI, *MI))
1927 return false;
1928 if (hasDualStoreDependence(*BI, *MI))
1929 return false;
1930
1931 const MachineBasicBlock *MBB = BI->getParent();
1932 // The implementation should be inline with isLegalToPacketizeTogether.
1933 // Hexagon PRM 7.3.4: a loop setup packet in loopN or spNloop0 cannot
1934 // contain a speculative indirect jump,
1935 // a new-value compare jump or a dealloc_return.
1936 // Speculative indirect jumps (predicate + .new + indirect):
1937 // if ([!]Ps.new) jumpr:t Rs
1938 // if ([!]Ps.new) jumpr:nt Rs
1939 // @note: We don't want to pull across a call to be on the safe side.
1940 if (QII->isLoopN(*MI)) {
1941 if ((QII->isPredicated(*BI) && QII->isPredicatedNew(*BI) &&
1942 QII->isJumpR(*BI)) ||
1943 QII->isNewValueJump(*BI) || QII->isDeallocRet(*BI) || BI->isCall()) {
1944 LLVM_DEBUG(dbgs() << "\nLoopN pull interference.");
1945 return false;
1946 }
1947 // loopN cannot be pulled too far.
1948 unsigned dist = HLV->getDistanceBetween(MBB, MI->getOperand(0).getMBB());
1949 if (!QII->isJumpWithinBranchRange(*MI, dist + SafetyBuffer)) {
1950 LLVM_DEBUG(dbgs() << "\nLoopN cannot be pulled too far";);
1951 return false;
1952 }
1953 }
1954
1955 // The opposite is also true.
1956 if (QII->isLoopN(*BI) &&
1957 ((QII->isPredicated(*MI) && QII->isPredicatedNew(*MI) &&
1958 QII->isJumpR(*MI)) ||
1959 QII->isNewValueJump(*MI) || QII->isDeallocRet(*MI) || MI->isCall())) {
1960 LLVM_DEBUG(dbgs() << "\tResident LoopN.");
1961 return false;
1962 }
1963
1964 // @todo Hexagon PRM 7.6.1:
1965 // Presence of NVJ adds more restrictions.
1966 if (QII->isNewValueJump(*BI) &&
1967 (MI->mayStore() || MI->getOpcode() == Hexagon::S2_allocframe ||
1968 MI->isCall())) {
1969 LLVM_DEBUG(dbgs() << "\nNew val Jump.");
1970 return false;
1971 }
1972
1973 // For memory operations, check aliasing.
1974 // Be conservative with ordered (volatile/atomic) or unknown (no memoperands)
1975 // memory references.
1976 if (BI->hasOrderedMemoryRef())
1977 return false;
1978
1979 // If packet has a new-value store, MI can't be a store instruction.
1980 if (QII->isNewValueStore(*BI) && MI->mayStore()) {
1981 LLVM_DEBUG(dbgs() << "\nNew Value Store to store.");
1982 return false;
1983 }
1984
1985 if ((QII->isMemOp(*BI) && MI->mayStore()) ||
1986 (QII->isMemOp(*MI) && BI->mayStore())) {
1987 LLVM_DEBUG(dbgs() << "\nSlot 0 not available for store because of memop.");
1988 return false;
1989 }
1990 return true;
1991}
1992
1993// @note: This function leaves the packet in an invalid state.
1994// GA and GB are left in the packet and it is the responsibility of the caller
1995// to move/delete them to appropriate places.
1996// @warning: Only works for limited set of branches handled
1997// in HexagonInstrInfo::getCompoundOpcode.
1998MachineInstr *GlobalScheduler::generateCompoundIfPossible(MIInstIterType MII,
1999 MIInstIterType &GA,
2000 MIInstIterType &GB) {
2001 assert(MII->isBundle());
2002 MachineInstr *NewMI = NULL;
2003 MachineBasicBlock *MBB = MII->getParent();
2004 GA = MBB->instr_end();
2005 GB = MBB->instr_end();
2006 ++MII; // Skipping Bundle header.
2007 while ((MII != MBB->instr_end()) && MII->isInsideBundle()) {
2008 if (MII->isCompare() &&
2010 if (GA != MBB->instr_end()) {
2011 GA = MBB->instr_end();
2012 break;
2013 }
2014 GA = MII;
2015 }
2016 if (MII->isBranch() &&
2018 if (GB != MBB->instr_end()) {
2019 GB = MBB->instr_end();
2020 break;
2021 }
2022 GB = MII;
2023 }
2024 ++MII;
2025 }
2026 int CmpOpcode = 0;
2027 if ((GA != MBB->instr_end()) && (GB != MBB->instr_end())) {
2028 CmpOpcode = QII->getCompoundOpcode(*GA, *GB);
2029 if (CmpOpcode != -1) {
2030 LLVM_DEBUG(dbgs() << "\nFound Compound pair: " << *GA << *GB;);
2031 assert(GA->getNumOperands() == 3);
2032 DebugLoc dl = GB->getDebugLoc();
2033 NewMI = BuildMI(*MBB, GB, dl, QII->get(CmpOpcode));
2034 Register PredReg = GA->getOperand(0).getReg();
2035 MachineOperand *PredUse =
2036 NewMI->findRegisterUseOperand(PredReg, /*TRI=*/nullptr);
2037 assert(PredUse && PredUse->isImplicit() &&
2038 "Missing compound predicate use");
2039 PredUse->setIsInternalRead();
2040 NewMI->addOperand(GA->getOperand(1)); // LHS of compare
2041 NewMI->addOperand(GA->getOperand(2)); // RHS of compare
2042 // All the MIs in the HexagonII::HCG_B category have MBB as 2nd operand.
2043 NewMI->addOperand(GB->getOperand(1)); // The branch target.
2044 unsigned dist = HLV->getDistanceBetween(MBB, GB->getOperand(1).getMBB());
2045 if (!QII->isJumpWithinBranchRange(*NewMI, dist + SafetyBuffer +
2046 SafetyBufferDelta)) {
2047 NewMI->eraseFromBundle();
2048 LLVM_DEBUG(dbgs() << ".....NO (Branch too far, cannot form)";);
2049 return NULL;
2050 }
2051 LLVM_DEBUG(dbgs() << "\nNew Compound Instruction:" << *NewMI;);
2052 }
2053 }
2054 return NewMI;
2055}
2056
2057void GlobalScheduler::generateCompoundsPostSched() {
2058 DenseSet<MachineInstr *>::iterator it = ToBeSqueezed.begin();
2059 while (it != ToBeSqueezed.end()) {
2060 auto MBB = (*it)->getParent();
2061 MIInstIterType GA = MBB->instr_end(), GB = MBB->instr_end();
2062 MachineInstr *NewMI =
2063 generateCompoundIfPossible((*it)->getIterator(), GA, GB);
2064 (void)NewMI;
2065 assert(NewMI && "Wrong Analysis of compound packets.");
2066 GA->eraseFromBundle();
2067 GB->eraseFromBundle();
2068 updateBundle(*it, QII);
2069 ++it;
2070 }
2071}
2072
2073// Check if the machine instructions belong in the same bundle
2075 if (MI1->isInsideBundle() && MI2->isInsideBundle() &&
2077 return true;
2078 return false;
2079}
2080
2081// Returns true if any of the conditions happen:
2082// (1) If a packet contains endloopN, it cannot perform an auto-AND with
2083// predicate register P3
2084// (2) If a packet contains a register transfer from a general register to a
2085// predicate register, no other instruction in the packet can write to the same
2086// predicate register.
2087// (3) Instructions spNloop0, decbin, tlbmatch, memw_locked, memd_locked,
2088// add:carry, sub:carry, sfcmp, and dfcmp cannot be grouped with another
2089// instruction that sets the same predicate register.
2090bool GlobalScheduler::failsSpecialConditions(MachineInstr *BundleMI,
2091 Register DestReg) {
2092
2093 if (!BundleMI || !BundleMI->getParent())
2094 return true;
2096 E = std::next(I);
2097 E != BundleMI->getParent()->instr_end() && E->isInsideBundle(); ++E) {
2098 MachineInstr &MI = *E;
2099 auto OpC = MI.getOpcode();
2100 // Case 1
2101 if (QII->isEndLoopN(OpC) && DestReg == Hexagon::P3)
2102 return true;
2103 // Case 2
2104 if ((OpC == Hexagon::C2_tfrrp) && MI.getNumOperands() > 0 &&
2105 (DestReg == MI.getOperand(0).getReg()))
2106 return true;
2107 // Case 3
2108 if ((OpC == Hexagon::S2_cabacdecbin) ||
2109 ((QII->isSoftwarePipelineLoopInstr(MI) || OpC == Hexagon::A4_tlbmatch ||
2110 QII->isFloatCompare(MI)) &&
2111 MI.getNumOperands() > 0 && MI.getOperand(0).getReg() == DestReg) ||
2112 ((OpC == Hexagon::S2_storew_locked ||
2113 OpC == Hexagon::S4_stored_locked || OpC == Hexagon::A6_vminub_RdP ||
2114 OpC == Hexagon::A5_ACS || OpC == Hexagon::F2_sfinvsqrta ||
2115 OpC == Hexagon::F2_sfrecipa) &&
2116 MI.getNumOperands() > 1 && MI.getOperand(1).getReg() == DestReg) ||
2117 ((OpC == Hexagon::A4_addp_c || OpC == Hexagon::A4_subp_c) &&
2118 MI.getNumOperands() > 2 && MI.getOperand(3).getReg() == DestReg))
2119 return true;
2120 }
2121 return false;
2122}
2123
2124// Returns true if Reg can be used as a .new predicate source in a packet,
2125// i.e. it is a non-fake predicate register whose definition (Producer) is
2126// not a late-predicate instruction (e.g. A4_addp_c, A4_subp_c).
2127// Sentinel marks the end of the valid iterator range for Producer.
2128bool GlobalScheduler::canNewifyPredReg(unsigned Reg, MICInstIterType Producer,
2129 MICInstIterType Sentinel) const {
2130 if (TRI->isFakeReg(Reg))
2131 return false;
2132 if (TRI->getMinimalPhysRegClass(Reg) != &Hexagon::PredRegsRegClass)
2133 return false;
2134 if (Producer != Sentinel && QII->isPredicateLate(Producer->getOpcode()))
2135 return false;
2136 return true;
2137}
2138
2139// Given a machine instruction, get the defs of the uses and return them as
2140// reference. It uses the infrastructure created in this pass, ie. MIUseDefs
2141bool GlobalScheduler::getDefinitions(MachineInstr *MI, MachineInstr *&Def1,
2142 MachineInstr *&Def2, MachineInstr *&Def3) {
2143
2144 auto MBB = MI->getParent();
2145 if (MI->getNumOperands() < 3)
2146 return false;
2147 Register Reg1 = MI->getOperand(1).getReg();
2148 Register Reg2 = MI->getOperand(2).getReg();
2149 auto Reg3 =
2150 (MI->getNumOperands() == 4) ? MI->getOperand(3).getReg() : Register(0);
2151 const MIUseDef_t &MIUseDefs = HLV->getMIUseDefs();
2152 if (&MBB->front() == MI)
2153 return false;
2154 for (auto DefSearch = std::prev(MI->getIterator());
2155 DefSearch != MBB->instr_begin(); --DefSearch) {
2156 if (DefSearch->isBundle())
2157 continue;
2158
2159 MIUseDef_t::const_iterator DefIter = MIUseDefs.find(&*DefSearch);
2160 if (DefIter == MIUseDefs.end())
2161 continue;
2162
2163 const BitVector &Defs = DefIter->second.second;
2164 if (Defs[Reg1])
2165 Def1 = &*DefSearch;
2166 if (Defs[Reg2])
2167 Def2 = &*DefSearch;
2168 if (Reg3 && Defs[Reg3])
2169 Def3 = &*DefSearch;
2170
2171 if (Def1 && Def2 && (!Reg3 || (Reg3 && Def3)))
2172 return true;
2173 }
2174 return false;
2175}
2176
2177// Exploits a feature of the Hexagon hardware that predicate instructions
2178// in a packet are internally auto ANDed, so a later AND is unnecessary.
2179// Updating liveness is not necessary.
2180void GlobalScheduler::generateAutoAndPredicates(MachineFunction &Fn) {
2181
2182 SmallVector<MachineInstr *, 4> ToBeErased;
2183 for (auto &MBB : Fn) {
2184 for (auto MII = MBB.instr_begin(), ME = MBB.instr_end(); MII != ME; ++MII) {
2185 unsigned OpC = MII->getOpcode();
2186 // TODO check for other opcode types too
2187 if (OpC != Hexagon::C2_and && OpC != Hexagon::C2_andn &&
2188 OpC != Hexagon::C4_and_and && OpC != Hexagon::C4_and_andn)
2189 continue;
2190
2191 Register DestPred = MII->getOperand(0).getReg();
2192 Register Reg1 = MII->getOperand(1).getReg();
2193 Register Reg2 = MII->getOperand(2).getReg();
2194 auto Reg3 = MII->getNumOperands() == 4 ? MII->getOperand(3).getReg()
2195 : Register(0);
2196
2197 // Skip if the operands are the same register
2198 if (Reg1 == Reg2)
2199 continue;
2200 if (Reg3 != 0 && Reg3 == Reg2)
2201 continue;
2202
2203 // Skip if any of the regs are not killed in the AND instruction.
2204 // We don't want any uses of the regs after the AND.
2205 if (!MII->getOperand(1).isKill() || !MII->getOperand(2).isKill() ||
2206 (Reg3 != 0 && !MII->getOperand(3).isKill()))
2207 continue;
2208
2209 // Check if the result of the AND instruction (DestPred) is used by a
2210 // .new instruction within the same packet. If so, skip this AND.
2211 // TODO: This could be handled by replacing the .new use with a regular
2212 // use. Another option is to pullup the .new use if possible
2213 bool UsedByDotNew = false;
2214 auto AndBundleStart = getBundleStart(MII);
2215 auto AndBundleEnd = getBundleEnd(MII);
2216 for (auto BundledII = AndBundleStart; BundledII != AndBundleEnd;
2217 ++BundledII) {
2218 if (&*BundledII == &*MII)
2219 continue;
2220 int UseIdx = BundledII->findRegisterUseOperandIdx(DestPred, TRI);
2221 if (UseIdx >= 0 && QII->isDotNewOperand(*BundledII, UseIdx)) {
2222 UsedByDotNew = true;
2223 break;
2224 }
2225 }
2226 if (UsedByDotNew)
2227 continue;
2228
2229 // Find definitions using MIIDefSet in the same MBB.
2230 MachineInstr *Def1 = nullptr;
2231 MachineInstr *Def2 = nullptr;
2232 MachineInstr *Def3 = nullptr;
2233 if (!getDefinitions(&*MII, Def1, Def2, Def3))
2234 continue;
2235
2236 // Check if the defs are compare instructions
2237 if (!QII->definesPredicateReg(*Def1) ||
2238 !QII->definesPredicateReg(*Def2) ||
2239 (Def3 && !QII->definesPredicateReg(*Def3)))
2240 continue;
2241
2242 // Check if both definitions are in the same bundle
2243 if (!checkIfSameBundle(Def1, Def2))
2244 continue;
2245 if (Def3 && !checkIfSameBundle(Def1, Def3))
2246 continue;
2247
2248 // Check if there are any uses of the predicates before the use in the AND
2249 // instruction If there are, we cannot do this transformation.
2250 MICInstIterType Use;
2251 SmallPtrSet<MachineInstr *, 2> Exception;
2252 auto MIStart = getBundleStart(Def1->getIterator());
2253 auto MIEnd = getBundleEnd(MII);
2254 Exception.insert(&*MII);
2255 if (HLV->isUsedWithin(MIStart, MIEnd, Reg1, Use, &Exception) ||
2256 HLV->isUsedWithin(MIStart, MIEnd, Reg2, Use, &Exception) ||
2257 (Def3 && HLV->isUsedWithin(MIStart, MIEnd, Reg3, Use, &Exception)))
2258 continue;
2259
2260 // Check some special conditions which makes auto-and not possible
2261 if (failsSpecialConditions(&*MIStart, DestPred))
2262 continue;
2263
2264 LLVM_DEBUG(dbgs() << "\n[Found predicate auto and candidate]: ";
2265 MII->dump());
2266
2267 std::optional<unsigned> NewOpC;
2268 switch (OpC) {
2269 // For C2_and: Pd = and(Ps, Pt) - both compares write to DestPred
2270 // (1) Change the def registers
2271 case Hexagon::C2_and:
2272 Def1->getOperand(0).setReg(DestPred);
2273 Def2->getOperand(0).setReg(DestPred);
2274 break;
2275
2276 // For C2_andn: Pd = and(Ps, !Pt) - Ps writes to DestPred, Pt writes
2277 // inverted to DestPred The second operand is the one that gets negated.
2278 // (1) Invert the opcode of the second def
2279 // (2) Change the def registers
2280 case Hexagon::C2_andn:
2281 LLVM_DEBUG(dbgs() << "Get inverted opcode for: "; Def2->dump());
2282 NewOpC = QII->getInvertedCompare(Def2->getOpcode());
2283 if (!NewOpC)
2284 continue;
2285 Def2->setDesc(QII->get(NewOpC.value()));
2286 Def1->getOperand(0).setReg(DestPred);
2287 Def2->getOperand(0).setReg(DestPred);
2288 break;
2289
2290 // (1) Change the three def registers
2291 case Hexagon::C4_and_and:
2292 Def1->getOperand(0).setReg(DestPred);
2293 Def2->getOperand(0).setReg(DestPred);
2294 Def3->getOperand(0).setReg(DestPred);
2295 break;
2296
2297 // (1) Change the three def registers
2298 // (2) Invert the last register's def opcode
2299 case Hexagon::C4_and_andn:
2300 LLVM_DEBUG(dbgs() << "Get inverted opcode for: "; Def3->dump());
2301 NewOpC = QII->getInvertedCompare(Def3->getOpcode());
2302 if (!NewOpC)
2303 continue;
2304 Def3->setDesc(QII->get(NewOpC.value()));
2305 Def1->getOperand(0).setReg(DestPred);
2306 Def2->getOperand(0).setReg(DestPred);
2307 Def3->getOperand(0).setReg(DestPred);
2308 break;
2309
2310 default:
2311 continue;
2312 }
2313
2314 ToBeErased.push_back(&*MII);
2315 }
2316 }
2317
2318 // Erase the redundant AND instructions
2319 for (MachineInstr *It : ToBeErased) {
2320 if (It->isBundled()) {
2321 auto Head = &*getBundleStart(It->getIterator());
2322 It->eraseFromBundle();
2323 updateBundle(Head, QII);
2324 } else
2325 It->eraseFromParent();
2326 }
2327}
2328
2329void GlobalScheduler::packetize() {
2330 DenseSet<unsigned> DoneMBBs;
2331 HexagonPacketizerList Packetizer(MF, MLI, AA, MBPI, false);
2332 SmallVectorImpl<MachineInstr *>::iterator PacketOpp = SpecPacketOpp.begin();
2333 // The Entries are the last instruction where a new MI was scheduled.
2334 // For now we only move up into the MBB.
2335 for (; PacketOpp != SpecPacketOpp.end(); ++PacketOpp) {
2336 MachineBasicBlock *MBB = (*PacketOpp)->getParent();
2337 if (!DoneMBBs.insert(MBB->getNumber()).second)
2338 continue;
2339 MachineBasicBlock::iterator RegionBeg = MBB->begin();
2340 MachineBasicBlock::iterator RegionEnd = std::next(RegionBeg);
2341 for (; RegionBeg != MBB->end(); RegionBeg = RegionEnd) {
2342 // Find scheduling regions and schedule / packetize each region.
2343 // TODO: Find all the regions (unpacketized) and make bundles.
2344 while (RegionBeg != MBB->end() && RegionBeg->isBundled())
2345 ++RegionBeg;
2346 if (RegionBeg == MBB->end())
2347 break;
2348 RegionEnd = std::next(RegionBeg);
2349 while (RegionEnd != MBB->end() && !RegionEnd->isBundled())
2350 ++RegionEnd;
2351 // Skip regions with one instruction.
2352 if (RegionBeg == std::prev(RegionEnd))
2353 continue;
2354 Packetizer.PacketizeMIs(MBB, RegionBeg, RegionEnd);
2355 }
2356 }
2357 Packetizer.unpacketizeSoloInstrs(MF);
2358}
2359
2360// @note When generating a compound instruction, we do not want to
2361// update the liveness of the BUNDLE/MBB because we might decompose later.
2362void GlobalScheduler::getResourcesReadyForBundle(MIInstIterType MII,
2363 bool Squeeze,
2364 MachineInstr *InstrToSkip) {
2365 assert(MII->isBundle());
2366
2367 bool GeneratedCompoundInstr = false;
2368 MachineInstr *NewMI = NULL;
2369 MachineBasicBlock *MBB = MII->getParent();
2370 MIInstIterType GA = MBB->instr_end(), GB = MBB->instr_end();
2371 // MIs because they might be pointing to MIs which are removed from Bundle.
2372 MachineInstr *GAPos, *GBPos;
2373 if (Squeeze && EnableSqueeze &&
2374 (QII->nonDbgBundleSize(*MII) == HEXAGON_PACKET_SIZE)) {
2375 // handle compound/duplex stuff.
2376 LLVM_DEBUG(dbgs() << "\nCompound can be made in this bundle.";);
2377 NewMI = generateCompoundIfPossible(MII, GA, GB);
2378 if (NewMI != NULL) {
2379 GeneratedCompoundInstr = true;
2380 MIInstIterType GANext = std::next(GA);
2381 MIInstIterType GBNext = std::next(GB);
2382 GAPos = GANext != MBB->instr_end() ? &*GANext : nullptr;
2383 GBPos = GBNext != MBB->instr_end() ? &*GBNext : nullptr;
2384 GA = GA->removeFromBundle()->getIterator();
2385 GB = GB->removeFromBundle()->getIterator();
2386 }
2387 }
2388
2389 initPacketizerStateLoc();
2390 ResourceTracker->clearResources();
2391 // Add already packetized instructions.
2392 ++MII; // Skipping Bundle header.
2393
2394 // For TinyCore with Duplexes, change the opcodes of MII to Big Core.
2395 MIInstIterType SavedMII = MII;
2396 auto &ST = MII->getParent()->getParent()->getSubtarget<HexagonSubtarget>();
2397 if (ST.isTinyCoreWithDuplex())
2398 QII->translateInstrsForDup(SavedMII, true);
2399
2400 while ((MII != MBB->instr_end()) && MII->isInsideBundle()) {
2401 assert(ResourceTracker->canReserveResources(*MII) ||
2402 TII->isZeroCost(MII->getOpcode()));
2403 if (!(InstrToSkip && InstrToSkip == &*MII)) {
2404 addToPacketPseudo(&*MII);
2405 }
2406 ++MII;
2407 }
2408
2409 // Restore the opcodes for Tiny Core with Duplexes.
2410 if (ST.isTinyCoreWithDuplex())
2411 QII->translateInstrsForDup(SavedMII, false);
2412
2413 if (GeneratedCompoundInstr) {
2414 // Group B MI should occur 'after' group A MI.
2415 MIInstIterType GBPosMII = GBPos ? GBPos->getIterator() : MBB->instr_end();
2416 MBB->insert(GBPosMII, &*GB);
2417 if (!GB->isBundled())
2418 GB->bundleWithPred();
2419 MIInstIterType GAPosMII = GAPos ? GAPos->getIterator() : MBB->instr_end();
2420 MBB->insert(GAPosMII, &*GA);
2421 assert(GA->isBundled());
2422 NewMI->eraseFromBundle();
2423 }
2424}
2425
2426// TODO: Deal with constant extenders later.
2427// For that we have to try allocate resources for two instructions.
2428bool GlobalScheduler::canReserveResources(MIInstIterType MII) const {
2429 if (QII->isExtended(*MII) || QII->isConstExtended(*MII))
2430 return false;
2431 return ResourceTracker->canReserveResources(*MII);
2432}
2433
2434// The usage of \p Reg is replaced by \p ScratchReg.
2435// @note: Does not do anything with the liveness.
2436void GlobalScheduler::replaceUsageOfReg(unsigned Reg, unsigned ScratchReg,
2437 MachineBasicBlock *MBB,
2438 const MachineInstr *ExceptMI) const {
2439 assert(Reg != ScratchReg);
2440 for (MIInstIterType MII = MBB->instr_begin(), MIE = MBB->instr_end();
2441 MII != MIE; ++MII) {
2442 MachineInstr *MI = &*MII;
2443 if (MI == ExceptMI)
2444 continue;
2445 for (unsigned i = 0; i < MI->getNumOperands(); ++i) {
2446 MachineOperand &MO = MI->getOperand(i);
2447 if (MO.isReg() && (MO.getReg() == Reg))
2448 MO.setReg(ScratchReg);
2449 }
2450 }
2451}
2452
2453void GlobalScheduler::markLiveInsAsUsed(std::unique_ptr<RegScavenger> &RS,
2454 MachineBasicBlock *MBB) const {
2456 lit != MBB->livein_end(); ++lit) {
2457 RS->setRegUsed((*lit).PhysReg);
2458 LLVM_DEBUG(dbgs() << printReg((*lit).PhysReg, TRI););
2459 }
2460}
2461
2462void GlobalScheduler::markLiveOutsAsUsed(std::unique_ptr<RegScavenger> &RS,
2463 MachineBasicBlock *MBB) const {
2464 const BitVector &LO = HLV->getLiveOuts(MBB);
2465 int Reg = LO.find_first();
2466 while (Reg >= 0) {
2467 RS->setRegUsed(Reg);
2468 LLVM_DEBUG(dbgs() << printReg(Reg, TRI););
2469 Reg = LO.find_next(Reg);
2470 }
2471}
2472
2473void GlobalScheduler::markAllRegsAsUsed(std::unique_ptr<RegScavenger> &RS,
2474 const MachineBasicBlock *MBB) const {
2475 // We have to insert a A2_tfr just before the TargetPacket.
2476 // Conservative approach: Traverse all the MIs in DstBB and mark all the
2477 // defs and uses as 'used' in the RegScav.
2478 const MIUseDef_t &MIUseDefs = HLV->getMIUseDefs();
2479 BitVector MBBUseDef(TRI->getNumRegs());
2480 for (MICInstIterType I = MBB->instr_begin(); I != MBB->instr_end(); ++I) {
2481 if (I->isBundle() || I->isDebugInstr())
2482 continue;
2483 MIUseDef_t::const_iterator MIUseDef = MIUseDefs.find(&*I);
2484 assert(MIUseDef != MIUseDefs.end());
2485 MBBUseDef |= MIUseDef->second.first;
2486 MBBUseDef |= MIUseDef->second.second;
2487 }
2488 int Reg = MBBUseDef.find_first();
2489 while (Reg >= 0) {
2490 RS->setRegUsed(Reg);
2491 LLVM_DEBUG(dbgs() << printReg(Reg, TRI););
2492 Reg = MBBUseDef.find_next(Reg);
2493 }
2494}
2495
2496// We want to split the critical edge only when there is a predecessor of ToBB
2497// which is also the layout predecessor of ToBB.
2499 MachineBasicBlock *ToBB) {
2500 // Find the layout predecessor of ToBB.
2501 assert(FromBB->isSuccessor(ToBB));
2502 MachineBasicBlock *LP = NULL;
2504 pe = ToBB->pred_end();
2505 pi != pe; ++pi)
2506 if ((*pi)->isLayoutSuccessor(ToBB))
2507 LP = *pi;
2508 return LP;
2509}
2510
2511MachineBasicBlock *GlobalScheduler::splitCriticalEdge(MachineBasicBlock *FromBB,
2512 MachineBasicBlock *ToBB,
2513 MachineBasicBlock *LP) {
2514 assert(LP->isLayoutSuccessor(ToBB));
2515 MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock();
2516 // We want to insert just before the ToBB because then we don't have to worry
2517 // about the branch range of (FromBB->ToBB).
2518 MF.insert(MachineFunction::iterator(ToBB), NewBB);
2519 FromBB->ReplaceUsesOfBlockWith(ToBB, NewBB);
2520 NewBB->addSuccessor(ToBB);
2521
2522 // Inform HLV of NewBB.
2523 HLV->addNewMBB(NewBB);
2524
2525 // According to the HexagonInstrInfo::getBranchingInstrs
2526 // Only the last element can be a conditional branching instruction.
2527 SmallVector<MachineInstr *, 2> Jumpers = QII->getBranchingInstrs(*LP);
2528 // Jumpers.empty || Jumpers[0] is predicated => fall-through
2529 if ((LP != FromBB) &&
2530 (Jumpers.empty() || !Jumpers[0]->isUnconditionalBranch())) {
2531 DebugLoc dl;
2532 MachineInstr *JumpMI =
2533 BuildMI(*LP, LP->instr_end(), dl, QII->get(Hexagon::J2_jump))
2534 .addMBB(ToBB);
2535 // Update liveness.
2536 HLV->addNewMI(JumpMI, LP);
2537 }
2538 LLVM_DEBUG(dbgs() << "\nLayout Pred after update:" << *LP;);
2539
2540 // We add a jump as a safe-measure, if this is redundant it will be removed.
2541 DebugLoc dl;
2542 MachineInstr *JumpMI =
2543 BuildMI(*NewBB, NewBB->instr_end(), dl, QII->get(Hexagon::J2_jump))
2544 .addMBB(ToBB);
2545 HLV->addNewMI(JumpMI, NewBB);
2546 // Update the branches in LP, invalidate the analyzeBranch of LP and of FromBB
2547 if (AnalyzeBranchInfo.hasABInfo(LP))
2548 AnalyzeBranchInfo.invalidate(LP);
2549 if (AnalyzeBranchInfo.hasABInfo(FromBB))
2550 AnalyzeBranchInfo.invalidate(FromBB);
2551 return NewBB;
2552}
2553
2554// The def should not have subregs.
2555bool GlobalScheduler::hasOneDef(const MachineInstr *MI, unsigned &DefR) const {
2556 DefR = 0;
2557 const MIUseDef_t &MIUseDefs = HLV->getMIUseDefs();
2558 MIUseDef_t::const_iterator MIUseDef = MIUseDefs.find(MI);
2559 if (MIUseDef == MIUseDefs.end())
2560 return false;
2561 const BitVector &Defs = MIUseDef->second.second;
2562 unsigned DefsCount = Defs.count();
2563 // An MI which does not defines a reg should not be here.
2564 assert(DefsCount);
2565 // We don't want to process an MI which defines multiple/no regs.
2566 if (DefsCount != 1)
2567 return false;
2568 DefR = Defs.find_first();
2569 // If this register has a sub-reg we do not want to handle that situation.
2570 return !MCSubRegIterator(DefR, TRI, false).isValid();
2571}
2572
2573// The use should not have subregs.
2574bool GlobalScheduler::hasOneUse(const MachineInstr *MI, unsigned &UseR) const {
2575 UseR = 0;
2576 const MIUseDef_t &MIUseDefs = HLV->getMIUseDefs();
2577 MIUseDef_t::const_iterator MIUseDef = MIUseDefs.find(MI);
2578 if (MIUseDef == MIUseDefs.end())
2579 return false;
2580 const BitVector &Uses = MIUseDef->second.first;
2581 unsigned UsesCount = Uses.count();
2582 // We don't want to process an MI which defines multiple/no regs.
2583 if (UsesCount != 1)
2584 return false;
2585 UseR = Uses.find_first();
2586 // If this register has a sub-reg we do not want to handle that situation.
2587 return !MCSubRegIterator(UseR, TRI, false).isValid();
2588}
2589
2590// MI should have just one def and just one usage.
2591// The def and use should not have subregs.
2592bool GlobalScheduler::hasOneDefAndUse(const MachineInstr *MI, unsigned &Def,
2593 unsigned &Use) const {
2594 return hasOneDef(MI, Def) && hasOneUse(MI, Use);
2595}
2596
2597// Returns later of the two in a linear sequence which might be
2598// I1 .. I2 .. Sentinel, or I2 .. I1 .. Sentinel
2599// If I1 == I2, returns I2.
2600MICInstIterType GlobalScheduler::laterOfTheTwo(MICInstIterType I1,
2601 MICInstIterType I2,
2602 MICInstIterType Sentinel) const {
2603 if (I2 == Sentinel)
2604 return I2;
2605 MICInstIterType Temp = I1;
2606 while (Temp != Sentinel) {
2607 if (Temp == I2)
2608 return I2;
2609 ++Temp;
2610 }
2611 return I1;
2612}
2613
2614// A more exhaustive dependence analysis for load bypass, more aggressive
2615// moves, etc. Used from the HVX local pullup.
2616int GreedyPullup::dstDependence(MICInstIterType DestBeg,
2617 MICInstIterType DestEnd, MICInstIterType MII,
2618 std::vector<const MachineInstr *> &DepTrueVec,
2619 std::vector<const MachineInstr *> &DepAntiVec,
2620 std::vector<const MachineInstr *> &DepOutputVec,
2621 std::vector<unsigned> *Regs) const {
2622
2623 if (DestBeg == DestEnd)
2624 return 0;
2625
2626 unsigned dep = Dependency::Independent;
2627
2628 SmallVector<unsigned> UseRegs;
2629 SmallVector<unsigned> DefRegs;
2630 for (const MachineOperand &MO : MII->operands()) {
2631 if (MO.isReg()) {
2632 if (MO.isUse())
2633 UseRegs.push_back(MO.getReg());
2634 else if (MO.isDef())
2635 DefRegs.push_back(MO.getReg());
2636 }
2637 }
2638
2639 bool addedTrueDep = false, addedFalseDep = false;
2640 auto I = DestEnd;
2641 auto &MIUseDefs = HLV->getMIUseDefs();
2642 do {
2643 --I;
2644 if (!I->isBundle()) {
2645 if (shouldNotBeCrossed(&*I, &*MII)) {
2646 dep = Dependency::Unknown;
2647 break;
2648 }
2649 if (I->isDebugInstr())
2650 continue;
2651 for (auto RegI = UseRegs.begin(), RegE = UseRegs.end(); RegI != RegE;
2652 ++RegI) {
2653 for (MCRegAliasIterator AI(*RegI, TRI, true); AI.isValid(); ++AI) {
2654 if (MIUseDefs[&*I].second[*AI]) {
2655 DepTrueVec.push_back(&*I);
2656 if (Regs)
2657 Regs->push_back(*RegI);
2658 addedTrueDep = true;
2659 dep |= Dependency::RAW;
2660 break;
2661 }
2662 }
2663
2664 if (addedTrueDep) {
2665 UseRegs.erase(RegI);
2666 addedTrueDep = false;
2667 break;
2668 }
2669 }
2670
2671 for (auto RegI = DefRegs.begin(), RegE = DefRegs.end(); RegI != RegE;
2672 ++RegI) {
2673 for (MCRegAliasIterator AI(*RegI, TRI, true); AI.isValid(); ++AI) {
2674 if (MIUseDefs[&*I].second[*AI]) { // WAW case is first
2675 addedFalseDep = true; // WAW prevents any movement, so stop
2676 dep |= Dependency::WAW;
2677 DepOutputVec.push_back(&*I);
2678 break;
2679 }
2680 }
2681
2682 for (MCRegAliasIterator AI(*RegI, TRI, true); AI.isValid(); ++AI) {
2683 if (MIUseDefs[&*I].first[*AI]) {
2684 DepAntiVec.push_back(&*I);
2685 dep |= Dependency::WAR;
2686 break;
2687 }
2688 }
2689
2690 if (addedFalseDep) {
2691 DefRegs.erase(RegI);
2692 addedFalseDep = false;
2693 break;
2694 }
2695 }
2696 }
2697
2698 if (I == DestBeg)
2699 break;
2700
2701 } while (I != DestBeg);
2702
2703 return dep;
2704}
2705
2706//===----------------------------------------------------------------------===//
2707// GreedyPullup Functions
2708//===----------------------------------------------------------------------===//
2709// Returns true if Resources (MII) /\ Resources [DestBeg, DestEnd) != NULL
2710// Use(MII) /\ Def[DestBeg, DestEnd) != NULL
2711// Def(MII) /\ Def+Use[DestBeg, DestEnd) != NULL
2712// For .new MII: Use(MII) /\ Def(Bundle(MII)) == NULL
2713// [DestBeg, DestEnd) can span multiple bundles.
2714// \p DepTrue is the instruction which defines the Operand used by MII.
2715// \p DepAnti is the instruction which uses the Operand defined by MII.
2716// @note: Care must be taken because DepTrue and DepAnti will only give
2717// the def/use of the last operand (there might be more Deps).
2718int GreedyPullup::dstDependence(MICInstIterType DestBeg,
2719 MICInstIterType DestEnd, MICInstIterType MII,
2720 MICInstIterType &DepTrue,
2721 MICInstIterType &DepAnti, unsigned HLXUseReg,
2722 bool IsPullDown) const {
2723 LLVM_DEBUG(dbgs() << "\t[DstDependence]";);
2724 const MachineInstr *MI = &*MII;
2725 const MachineBasicBlock *SrcMBB = MII->getParent();
2726 // Initialize iterators to safe defaults
2727 MICInstIterType DepTrueP = SrcMBB->instr_end(),
2728 DepTrueQ = SrcMBB->instr_end(),
2729 DepAntiP = SrcMBB->instr_end();
2730 DepTrue = SrcMBB->instr_end();
2731 DepAnti = SrcMBB->instr_end();
2732
2733 assert(!shouldNotBePulledUp(&*MII));
2734 MICInstIterType DestBundle =
2735 DestBeg->isBundled() ? getBundleStart(DestBeg) : DestBeg;
2736 MICInstIterType MIBegin = DestBeg;
2737 bool IsMIInDestBundle = false;
2738 for (; MIBegin != DestEnd; ++MIBegin) {
2739 // Need to pass isMIInDestBundle to create single packet HLX load-use-store
2740 // Only do this for local pullup
2741 IsMIInDestBundle = false;
2742 if (!IsPullDown && DestBundle->isBundle() && MIBegin->isBundled())
2743 IsMIInDestBundle = (DestBundle == getBundleStart(MIBegin));
2744 if (!shouldNotBeCrossed(&*MIBegin, &*MII, IsMIInDestBundle))
2745 continue;
2746 LLVM_DEBUG(dbgs() << "<<Unknown dependency>>";);
2747 return Dependency::Unknown;
2748 }
2749 // If MII points to a branch, check that there are no instructions
2750 // between dest bundle end and MII
2751 if (MII->isBranch() || MII->isTerminator() || MII->isReturn()) {
2752 // Only allow local pullup for unbundled endloop.
2753 // Do not allow endloop to be pulled down.
2754 // Check that there are no instructions between DestBundle and endloop.
2755 MICInstIterType SrcBundle = getBundleStart(MII);
2756 if (SrcBundle->getBundleSize() != 1 || SrcMBB != DestBeg->getParent() ||
2757 (laterOfTheTwo(MII, DestBeg, SrcMBB->instr_end()) == DestBeg) ||
2758 getBundleEnd(DestBeg) != SrcBundle) {
2759 LLVM_DEBUG(dbgs() << "<<Unknown dependency>>";);
2760 return Dependency::Unknown;
2761 }
2762 }
2763 unsigned dep = Dependency::Independent;
2764
2765 auto CheckDep = [&](const MachineOperand &MO, unsigned Reg) -> void {
2766 bool IsDef = MO.isReg() ? MO.isDef() : true; // regmask clobbers are defs
2767 const MachineInstr *MI = MO.getParent();
2768 unsigned OpIdx = MO.isReg() ? MO.getOperandNo() : 0;
2769 // Use/Def should not be Defined.
2770 bool destIsBundle = (DestBeg->isBundle() || DestBeg->isBundledWithPred());
2771 // However, return Dependency::Independent for:
2772 // Reg is known to be HLX .new use and has def in Dest bundle
2773 // Reg is known to be use of a HLX load and has tmp def in Dest bundle
2774 if (HLV->isDefinedWithin(DestBeg, DestEnd, Reg, DepTrueP)) {
2775 bool depInDestBundle =
2776 destIsBundle && (getBundleStart(DepTrueP) == getBundleStart(DestBeg));
2777
2778 // DestBundle could have a regular def and a .tmp def
2779 // Regular def could also be a redundant copy (such as l0 = l0)
2780 bool tmpDef = QII->isDotTmpInst(*DepTrueP);
2781 bool regularDef = !tmpDef;
2782 if (depInDestBundle &&
2783 HLV->isDefinedWithin(DestBeg, DepTrueP, Reg, DepTrueQ)) {
2784 tmpDef |= QII->isDotTmpInst(*DepTrueQ);
2785 regularDef |= !tmpDef;
2786 }
2787
2788 bool hasHLXDep = depInDestBundle && (HLXUseReg == Reg);
2789 if (!IsDef) {
2790 // Pull up HLX load use or store.
2791 // We know that DestBundle has .tmp load that feeds the load use
2792 // or DestBundle has a def that feeds .new store
2793 if (hasHLXDep)
2794 return;
2795 LLVM_DEBUG(dbgs() << "<<RAW dependency>>";);
2796 dep |= Dependency::RAW;
2797 } else { // is Def.
2798 if (hasHLXDep && !regularDef)
2799 return;
2800 LLVM_DEBUG(dbgs() << "<<WAW dependency>>";);
2801 dep |= Dependency::WAW;
2802 }
2803 assert(DepTrueP != DestEnd);
2804 DepTrue = DepTrueP;
2805 }
2806 // Defs should not be used in the same packet via operand forwarding (.new,
2807 // .tmp or .cur).
2808 if (!IsDef)
2809 return;
2810 MICInstIterType LastII = DestEnd;
2811 while (HLV->isUsedWithin(DestBeg, LastII, Reg, DepAntiP)) {
2812 bool depInDestBundle =
2813 destIsBundle && (getBundleStart(DepAntiP) == getBundleStart(DestBeg));
2814 const MachineInstr *DepMI = &*DepAntiP;
2815 int UseIdx = DepMI->findRegisterUseOperandIdx(Reg, TRI);
2816 assert(UseIdx >= 0);
2817 // TODO: Packet can have both .cur and .new
2818 bool DefViaRegMask = !MO.isReg(); // regmask clobber has no def operand
2819 if (!EnableDefUseSamePacket || !depInDestBundle ||
2820 !QII->isSafeInBundleWAR(*MI, OpIdx, *DepMI, UseIdx, IsPullDown,
2821 DefViaRegMask)) {
2822 dep |= Dependency::WAR;
2823 assert(DepAntiP != DestEnd);
2824 DepAnti = DepAntiP;
2825 LLVM_DEBUG(dbgs() << "<<WAR dependency>>";);
2826 return;
2827 }
2828 // Safe only if inserted into same bundle as use; callers decide.
2829 dep |= Dependency::WAR_SameBundle;
2830 DepAnti = DepAntiP;
2831 LLVM_DEBUG(dbgs() << "<<WAR_SameBundle dependency>>";);
2832 LastII = DepAntiP;
2833 }
2834 };
2835 // TODO: Check if instruction to be pulled up can be newified
2836 for (unsigned i = 0; i < MI->getNumOperands(); ++i) {
2837 const MachineOperand &MO = MI->getOperand(i);
2838 if (MO.isReg() && MO.getReg()) {
2839 // If this reg has subregs, check dependencies for each subreg
2840 if (MCSubRegIterator(MO.getReg(), TRI, false).isValid()) {
2841 for (MCPhysReg R : TRI->subregs(MO.getReg()))
2842 CheckDep(MO, R);
2843 } else
2844 CheckDep(MO, MO.getReg());
2845 } else if (MO.isRegMask()) {
2846 for (unsigned R = 1, NR = TRI->getNumRegs(); R != NR; ++R)
2847 if (MO.clobbersPhysReg(R))
2848 CheckDep(MO, R);
2849 }
2850 }
2851 return dep;
2852}
2853
2854// Dependence of RMII within the same packet.
2855// \p SrcBeg and \p SrcEnd are begin and end of the bundle respectively.
2856// \p DepSet, if non-null, collects the same-packet instructions that must
2857// move with RMII.
2858int GreedyPullup::srcDependence(MIInstIterType SrcBeg, MIInstIterType SrcEnd,
2859 MIInstIterType RMII,
2860 SmallPtrSetImpl<MachineInstr *> *DepSet) const {
2861 LLVM_DEBUG(dbgs() << "\t[SrcDependence]";);
2862 bool PreventDuplex = PreventDuplexSep.getNumOccurrences()
2864 : TM->getOptLevel() <= CodeGenOptLevel::Default;
2865 return QII->srcDependence(SrcBeg, SrcEnd, RMII, HLV->getMIUseDefs(), DepSet,
2866 PreventDuplex, /*IsPullDown=*/false);
2867}
2868
2869bool GreedyPullup::singleTrueDep(MICInstIterType SrcBeg, MICInstIterType SrcEnd,
2870 MICInstIterType MII, unsigned &Reg) const {
2871 const MachineInstr *MI = &*MII;
2872 bool TD = false;
2873 MICInstIterType DepTrueP = SrcEnd;
2874 for (unsigned i = 0; i < MI->getNumOperands(); ++i) {
2875 const MachineOperand &MO = MI->getOperand(i);
2876 if (MO.isReg() && MO.isUse() && MO.getReg()) {
2877 if (HLV->isDefinedWithin(SrcBeg, SrcEnd, MO.getReg(), DepTrueP)) {
2878 if (TD)
2879 return false;
2880 Reg = MO.getReg();
2881 TD = true;
2882 }
2883 }
2884 }
2885 return true;
2886}
2887
2888// Is it okay to execute MI as the first instruction in the MBB.
2889MIIterType GreedyPullup::findInsertionPtSpecLocal(MachineInstr *MI) {
2890 LLVM_DEBUG(dbgs() << "\n[findInsertionPtSpecLocal]");
2891 assert(!shouldNotBePulledUp(MI));
2892 MachineBasicBlock *MBB = MI->getParent();
2893 // First instruction in MBB. Bundled MI can never be the first because
2894 // there will be a Bundle header.
2895 if (MI == &*MBB->getFirstNonDebugInstr())
2896 return MBB->begin();
2897 std::pair<MIInstIterType, MIInstIterType> ParentBundle = getParentBundle(MI);
2898
2899 if (MI->isBundled()) {
2900 // Inside the packet, check only for Src Dependency,
2901 // i.e. are there any consumers of MI within the same packet.
2902 unsigned SrcDep = srcDependence(ParentBundle.first, ParentBundle.second,
2903 MI->getIterator());
2904 // True/Unknown dependence => bail out.
2905 if (!Dependency::hasOnly(SrcDep, Dependency::Independent))
2906 return MBB->end();
2907 // MI is in the first bundle and it has no consumer in the same packet.
2908 if (ParentBundle.first == MBB->getFirstNonDebugInstr())
2909 return MBB->begin();
2910 }
2911
2912 // If MI can execute as the first instruction.
2913 MIIterType InsPos = findInsertPtSpec(MI, MBB, false, false);
2914
2915 return InsPos;
2916}
2917
2918// Local pullup pass to schedule HVX instructions, while avoiding interlock
2919// stalls. Schedule the load bypass opportunities in the basic block
2920// first.
2921void GreedyPullup::localPullupHVX(SchedulingRegion_t::SRAtom_t *SR) {
2923 return;
2924
2925 // Only on innermost loops.
2927 auto *L = MLI.getLoopFor(SR);
2928 if (!L)
2929 return;
2930 if (!isSuperblockLoop(L))
2931 return;
2932 }
2933
2934 // Check if the majority of instructions in the block are HVX instructions.
2935 if (EnableHVXSuperblockHeuristic && !isProfitableToScheduleHVX(SR))
2936 return;
2937
2938 // Route HVX vector pullup through the shared local-pullup engine. HVXMode
2939 // admits plain HVX vector ops as candidates, applies the same
2940 // intermediate-packet-aware dependence checks as scalar pullup, and
2941 // generates .cur load bypasses where profitable.
2942 localPullupImpl(SR, /*HVXMode=*/true);
2943}
2944
2945// InstrToMove is the instruction to be moved to the same packet as LoadInstr
2946// to utilize the load bypass (.cur).
2947// LoadInstr is inside DestBundle.
2948void GreedyPullup::genLoadBypass(MachineInstr *LoadInstr,
2949 MachineInstr *InstrToMove) {
2950 assert(LoadInstr->isBundled() && "Load bypass requires a bundle");
2951 MachineInstr *DestBundle = &*getBundleStart(LoadInstr->getIterator());
2952 int CurOpcode = QII->getDotCurOp(*LoadInstr);
2953 LoadInstr->setDesc(QII->get(CurOpcode));
2954 MIBundleBuilder Bundle(DestBundle);
2955 Bundle.insert(std::next(LoadInstr->getIterator()), InstrToMove);
2956 unsigned DestReg = LoadInstr->getOperand(0).getReg();
2957 for (auto &MO : InstrToMove->operands()) {
2958 if (!MO.isReg())
2959 continue;
2960 if (!MO.isUse())
2961 continue;
2962 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI) {
2963 if (*AI == DestReg)
2964 MO.setIsInternalRead();
2965 }
2966 }
2967}
2968
2969// Returns true if a single RAW dependence on \p DepTrue can be resolved via a
2970// .cur load bypass: \p DepTrue must be a .cur-able HVX load that lives in
2971// DestBundle, there must be no WAW on the destination, and no instruction
2972// other than the consumer being pulled up may read the load's def reg within
2973// the destination packet [next(DestBundle), PktEnd). \p Consumer is the
2974// instruction being pulled up; the cur-load must be its only true-dependence
2975// producer in the pulled region (see the intermediate-producer check below).
2976bool GreedyPullup::canGenCurBypass(MIInstIterType DestBundle,
2977 MachineInstr *DepTrue, MIInstIterType PktEnd,
2978 int DstDep, MachineInstr *Consumer,
2979 const MachineInstr *Exempt) {
2980 assert(Consumer && "Consumer is required for .cur bypass correctness checks");
2981 if (!DepTrue || Dependency::has(DstDep, Dependency::WAW))
2982 return false;
2983 // .cur load bypass is keyed on the mayBeCurLoad TSFlag, not on HVX: any load
2984 // with a .cur form (present or future) is eligible.
2985 if (!QII->mayBeCurLoad(*DepTrue))
2986 return false;
2987 if (&*getBundleStart(DepTrue->getIterator()) != &*DestBundle)
2988 return false;
2989 // If DestBundle is a real bundle, the load must be bundled inside it.
2990 if (DestBundle->isBundle() && !DepTrue->isBundled())
2991 return false;
2992 // No other consumer of the load's def reg may exist in the packet.
2993 unsigned DestReg = DepTrue->getOperand(0).getReg();
2994 for (auto &MI :
2995 iterator_range<MIInstIterType>(std::next(DestBundle), PktEnd)) {
2996 if (&MI == DepTrue)
2997 continue;
2998 for (const MachineOperand &MOP : MI.operands()) {
2999 if (MOP.isReg() && MOP.isUse() && !MOP.isDebug() && MOP.getReg() &&
3000 !MOP.isUndef() && TRI->regsOverlap(MOP.getReg(), DestReg))
3001 return false;
3002 }
3003 }
3004 // .cur only forwards the load's primary def; a post-increment
3005 // load's second (tied pointer) def is not forwarded, so masking the whole
3006 // RAW bit is unsound if the consumer reads that other def instead.
3007 if (Consumer) {
3008 for (const MachineOperand &Def : DepTrue->operands()) {
3009 if (!Def.isReg() || !Def.isDef() || !Def.getReg() ||
3010 Def.getReg() == DestReg)
3011 continue;
3012 for (const MachineOperand &Use : Consumer->operands()) {
3013 if (Use.isReg() && Use.isUse() && !Use.isUndef() && Use.getReg() &&
3014 TRI->regsOverlap(Use.getReg(), Def.getReg()))
3015 return false;
3016 }
3017 }
3018 }
3019 // The caller masks the whole RAW bit, which is only sound if the cur-load is
3020 // the consumer's sole producer across the hoisted region. Refuse if any
3021 // instruction between DestBundle and the consumer defines a reg the consumer
3022 // reads (use-before-def); the scalar dependence surfaces only one producer.
3023 for (MIInstIterType MI = std::next(DestBundle);
3024 MI != Consumer->getIterator() &&
3025 MI != Consumer->getParent()->instr_end();
3026 ++MI) {
3027 if (&*MI == DepTrue || &*MI == Exempt || MI->isBundle())
3028 continue;
3029 for (const MachineOperand &Def : MI->operands()) {
3030 if (!Def.isReg() || !Def.isDef() || !Def.getReg())
3031 continue;
3032 bool ConsumerReads =
3033 llvm::any_of(Consumer->operands(), [&](const MachineOperand &Use) {
3034 return Use.isReg() && Use.isUse() && !Use.isUndef() &&
3035 Use.getReg() && TRI->regsOverlap(Use.getReg(), Def.getReg());
3036 });
3037 if (ConsumerReads)
3038 return false;
3039 }
3040 }
3041 return true;
3042}
3043// Check if moving SrcMI to DestBundle will cause an interlock-stall due to
3044// input latency.
3045bool GreedyPullup::canCauseInterlockStall(MIInstIterType DestBundle,
3046 MachineInstr *SrcMI,
3047 const InstrItineraryData *II) {
3048 bool PrevOK = true;
3049 auto PrevEnd = std::prev(DestBundle);
3050 auto *MBB = SrcMI->getParent();
3051 MachineInstr *PrevStart = nullptr;
3052 if (PrevEnd != MBB->end()) {
3053 if (PrevEnd->isBundled())
3054 PrevStart = &*getBundleStart(PrevEnd);
3055 else
3056 PrevStart = &*PrevEnd;
3057 }
3058
3059 if (PrevEnd != MBB->end() && PrevStart != nullptr) {
3060 std::vector<const MachineInstr *> DepTruePrevVec, DepAntiPrevVec,
3061 DepOutputPrevVec;
3062 std::vector<unsigned> TrueRegs;
3063 int dep = dstDependence(PrevStart->getIterator(), DestBundle,
3064 SrcMI->getIterator(), DepTruePrevVec,
3065 DepAntiPrevVec, DepOutputPrevVec, &TrueRegs);
3066 if (Dependency::has(dep, Dependency::RAW)) {
3067 unsigned RegIdx = 0;
3068 for (auto DepTruePrev : DepTruePrevVec) {
3069 int DefIdx = -1, UseIdx = -1;
3070 for (MCRegAliasIterator AI(TrueRegs[RegIdx], TRI, true);
3071 AI.isValid() && DefIdx == -1; ++AI)
3072 DefIdx = DepTruePrev->findRegisterDefOperandIdx(*AI, /*TRI=*/nullptr);
3073 for (MCRegAliasIterator AI(TrueRegs[RegIdx], TRI, true);
3074 AI.isValid() && UseIdx == -1; ++AI)
3075 UseIdx = SrcMI->findRegisterUseOperandIdx(*AI, /*TRI=*/nullptr);
3076 std::optional<unsigned> OpLatency =
3077 QII->getOperandLatency(II, *DepTruePrev, DefIdx, *SrcMI, UseIdx);
3078 if (!OpLatency) {
3079 ++RegIdx;
3080 continue;
3081 }
3082 int Latency = MF.getSubtarget<HexagonSubtarget>().updateLatency(
3083 *SrcMI, const_cast<MachineInstr &>(*DepTruePrev), false,
3084 *OpLatency);
3085 if (Latency > 1) {
3086 PrevOK = false;
3087 break;
3088 }
3089 ++RegIdx;
3090 }
3091 }
3092 }
3093 return !PrevOK;
3094}
3095
3096// Find all uses of .tmp HLX load and attempt to pullup the uses
3097// to the load's bundle
3098void GreedyPullup::localPullupHLXLoadUses(SchedulingRegion_t::SRAtom_t *SR,
3099 MachineInstr *HLXLoadMI,
3100 MachineInstr *HLXCopyMI) {
3101 LLVM_DEBUG(dbgs() << "\n\n\t\t[LocalPullupHLXLoadUses]");
3102 MIIterType BI =
3104 HLXLoadMI->getIterator());
3105 MIInstIterType DestBundle = BI.getInstrIterator();
3106 unsigned HLXLoadDestReg = HLXLoadMI->getOperand(0).getReg();
3107 unsigned NumLoadUsesPullups = 0;
3108 // List of uses of HLX load that can be pulled up
3109 SmallVector<MachineInstr *, 4> LoadUses;
3110
3111 if (!HLXCopyMI || !HLXLoadDestReg ||
3112 (HLXCopyMI->getOperand(0).getReg() != HLXLoadDestReg))
3113 return;
3114 LLVM_DEBUG(dbgs() << "\nFound HLX load pseudo";
3115 dbgs() << "\nFinding uses of HLX load for pullup into: "
3116 << *DestBundle;);
3117 MachineBasicBlock *MBB = HLXCopyMI->getParent();
3118 MIInstIterType LoadBundleEnd = getBundleEnd(DestBundle);
3119 // Early exit if DestBundle is last bundle in MBB
3120 if (LoadBundleEnd == MBB->end())
3121 return;
3122
3123 // Find all uses of the load
3124 MICInstIterType NextLoadRegDef = MBB->instr_end();
3125 MICInstIterType DepTrueP = MBB->instr_end();
3126 while (HLV->isDefinedWithin(LoadBundleEnd, NextLoadRegDef, HLXLoadDestReg,
3127 DepTrueP))
3128 NextLoadRegDef = DepTrueP;
3129 MICInstIterType PrevLoadRegUse = NextLoadRegDef;
3130 // Instruction that defines HLXLoadDestReg may also use the same register
3131 // Allow isUsedWithin to find it
3132 if (PrevLoadRegUse != MBB->instr_end())
3133 ++PrevLoadRegUse;
3134 while (HLV->isUsedWithin(LoadBundleEnd, PrevLoadRegUse, HLXLoadDestReg,
3135 DepTrueP)) {
3136 LLVM_DEBUG(dbgs() << "\nFound use: "; DepTrueP->dump(););
3137 LoadUses.push_back(&*DepTrueP.getNonConst());
3138 PrevLoadRegUse = DepTrueP;
3139 }
3140
3141 // Check if the load reg is live out from MBB
3142 bool LoadRegIsLiveOut = HLV->isLiveOut(MBB, HLXLoadDestReg) &&
3143 (NextLoadRegDef == MBB->instr_end());
3144
3145 // Check if the bundle contains a call that reads the loaded register
3146 MICInstIterType BStart = getBundleStart(DestBundle);
3147 MICInstIterType BEnd = getBundleEnd(DestBundle);
3148
3149 bool BundleHasCallUse =
3150 QII->hasCallUseInBundle(BStart, BEnd, HLXLoadDestReg, *TRI);
3151
3152 // Attempt to pull up each use of the load
3153 // Iteration order: Nearest to farthest
3154 for (MachineInstr *SrcMI : reverse(LoadUses)) {
3155 if (!HLXCopyMI && (DestBundle->getBundleSize() >= HEXAGON_PACKET_SIZE))
3156 continue;
3157 MIInstIterType SrcMII = SrcMI->getIterator();
3158 // If Use is not bundled, create a single instruction bundle for it
3159 if (!SrcMI->isBundled())
3160 finalizeBundle(*(SrcMI->getParent()), SrcMII, std::next(SrcMII));
3161 // Check if resources are available in Bundle.
3162 std::pair<MIInstIterType, MIInstIterType> ParentBundle =
3163 getParentBundle(&*SrcMII);
3164
3165 LLVM_DEBUG(dbgs() << "\nChecking Resources for: " << *SrcMII;);
3166 if (!isLegalToPacketizeWith(BI, SrcMI) || isSoloInstruction(*SrcMI) ||
3167 shouldNotBePulledUp(SrcMI))
3168 continue;
3169 MICInstIterType DepTrue = MBB->instr_end(), DepAnti = MBB->instr_end();
3170 int DstDep = dstDependence(DestBundle, ParentBundle.first, SrcMII, DepTrue,
3171 DepAnti, HLXLoadDestReg);
3172 int SrcDep = srcDependence(ParentBundle.first, ParentBundle.second, SrcMII);
3173 MIInstIterType DestPos = DestBundle;
3174 getResourcesReadyForBundle(DestPos);
3175 // Delete copy and attempt to pull up the last use
3176 if ((!Dependency::hasOnly(DstDep, Dependency::Independent) ||
3177 !canReserveResources(SrcMII)) &&
3178 !LoadRegIsLiveOut && (NumLoadUsesPullups == (LoadUses.size() - 1)) &&
3179 SrcMI == LoadUses.front() && !BundleHasCallUse) {
3180 LLVM_DEBUG(dbgs() << "\nAttempting to pullup last use by erasing copy: ";
3181 HLXCopyMI->dump(););
3182 HLXCopyMI = HLXCopyMI->removeFromBundle();
3183 DstDep = dstDependence(DestBundle, ParentBundle.first, SrcMII, DepTrue,
3184 DepAnti, HLXLoadDestReg);
3185 getResourcesReadyForBundle(DestPos);
3186 }
3187 // Speculate when there are no dependencies across scheduling path.
3188 if (!(Dependency::hasOnly(DstDep, Dependency::Independent)) ||
3189 !(Dependency::hasOnly(SrcDep, Dependency::Independent)))
3190 continue;
3191 LLVM_DEBUG(dbgs() << "[Can add to packet]";);
3192 if (!canReserveResources(SrcMII)) {
3193 LLVM_DEBUG(dbgs() << " .....NO");
3194 continue;
3195 }
3196 LLVM_DEBUG(dbgs() << "..... YES (Resource available)";);
3197 MachineInstr *InstrToMove = removeMI(SrcMI, QII, nullptr);
3198
3199 MachineOperand *Op = nullptr;
3200 for (MCRegAliasIterator AI(HLXLoadDestReg, TRI, true); AI.isValid(); ++AI) {
3201 Op = InstrToMove->findRegisterUseOperand(*AI, /*TRI=*/nullptr);
3202 if (Op)
3203 break;
3204 }
3205 assert(Op && "Could not find use operand!");
3206 Op->setIsInternalRead();
3207
3208 // Load use must be inserted after the HLX load instruction
3209 // in the bundle to avoid confusing finalizeBundle about liveness
3210 // of the use reg
3211 MIBundleBuilder Bundle(&*DestBundle);
3212 Bundle.insert(std::next(HLXLoadMI->getIterator()), InstrToMove);
3213
3214 // Update pullup count. This might be useful in doing another
3215 // iteration of global pullup into these MBBs.
3216 ++LocalPullups;
3217 ++NumLoadUsesPullups;
3218 LLVM_DEBUG(dbgs() << "\nSpeculated Local MI:\t" << *InstrToMove
3219 << "\nMBB: " << *InstrToMove->getParent());
3220
3221 HLV->updateLocalLiveness(SR, true);
3222 }
3223 // Keep the copy if all uses could not be pulled up, if register is live out,
3224 // if there are no in-bundle uses, or if a call in the bundle reads the reg.
3225 if (NumLoadUsesPullups != LoadUses.size() || LoadRegIsLiveOut ||
3226 BundleHasCallUse) {
3227 // Add back copy if last use could not be pulled up
3228 if (!HLXCopyMI->isBundled()) {
3229 LLVM_DEBUG(dbgs() << "\nRestoring copy\n");
3230 MIBundleBuilder Bundle(&*DestBundle);
3231 Bundle.insert(std::next(HLXLoadMI->getIterator()), HLXCopyMI);
3232 HLV->updateLocalLiveness(SR, true);
3233 }
3234 } else {
3235 // Delete the copy if all uses have been pulled up
3236 if (HLXCopyMI->isBundled())
3237 HLXCopyMI->eraseFromBundle();
3238 else
3239 MF.deleteMachineInstr(HLXCopyMI);
3240 HLV->updateLocalLiveness(SR, true);
3241 }
3242}
3243
3244// Find reaching def of .new HLX store and attempt to pullup the store
3245// to the reaching def's bundle
3246void GreedyPullup::localPullupHLXStore(SchedulingRegion_t::SRAtom_t *SR,
3247 MachineInstr *HLXStoreMI,
3248 MachineInstr *HLXCopyMI) {
3249 LLVM_DEBUG(dbgs() << "\n\n\t\t[LocalPullupHLXStore]");
3250 MIIterType BI =
3252 HLXStoreMI->getIterator());
3253 MIInstIterType SrcBundle = BI.getInstrIterator();
3254 unsigned HLXStoreSrcReg = HLXStoreMI->getOperand(1).getReg();
3255
3256 // Bundle with Def instruction is the destination bundle
3257 MachineInstr *DestMI = nullptr;
3258 // Check if .new HLX store has a HLX copy that feeds it
3259 if (!HLXCopyMI || !HLXStoreSrcReg ||
3260 HLXCopyMI->getOperand(0).getReg() != HLXStoreSrcReg)
3261 return;
3262 LLVM_DEBUG(dbgs() << "\nFound HLX store pseudo";
3263 dbgs() << "\nFinding def for HLX store to be pulled up from: "
3264 << *SrcBundle;);
3265 MachineBasicBlock *MBB = HLXCopyMI->getParent();
3266 MIInstIterType StoreBundleStart = getBundleStart(SrcBundle);
3267
3268 MICInstIterType DepTrueP = MBB->instr_end();
3269 if (HLV->isDefinedWithin(MBB->instr_front().getIterator(), StoreBundleStart,
3270 HLXStoreSrcReg, DepTrueP))
3271 DestMI = &*DepTrueP.getNonConst();
3272
3273 if (!DestMI)
3274 return;
3275 MIInstIterType DestMII = DestMI->getIterator();
3276 // If Def is not bundled, create a single instruction bundle for it
3277 if (!DestMI->isBundled())
3278 finalizeBundle(*(DestMI->getParent()), DestMII, std::next(DestMII));
3279 std::pair<MICInstIterType, MICInstIterType> ParentBundle =
3280 getParentBundle(DestMI);
3281
3282 // Check if resources are available in Bundle.
3283 LLVM_DEBUG(dbgs() << "\nChecking Resources for: " << *HLXStoreMI;);
3284 MIInstIterType DestPos = getBundleStart(DestMII);
3285 if (!isLegalToPacketizeWith(&*DestPos, HLXStoreMI))
3286 return;
3287 MICInstIterType DepTrue = MBB->instr_end(), DepAnti = MBB->instr_end();
3288 int DstDep =
3289 dstDependence(ParentBundle.first, SrcBundle, HLXStoreMI->getIterator(),
3290 DepTrue, DepAnti, HLXStoreSrcReg);
3291
3292 // .new HLX store cannot have dependence on any instruction other than
3293 // feeder copy in source packet. Skip srcDependence check.
3294
3295 // Speculate when there are no dependencies across scheduling path.
3296 if (!Dependency::hasOnly(DstDep, Dependency::Independent))
3297 return;
3298 LLVM_DEBUG(dbgs() << "[Can add to packet]";);
3299 getResourcesReadyForBundle(DestPos);
3300 if (!canReserveResources(HLXStoreMI->getIterator())) {
3301 LLVM_DEBUG(dbgs() << " .....NO");
3302 return;
3303 }
3304 LLVM_DEBUG(dbgs() << "..... YES (Resource available)";);
3305
3306 // Remove the MI before creating the bundle builder, so that the
3307 // builder has the correct iterator bundle end.
3308 MachineInstr *InstrToMove = removeMI(HLXStoreMI, QII, nullptr);
3309
3310 // HLX store must be inserted after the def in the bundle to avoid confusing
3311 // finalizeBundle about liveness of the def reg
3312 MIBundleBuilder Bundle(&*(DestPos));
3313 Bundle.insert(std::next(DestMII), InstrToMove);
3314
3315 if (HLXCopyMI->isBundled())
3316 HLXCopyMI->eraseFromBundle();
3317 else
3318 HLXCopyMI->eraseFromParent();
3319
3320 // Update pullup count. This might be useful in doing another
3321 // iteration of global pullup into these MBBs.
3322 ++LocalPullups;
3323 LLVM_DEBUG(dbgs() << "\nSpeculated Local MI:\t" << *InstrToMove
3324 << "\nMBB: " << *InstrToMove->getParent());
3325 HLV->updateLocalLiveness(SR, true);
3326}
3327
3328// Pullup HLX instructions to create more dense bundles for
3329// HLX load/store instructions.
3330// This will help eliminate HLX copy instructions inserted during pseudo
3331// expansion. Find uses of a .tmp HLX load and try to pullup into the load's
3332// bundle Pullup .new HLX store into a bundle containing its def.
3333void GreedyPullup::localPullupHLX(SchedulingRegion_t::SRAtom_t *SR) {
3334 if (!useHLXOps || !EnableHLXLoadStorePullup)
3335 return;
3336
3337 assert(!SR->empty());
3338 LLVM_DEBUG(dbgs() << "\n\n\t\t[LocalPullupHLX]\tBB#" << SR->getNumber(););
3341 for (MIIterType BI = SR->begin(); BI != SR->end(); ++BI) {
3342 // Do not count DBG instructions if they are present.
3343 if (BI->isDebugInstr())
3344 continue;
3345 // Only look for bundles where HLX load or HLX store pseudos
3346 // were expanded
3347 if (!BI->isBundle() || (!BI->mayLoad() && !BI->mayStore()))
3348 continue;
3349 MachineInstr *HLXLoadMI = nullptr;
3350 MachineInstr *HLXStoreMI = nullptr;
3351 SmallVector<MachineInstr *, 2> HLXCopies;
3352 MIInstIterType MII = BI.getInstrIterator();
3353 for (++MII; // Skip the bundle header.
3354 (MII != SR->instr_end()) && MII->isInsideBundle(); ++MII) {
3355 if (!QII->isHLXVec(*MII))
3356 continue;
3357 switch (MII->getOpcode()) {
3358 case Hexagon::LX_L16b_tmp:
3359 HLXLoadMI = &*MII;
3360 break;
3361 case Hexagon::LX_S16b_new:
3362 HLXStoreMI = &*MII;
3363 break;
3364 case Hexagon::LX_assign:
3365 if (MII->getOperand(0).getReg() == MII->getOperand(1).getReg()) {
3366 HLXCopies.push_back(&*MII);
3367 }
3368 break;
3369 default:
3370 break;
3371 }
3372 }
3373
3374 // Collect all copies and match them to HLX loads/stores by checking
3375 // register operands.
3376 MachineInstr *HLXLoadCopyMI = nullptr;
3377 MachineInstr *HLXStoreCopyMI = nullptr;
3378 for (MachineInstr *CopyMI : HLXCopies) {
3379 Register HLXCopyReg = CopyMI->getOperand(0).getReg();
3380 // If source operand of LX_assign is marked internal,
3381 // it corresponds to HLX load
3382 bool IsInternal = CopyMI->getOperand(1).isInternalRead();
3383 // If we have both HLX load and store in same packet, with two identical
3384 // copies, pair one copy with load and one copy with store.
3385 if (HLXStoreMI && !HLXStoreCopyMI && !IsInternal &&
3386 HLXStoreMI->getOperand(1).getReg() == HLXCopyReg)
3387 HLXStoreCopyMI = CopyMI;
3388 else if (HLXLoadMI && !HLXLoadCopyMI &&
3389 HLXLoadMI->getOperand(0).getReg() == HLXCopyReg)
3390 HLXLoadCopyMI = CopyMI;
3391 }
3392 if (HLXLoadCopyMI)
3393 HLXLoadPseudos.push_back(std::make_pair(HLXLoadMI, HLXLoadCopyMI));
3394 if (HLXStoreCopyMI)
3395 HLXStorePseudos.push_back(std::make_pair(HLXStoreMI, HLXStoreCopyMI));
3396 }
3397
3398 for (auto &LoadPseudo : HLXLoadPseudos)
3399 localPullupHLXLoadUses(SR, LoadPseudo.first, LoadPseudo.second);
3400
3401 for (auto &StorePseudo : HLXStorePseudos)
3402 localPullupHLXStore(SR, StorePseudo.first, StorePseudo.second);
3403}
3404
3405// Try the two-load .cur load-bypass pull-up for a single-instruction cluster.
3406//
3407// This handles a consumer with up to two RAW producers that share a packet,
3408// where one producer is a .cur-able load. The load is rewritten to its .cur
3409// form (forwarding its result within the packet, freeing a register-read
3410// slot); the second producer, if any, is relocated to a loop-predecessor
3411// packet via lastChanceGlobalPullup so the consumer fits.
3412//
3413// Uses the cluster pullup dependence check, which also covers the packets in
3414// between, so SrcMI never moves past a packet it depends on.
3415//
3416// Returns true if it moved SrcMI (caller should skip the common cluster
3417// machinery for this candidate).
3418bool GreedyPullup::tryTwoLoadCurBypass(
3419 MIIterType &BI, SchedulingRegion_t::SRAtom_t *SR,
3420 MIInstIterType &DestBundle, MIIterType &SrcBundle, MIIterType &NextBI,
3421 bool isNextBISrc, MIIterType &Next, MachineInstr *SrcMI,
3422 SmallPtrSetImpl<MachineInstr *> &PulledUpSet) {
3423 MIInstIterType SrcMII = SrcMI->getIterator();
3424 std::pair<MIInstIterType, MIInstIterType> ParentBundle =
3425 getParentBundle(&*SrcMII);
3426
3427 // Enumerate producers via the vector dependence overload; only the vector
3428 // form can express two RAW producers of a single consumer.
3429 std::vector<const MachineInstr *> DepTrueVec, DepAntiVec, DepOutputVec;
3430 int VecDstDep = dstDependence(DestBundle, ParentBundle.first, SrcMII,
3431 DepTrueVec, DepAntiVec, DepOutputVec);
3432
3433 LLVM_DEBUG(dbgs() << "\n[TwoLoadCur] Candidate consumer: " << *SrcMI
3434 << "\t\tRAW producers=" << DepTrueVec.size()
3435 << " output deps=" << DepOutputVec.size() << "\n");
3436
3437 if (!Dependency::has(VecDstDep, Dependency::RAW) || DepTrueVec.size() > 2) {
3438 LLVM_DEBUG(dbgs() << "[TwoLoadCur] Reject: no RAW dep or >2 producers.\n");
3439 return false;
3440 }
3441
3442 bool GenCur = false;
3443 bool PotentialGenCur = false;
3444 const MachineInstr *DepTrue = nullptr;
3445 const MachineInstr *Other = nullptr;
3446
3447 auto IsCurLoad = [&](const MachineInstr *MI) {
3448 return QII->isHVXVec(*MI) && QII->mayBeCurLoad(*MI);
3449 };
3450
3451 if (DepTrueVec.size() == 1) {
3452 const MachineInstr *V0 = DepTrueVec[0];
3453 if (!Dependency::has(VecDstDep, Dependency::WAW) && IsCurLoad(V0) &&
3454 getBundleStart(V0->getIterator()) == DestBundle) {
3455 GenCur = true;
3456 DepTrue = V0;
3457 }
3458 } else if (DepTrueVec.size() == 2 && DepOutputVec.size() <= 1) {
3459 const MachineInstr *V0 = DepTrueVec[0];
3460 const MachineInstr *V1 = DepTrueVec[1];
3461 if (getBundleStart(V0->getIterator()) ==
3462 getBundleStart(V1->getIterator())) {
3463 if (IsCurLoad(V0)) {
3464 DepTrue = V0;
3465 Other = V1;
3466 } else if (IsCurLoad(V1)) {
3467 DepTrue = V1;
3468 Other = V0;
3469 }
3470 if (Other && (!Dependency::has(VecDstDep, Dependency::WAW) ||
3471 Other == DepOutputVec[0]))
3472 PotentialGenCur = true;
3473 }
3474 }
3475
3476 if (!GenCur && !PotentialGenCur)
3477 return false;
3478
3479 LLVM_DEBUG(dbgs() << "[TwoLoadCur] Selected "
3480 << (DepTrueVec.size() == 1 ? "single-load" : "two-load")
3481 << " case: GenCur=" << GenCur
3482 << " PotentialGenCur=" << PotentialGenCur << "\n");
3483
3484 // Validate the load actually lives at the head of the destination bundle.
3485 if (GenCur && DestBundle->isBundle()) {
3486 if (!DepTrue->isBundled() ||
3487 getBundleStart(DepTrue->getIterator()) != DestBundle)
3488 GenCur = false;
3489 }
3490
3491 // The load result must not be consumed by any other instruction between the
3492 // destination bundle and the source bundle (otherwise .cur forwarding is
3493 // unsafe). The second producer (Other) is exempt.
3494 if (GenCur) {
3495 Register DestReg = DepTrue->getOperand(0).getReg();
3496 for (MIInstIterType MI = std::next(DestBundle);
3497 MI != NextBI.getInstrIterator(); ++MI) {
3498 if (&*MI == Other)
3499 continue;
3500 bool Reads = llvm::any_of(MI->operands(), [&](const MachineOperand &MO) {
3501 return MO.isReg() && MO.isUse() && !MO.isUndef() && MO.getReg() &&
3502 TRI->regsOverlap(MO.getReg(), DestReg);
3503 });
3504 if (Reads) {
3505 GenCur = false;
3506 PotentialGenCur = false;
3507 break;
3508 }
3509 }
3510 }
3511
3512 if (!GenCur && !PotentialGenCur)
3513 return false;
3514
3515 // Guard against a third, non-forwardable RAW producer the two-element vector
3516 // dependence misses (use-before-def). Other is relocated later, so exempt it.
3517 if (DepTrue &&
3518 !canGenCurBypass(DestBundle, const_cast<MachineInstr *>(DepTrue),
3519 NextBI.getInstrIterator(), VecDstDep, SrcMI, Other)) {
3520 LLVM_DEBUG(dbgs() << "[TwoLoadCur] Reject: unsafe intermediate RAW "
3521 "producer (canGenCurBypass).\n");
3522 return false;
3523 }
3524
3525 // Allow WAR_SameBundle (SrcMI joins that packet) and, for a .cur, RAW (the
3526 // load is forwarded and the other producer is moved away); any other
3527 // dependence blocks the move.
3528 MachineBasicBlock *MBB = SrcMI->getParent();
3529 MICInstIterType ScalarDepTrue = MBB->instr_end();
3530 MICInstIterType ScalarDepAnti = MBB->instr_end();
3531 int ScalarDstDep = dstDependence(DestBundle, ParentBundle.first, SrcMII,
3532 ScalarDepTrue, ScalarDepAnti);
3533 int DstDepMasked = ScalarDstDep & ~Dependency::WAR_SameBundle;
3534 if (GenCur || PotentialGenCur)
3535 DstDepMasked &= ~Dependency::RAW;
3536 if (!Dependency::hasOnly(DstDepMasked, Dependency::Independent)) {
3537 LLVM_DEBUG(dbgs() << "[TwoLoadCur] Reject: scalar dest dependence not "
3538 "independent after masking.\n");
3539 return false;
3540 }
3541
3542 int SrcDep = srcDependence(ParentBundle.first, ParentBundle.second, SrcMII);
3543 if (!Dependency::hasOnly(SrcDep, Dependency::Independent)) {
3544 LLVM_DEBUG(dbgs() << "[TwoLoadCur] Reject: source dependence not "
3545 "independent.\n");
3546 return false;
3547 }
3548
3549 auto &ST = MF.getSubtarget<HexagonSubtarget>();
3550 const InstrItineraryData *II = ST.getInstrItineraryData();
3551 if (canCauseInterlockStall(DestBundle, SrcMI, II)) {
3552 LLVM_DEBUG(dbgs() << "[TwoLoadCur] Reject: would cause an interlock "
3553 "stall.\n");
3554 return false;
3555 }
3556
3557 // Ensure the destination is a real bundle so we can pull into it.
3558 bool UndoDestBundle = false;
3559 if (!DestBundle->isBundle()) {
3560 finalizeBundle(*DestBundle->getParent(), DestBundle, std::next(DestBundle));
3561 DestBundle = std::prev(DestBundle);
3562 UndoDestBundle = true;
3563 }
3564
3565 MIInstIterType DestPos = DestBundle;
3566 getResourcesReadyForBundle(DestPos);
3567
3568 // PotentialGenCur forces the resource reservation to fail so we drop into
3569 // lastChanceGlobalPullup, which relocates the second producer to free a slot.
3570 bool CanReserve = canReserveResources(SrcMII) && !PotentialGenCur;
3571 bool CanBeMoved = false;
3572 if (!CanReserve) {
3573 const MachineInstr *LoadBypassCand = PotentialGenCur ? Other : nullptr;
3574 LLVM_DEBUG(dbgs() << "[TwoLoadCur] Resources tight; trying "
3575 "lastChanceGlobalPullup (LoadBypassCand="
3576 << (LoadBypassCand ? "Other" : "null") << ").\n");
3577 if ((CanBeMoved =
3578 lastChanceGlobalPullup(DestPos, SrcMII, LoadBypassCand))) {
3579 DestBundle = DestPos;
3580 if (LoadBypassCand)
3581 GenCur = true;
3582 }
3583 } else {
3584 // Single-load .cur bypass whose packet already has room: just packetize.
3585 LLVM_DEBUG(dbgs() << "[TwoLoadCur] Packet has room; packetizing "
3586 "directly.\n");
3587 CanBeMoved = isLegalToPacketizeWith(DestBundle, SrcMI);
3588 }
3589
3590 if (CanBeMoved) {
3591 // Keep NextBI/SrcBundle valid across the move.
3592 bool FixNextBI = false;
3593 if (SrcMII->isBundled()) {
3594 SrcBundle = getBundleStart(SrcMII);
3595 if (&*SrcBundle == &*NextBI)
3596 FixNextBI = true;
3597 } else if (&*SrcMII == &*NextBI) {
3598 NextBI = DestBundle;
3599 }
3600
3601 MachineInstr *SingleInstr = nullptr;
3602 MachineInstr *Instr = removeMI(&*SrcMII, QII, nullptr, &SingleInstr);
3603 if (SingleInstr && FixNextBI)
3604 NextBI = SingleInstr->getIterator();
3605
3606 if (GenCur)
3607 genLoadBypass(const_cast<MachineInstr *>(DepTrue), Instr);
3608 else
3609 MBB->insert(std::next(DestBundle), Instr);
3610
3611 LLVM_DEBUG(dbgs() << "[TwoLoadCur] Pulled up (GenCur=" << GenCur
3612 << "): " << *Instr);
3613 ++LocalPullups;
3614 PulledUpSet.insert(Instr);
3615 HLV->updateLocalLiveness(DestBundle->getParent(), true);
3616 return true;
3617 }
3618
3619 LLVM_DEBUG(dbgs() << "[TwoLoadCur] Reject: candidate could not be moved.\n");
3620 if (UndoDestBundle) {
3621 MIInstIterType I = std::next(DestPos);
3622 I->unbundleFromPred();
3623 DestBundle->eraseFromParent();
3624 DestBundle = I;
3625 }
3626 return false;
3627}
3628
3629// TODO: Handle non-packetized instructions.
3630// @note: Only speculated instructions can be done here.
3631void GreedyPullup::localPullup(SchedulingRegion_t::SRAtom_t *SR) {
3632 localPullupImpl(SR, /*HVXMode=*/false);
3633}
3634
3635// Shared local pullup engine. When HVXMode is set, plain HVX vector ops are
3636// admitted as pullup candidates and .cur load-bypass is generated; otherwise
3637// HVX vector ops are rejected (scalar/HLX behavior).
3638void GreedyPullup::localPullupImpl(SchedulingRegion_t::SRAtom_t *SR,
3639 bool HVXMode) {
3640 assert(!SR->empty());
3641 LLVM_DEBUG(dbgs() << "\n\n\t\t[LocalPullup]\tBB#" << SR->getNumber(););
3642
3643 // Sparse pullup and cluster pullup:
3644 // Enabled by default
3645 // Disabled for TinyCore.
3646
3647 // Allow pullup to/from unbundled instructions or from packets that have <= 2
3648 // instructions.
3649 bool AllowSparsePullup = EnableSparsePullup && !IsTinyCore;
3650
3651 // Allow pullup of cluster of dependent instructions.
3652 bool AllowClusterPullup = EnableClusterPullup && !IsTinyCore;
3653
3654 MIIterType NextBI = SR->begin();
3655 for (MIIterType BI = NextBI; BI != std::prev(SR->end()) && BI != SR->end();
3656 BI = NextBI) {
3657 NextBI = std::next(BI);
3658 if (BI->isDebugInstr())
3659 continue;
3660 MIInstIterType DestBundle = BI.getInstrIterator();
3661 if (!DestBundle->isBundle() && AllowSparsePullup) {
3662 if (isSoloInstruction(*DestBundle))
3663 continue;
3664 finalizeBundle(*(DestBundle->getParent()), DestBundle,
3665 std::next(DestBundle));
3666 DestBundle = std::prev(DestBundle);
3667 BI = DestBundle;
3668 }
3669 if (!DestBundle->isBundle())
3670 continue;
3671 LLVM_DEBUG(dbgs() << "\nDestBundle: " << *DestBundle;);
3672 MIIterType SrcBundle = BI;
3673
3674 // Move to the next bundle to find candidates for local pullup.
3675 // Check dependencies from DestBundle through the SrcBundle.
3676 unsigned NumBundles = 0;
3677 MIIterType Next = std::next(SrcBundle);
3678 for (SrcBundle = Next; SrcBundle != SR->end(); SrcBundle = Next) {
3679 Next = std::next(SrcBundle);
3680 // Do not count DBG instructions if they are present.
3681 if (SrcBundle->isDebugInstr())
3682 continue;
3683 // Verify max pull-up distance based on non-debug values,
3684 // otherwise we can quit earlier in case of -g code.
3685 if (++NumBundles > MaxPUBundles)
3686 break;
3687 if (DestBundle->getBundleSize() >= HEXAGON_PACKET_SIZE)
3688 break;
3689 LLVM_DEBUG(dbgs() << "\nSrcBundle: " << *SrcBundle;);
3690
3691 bool isNextBISrc = false;
3692 if (SrcBundle == std::next(BI))
3693 isNextBISrc = true;
3694
3695 // Pull an unbundled call into the previous packet when the call does
3696 // not depend on that packet, e.g.:
3697 // BUNDLE 4 {
3698 // S4_storeiri_io renamable $r16, 12
3699 // renamable $r0 = L2_loadrub_io killed renamable $r17, 8
3700 // renamable $r17 = A2_addi renamable $r16, 12
3701 // }
3702 // J2_call @Foo
3703 // The generic local pullup does not handle this: the call is not in a
3704 // bundle, and shouldNotBePulledUp rejects calls.
3705 // TODO: Handle this in sparse pullup if shouldNotBePulledUp is relaxed.
3706 if (!SrcBundle->isBundle() && isNextBISrc) {
3707 MIInstIterType MII = SrcBundle.getInstrIterator();
3708 MachineInstr &MI = *MII;
3709 if (MI.getOpcode() == Hexagon::J2_call) {
3710 if (isLegalToPacketizeWith(BI, &MI)) {
3711 MIInstIterType DestPos = DestBundle;
3712 getResourcesReadyForBundle(DestPos);
3713 ++DestPos; // Skip the bundle header.
3714 while (DestPos->isInsideBundle())
3715 ++DestPos;
3716 --DestPos;
3717 if (canReserveResources(MII)) {
3718 NextBI = std::next(SrcBundle);
3719 Next = std::next(SrcBundle);
3720 MachineInstr *InstrToMove = removeMI(&MI, QII, nullptr);
3721 MIBundleBuilder Bundle(&*DestBundle);
3722
3723 Bundle.insert(std::next(DestPos), InstrToMove);
3724
3725 // Update pullup count. This might be useful in doing another
3726 // iteration of global pullup into these MBBs.
3727 ++LocalPullups;
3728 LLVM_DEBUG(dbgs() << "\nSpeculated Local MI:\t" << *InstrToMove
3729 << "\nMBB: " << *InstrToMove->getParent());
3730 HLV->updateLocalLiveness(SR, true);
3731 continue;
3732 }
3733 }
3734 }
3735 }
3736
3737 // When the source bundle has <= 2 instructions, and pullup from sparse
3738 // bundles is disabled, skip the bundle
3739 if (SrcBundle->getBundleSize() <= 2 && !AllowSparsePullup)
3740 continue;
3741
3742 MIInstIterType SrcMII = SrcBundle.getInstrIterator();
3743 if (!SrcMII->isBundled() && AllowSparsePullup) {
3744 if (isSoloInstruction(*SrcMII) || shouldNotBePulledUp(&*SrcMII))
3745 continue;
3746 finalizeBundle(*(SrcMII->getParent()), SrcMII, std::next(SrcMII));
3747 MIInstIterType BundleHead = std::prev(SrcMII);
3748 SrcBundle = BundleHead;
3749 if (isNextBISrc)
3750 NextBI = BundleHead;
3751 SrcMII = BundleHead;
3752 }
3753 MIInstIterType SrcBundleEnd = getBundleEnd(SrcBundle.getInstrIterator());
3754
3756 SmallPtrSet<MachineInstr *, 4> SrcVisitedSet;
3757 // Find a suitable candidate for speculation to DestBundle and speculate.
3758 for (++SrcMII; // Skip the bundle header.
3759 (SrcMII != SR->instr_end()) && SrcMII->isInsideBundle(); ++SrcMII) {
3760 MachineInstr *SrcMI = &*SrcMII;
3761 if (isSoloInstruction(*SrcMI) || SrcMI->isDebugInstr() ||
3762 !SrcVisitedSet.insert(SrcMI).second)
3763 continue;
3764
3765 // Cluster pullup: collect dependent instructions in DepSet.
3766 // A cluster is a set of instructions with same-packet dependencies
3767 // (e.g., .tmp producer and .new consumer) that must be moved together.
3768 // DepSet will contain all instructions in SrcBundle that SrcMI depends
3769 // on.
3770 SmallPtrSet<MachineInstr *, 4> DepSet;
3771 int SrcDep =
3772 srcDependence(SrcBundle.getInstrIterator(), SrcBundleEnd, SrcMII,
3773 AllowClusterPullup ? &DepSet : nullptr);
3774 SmallPtrSet<MachineInstr *, 4> SrcClusterSet;
3775 if (Dependency::hasOnly(SrcDep, Dependency::Independent)) {
3776 SrcClusterSet.insert(SrcMI);
3777 SrcClusterMIs.push_back(SrcClusterSet);
3778 continue;
3779 }
3780 // If cluster pullup is enabled and we found same-packet dependencies,
3781 // create a cluster containing all dependent instructions.
3782 if (AllowClusterPullup) {
3783 set_union(SrcVisitedSet, DepSet);
3784 if (Dependency::hasOnly(SrcDep, Dependency::SamePacketRAW) ||
3785 Dependency::hasOnly(SrcDep, Dependency::SamePacketWAR) ||
3786 Dependency::hasOnly(SrcDep, Dependency::SamePacket)) {
3787 LLVM_DEBUG(dbgs() << "\nFound cluster of dependent instructions in "
3788 "same packet\n");
3789 for (auto *DepMI : DepSet) {
3790 LLVM_DEBUG(dbgs() << "Cluster MI: "; DepMI->dump());
3791 SrcClusterSet.insert(DepMI);
3792 }
3793 SrcClusterMIs.push_back(SrcClusterSet);
3794 }
3795 }
3796 }
3797
3798 // Sort the clusters by size in descending order
3799 if (AllowClusterPullup) {
3800 std::sort(SrcClusterMIs.begin(), SrcClusterMIs.end(),
3801 [](SmallPtrSet<MachineInstr *, 4> ClusterA,
3802 SmallPtrSet<MachineInstr *, 4> ClusterB) {
3803 return ClusterA.size() > ClusterB.size();
3804 });
3805 }
3806
3807 // Track which instructions have been successfully pulled up to avoid
3808 // pulling the same instruction multiple times (clusters may overlap).
3809 // Pull up clusters from largest to smallest.
3810 // Example candidate:
3811 // {
3812 // renamable $r7, renamable $r2 = L2_loadri_pi killed renamable $r2, 4
3813 // }
3814 // {
3815 // $l4 = LX_L16b_tmp killed renamable $r3
3816 // renamable $ll2 = LX_conv_h_b_lo internal killed renamable $l4
3817 // }
3818 // After cluster pullup:
3819 // {
3820 // $l4 = LX_L16b_tmp killed renamable $r3
3821 // renamable $ll2 = LX_conv_h_b_lo internal killed renamable $l4
3822 // renamable $r7, renamable $r2 = L2_loadri_pi killed renamable $r2, 4
3823 // }
3824 SmallPtrSet<MachineInstr *, 4> PulledUpSet;
3825 SmallPtrSet<MachineInstr *, 4> InsertAtEndSet;
3826 for (auto ClusterSet : SrcClusterMIs) {
3827 bool RejectCluster = false;
3828 // .cur load bypass state for this cluster (HVX mode, single consumer).
3829 MachineInstr *GenCurLoad = nullptr;
3830 MachineInstr *GenCurConsumer = nullptr;
3831 LLVM_DEBUG(dbgs() << "\nChecking pullup legality for cluster: \n";
3832 for (auto *SrcMI : ClusterSet) SrcMI->dump(););
3833
3834 // Two-load .cur bypass (off by default); see tryTwoLoadCurBypass.
3835 if (EnableHVXTwoLoadCurBypass && ClusterSet.size() == 1) {
3836 MachineInstr *SrcMI = *ClusterSet.begin();
3837 if (tryTwoLoadCurBypass(BI, SR, DestBundle, SrcBundle, NextBI,
3838 isNextBISrc, Next, SrcMI, PulledUpSet)) {
3839 continue;
3840 }
3841 }
3842
3843 // Skip this cluster if any instruction was already pulled up.
3844 for (auto *SrcMI : ClusterSet) {
3845 if (PulledUpSet.contains(SrcMI)) {
3846 LLVM_DEBUG(dbgs() << " .....NO, SrcMI has been pulled up: ";
3847 SrcMI->dump(););
3848 RejectCluster = true;
3849 break;
3850 }
3851 }
3852
3853 if (RejectCluster)
3854 continue;
3855
3856 for (auto *SrcMI : ClusterSet) {
3857 LLVM_DEBUG(dbgs() << "\nChecking legality for SrcMI: ";
3858 SrcMI->dump(););
3859
3860 // Do not pull up instructions with multi-cycle latencies, because
3861 // the pull-up pass doesn't correctly
3862 // account for instructions that stall for more than one cycle.
3863 // Exceptions for this: branches, instructions that utilize operand
3864 // forwarding, and HVX vector ops when invoked in HVX mode (their
3865 // latency is checked below via canCauseInterlockStall).
3866 if ((!QII->isTC1(*SrcMI) && !(HVXMode && QII->isHVXVec(*SrcMI)) &&
3867 (!QII->isDotTmpInst(*SrcMI) && !QII->isDotNewInst(*SrcMI) &&
3868 !QII->isDotCurInst(*SrcMI)) &&
3869 (!SrcMI->isBranch() && !SrcMI->isTerminator() &&
3870 !SrcMI->isReturn()))) {
3871 LLVM_DEBUG(dbgs() << " .....NO");
3872 RejectCluster = true;
3873 break;
3874 }
3875
3876 if (!isLegalToPacketizeWith(BI, SrcMI) || isSoloInstruction(*SrcMI) ||
3877 shouldNotBePulledUp(SrcMI)) {
3878 LLVM_DEBUG(dbgs() << " .....NO");
3879 RejectCluster = true;
3880 break;
3881 }
3882 MICInstIterType DepTrue = SR->instr_end(), DepAnti = SR->instr_end();
3883 int DstDep = dstDependence(DestBundle, SrcBundle.getInstrIterator(),
3884 SrcMI->getIterator(), DepTrue, DepAnti);
3885
3886 // A single RAW dependence on a .cur-able load in the destination
3887 // packet can be resolved with a .cur load bypass instead of blocking
3888 // the pullup. Keyed on mayBeCurLoad, not HVX, so any current-value
3889 // load benefits. Only the single-consumer cluster is handled; when
3890 // eligible the RAW bit is masked below so the check is satisfiable.
3891 bool ClusterGenCur =
3892 EnableHVXLocalPullupLB && ClusterSet.size() == 1 &&
3893 Dependency::has(DstDep, Dependency::RAW) &&
3894 DepTrue != SR->instr_end() &&
3895 canGenCurBypass(DestBundle, const_cast<MachineInstr *>(&*DepTrue),
3896 NextBI.getInstrIterator(), DstDep, SrcMI);
3897
3898 // Reject the cluster on any dependence except WAR_SameBundle (the
3899 // cluster joins the bundle) and a RAW resolved by a .cur bypass.
3900 int DstDepMasked = DstDep & ~Dependency::WAR_SameBundle;
3901 if (ClusterGenCur)
3902 DstDepMasked &= ~Dependency::RAW;
3903 if (!(Dependency::hasOnly(DstDepMasked, Dependency::Independent))) {
3904 LLVM_DEBUG(dbgs() << " .....NO");
3905 RejectCluster = true;
3906 break;
3907 }
3908 if (DstDep & Dependency::WAR_SameBundle)
3909 InsertAtEndSet.insert(SrcMI);
3910
3911 if (ClusterGenCur) {
3912 GenCurLoad = const_cast<MachineInstr *>(&*DepTrue);
3913 GenCurConsumer = SrcMI;
3914 }
3915
3916 // Reject if pulling SrcMI into DestBundle violates latency from the
3917 // previous packet (e.g., a multiply result with 2-cycle latency).
3918 // Skip for HLX instructions which have different timing semantics.
3919 if (!QII->isHLXVec(*SrcMI)) {
3920 auto &ST = MF.getSubtarget<HexagonSubtarget>();
3921 const InstrItineraryData *II = ST.getInstrItineraryData();
3922 if (canCauseInterlockStall(DestBundle, SrcMI, II)) {
3923 LLVM_DEBUG(dbgs() << " .....NO (latency violation)");
3924 RejectCluster = true;
3925 break;
3926 }
3927 }
3928
3929 LLVM_DEBUG(dbgs() << " .....YES");
3930 }
3931
3932 // Move to the next cluster if this cluster cannot be pulled up
3933 if (RejectCluster)
3934 continue;
3935
3936 // Check if all instructions in the cluster can fit in the destination
3937 // bundle given current resource constraints.
3938 LLVM_DEBUG(dbgs() << "Checking resources for cluster\n");
3939 MIInstIterType DestPos = DestBundle;
3940 getResourcesReadyForBundle(DestPos);
3941 for (auto *SrcMI : ClusterSet) {
3942 MIInstIterType SrcMII = SrcMI->getIterator();
3943 // Check if resources are available in Bundle.
3944 if (canReserveResources(SrcMII))
3945 addToPacketPseudo(SrcMI);
3946 else {
3947 RejectCluster = true;
3948 break;
3949 }
3950 }
3951
3952 if (RejectCluster)
3953 continue;
3954
3955 // All legality checks passed. Now physically move the cluster.
3956 LLVM_DEBUG(dbgs() << "[Can add to packet]";);
3957 for (auto *SrcMI : ClusterSet) {
3958 // If we have a single instruction bundle here, it means sparse
3959 // pullup is enabled
3960 if (!SrcBundle->isBundled() || SrcBundle->getBundleSize() == 1) {
3961 if (isNextBISrc)
3962 NextBI = std::next(SrcBundle);
3963 Next = std::next(SrcBundle);
3964 }
3965
3966 SmallVector<MachineInstr *, 4> UnbundledMIs;
3967 MachineInstr *InstrToMove = removeMI(SrcMI, QII, &UnbundledMIs);
3968 MIBundleBuilder Bundle(&*DestBundle);
3969
3970 // .cur load bypass: rewrite the load to .cur and let genLoadBypass
3971 // insert the consumer right after it (it performs its own insert and
3972 // marks the internal read), so skip the normal insertion below.
3973 if (GenCurLoad && SrcMI == GenCurConsumer) {
3974 genLoadBypass(GenCurLoad, InstrToMove);
3975 }
3976 // Insert at the end of the bundle: .new MIs, branches and
3977 // terminators go after their producers, and WAR_SameBundle defs go
3978 // after their reader so finalizeBundle does not mark the read
3979 // internal.
3980 else if (QII->isDotNewInst(*InstrToMove) || InstrToMove->isBranch() ||
3981 InstrToMove->isTerminator() ||
3982 InsertAtEndSet.contains(SrcMI))
3983 Bundle.insert(getBundleEnd(DestPos), InstrToMove);
3984 else {
3985 // Insert after any .tmp or .cur instructions at the beginning.
3986 // This maintains correct liveness: .tmp/.cur must be defined before
3987 // other instructions in the packet can use them.
3988 MIInstIterType InsertPos = std::next(DestPos);
3989 while (QII->isDotTmpInst(*InsertPos) ||
3990 QII->isDotCurInst(*InsertPos))
3991 ++InsertPos;
3992 Bundle.insert(InsertPos, InstrToMove);
3993 }
3994
3995 // Update pullup count. This might be useful in doing another
3996 // iteration of global pullup into these MBBs.
3997 ++LocalPullups;
3998 PulledUpSet.insert(InstrToMove);
3999 LLVM_DEBUG(dbgs() << "\nSpeculated Local MI:\t" << *InstrToMove);
4000
4001 // Handle unbundled instructions left behind after removing SrcMI.
4002 // If sparse pullup is enabled, rebundle them; otherwise track them
4003 // for iteration control.
4004 if (UnbundledMIs.empty())
4005 continue;
4006 MIInstIterType UnbundledII = UnbundledMIs.front()->getIterator();
4007 if (AllowSparsePullup) {
4008 MIInstIterType LastUnbundledII = UnbundledMIs.back()->getIterator();
4009 finalizeBundle(*(UnbundledII->getParent()), UnbundledII,
4010 std::next(LastUnbundledII));
4011 --UnbundledII;
4012 }
4013 if (isNextBISrc)
4014 NextBI = UnbundledII;
4015 SrcBundle = UnbundledII;
4016 Next = UnbundledII;
4017 } // end for
4018 LLVM_DEBUG(dbgs() << "\nMBB: "; DestBundle->getParent()->dump());
4019 HLV->updateLocalLiveness(SR, true);
4020 } // end for
4021 } // end for
4022 // If DestBundle is a single instruction bundle at this point,
4023 // unbundle the single instruction to retain compatibility with other APIs
4024 if (AllowSparsePullup && DestBundle->isBundle())
4025 updateBundle(&*DestBundle, QII);
4026 } // end for
4027 // If the last bundle in the scheduling region is a single instruction bundle,
4028 // unbundle the single instruction
4029 MIIterType LastBundle = std::prev(SR->end());
4030 if (AllowSparsePullup && LastBundle->isBundle())
4031 updateBundle(&*LastBundle, QII);
4032}
4033
4034bool GreedyPullup::mergePacketsAround(
4035 const SmallVectorImpl<MachineInstr *> &Candidates) {
4036 bool Changed = false;
4037 for (auto CMII : Candidates) {
4038 MachineInstr *MI = CMII;
4039 MIIterType DestBundle = MI;
4040 MachineBasicBlock *MBB = MI->getParent();
4041 // Since local-pull-up pulls up into preceding bundles,
4042 // we only want to push down into local bundles (immediate next for now).
4043 ++DestBundle;
4044
4045 while (DestBundle != MBB->end() && DestBundle->isDebugInstr())
4046 ++DestBundle;
4047
4048 if (DestBundle == MBB->end() || !DestBundle->isBundle() ||
4049 // Ignore these instructions for simplicity.
4050 shouldNotBePulledUp(MI))
4051 continue;
4052
4053 MICInstIterType DepTrue = MBB->instr_end(), DepAnti = MBB->instr_end();
4054 MIInstIterType DestEnd = getBundleEnd(DestBundle.getInstrIterator());
4055 int DstDep = dstDependence(DestBundle.getInstrIterator(), DestEnd,
4056 MI->getIterator(), DepTrue, DepAnti,
4057 /*HLXUseReg=*/0,
4058 /*isPullDown=*/true);
4059 int DstDepMasked = DstDep & ~Dependency::WAR_SameBundle;
4060 if (!Dependency::hasOnly(DstDepMasked, Dependency::Independent))
4061 continue;
4062
4063 // TODO: Only does a push-down in simple cases without any
4064 // analysis for .new/.cur.
4065 getResourcesReadyForBundle(DestBundle.getInstrIterator());
4066 if (canReserveResources(MI->getIterator()) &&
4067 isLegalToPacketizeWith(DestBundle, MI)) {
4068 LLVM_DEBUG(dbgs() << "\nCan push-down" << *MI);
4069 MachineInstr *MIToInsert = MI->removeFromParent();
4070 MIInstIterType InsertPos = DestBundle.getInstrIterator();
4071 // Insert as the first instruction in bundle (push-down).
4072 MBB->insert(++InsertPos, MIToInsert);
4073 HLV->updateLocalLiveness(MBB, false);
4074 Changed = true;
4075 }
4076 }
4077 return Changed;
4078}
4079
4080// Merge adjacent packets in a BB when possible.
4081// Currently pushing down the individual MIs into next packet.
4082// TODO: push down into later packets as well.
4083bool GreedyPullup::mergePackets() {
4084 bool Changed = false;
4085 for (auto MBB : LocalMergePackCand) {
4086 if (!MBB)
4087 continue;
4088 LLVM_DEBUG(dbgs() << "\nMerging packets within MBB#" << MBB->getNumber(););
4089 SmallVector<MachineInstr *, 2> Candidates;
4090 for (MIIterType MII = MBB->begin(); MII != MBB->end(); ++MII) {
4091 if (!MII->isBundle())
4092 Candidates.push_back(&*MII);
4093 }
4094 Changed |= mergePacketsAround(Candidates);
4095 }
4096 return Changed;
4097}
4098
4099// TODO: Form bigger scheduling regions more than 2 MBBs.
4100void GreedyPullup::globalPullup(SchedulingRegion_t &SR) {
4101 LLVM_DEBUG(dbgs() << "\n[GlobalPullup]";);
4102 // Start from the bottom of the scheduling region (Bottom-up scheduling)
4103 SchedulingRegion_t::reverse_iterator BlockI = SR.rbegin();
4104 assert(!SR.empty() && "Empty scheduling region!");
4105 DenseSet<const MachineBasicBlock *> IgnoreBlocks;
4106 for (++BlockI; BlockI != SR.rend(); ++BlockI) {
4107 if (IgnoreBlocks.find(*BlockI) != IgnoreBlocks.end())
4108 continue;
4109 SchedulingRegion_t::reverse_iterator SrcBlock = BlockI - 1;
4110 LLVM_DEBUG(dbgs() << "\n\t\t*****Speculating MIs from MBB#"
4111 << (*SrcBlock)->getNumber() << " to MBB#"
4112 << (*BlockI)->getNumber() << "*****");
4113 // Do not speculate into a SrcBlock from multiple Blocks.
4114 // Except: When PreciousMICanBeSpeculated.
4115 PulledUpII::iterator hasSpeculatedIns = SpeculatedIns.find(*BlockI);
4116 if (hasSpeculatedIns != SpeculatedIns.end()) {
4117 LLVM_DEBUG(
4118 dbgs() << "\nSrcMBB Already contains speculated ins. Skipping!";);
4119 continue;
4120 }
4121 for (MIInstIterType MII = (*SrcBlock)->instr_begin();
4122 MII != (*SrcBlock)->instr_end();) {
4123 MachineInstr *MIToMove = &*MII;
4124 // The MI might be moved so skip.
4125 ++MII;
4126 if (MIToMove->isDebugInstr())
4127 continue;
4128 LLVM_DEBUG(dbgs() << "\nChecking pullup for MI: "; MIToMove->dump());
4129 MIIterType TargetPacket = (*BlockI)->end();
4130 if (canMIBeSpeculated(MIToMove, *SrcBlock, *BlockI, TargetPacket)) {
4131 // TODO: If MI can be speculated that does not mean
4132 // we 'should' speculate it. Store in ScheduledMI and
4133 // then 'sort/prune' the list before speculating.
4134 LLVM_DEBUG(dbgs() << " .....YES (MICanBeSpeculated)";);
4135 bool done = speculateMI(MIToMove, *SrcBlock, *BlockI, TargetPacket);
4136 SpeculatedIns[*BlockI].push_back(MIToMove);
4137 ++GlobalSpeculatedIns;
4138 // Populate candidates for local push-down.
4139 LocalMergePackCand.insert(*SrcBlock);
4140 (void)done;
4141 assert(done && "Wrong Analysis");
4142 } else
4143 LLVM_DEBUG(dbgs() << " .....NO (MICanBeSpeculated)";);
4144 }
4145 }
4146 BlockI = SR.rbegin();
4147 for (++BlockI; BlockI != SR.rend(); ++BlockI) {
4148 if (IgnoreBlocks.find(*BlockI) != IgnoreBlocks.end())
4149 continue;
4150 SchedulingRegion_t::reverse_iterator SrcBlock = BlockI - 1;
4151 LLVM_DEBUG(dbgs() << "\n\t\t*****Predicating MIs from MBB#"
4152 << (*SrcBlock)->getNumber() << " to MBB#"
4153 << (*BlockI)->getNumber() << "*****");
4154 // Unlike speculation predication can be done from both successors.
4155 for (MIInstIterType MII = (*SrcBlock)->instr_begin();
4156 MII != (*SrcBlock)->instr_end();) {
4157 MachineInstr *MIToMove = &*MII;
4158 // The MI might be moved so skip.
4159 ++MII;
4160 if (MIToMove->isDebugInstr())
4161 continue;
4162 LLVM_DEBUG(dbgs() << "\nChecking pullup for MI: "; MIToMove->dump());
4163 MIIterType TargetPacket = (*BlockI)->end();
4164 MICInstIterType WithinPacket = (*BlockI)->instr_end();
4165 bool NeedToNewify = false, PreciousMIToInsert = false;
4166 if (canMIBePredicated(MIToMove, *SrcBlock, *BlockI, TargetPacket,
4167 WithinPacket, NeedToNewify, PreciousMIToInsert)) {
4168 // TODO: If MI can be predicated that does not mean
4169 // we 'should' predicate it. Store in ScheduledMI and
4170 // then 'sort/prune' the list before predicating.
4171 LLVM_DEBUG(dbgs() << " .....YES (MICanBePredicated)";);
4172 bool done = predicateMI(MIToMove, *SrcBlock, *BlockI, TargetPacket,
4173 WithinPacket, NeedToNewify, PreciousMIToInsert);
4174 (void)done;
4175 assert(done && "Wrong Analysis");
4176 ++GlobalPredicatedIns;
4177 // Populate candidates for local push-down.
4178 LocalMergePackCand.insert(*SrcBlock);
4179 if (PreciousMIToInsert) {
4180 // Once the destination bundle has 5 MIs we want to avoid subsequent
4181 // scheduling into this MBB, so that we skip different sanity checks
4182 // added to ensure consistency in resources available in bundle which
4183 // uses packetizer to track resources and the packetizer does not
4184 // validate more than four instructions in a bundle.
4185 IgnoreBlocks.insert(*BlockI);
4186 ToBeSqueezed.insert(&*TargetPacket);
4187 // Prevent any subsequent e.g. optimizations as well.
4188 IgnorePostSchedOpt.push_back(*BlockI);
4189 LLVM_DEBUG(dbgs() << "\nIgnoring MBB#" << (*BlockI)->getNumber()
4190 << " from further speculation";);
4191 break;
4192 }
4193 } else
4194 LLVM_DEBUG(dbgs() << " .....NO (MICanBePredicated)";);
4195 }
4196 }
4197 // TODO: Look for packetization opportunities or
4198 // or leave this task for MergePackets.
4199 // TODO: Perform branch/post-pullup optimizations.
4200}
4201
4202// Analyze a bundle/independent-instruction at a time.
4203// Perform a bottom up traversal on the def-use set of DstBB MIs.
4204// Resource available in BUNDLE && Dependency constraints are met => done!
4205// Returns the position *before* which \p SrcMI could be inserted.
4206// In case of BUNDLE the \p SrcMI can be inserted within that BUNDLE.
4207// TODO: Insert into a BUNDLE even if there are WAR dependencies
4208// See also findInsertPtPred().
4209// \p SpecPreciousMIComp = true, when speculating PreciousMI comp. code.
4210// \p SpecPreciousMI = true, when speculating PreciousMI.
4211// \p GlobalPrecious = true, when hoisting SrcMI from the innermost single block
4212// loop. Stop searching after the first available bundle with resources.
4213MIIterType GreedyPullup::findInsertPtSpec(MachineInstr *SrcMI,
4214 MachineBasicBlock *DstBB,
4215 bool SpecPreciousMI,
4216 bool SpecPreciousMIComp,
4217 bool GlobalPrecious) {
4218 LLVM_DEBUG(dbgs() << "\n[FindInsertPtSpec]";);
4219 MIIterType DstEnd = DstBB->end();
4220 MIInstIterType InsPos = DstBB->instr_end();
4221 MICInstIterType DepTrue = DstBB->instr_end(), DepAnti = DstBB->instr_end();
4222 if (shouldNotBePulledUp(SrcMI) ||
4223 (QII->isPredicated(*SrcMI) && QII->isPredicatedNew(*SrcMI)) ||
4224 isSoloInstruction(*SrcMI))
4225 return DstEnd;
4226 LLVM_DEBUG(dbgs() << "\nChecking Resource conflict\n";);
4227
4228 // Perform a bottom up traversal on the def-use set of DstBB MIs.
4229 MIRIterType MII = getSpeculationBeginPoint(SrcMI, DstBB);
4230 for (; MII != DstBB->rend(); ++MII) {
4231 MachineInstr *MI = &*MII;
4232 if (MI->isDebugInstr())
4233 continue;
4234 LLVM_DEBUG(dbgs() << "\n\tAgainst:\t* " << *MI;);
4235 // Check for dependencies [RangeBeg, MII) <- in reverse order.
4236 if (MI->isBundle()) {
4237 int DstDep = dstDependence(MI->getIterator(), InsPos,
4238 SrcMI->getIterator(), DepTrue, DepAnti);
4239 if (!Dependency::hasOnly(DstDep, Dependency::Independent))
4240 break;
4241 // A precious MI takes this bundle as the insertion point before the
4242 // resource check; speculateMI() inserts it just before the bundle if it
4243 // does not fit. Other MIs only move into bundles with free resources.
4244 if (SpecPreciousMI)
4245 InsPos = MI->getIterator();
4246 // Continue searching higher up.
4247 LLVM_DEBUG(
4248 dbgs() << "\n\tNo conflict (BUNDLE)! Checking resources.....\n";);
4249 // Check if resources are available in BUNDLE or not.
4250 getResourcesReadyForBundle(MI->getIterator(), SpecPreciousMI);
4251 if (canReserveResources(SrcMI->getIterator())) {
4252 if (!isLegalToPacketizeWith(MI, SrcMI) || NoSpecInBundle)
4253 break;
4254 InsPos = MI->getIterator();
4255 LLVM_DEBUG(dbgs() << ".....(Resources available. Checking higher up)";);
4256 if (GlobalPrecious && InsPos->isBundle())
4257 break;
4258 // Check for dst dep from insertion point until the end of DstBB.
4259 } else {
4260 LLVM_DEBUG(
4261 dbgs() << ".....(No Resources (BUNDLE) Checking further up)";);
4262 // Keep searching higher up; SrcMI is not placed in this bundle.
4263 }
4264 } else {
4265 // Check for dst dep from insertion point until the end of DstBB.
4266 int DstDep = dstDependence(MI->getIterator(), InsPos,
4267 SrcMI->getIterator(), DepTrue, DepAnti);
4268 if (!Dependency::hasOnly(DstDep, Dependency::Independent))
4269 break;
4270 // TODO: Move this somewhere else and abstract it together with
4271 // the code in isLegalToPacketize.
4272 if (QII->isLoopN(*SrcMI)) {
4273 // loopN cannot be pulled too far.
4274 unsigned dist = HLV->getDistanceBetween(MI->getParent(),
4275 SrcMI->getOperand(0).getMBB());
4276 if (!QII->isJumpWithinBranchRange(*SrcMI, dist + SafetyBuffer)) {
4277 LLVM_DEBUG(dbgs() << "\nLoopN cannot be pulled too far into MBB";);
4278 break;
4279 }
4280 }
4281 // Continue searching higher up.
4282 InsPos = MI->getIterator();
4283 LLVM_DEBUG(dbgs() << "No conflict! Checking further up .....\n";);
4284 }
4285 }
4286
4287 if (InsPos == DstBB->instr_end())
4288 return DstEnd;
4289
4290 assert(!InsPos->isInsideBundle());
4291
4292 if (inBetweenBarriers(&*InsPos, DstBB))
4293 return DstEnd;
4294
4295 // Don't speculate outside a bundle when there are multiple execution
4296 // paths from the DstBB. When SpecPreciousMI = true, then in that case if
4297 // InsPos is a bundle then SpeculateMI will insert SrcMI 'just' before
4298 // the BUNDLE when the resources are not available.
4299 // For details see speculateMI().
4300 // TODO: What if resources were available in BUNDLE then higher up
4301 // InsPos was not in a BUNDLE, that time speculation will not happen.
4302 if (!InsPos->isBundle() && !SpecPreciousMIComp && (DstBB->succ_size() > 1))
4303 return DstEnd;
4304
4305 return InsPos;
4306}
4307
4308// @note: The SrcMI can be modified by this function.
4309MIIterType GreedyPullup::findInsertPtPred(MachineInstr *SrcMI,
4310 MachineBasicBlock *DstBB,
4311 bool &NeedToNewify,
4312 MICInstIterType &WithinPacket,
4313 bool PredPreciousMI) {
4314 LLVM_DEBUG(dbgs() << "\n[FindInsertPtPred]";);
4315 MIIterType DstEnd = DstBB->end();
4316 MIInstIterType InsPos = DstBB->instr_end();
4317 MICInstIterType DepTrue = DstBB->instr_end(), DepAnti = DstBB->instr_end();
4318 if (shouldNotBePulledUp(SrcMI) || !QII->isPredicated(*SrcMI) ||
4319 QII->isPredicatedNew(*SrcMI) || isSoloInstruction(*SrcMI))
4320 return DstEnd;
4321 NeedToNewify = false;
4322 WithinPacket = DstBB->instr_end();
4323 LLVM_DEBUG(dbgs() << "\n[FindInsertionPointPredicatedIns]" << *SrcMI;);
4324 LLVM_DEBUG(dbgs() << "\nChecking Resource conflict\n";);
4325 // Perform a bottom up traversal on the def-use set of DstBB MIs.
4326 for (MIRIterType MII = DstBB->rbegin(); MII != DstBB->rend(); ++MII) {
4327 MachineInstr *MI = &*MII;
4328 if (MI->isDebugInstr())
4329 continue;
4330 LLVM_DEBUG(dbgs() << "Against:\t* " << *MI;);
4331 // Check for dependencies [RangeBeg, MII) <- in reverse order.
4332 if (MI->isBundle()) {
4333 // Check if resources are available in BUNDLE or not.
4334 getResourcesReadyForBundle(MI->getIterator(), PredPreciousMI);
4335 if (canReserveResources(SrcMI->getIterator())) {
4336 if (!isLegalToPacketizeWith(MI, SrcMI) || NoPredInBundle)
4337 break;
4338 // Check for dst dep from insertion point until the end of DstBB.
4339 int DstDep = dstDependence(MI->getIterator(), InsPos,
4340 SrcMI->getIterator(), DepTrue, DepAnti);
4341 // check for .new and look no further.
4342 if (Dependency::hasOnly(DstDep, Dependency::RAW)) {
4343 // The dstMI should define a predicate which SrcMI should use.
4344 // And SrcMI should be newifiable.
4345 // Set NeedToNewify = true;
4346 // For RAW in the packet this is perfectly fine and
4347 // no need for further analysis.
4349 << "Read after write dependency with: " << *DepTrue;);
4350 unsigned DefP = 0;
4351 if ((InsPos != DepTrue) && hasOneDef(&*DepTrue, DefP)) {
4352 if (canNewifyPredReg(DefP, DepTrue, DstBB->instr_end()) &&
4353 SrcMI->readsRegister(DefP, /*TRI=*/nullptr) &&
4354 isNewifiable(*SrcMI, &Hexagon::PredRegsRegClass)) {
4355 InsPos = MI->getIterator();
4356 WithinPacket = DepTrue;
4357 NeedToNewify = true;
4358 LLVM_DEBUG(dbgs() << "\tokay (BUNDLE)!";);
4359 }
4360 } else {
4361 LLVM_DEBUG(dbgs() << "\tNot okay (BUNDLE)!";);
4362 }
4363 break;
4364 }
4365 // WAR is fine in the same packet, but look no further.
4366 int DstDepMasked = DstDep & ~Dependency::WAR_SameBundle;
4367 if (Dependency::hasOnly(DstDepMasked, Dependency::RAW)) {
4368 unsigned DepReg = 0;
4369 LLVM_DEBUG(dbgs() << "WAR_SameBundle dependency with: " << *DepAnti;);
4370 if (singleTrueDep(MI->getIterator(), InsPos, SrcMI->getIterator(),
4371 DepReg)) {
4372 MICIterType MIBundle = &*MII;
4373 MICInstIterType Sentinel =
4374 MIBundle == DstBB->end()
4375 ? DstBB->instr_end()
4376 : std::next(MIBundle).getInstrIterator();
4377 if (canNewifyPredReg(DepReg, DepTrue, Sentinel)) {
4378 // WAR for one and RAW for the predicate ins.
4379 InsPos = MI->getIterator();
4380 WithinPacket = laterOfTheTwo(DepTrue, DepAnti, Sentinel);
4381 assert(WithinPacket != Sentinel);
4382 NeedToNewify = true;
4383 LLVM_DEBUG(dbgs() << "Single RAW dependency with: " << *DepTrue;);
4384 }
4385 }
4386 // TODO: Enable this case of only WAR. WithinPacket = DepAnti;
4387 LLVM_DEBUG(dbgs() << "Write after read, okay (BUNDLE)!";);
4388 }
4389 // can look further up.
4390 if (Dependency::hasOnly(DstDep, Dependency::Independent)) {
4391 InsPos = MI->getIterator();
4392 LLVM_DEBUG(dbgs() << "No conflict (BUNDLE)! Checking further up!\n";);
4393 continue;
4394 }
4395 break;
4396 } else {
4397 LLVM_DEBUG(dbgs() << "No Resources";);
4398 // We don't want to move further up because we haven't analyzed the
4399 // dependencies for this packet. We might, but that will make things
4400 // more complicated.
4401 break;
4402 }
4403 } else {
4404 // Check for dst dep from insertion point until the end of DstBB.
4405 int DstDep = dstDependence(MI->getIterator(), InsPos,
4406 SrcMI->getIterator(), DepTrue, DepAnti);
4407 if (!Dependency::hasOnly(DstDep, Dependency::Independent))
4408 break;
4409 // Continue searching higher up.
4410 InsPos = MI->getIterator();
4411 LLVM_DEBUG(dbgs() << "No conflict! Checking further up .....\n";);
4412 }
4413 }
4414 if (InsPos == DstBB->instr_end())
4415 return DstEnd;
4416
4417 assert(!InsPos->isInsideBundle());
4418 if (inBetweenBarriers(&*InsPos, DstBB))
4419 return DstEnd;
4420 return InsPos;
4421}
4422
4423// Is the instruction a candidate for the "last chance global pullup"?
4424// That is, these are the instructions from single block innermost loops that
4425// could be hoisted to the loop entry AND copied to a downstream packet to
4426// free up a resource.
4427// Here, y is a candidate for the "last chance global pullup".
4428// {
4429// x = ...
4430// y = y1, y2 <--- where y1, y2 are loop invariant
4431// }
4432// z = ...
4433// {
4434// ...
4435// ... = y<killed>
4436// }
4437// br Loop
4438//
4439// Only V6_vcombine is handled.
4440// See GreedyPullup::lastChanceGlobalPullup for more details.
4441MachineInstr *
4442GreedyPullup::isLastChanceGlobalPullupCand(const MachineInstr *MI) {
4443 if (MI->getOpcode() != Hexagon::V6_vcombine)
4444 return nullptr;
4445 auto *MBB = MI->getParent();
4446
4447 unsigned Op0 = MI->getOperand(0).getReg();
4448 unsigned Op1 = MI->getOperand(1).getReg();
4449 unsigned Op2 = MI->getOperand(2).getReg();
4450 MICInstIterType DefUseR = MBB->instr_end();
4451
4452 if (MBB->isLiveIn(Op1) && MBB->isLiveIn(Op2) && // y1, y2 live in
4453 !HLV->isDefinedWithin(MBB->instr_begin(), MBB->instr_end(), Op1,
4454 DefUseR) && // and y1, y2 are loop invariant
4455 !HLV->isDefinedWithin(MBB->instr_begin(), MBB->instr_end(), Op2,
4456 DefUseR)) {
4457 if (HLV->isDefinedWithin(std::next(MI->getIterator()), MBB->instr_end(),
4458 Op0, DefUseR)) {
4459 // Cannot be live out.
4460 for (MCRegAliasIterator AI(Op0, TRI, true); AI.isValid(); ++AI)
4461 if (HLV->isLiveOut(MBB, *AI))
4462 return nullptr;
4463
4464 // Find the point where it's killed.
4465 MICInstIterType Use = MBB->instr_end();
4466 if (!HLV->isUsedWithin(std::next(DefUseR), MBB->instr_end(), Op0, Use))
4467 return nullptr;
4468
4469 auto regmaskMOs = collectRegmaskMOs(*MBB);
4470 for (auto *MO : regmaskMOs)
4471 if (MO->clobbersPhysReg(Op0) || MO->clobbersPhysReg(Op1) ||
4472 MO->clobbersPhysReg(Op2))
4473 return nullptr;
4474
4475 MachineInstr *InsertBundle = (MachineInstr *)(const_cast<MachineInstr *>(
4476 &*getBundleStart(Use->getIterator())));
4477
4478 if (!InsertBundle->isBundle())
4479 return nullptr;
4480
4481 return InsertBundle;
4482 }
4483 }
4484 return nullptr;
4485}
4486
4487// Attempt to hoist/copy an instruction from BundleHead to make room for
4488// InstrToMove, if beneficial.
4489// Here, y is a candidate for the "last chance global pullup"
4490// Loop:
4491// {
4492// x = ...
4493// y = y1, y2 <--- where y1, y2 are loop invariant
4494// }
4495// z = ... <--- z could be moved to the packet above if not for y
4496// {
4497// ...
4498// ... = y<killed>
4499// }
4500// br Loop
4501//
4502// If the last chance global pullup is successful, we will end up with:
4503// {
4504// y = y1, y2 <--- global pull up to make it live into the loop
4505// }
4506// Loop:
4507// {
4508// x = ...
4509// z = ... <---- z will get moved to the packet
4510// }
4511// {
4512// y = y1,y2 <--- make it live into the loop
4513// ... = y<killed> <-- uses old value (3.3.1 packet execution semantics)
4514// }
4515// br Loop
4516//
4517bool GreedyPullup::lastChanceGlobalPullup(MIInstIterType &BundleHead,
4518 MIInstIterType InstrToMove,
4519 const MachineInstr *LoadBypassCand) {
4520 if (!EnableHVXLCGP)
4521 return false;
4522 if (EnableLCGPForLoadBypassOnly && LoadBypassCand == nullptr)
4523 return false;
4524 MachineLoop *Loop = MLI.getLoopFor(BundleHead->getParent());
4525 if (!isSuperblockLoop(Loop))
4526 return false;
4527 if (InstrToMove->getOpcode() == Hexagon::V6_vcombine)
4528 return false;
4529 auto MII = BundleHead->getIterator();
4530 MachineInstr *SingleInstr = nullptr;
4531 std::vector<std::pair<MachineInstr *, MachineInstr *>> candidatesForHoist;
4532 auto MBB = MII->getParent();
4533
4534 for (++MII; MII->isInsideBundle(); ++MII)
4535 if (auto *InsertBundle = isLastChanceGlobalPullupCand(&*MII))
4536 candidatesForHoist.emplace_back(&*MII, InsertBundle);
4537
4538 // Find a place to insert
4539 for (auto Cand : candidatesForHoist) {
4540 // Check if it's worth kicking it out
4541 getResourcesReadyForBundle(BundleHead->getIterator(), false,
4542 Cand.first); // kick out
4543 if (!canReserveResources(InstrToMove))
4544 continue;
4545
4546 // We have our candidate; Check if we can place it in the outer scope.
4547 auto *Pred = Loop->getLoopPredecessor();
4548
4549 if (Pred) {
4550 auto TargetPacket = findInsertPtSpec(Cand.first, Pred, false, true);
4551 if (TargetPacket != Pred->end()) {
4552 // We have the packet to which to copy.
4553 for (MIIterType BI = Cand.second; BI != MBB->end(); ++BI) {
4554 if (LoadBypassCand && LoadBypassCand != &*Cand.first)
4555 continue;
4556 if (!BI->isBundle())
4557 continue;
4558 getResourcesReadyForBundle(BI->getIterator());
4559 if (canReserveResources(Cand.first->getIterator())) {
4560 if (isLegalToPacketizeWith(BI, Cand.first)) {
4561 // Now find a spot to copy to make it live in
4562 // Cand.second is the place where it's killed
4563 // Copy the instruction to make it live out of the loop;
4564 MachineInstr *ClonedInstr = MF.CloneMachineInstr(Cand.first);
4565 MIBundleBuilder Bundle(&*BI);
4566 MICInstIterType Use = MBB->instr_end();
4567 if (HLV->isUsedWithin(std::next(BI.getInstrIterator()),
4568 getBundleEnd(BI.getInstrIterator()),
4569 Cand.first->getOperand(0).getReg(), Use)) {
4570 ++Use;
4571 MachineInstr *UseMI = const_cast<MachineInstr *>(&*Use);
4572 Bundle.insert(UseMI->getIterator(), ClonedInstr);
4573 BI->addRegisterDefined(Cand.first->getOperand(0).getReg());
4574 } else {
4575 MIInstIterType DestPos = BI->getIterator();
4576 Bundle.insert(std::next(DestPos), ClonedInstr);
4577 }
4578
4579 assert(!MBB->isLiveIn(Cand.first->getOperand(0).getReg()) &&
4580 "Already live-in");
4581 MBB->addLiveIn(
4582 Cand.first->getOperand(0).getReg()); // Make sure it's live in
4583
4584 auto *Instr =
4585 removeMI(Cand.first, QII, nullptr,
4586 &SingleInstr); // may invalidate the bundle, DestPos
4587 // invalidated
4588
4589 // Not a bundle any longer; turn into a single instruction bundle,
4590 // as the local pullup pass expects a bundle into which to move
4591 // the instruction.
4592 if (SingleInstr) {
4593 BundleHead = SingleInstr->getIterator();
4594 finalizeBundle(*BundleHead->getParent(), BundleHead,
4595 std::next(BundleHead));
4596 BundleHead = std::prev(BundleHead);
4597 }
4598
4599 // Now hoist to the predecessor (i.e. global move)
4600 MIInstIterType DestPos = TargetPacket.getInstrIterator();
4601 // Already a bundle
4602 if (DestPos->isBundle()) {
4603 MIBundleBuilder HoistBundle(&*TargetPacket);
4604 HoistBundle.insert(std::next(DestPos), Instr);
4605 } else {
4606 // Check if it's safe to form a bundle
4607 finalizeBundle(*Pred, DestPos, std::next(DestPos));
4608 auto CheckBundle = std::prev(DestPos);
4609 getResourcesReadyForBundle(CheckBundle);
4610 if (canReserveResources(Instr->getIterator()) &&
4611 isLegalToPacketizeWith(CheckBundle, Instr)) {
4612 MIBundleBuilder HoistBundle(&*CheckBundle);
4613 HoistBundle.insert(std::next(CheckBundle), Instr);
4614 } else {
4615 DestPos->unbundleFromPred();
4616 CheckBundle->eraseFromParent();
4617 Pred->insertAfter(&*DestPos, Instr);
4618 }
4619 }
4620 HLV->updateLocalLiveness(Pred, true);
4621 return true;
4622 }
4623 }
4624 }
4625 }
4626 }
4627 }
4628 return false;
4629}
4630
4631// Currently we are only interested in speculating to
4632// immediate (dominating) predecessor.
4633bool GreedyPullup::canMIBeSpeculated(MachineInstr *MI, MachineBasicBlock *SrcBB,
4634 MachineBasicBlock *DstBB,
4635 MIIterType &TargetPacket) {
4636 LLVM_DEBUG(dbgs() << "\n[canMIBeSpeculated]");
4637 TargetPacket = DstBB->end();
4638
4639 MachineLoop *L = MLI.getLoopFor(SrcBB);
4640 bool isSuperBlockL = isSuperblockLoop(L);
4641 if (isSuperBlockL) {
4642 if (!isLoopInvariant(*MI))
4643 return false;
4644 }
4645
4646 // No dependency in the current SrcBB
4647 if (shouldNotBePulledUp(MI) || findInsertionPtSpecLocal(MI) != SrcBB->begin())
4648 return false;
4649 LLVM_DEBUG(dbgs() << " .....YES";);
4650 ABI &abi = AnalyzeBranchInfo.getOrCreate(DstBB, QII);
4651 // TODO: Handle SchedulingRegions with more than 2 blocks.
4652 if (!abi.AnalysisValid)
4653 return false;
4654 assert(abi.TBB && abi.FBB);
4655 if (!DstBB->isSuccessor(SrcBB))
4656 return false;
4657 bool SrcIsTBB = (abi.TBB == SrcBB);
4658 MachineBasicBlock *OtherBB = abi.FBB;
4659 if (!SrcIsTBB) {
4660 assert(abi.FBB == SrcBB);
4661 OtherBB = abi.TBB;
4662 }
4663
4664 assert(isSuperBlockL || SrcBB->pred_size() == 1);
4665
4666 if (!safeToSpeculate(MI, DstBB))
4667 return false;
4668 LLVM_DEBUG(dbgs() << " .....YES (SafeToSpeculate)";);
4669 // The def(s) of MI should not be live-in in the 'Other' branch.
4670 // TODO: If it is live-in in the 'Other' branch, even then we can speculate
4671 // provided we assign the live-in value to a new register
4672 // and replace the usage with the new register in the 'Other' branch.
4673 bool DefLiveInOtherBB = HLV->isDefLiveIn(MI, OtherBB);
4674 MIIterType TargetPacketIntMI = DstBB->end();
4675 bool PreciousMIShouldBeSpeculated = false;
4676 if (DefLiveInOtherBB) {
4677 LLVM_DEBUG(dbgs() << " ..... (DefLiveInOtherBB)";);
4678 if (!preciousToSpeculate(MI, SrcBB, DstBB, OtherBB))
4679 return false;
4680 LLVM_DEBUG(dbgs() << " .....YES (PreciousToSpeculate)";);
4681 if (!preciousMICanBeSpeculated(MI, SrcBB, DstBB, OtherBB, TargetPacketIntMI,
4682 1))
4683 return false;
4684 PreciousMIShouldBeSpeculated = true;
4685 LLVM_DEBUG(dbgs() << " .....YES (PreciousMICanBeSpeculated)";);
4686 } else
4687 LLVM_DEBUG(dbgs() << " ..... (DefNotLiveInOtherBB)";);
4688
4689 // If MI is loop invariant in the innermost single-block loop, try hard
4690 // to hoist during global pull-up. This is indicated with GlobalPrecious;
4691 bool GlobalPrecious = false;
4692 if ((EnableSingleLoopSuperblock && useHVXOps && isSuperBlockL &&
4694 isLoopInvariant(*MI))
4695 GlobalPrecious = true;
4696
4697 TargetPacket = findInsertPtSpec(MI, DstBB, PreciousMIShouldBeSpeculated,
4698 false, GlobalPrecious);
4699
4700 // Verify what we did was correct.
4701 if (DefLiveInOtherBB) {
4702 MICInstIterType TestIt = DstBB->instr_begin();
4703 // MI cannot be at or before the position of the inserted A2_tfr.
4704 while (TestIt != TargetPacketIntMI.getInstrIterator()) {
4705 assert(TestIt != TargetPacket.getInstrIterator());
4706 ++TestIt;
4707 }
4708 }
4709
4710 if (TargetPacket != DstBB->end()) {
4711 LLVM_DEBUG(dbgs() << "<<Resource available for speculation>>";);
4712 LLVM_DEBUG(if (TargetPacket->isBundle()) dbgs()
4713 << "\nInsert MI inside: " << *TargetPacket;
4714 else dbgs() << "\nInsert MI just before: " << *TargetPacket;);
4715 return true;
4716 }
4717 assert(!PreciousMIShouldBeSpeculated);
4718 return false;
4719}
4720
4721bool GreedyPullup::safeToSpeculate(MachineInstr *MI,
4722 MachineBasicBlock *DstBB) const {
4723 const MachineFunction &MF = *MI->getParent()->getParent();
4724 LLVM_DEBUG(dbgs() << "\n[SafeToSpeculate]";);
4725 if (QII->isPredicated(*MI) || QII->isMemOp(*MI) ||
4726 MI->hasUnmodeledSideEffects()) // To simplify.
4727 return false;
4728 if (MI->mayStore())
4729 return false;
4730 // Do not speculate instructions that modify reserved global registers.
4731 const MachineRegisterInfo &MRI = MF.getRegInfo();
4732 for (const MachineOperand &Op : MI->operands()) {
4733 if (!Op.isReg() || !Op.isDef())
4734 continue;
4735 unsigned R = Op.getReg();
4736 if (MRI.isReserved(R) && TRI->isGlobalReg(R))
4737 return false;
4738 }
4739 if (!MI->mayLoad())
4740 return true;
4741 // For simplification we want to analyze safety of simplest load.
4742 // TODO: Load from absolute address can be added as well.
4743 unsigned DefR = 0, UseR = 0, BaseR = 0, OffR = 0;
4744 if (!MI->hasOneMemOperand() || (*MI->memoperands_begin())->isVolatile() ||
4745 !(*MI->memoperands_begin())->getValue() ||
4746 !hasOneDefAndUse(MI, DefR, UseR))
4747 return false;
4748 // This check is for safety if getUnderlyingObject is messed up.
4749 MICInstIterType DefUseR = DstBB->instr_end();
4750 if (!MI->getParent()->isLiveIn(UseR) ||
4751 HLV->isDefinedWithin(MI->getParent()->instr_begin(), MI->getIterator(),
4752 UseR, DefUseR))
4753 return false;
4754 if (!QII->getBaseAndOffsetPosition(*MI, BaseR, OffR))
4755 return false;
4756 const Value *MIVal =
4757 getUnderlyingObject((*MI->memoperands_begin())->getValue());
4758 if (!MIVal)
4759 return false;
4760 bool LoadFromSameObject = false;
4761 assert(DefR && UseR);
4762 LLVM_DEBUG(dbgs() << "\nChecking if any loads as same as: " << *MI
4763 << "\tValue: ";
4764 MIVal->dump(););
4765 for (MICInstIterType MIIt = DstBB->instr_begin(); MIIt != DstBB->instr_end();
4766 ++MIIt) {
4767 const MachineInstr *MII = &*MIIt;
4768 if (MII->isDebugInstr())
4769 continue;
4770 unsigned DefP = 0, UseP = 0, BaseP = 0, OffP = 0;
4771 if (MII->mayLoad() &&
4772 !(QII->isPredicated(*MII) || QII->isMemOp(*MII) ||
4773 shouldNotBeCrossed(MII, MI)) &&
4774 MII->hasOneMemOperand() && hasOneDefAndUse(MII, DefP, UseP)) {
4775 LLVM_DEBUG(dbgs() << "\nAgainst: " << *MII;);
4776 MachineMemOperand *mmo = *MII->memoperands_begin();
4777 // There is already a load from same address => safe.
4778 if (UseP == UseR) {
4779 MICInstIterType DefUseP = DstBB->instr_end();
4780 if (HLV->isDefinedWithin(MII->getIterator(), DstBB->instr_end(), UseP,
4781 DefUseP))
4782 return false;
4783 // We have to check the immediate part also!
4784 if (mmo->isVolatile() || !mmo->getValue() ||
4785 !QII->getBaseAndOffsetPosition(*MII, BaseP, OffP))
4786 continue;
4787 // Cannot safely speculate a load with a stricter alignment
4788 // requirement.
4789 if ((*MI->memoperands_begin())->getAlign() > mmo->getAlign())
4790 continue;
4791 assert(MII->getOperand(BaseP).getReg() ==
4792 MI->getOperand(BaseR).getReg());
4793 const Value *MIIVal = getUnderlyingObject(mmo->getValue());
4794 if (MIVal == MIIVal) {
4795 LoadFromSameObject = true;
4796 LLVM_DEBUG(dbgs() << "\n\tLoad from same object:"
4797 << "\n\tValue: ";
4798 MIIVal->dump(););
4799 }
4800 }
4801 }
4802 if (MII->modifiesRegister(UseR, TRI))
4803 LoadFromSameObject = false;
4804 }
4805 return LoadFromSameObject;
4806}
4807
4808// Approach1: Check if there is a spare register available such that
4809// the def(MI) can be assigned to that spare register to preserve
4810// liveness in the OtherBB and change the usage of def(MI) in otherBB
4811// to the spare reg. The spare register should not be livein in otherBB.
4812// TODO: Implement Approach2 as well.
4813// Approach2: Check if there is just one MI in the OtherBB which uses
4814// def(MI) (account for aliasing etc.) and if that can be speculated first.
4815// In this approach we won't have to insert compensation code.
4816// Approach3: Split critical edge and insert a copy into the critical BB.
4817// This is a costly operation so it should be done very selectively.
4818bool GreedyPullup::preciousMICanBeSpeculated(MachineInstr *MI,
4819 MachineBasicBlock *SrcBB,
4820 MachineBasicBlock *DstBB,
4821 MachineBasicBlock *OtherBB,
4822 MIIterType &TargetPacket,
4823 unsigned ApproachNum) {
4824 LLVM_DEBUG(dbgs() << "\n[PreciousMICanBeSpeculated]";);
4825 assert(preciousToSpeculate(MI, SrcBB, DstBB, OtherBB));
4826 if (ApproachNum != 1)
4827 return false;
4828
4829 unsigned DefR, UseR;
4830 if (!hasOneDefAndUse(MI, DefR, UseR))
4831 return false;
4832 // TODO: We can remove this, then we have to replace all the usage
4833 // of DefR recursively for OtherBB and all its successors. That is not
4834 // worth it for speculating a single instruction.
4835 bool splitEdge = false;
4836 if (HLV->isLiveOut(OtherBB, DefR))
4837 splitEdge = true;
4838 MachineBasicBlock *LP = nullptr;
4839 if (OtherBB->pred_size() > 1) {
4840 LP = ShouldSplitCriticalEdge(DstBB, OtherBB);
4841 if (!LP)
4842 return false;
4843 LLVM_DEBUG(dbgs() << "\nCritical edge will be split during speculation.";);
4844 }
4845 if (splitEdge ^ (LP != nullptr)) // Both true or both false (for now).
4846 return false;
4847
4848 // TODO: Reconsider the design of this and the MICanBeSpeculated
4849 // because FindInsertionPoint is called twice for MI.
4850 // We need to find the insertion point of MI because we should know
4851 // that MI can be inserted at some position. This function inserts
4852 // an extra instruction so we better be sure in the first place.
4853 TargetPacket = findInsertPtSpec(MI, DstBB, true, false);
4854 if (TargetPacket == DstBB->end()) {
4855 LLVM_DEBUG(dbgs() << "\nPrecious MI cannot be speculated: " << *MI);
4856 return false;
4857 } else {
4858 LLVM_DEBUG(dbgs() << "<<Resource available for speculating PreciousMI>>";);
4859 LLVM_DEBUG(if (TargetPacket->isBundle()) dbgs()
4860 << "\nInsert MI inside: " << *TargetPacket;
4861 else dbgs() << "\nInsert MI just before: " << *TargetPacket;);
4862 }
4863
4864 std::unique_ptr<RegScavenger> RS(new RegScavenger());
4865 RS->enterBasicBlock(*DstBB);
4866 // Mark all the live-ins and their aliases of MBBs involved as used.
4867 LLVM_DEBUG(dbgs() << "\nMarking Liveins:";);
4868 markLiveInsAsUsed(RS, DstBB);
4869 markLiveInsAsUsed(RS, SrcBB);
4870 markLiveInsAsUsed(RS, OtherBB);
4871 markLiveOutsAsUsed(RS, DstBB);
4872 markLiveOutsAsUsed(RS, SrcBB);
4873 // Instead of advancing the scavenger with RS->forward(), conservatively mark
4874 // every register used in DstBB as used.
4875 // TODO: Only the instructions up to TargetPacket need to be considered.
4876 markAllRegsAsUsed(RS, DstBB);
4877 if (!Hexagon::IntRegsRegClass.contains(DefR))
4878 return false;
4879 // Use IntRegs: getMinimalPhysRegClass often returns IntRegsLow8 (R0-R7),
4880 // which would needlessly restrict the scavenged register.
4881 const TargetRegisterClass *RC = &Hexagon::IntRegsRegClass;
4882 unsigned ScratchReg = RS->FindUnusedReg(RC);
4883 if (ScratchReg == 0 || SrcBB->isLiveIn(ScratchReg))
4884 return false;
4885 LLVM_DEBUG(dbgs() << "\nRegister " << printReg(ScratchReg, TRI)
4886 << " available for speculating PreciousMI\n\t" << *MI;);
4887
4888 // Give up if ScratchReg is defined in OtherBB. This keeps the later register
4889 // replacement simple; scavenging another register is not worth it for a
4890 // single instruction.
4891 for (MIInstIterType OMBBI = OtherBB->instr_begin();
4892 OMBBI != OtherBB->instr_end(); ++OMBBI) {
4893 if (OMBBI->modifiesRegister(ScratchReg, TRI))
4894 return false;
4895 // We cannot replace implicit register uses.
4896 if (OMBBI->hasRegisterImplicitUseOperand(DefR))
4897 return false;
4898 }
4899
4900 // Compensation code is created in OtherBB and then moved to DstBB.
4901 DebugLoc dl;
4902 MachineInstr *NewMI = BuildMI(*OtherBB, OtherBB->instr_begin(), dl,
4903 QII->get(Hexagon::A2_tfr), ScratchReg)
4904 .addReg(DefR);
4905 LLVM_DEBUG(dbgs() << "\nCompensation code:" << *NewMI;);
4906 MIIterType NewMIPos = findInsertPtSpec(NewMI, DstBB, false, true);
4907
4908 // TODO: If TargetPacket==NewMIPos we bail out in this case,
4909 // which is sub-optimal. We should modify speculateMI just like
4910 // predicateMI so that it can be clearly specified that NewMI
4911 // can be inserted 'just' before the BUNDLE or inside.
4912 bool invalidSpeculation = (NewMIPos == DstBB->end());
4913 // Returns NewMIPos when TargetPacket = NewMIPos.
4914 MICInstIterType laterOne =
4915 laterOfTheTwo(TargetPacket.getInstrIterator(),
4916 NewMIPos.getInstrIterator(), DstBB->instr_end());
4917 // Requirements on linear ordering of NewMIPos and TargetPacket:
4918 // When TargetPacket is BUNDLE then NewMIPos < TargetPacket
4919 // When TargetPacket is not BUNDLE then NewMIPos <= TargetPacket
4920 // Otherwise the Speculation has to be reverted.
4921 if (laterOne == NewMIPos.getInstrIterator()) {
4922 if (TargetPacket->isBundle() || (NewMIPos != TargetPacket))
4923 invalidSpeculation = true;
4924 }
4925
4926 if (invalidSpeculation) {
4927 LLVM_DEBUG(
4928 dbgs() << "\nSupporting MI for precious MI cannot be speculated: "
4929 << *NewMI);
4930 NewMI->eraseFromParent();
4931 return false;
4932 } else {
4933 LLVM_DEBUG(dbgs() << "<<Resource available for speculating Comp code>>";);
4934 LLVM_DEBUG(if (NewMIPos->isBundle()) dbgs()
4935 << "\nInsert MI inside: " << *NewMIPos;
4936 else dbgs() << "\nInsert MI just before: " << *NewMIPos;);
4937 }
4938
4939 // The position (P) of compensation code should be before the
4940 // position (P') MI that needs to be speculated when P is a bundle.
4941 // When P is not bundle then P may be before or same as P'.
4942 assert(laterOfTheTwo(TargetPacket.getInstrIterator(),
4943 NewMIPos.getInstrIterator(),
4944 DstBB->instr_end()) == TargetPacket.getInstrIterator());
4945
4946 // Replace usage of Reg with ScratchReg in OtherBB.
4947 // Speculate after substitution so that liveness update is correct.
4948 if (!splitEdge && !LP)
4949 replaceUsageOfReg(DefR, ScratchReg, OtherBB, NewMI);
4950
4951 // Since we know that ScratchReg is not live-in in the SrcBB,
4952 // we can safely speculate NewMI into DstBB
4953 bool done = speculateMI(NewMI, OtherBB, DstBB, NewMIPos);
4954 (void)done;
4955 assert(done && "Wrong Analysis of speculation of precious MI");
4956 TargetPacket = NewMIPos;
4957 SpeculatedIns[DstBB].push_back(NewMI);
4958 if (splitEdge && LP) {
4959 MachineBasicBlock *NewCritBB = NULL;
4960 NewCritBB = splitCriticalEdge(DstBB, OtherBB, LP);
4961 assert(NewCritBB);
4962 LLVM_DEBUG(dbgs() << "\nNew critical MBB:" << *NewCritBB;);
4963 LLVM_DEBUG(dbgs() << *DstBB << *OtherBB;);
4964 DebugLoc dl;
4965 MachineInstr *NewMI = BuildMI(*NewCritBB, NewCritBB->instr_begin(), dl,
4966 QII->get(Hexagon::A2_tfr), DefR)
4967 .addReg(ScratchReg);
4968 SpecPacketOpp.push_back(NewMI);
4969 NewCritBB->removeLiveIn(DefR);
4970 // Update liveness.
4971 HLV->addNewMI(NewMI, NewCritBB);
4972 LLVM_DEBUG(dbgs() << "\nAdding MI to New critical MBB:" << *NewCritBB;);
4973 }
4974 return true;
4975}
4976
4977bool GreedyPullup::preciousToSpeculate(const MachineInstr *MI,
4978 const MachineBasicBlock *SrcBB,
4979 const MachineBasicBlock *DstBB,
4980 const MachineBasicBlock *OtherBB) const {
4981 if (SpeculateAllInst)
4982 return true;
4983
4984 LLVM_DEBUG(dbgs() << "\n[PreciousToSpeculate]";);
4985 // When we want to speculate within a loop and the otherBB is outside loop.
4986 MachineLoop *SrcLoop = MLI.getLoopFor(SrcBB);
4987 MachineLoop *DstLoop = MLI.getLoopFor(DstBB);
4988 MachineLoop *OtherBBLoop = MLI.getLoopFor(OtherBB);
4989 return (SrcLoop && MI->mayLoad() && (SrcLoop != OtherBBLoop) &&
4990 (SrcLoop == DstLoop));
4991}
4992
4993bool GreedyPullup::preciousToPredicate(const MachineInstr *MI,
4994 const MachineBasicBlock *SrcBB,
4995 const MachineBasicBlock *DstBB,
4996 const MachineBasicBlock *OtherBB) const {
4997 if (PredicateAllInst)
4998 return true;
4999
5000 MachineLoop *SrcLoop = MLI.getLoopFor(SrcBB);
5001 MachineLoop *DstLoop = MLI.getLoopFor(DstBB);
5002 MachineLoop *OtherBBLoop = MLI.getLoopFor(OtherBB);
5003 // When we want to speculate within a loop and the otherBB is outside loop.
5004 return (MI->mayLoad() && SrcLoop && (SrcLoop == DstLoop) &&
5005 (SrcLoop != OtherBBLoop));
5006}
5007
5008bool GreedyPullup::canMIBePredicated(MachineInstr *MI, MachineBasicBlock *SrcBB,
5009 MachineBasicBlock *DstBB,
5010 MIIterType &TargetPacket,
5011 MICInstIterType &WithinPacket,
5012 bool &NeedToNewify, bool &Precious) {
5013 // Initialize iterators to safe defaults
5014 TargetPacket = DstBB->end();
5015 WithinPacket = DstBB->instr_end();
5016
5017 if (!EnablePullupPred)
5018 return false;
5019 LLVM_DEBUG(dbgs() << "\n[MICanBePredicated]");
5020
5021 MachineLoop *L = MLI.getLoopFor(SrcBB);
5022 if (isSuperblockLoop(L)) {
5023 if (!isLoopInvariant(*MI))
5024 return false;
5025 }
5026
5027 // No dependency in the current SrcBB
5028 if (shouldNotBePulledUp(MI) || findInsertionPtSpecLocal(MI) != SrcBB->begin())
5029 return false;
5030 LLVM_DEBUG(dbgs() << " .....YES";);
5031 ABI &abi = AnalyzeBranchInfo.getOrCreate(DstBB, QII);
5032 if (!abi.AnalysisValid)
5033 return false;
5034 assert(abi.TBB && abi.FBB);
5035 if (!DstBB->isSuccessor(SrcBB))
5036 return false;
5037 bool SrcIsTBB = (abi.TBB == SrcBB);
5038 MachineBasicBlock *OtherBB = abi.FBB;
5039 if (!SrcIsTBB) {
5040 assert(abi.FBB == SrcBB);
5041 OtherBB = abi.TBB;
5042 }
5043 SmallVector<MachineOperand, 4> Cond = abi.Cond;
5044 // Checking the first two is faster than checking isPredicable.
5045 if (QII->isPredicated(*MI) || QII->isMemOp(*MI) || !QII->isPredicable(*MI))
5046 return false;
5047 // Even if def is live-in we should be able to predicate as long
5048 // as we do not cross the existing def in the MBB which we don't anyway.
5049
5050 // Clone the MI for analysis
5051 DebugLoc dl;
5052 // Manage resources properly.
5053 MachineInstr *PredMI =
5054 BuildMI(*SrcBB, SrcBB->instr_begin(), dl, QII->get(MI->getOpcode()));
5055 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
5056 PredMI->addOperand(MI->getOperand(i));
5057 if (!SrcIsTBB) {
5058 // If the branch condition cannot be reversed.
5059 if (QII->reverseBranchCondition(Cond)) {
5060 PredMI->eraseFromParent();
5061 return false;
5062 }
5063 }
5064 if (!QII->PredicateInstruction(*PredMI, Cond)) {
5065 PredMI->eraseFromParent();
5066 return false;
5067 }
5068 LLVM_DEBUG(dbgs() << "\nPredicated MI for analysis:" << *PredMI);
5069 TargetPacket =
5070 findInsertPtPred(PredMI, DstBB, NeedToNewify, WithinPacket, false);
5071 if (TargetPacket == DstBB->end()) {
5072 LLVM_DEBUG(dbgs() << "\nNo resources available for MI; is it precious?";);
5073 Precious = preciousToPredicate(MI, SrcBB, DstBB, OtherBB);
5074 if (Precious) {
5075 LLVM_DEBUG(
5076 dbgs() << "\nMI is Precious, trying the squeeze the dest. BUNDLE");
5077 TargetPacket =
5078 findInsertPtPred(PredMI, DstBB, NeedToNewify, WithinPacket, Precious);
5079 }
5080 }
5081 PredMI->eraseFromParent();
5082 if (TargetPacket != DstBB->end()) {
5083 LLVM_DEBUG(dbgs() << "<<Resource available for predication>>";);
5084 LLVM_DEBUG(if (TargetPacket->isBundle()) dbgs()
5085 << "\nInsert MI inside: " << *TargetPacket;
5086 else dbgs() << "\nInsert MI just before: " << *TargetPacket;);
5087 return true;
5088 }
5089 return false;
5090}
5091
5092// When \p DstPos is a BUNDLE, MI can be moved in that
5093// BUNDLE, otherwise just before the DstPos
5094bool GreedyPullup::speculateMI(MachineInstr *MI, MachineBasicBlock *SrcBB,
5095 MachineBasicBlock *DstBB, MIIterType DstPos) {
5096 LLVM_DEBUG(dbgs() << "\n[SpeculateMI]");
5097 // Remove the MI from SrcBB and put it into DstBB at TargetPacket.
5098 assert(DstPos->getParent() == DstBB);
5099 MachineInstr *InstrToMove;
5100
5101 if (DstPos->isBundle()) {
5102 MIInstIterType DstPack = DstPos.getInstrIterator();
5103 getResourcesReadyForBundle(DstPack);
5104 if (canReserveResources(MI->getIterator()) &&
5105 isLegalToPacketizeWith(DstPos, MI)) {
5106 InstrToMove = removeMI(MI, QII, &SpecPacketOpp);
5107 MIBundleBuilder Bundle(&*DstPos);
5108 Bundle.insert(std::next(DstPack), InstrToMove);
5109 } else {
5110 // If there are no resources then insert just before the BUNDLE.
5111 // TODO: Do this only in special cases.
5112 InstrToMove = removeMI(MI, QII, &SpecPacketOpp);
5113 DstBB->insert(DstPos, InstrToMove);
5114 SpecPacketOpp.push_back(&*DstPos);
5115 }
5116 } else {
5117 // Move the instruction.
5118 InstrToMove = removeMI(MI, QII, &SpecPacketOpp);
5119 DstBB->insert(DstPos, InstrToMove);
5120 // Since an instruction is moved besides another unpacketized insn
5121 // we might be able to packetize them and possibly other nearby insn.
5122 SpecPacketOpp.push_back(&*DstPos);
5123 // TODO: Make the bundle if possible, or leave this task to mergePackets.
5124 }
5125 // Update Liveness
5126 LLVM_DEBUG(dbgs() << "\n[Liveness incrementalUpdate]";);
5127 HLV->incrementalUpdate(InstrToMove->getIterator(), SrcBB, DstBB);
5128 // Mark MI as moved with speculation.
5129 LLVM_DEBUG(dbgs() << "\nSpeculated MI:\t" << *MI;);
5130 LLVM_DEBUG(dbgs() << "\nDstMBB: " << *DstBB << "\nSrcMBB: " << *SrcBB);
5131 return true;
5132}
5133
5134bool GreedyPullup::predicateMI(MachineInstr *MI, MachineBasicBlock *SrcBB,
5135 MachineBasicBlock *DstBB, MIIterType DstPack,
5136 MICInstIterType WithinPacket, bool NeedToNewify,
5137 bool Precious) {
5138 LLVM_DEBUG(dbgs() << "\n[PredicateMI]");
5139 // Remove the MI from SrcBB and put it into DstBB at DstPos.
5140 // Update Liveness
5141 // Mark MI as moved with predication.
5142 assert(DstPack->getParent() == DstBB);
5143 ABI &abi = AnalyzeBranchInfo.getOrCreate(DstBB, QII);
5144 assert(abi.AnalysisValid);
5145 bool SrcIsTBB = (abi.TBB == SrcBB);
5146 SmallVector<MachineOperand, 4> Cond = abi.Cond;
5147 if (!SrcIsTBB) {
5148 // If the branch condition cannot be reversed.
5149 bool Reversed = !QII->reverseBranchCondition(Cond);
5150 (void)Reversed;
5151 assert(Reversed);
5152 }
5153 bool Predicated = QII->PredicateInstruction(*MI, Cond);
5154 (void)Predicated;
5156 // Convert to dot.new as well.
5157 if (NeedToNewify) {
5158 int NewOpcode = QII->getDotNewPredOp(*MI, MBPI);
5159 MI->setDesc(QII->get(NewOpcode));
5160 }
5161
5162 MachineInstr *InstrToMove;
5163 if (DstPack->isBundle()) {
5164 MIInstIterType DstPos = DstPack.getInstrIterator();
5165 getResourcesReadyForBundle(DstPos);
5166 // When the MI is Precious, => it is being inserted into the bundle
5167 // by making compound i.e., five instructions into a BUNDLE.
5168 [[maybe_unused]] bool Reserved = canReserveResources(MI->getIterator());
5169 [[maybe_unused]] bool LegalPacket = isLegalToPacketizeWith(DstPack, MI);
5170 assert(((Reserved && LegalPacket) || Precious) && "Wrong analysis.");
5171
5172 InstrToMove = removeMI(MI, QII, &SpecPacketOpp);
5173 MIBundleBuilder Bundle(&*DstPack);
5174 if (WithinPacket != DstBB->instr_end()) {
5175 assert(WithinPacket->isBundledWithPred());
5176 DstPos = const_cast<MachineInstr *>(&*WithinPacket)->getIterator();
5177 }
5178 Bundle.insert(std::next(DstPos), InstrToMove);
5179 } else {
5180 // Move the instruction.
5181 InstrToMove = removeMI(MI, QII, &SpecPacketOpp);
5182 DstBB->insert(DstPack, InstrToMove);
5183 // Since an instruction is moved besides another unpacketized insn
5184 // we might be able to packetize them and possibly other nearby insn.
5185 SpecPacketOpp.push_back(&*DstPack);
5186 // TODO: Make the bundle if possible, or leave this task to mergePackets.
5187 }
5188
5189 // Update Liveness
5190 LLVM_DEBUG(dbgs() << "\n[Liveness incrementalUpdate]";);
5191 HLV->incrementalUpdate(InstrToMove->getIterator(), SrcBB, DstBB);
5192 // Mark MI as moved with speculation.
5193 LLVM_DEBUG(dbgs() << "\nPredicated MI:\t" << *MI;);
5194 LLVM_DEBUG(dbgs() << "\nDstMBB: " << *DstBB << "\nSrcMBB: " << *SrcBB);
5195 return true;
5196}
5197
5198//===----------------------------------------------------------------------===//
5199// HexagonGlobalScheduler Functions
5200//===----------------------------------------------------------------------===//
5201
5202void HexagonGlobalSchedulerV2::generateCFG(MachineFunction &MF) {
5203 GS->generateCFG(MF);
5204}
5205
5206bool HexagonGlobalSchedulerV2::runOnMachineFunction(MachineFunction &MF) {
5207 auto &ST = MF.getSubtarget<HexagonSubtarget>();
5208 if (!EnableGlobalSched || !ST.usePackets() || skipFunction(MF.getFunction()))
5209 return false;
5210
5211 TM = static_cast<const HexagonTargetMachine *>(&MF.getTarget());
5212 QII = ST.getInstrInfo();
5213 TRI = ST.getRegisterInfo();
5214
5215 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
5216 HexagonLiveVariables *HLV = &getAnalysis<HexagonLiveVariables>();
5217 if (!HLV->HLVComplete) {
5218 LLVM_DEBUG(dbgs() << "\nHexagon Live Variables Analysis unavailable."
5219 << "\nExiting Hexagon Global Scheduler");
5220 return false;
5221 }
5222 const MachineBranchProbabilityInfo *MBPI =
5223 &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI();
5224 MachineLoopInfo *MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
5225
5226 GS.reset(new GreedyPullup(TM, QII, TRI, MF, *MLI, AA, MBPI, HLV));
5227
5228 assert(verifyMachineFunction(MF, "VLIW Packetizer") &&
5229 "Invalid IR after Packetizer");
5230 generateCFG(MF);
5231 LLVM_DEBUG(MF.dump(););
5232 assert(verifyMachineFunction(MF, "After GenerateCFG") &&
5233 "Invalid CFG transformation.");
5234 GS->formSchedulingRegions(MF);
5235 // TODO: Mechanism of sorting the scheduling regions.
5236 GS->printSchedulingRegions();
5237 GS->pruneSchedulingRegions(&GlobalScheduler::pruneCriteria);
5238 LLVM_DEBUG(dbgs() << "\nScheduling regions before sorting";);
5239 GS->printSchedulingRegions();
5240 GS->sortSchedulingRegions();
5241 LLVM_DEBUG(dbgs() << "\nScheduling regions after sorting";);
5242 GS->printSchedulingRegions();
5243 LLVM_DEBUG(MF.dump(););
5244 GS->schedule();
5245 assert(verifyMachineFunction(MF, "After Scheduling") &&
5246 "Invalid Scheduling.");
5247 if (PostSchedPack)
5248 GS->packetize();
5249 assert(verifyMachineFunction(MF, "After post-schedule packetization") &&
5250 "Invalid Opts.");
5251 if (PostSchedOpt) {
5252 // Regenerate distance map because so many instructions have
5253 // been moved.
5254 HLV->regenerateDistanceMap(MF);
5255 GS->performExposedOptimizations();
5256 assert(verifyMachineFunction(MF, "After post-schedule branch opt") &&
5257 "Invalid Opts.");
5258 }
5259 GS->generateCompoundsPostSched();
5260 GS->generateAutoAndPredicates(MF);
5261 return true;
5262}
5263
5264//===----------------------------------------------------------------------===//
5265// Public Constructor Functions
5266//===----------------------------------------------------------------------===//
5267
5269 return new HexagonGlobalSchedulerV2();
5270}
MachineInstrBuilder & UseMI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator MBBI
Function Alias Analysis false
always inline
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
const HexagonInstrInfo * TII
static cl::opt< bool > EnableSqueeze("try-squeeze-bundle", cl::Hidden, cl::init(true), cl::desc("Try putting 5 instructions in bundle"))
static cl::opt< bool > PullUnsafeMemops("pull-unsafe-memops", cl::Hidden, cl::init(true), cl::desc("Pull up loads which have no memoperands"))
static cl::opt< bool > DisableHVXLocalPullupAndSuperblock("disable-hvx-sched-superblock", cl::Hidden, cl::init(false), cl::desc("Disable single block loops in superblocks and the HVX local " "pull-up pass."))
static cl::opt< bool > PostSchedOpt("post-sched-opt", cl::Hidden, cl::init(true), cl::desc("Optimize after global scheduling"))
static MachineInstr * updateBundle(MachineInstr *BundleHead, const HexagonInstrInfo *QII, SmallVectorImpl< MachineInstr * > *SpecScope=nullptr)
static bool isEmptyBlock(MachineBasicBlock *MBB)
static std::pair< MIInstIterType, MIInstIterType > getParentBundle(MachineInstr *MI)
static MIRIterType getSpeculationBeginPoint(MachineInstr *SrcMI, MachineBasicBlock *DstBB)
static cl::opt< bool > NoPredInBundle("nopred-sched-bundle", cl::Hidden, cl::desc("Do not put predicated instructions in bundle"))
static cl::opt< bool > EnableLocalMergePackets("enable-local-merge-packets", cl::Hidden, cl::init(true), cl::desc("Push down local MIs into the next packet"))
static cl::opt< bool > PreventDuplexSep("prevent-duplex-sep-v2", cl::Hidden, cl::init(true), cl::desc("Prevent separation of duplex while pullup in global scheduler V2"))
static cl::opt< bool > EnableSparsePullup("enable-sparse-pullup", cl::Hidden, cl::init(true), cl::desc("Enable pullup to/from sparse packets"))
static cl::opt< bool > PostSchedPack("post-sched-packet", cl::Hidden, cl::init(true), cl::desc("Packetize unbundled MIs after global scheduling"))
static cl::opt< bool > EnableHVXLocalPullup("enable-hvx-local-pullup", cl::Hidden, cl::init(true), cl::desc("Enable the HVX local pull-up pass."))
static cl::opt< bool > EnableHVXLocalPullupInnermost("enable-hvx-local-pullup-innermost", cl::Hidden, cl::init(false), cl::desc("Enable the HVX local pull-up pass on single block innermost " "loops only."))
static cl::opt< unsigned > MaxPUBundles("hexagon-pullup-distance", cl::Hidden, cl::init(10), cl::desc("Maximum number of bundles to check for local pull-up"))
static cl::opt< bool > VerifyGlobalSched("verify-global-sched", cl::Hidden, cl::init(false), cl::desc("Run the machine verifier at several stages of global scheduler"))
static void transferLiveIns(const MachineBasicBlock *From, MachineBasicBlock *To)
static MachineBasicBlock * ShouldSplitCriticalEdge(MachineBasicBlock *FromBB, MachineBasicBlock *ToBB)
static cl::opt< bool > NoSpecInBundle("nospec-sched-bundle", cl::Hidden, cl::desc("Do not put speculated instructions in bundle"))
static cl::opt< bool > EnableLocalPullup("enable-local-pullup", cl::Hidden, cl::init(true), cl::desc("Speculate local MIs in parent BUNDLEs"))
static MachineInstr * removeMI(MachineInstr *MI, const HexagonInstrInfo *QII, SmallVectorImpl< MachineInstr * > *SpecPacketOpp=nullptr, MachineInstr **singleInstr=nullptr)
static cl::opt< bool > EnableHVXLCGP("enable-hvx-lcgp", cl::Hidden, cl::init(true), cl::desc("Enable the HVX last chance global pull-up pass."))
static bool checkIfSameBundle(MachineInstr *MI1, MachineInstr *MI2)
static cl::opt< bool > EnableLCGPForLoadBypassOnly("enable-lcgp-for-load-bypass-only", cl::Hidden, cl::init(true), cl::desc("Enable the HVX last chance global pull-up for load-bypass-only"))
static cl::opt< bool > EnableHVXSuperblockHeuristic("enable-hvx-superblock-heuristic", cl::Hidden, cl::init(true), cl::desc("Run HVX scheduling only on blocks whose ratio of HVX " "instructions exceeds -hvx-sched-profit-ratio."))
static cl::opt< bool > EnableSingleLoopSuperblock("enable-single-loop-superblock", cl::Hidden, cl::init(true), cl::desc("Enable superblocks consisting of single block loops."))
static cl::opt< bool > EnableHVXTwoLoadCurBypass("enable-hvx-two-load-cur-bypass", cl::Hidden, cl::init(false), cl::desc("Enable the two-load .cur load-bypass case in local pull-up."))
static std::vector< const MachineOperand * > collectRegmaskMOs(const MachineBasicBlock &MBB)
static cl::opt< bool > EnableHLXLoadStorePullup("enable-hlx-load-store-pullup", cl::Hidden, cl::init(true), cl::desc("Pull up HLX .tmp load uses and .new HLX stores to remove the " "copies inserted by HLX load/store expansion"))
static cl::opt< bool > EnableClusterPullup("enable-cluster-pullup", cl::Hidden, cl::init(true), cl::desc("Enable pullup for dependent instruction groups"))
Enable cluster pullup optimization.
static cl::opt< bool > EnableHVXLocalPullupLB("enable-hvx-local-pullup-load-bypass", cl::Hidden, cl::init(true), cl::desc("Enable the HVX local pull-up pass (load bypass only)."))
static cl::opt< bool > EnablePullupPred("enable-pullup-pred", cl::Hidden, cl::init(true), cl::desc("Use pullup predication"))
static bool inBetweenBarriers(MICIterType Iter, const MachineBasicBlock *DstBB)
static cl::opt< bool > EnableGlobalSched("enable-global-sched", cl::Hidden, cl::init(false), cl::desc("Enable global scheduler optimizer"))
static cl::opt< bool > PredicateAllInst("predicate-all-inst", cl::Hidden, cl::desc("Try predicating all possible instructions."))
bool endloopAfterMI(MachineBasicBlock::instr_iterator MII, MachineBasicBlock *MBB)
static cl::opt< float > HVXSchedProfitRatio("hvx-sched-profit-ratio", cl::Hidden, cl::init(0.80), cl::desc("Ratio of HVX instruction/Total instructions " "for the profitability check."))
static cl::opt< bool > SpeculateAllInst("speculate-all-inst", cl::Hidden, cl::desc("Try speculating all possible instructions."))
cl::opt< bool > OneComplexPerPacket
static const unsigned SafetyBuffer
cl::opt< bool > EnableDefUseSamePacket("enable-def-use-same-packet", cl::Hidden, cl::init(true), cl::desc("Allow moving an instruction out of a packet that redefines one of " "its source registers"))
cl::opt< bool > OneFloatPerPacket
#define HEXAGON_PACKET_SIZE
static bool isSchedBarrier(const MachineInstr &MI)
IRTranslator LLVM IR MI
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
SmallVector< MachineOperand, 4 > Cond
if(!TBB||Cond.size()< 1) return false
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
R600 Packetizer
MachineRegisterInfo & MRI
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
This file declares the machine register scavenger class.
Remove Loads Into Fake Uses
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:479
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
Value * RHS
static MachineBasicBlock & splitEdge(MachineBasicBlock &MBB, MachineBasicBlock &Succ, int SuccCount, MachineInstr *Br, MachineInstr *&UncondBr, const X86InstrInfo &TII)
AnalysisUsage & addRequired()
int find_first() const
Returns the index of the first set bit, -1 if none of the bits are set.
Definition BitVector.h:318
size_type count() const
Returns the number of bits which are set.
Definition BitVector.h:182
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT, true > const_iterator
Definition DenseMap.h:679
iterator end()
Definition DenseMap.h:686
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
bool isHLXVec(const MachineInstr &MI) const
bool isPredicated(const MachineInstr &MI) const override
Returns true if the instruction is already predicated.
bool definesPredicateReg(const MachineInstr &MI) const
bool isCompoundBranchInstr(const MachineInstr &MI) const
bool isJumpR(const MachineInstr &MI) const
bool invertAndChangeJumpTarget(MachineInstr &MI, MachineBasicBlock *NewTarget) const
bool isDotTmpInst(const MachineInstr &MI) const
bool isSoftwarePipelineLoopInstr(const MachineInstr &MI) const
unsigned nonDbgBundleSize(MachineBasicBlock::const_iterator BundleHead) const
int getDotNewPredOp(const MachineInstr &MI, const MachineBranchProbabilityInfo *MBPI) const
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify) const override
Analyze the branching code at the end of MBB, returning true if it cannot be understood (e....
bool isPredicatedNew(const MachineInstr &MI) const
bool isJumpWithinBranchRange(const MachineInstr &MI, unsigned offset) const
std::optional< unsigned > getOperandLatency(const InstrItineraryData *ItinData, const MachineInstr &DefMI, unsigned DefIdx, const MachineInstr &UseMI, unsigned UseIdx) const override
getOperandLatency - Compute and return the use operand latency of a given pair of def and use.
int srcDependence(MachineBasicBlock::instr_iterator SrcBeg, MachineBasicBlock::instr_iterator SrcEnd, MachineBasicBlock::instr_iterator RMII, const MIUseDefMap &MIUseDefs, SmallPtrSetImpl< MachineInstr * > *DepSet=nullptr, bool PreventDuplexSep=true, bool IsPullDown=false) const
Compute the intra-packet dependence of RMII against the rest of the bundle [SrcBeg,...
bool hasCallUseInBundle(MachineBasicBlock::const_instr_iterator MIBegin, MachineBasicBlock::const_instr_iterator MIEnd, unsigned Reg, const TargetRegisterInfo &TRI) const
void findInstrPredicate(MachineInstr *MI, SmallVectorImpl< MachineOperand > &Cond) const
findInstrPredicate - Set the predicate of the instruction in the specified predicate vector First ent...
bool reverseBranchCondition(SmallVectorImpl< MachineOperand > &Cond) const override
Reverses the branch condition of the specified condition list, returning false on success and true if...
bool isLoopN(const MachineInstr &MI) const
bool isFloatCompare(const MachineInstr &MI) const
bool isConstExtended(const MachineInstr &MI) const
bool PredOpcodeHasJMP_c(unsigned Opcode) const
bool isDotCurInst(const MachineInstr &MI) const
bool areMemAccessesDependent(AAResults *AA, const MachineInstr *MIa, const MachineInstr *MIb) const
Return true if the memory accesses of MIa and MIb may depend on each other.
bool isExtended(const MachineInstr &MI) const
bool isPredicateLate(unsigned Opcode) const
bool isMemOp(const MachineInstr &MI) const
bool isDeallocRet(const MachineInstr &MI) const
bool isDotNewInst(const MachineInstr &MI) const
void translateInstrsForDup(MachineFunction &MF, bool ToBigInstrs=true) const
bool isTC1(const MachineInstr &MI) const
std::optional< unsigned > getInvertedCompare(const int OpC) const
bool isDotNewOperand(const MachineInstr &MI, unsigned OpIndex) const
Should be able to tell if the operand in question is .new.
int getDotCurOp(const MachineInstr &MI) const
bool isSafeInBundleWAR(const MachineInstr &DefMI, unsigned DefOpIdx, const MachineInstr &UseMI, unsigned UseOpIdx, bool IsPullDown=false, bool DefViaRegMask=false) const
A use (UseMI) can share a bundle with an instruction that redefines the same register (DefMI),...
bool isHVXVec(const MachineInstr &MI) const
bool mayBeCurLoad(const MachineInstr &MI) const
bool isNewValueJump(const MachineInstr &MI) const
bool PredicateInstruction(MachineInstr &MI, ArrayRef< MachineOperand > Cond) const override
Convert the instruction into a predicated instruction.
unsigned nonDbgBBSize(const MachineBasicBlock *BB) const
getInstrTimingClassLatency - Compute the instruction latency of a given instruction using Timing Clas...
bool isEndLoopN(unsigned Opcode) const
bool getBaseAndOffsetPosition(const MachineInstr &MI, unsigned &BasePos, unsigned &OffsetPos) const override
For instructions with a base and offset, return the position of the base register and offset operands...
bool isPredicable(const MachineInstr &MI) const override
Return true if the specified instruction can be predicated.
HexagonII::CompoundGroup getCompoundCandidateGroup(const MachineInstr &MI) const
SmallVector< MachineInstr *, 2 > getBranchingInstrs(MachineBasicBlock &MBB) const
bool isNewValueStore(const MachineInstr &MI) const
unsigned getCompoundOpcode(const MachineInstr &GA, const MachineInstr &GB) const
unsigned getDistanceBetween(const MachineBasicBlock *From, const MachineBasicBlock *To, unsigned BufferPerMBB=HEXAGON_INSTR_SIZE) const
Returns the linear distance (as per layout) of MI from the Function.
bool isUsedWithin(MICInstIterType MIBegin, MICInstIterType MIEnd, unsigned Reg, MICInstIterType &Use, SmallPtrSet< MachineInstr *, 2 > *ExceptionsList=nullptr) const
bool incrementalUpdate(MICInstIterType MIDelta, MachineBasicBlock *From, MachineBasicBlock *To)
incrementalUpdate - update the liveness when MIDelta is moved from From to To.
bool updateLocalLiveness(MachineFunction &Fn)
updateLocalLiveness - update only kill flags of operands.
const BitVector & getLiveOuts(const MachineBasicBlock *MBB) const
bool isDefLiveIn(const MachineInstr *MI, const MachineBasicBlock *MBB) const
void regenerateDistanceMap(const MachineFunction &Fn)
void addNewMBB(MachineBasicBlock *MBB)
addNewMBB - inform the LiveVariable Analysis that new MBB has been added.
bool isLiveOut(const MachineBasicBlock *MBB, unsigned Reg) const
bool isDefinedWithin(MICInstIterType MIBegin, MICInstIterType MIEnd, unsigned Reg, MICInstIterType &Def) const
void addNewMI(MachineInstr *MI, MachineBasicBlock *MBB)
unsigned getLoopDepth() const
Return the nesting level of this loop.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
livein_iterator livein_end() const
bool isEHPad() const
Returns true if the block is a landing pad.
MachineInstrBundleIterator< const MachineInstr > const_iterator
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI iterator getFirstNonDebugInstr(bool SkipPseudoOp=true)
Returns an iterator to the first non-debug instruction in the basic block, or end().
LLVM_ABI void removeLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll())
Remove the specified register from the live in set.
LiveInVector::const_iterator livein_iterator
LLVM_ABI livein_iterator livein_begin() const
bool hasAddressTaken() const
Test whether this block is used as something other than the target of a terminator,...
LLVM_ABI void dump() const
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
SmallVectorImpl< MachineBasicBlock * >::iterator succ_iterator
SmallVectorImpl< MachineBasicBlock * >::iterator pred_iterator
LLVM_ABI void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
Instructions::iterator instr_iterator
LLVM_ABI void ReplaceUsesOfBlockWith(MachineBasicBlock *Old, MachineBasicBlock *New)
Given a machine basic block that branched to 'Old', change the code and CFG so that it branches to 'N...
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
succ_reverse_iterator succ_rbegin()
LLVM_ABI bool isLayoutSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB will be emitted immediately after this block, such that if this bloc...
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing function and deletes it.
Instructions::const_iterator const_instr_iterator
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
reverse_iterator rbegin()
LLVM_ABI bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI bool isLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void dump() const
dump - Print the current MachineFunction to cerr, useful for debugger use.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
bool verify(Pass *p=nullptr, const char *Banner=nullptr, raw_ostream *OS=nullptr, bool AbortOnError=true) const
Run the current MachineFunction through the machine code verifier, useful for debugger use.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
const MachineJumpTableInfo * getJumpTableInfo() const
getJumpTableInfo - Return the jump table info object for the current function.
void splice(iterator InsertPt, iterator MBBI)
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
static MachineInstrBundleIterator getAtBundleBegin(instr_iterator MI)
Get the bundle iterator for the given instruction's bundle.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
bool isReturn(QueryType Type=AnyInBundle) const
bool isTerminator(QueryType Type=AnyInBundle) const
Returns true if this instruction part of the terminator for a basic block.
bool mayLoadOrStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read or modify memory.
const MachineBasicBlock * getParent() const
bool readsRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr reads the specified register.
bool isCall(QueryType Type=AnyInBundle) const
bool isBundle() const
bool isDebugInstr() const
unsigned getNumOperands() const
Retuns the total number of operands.
LLVM_ABI void addOperand(MachineFunction &MF, const MachineOperand &Op)
Add the specified operand to the instruction.
LLVM_ABI MachineInstr * removeFromBundle()
Unlink this instruction from its basic block and return it without deleting it.
bool isBranch(QueryType Type=AnyInBundle) const
Returns true if this is a conditional, unconditional, or indirect branch.
bool modifiesRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr modifies (fully define or partially define) the specified register.
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
LLVM_ABI int findRegisterUseOperandIdx(Register Reg, const TargetRegisterInfo *TRI, bool isKill=false) const
Returns the operand index that is a use of the specific register or -1 if it is not found.
LLVM_ABI unsigned getBundleSize() const
Return the number of instructions inside the MI bundle, excluding the bundle header.
mop_range operands()
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
bool isUnconditionalBranch(QueryType Type=AnyInBundle) const
Return true if this is a branch which always transfers control flow to some other block.
LLVM_ABI void eraseFromBundle()
Unlink 'this' from its basic block and delete it.
bool hasOneMemOperand() const
Return true if this instruction has exactly one MachineMemOperand.
mmo_iterator memoperands_begin() const
Access to memory operands of the instruction.
bool isInsideBundle() const
Return true if MI is in a bundle (but not the first MI in a bundle).
LLVM_ABI bool hasOrderedMemoryRef() const
Return true if this instruction may have an ordered or volatile memory reference, or if the informati...
MachineOperand * findRegisterUseOperand(Register Reg, const TargetRegisterInfo *TRI, bool isKill=false)
Wrapper for findRegisterUseOperandIdx, it returns a pointer to the MachineOperand rather than an inde...
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
LLVM_ABI void removeOperand(unsigned OpNo)
Erase an operand from an instruction, leaving it with one fewer operand than it started with.
LLVM_ABI void dump() const
LLVM_ABI void addRegisterDefined(Register Reg, const TargetRegisterInfo *RegInfo=nullptr)
We have determined MI defines a register.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
bool isBundled() const
Return true if this instruction part of a bundle.
LLVM_ABI bool ReplaceMBBInJumpTables(MachineBasicBlock *Old, MachineBasicBlock *New)
ReplaceMBBInJumpTables - If Old is the target of any jump tables, update the jump tables to branch to...
LLVM_ABI unsigned getOperandNo() const
Returns the index of this operand in the instruction that it belongs to.
void setIsInternalRead(bool Val=true)
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isRegMask() const
isRegMask - Tests if this is a MO_RegisterMask operand.
MachineBasicBlock * getMBB() const
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
Register getReg() const
getReg - Returns the register number.
static bool clobbersPhysReg(const uint32_t *RegMask, MCRegister PhysReg)
clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
bool isMBB() const
isMBB - Tests if this is a MO_MachineBasicBlock operand.
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
iterator erase(const_iterator CI)
typename SuperClass::iterator iterator
void push_back(const T &Elt)
std::reverse_iterator< const_iterator > const_reverse_iterator
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
std::reverse_iterator< iterator > reverse_iterator
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
LLVM_ABI void dump() const
Support for debugging, callable in GDB: V->dump()
int getNumOccurrences() const
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
iterator find(const_arg_type_t< ValueT > V)
Definition DenseSet.h:175
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
initializer< Ty > init(const Ty &Val)
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< InstrNode * > Instr
Definition RDFGraph.h:389
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
bool empty() const
Definition BasicBlock.h:101
std::reverse_iterator< iterator > rbegin() const
Definition BasicBlock.h:93
iterator end() const
Definition BasicBlock.h:89
std::reverse_iterator< iterator > rend() const
Definition BasicBlock.h:96
LLVM_ABI iterator begin() const
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:360
LLVM_ABI void finalizeBundle(MachineBasicBlock &MBB, MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
finalizeBundle - Finalize a machine instruction bundle which includes a sequence of instructions star...
MachineBasicBlock::instr_iterator getBundleStart(MachineBasicBlock::instr_iterator I)
Returns an iterator to the first instruction in the bundle containing I.
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
void initializeHexagonGlobalSchedulerV2Pass(PassRegistry &)
bool operator>=(int64_t V1, const APSInt &V2)
Definition APSInt.h:359
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
bool operator>(int64_t V1, const APSInt &V2)
Definition APSInt.h:361
LLVM_ABI void verifyMachineFunction(const std::string &Banner, const MachineFunction &MF)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
MachineBasicBlock::instr_iterator getBundleEnd(MachineBasicBlock::instr_iterator I)
Returns an iterator pointing beyond the bundle containing I.
bool set_union(S1Ty &S1, const S2Ty &S2)
set_union(A, B) - Compute A := A u B, return whether A changed.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
@ Other
Any other memory.
Definition ModRef.h:68
FunctionPass * createHexagonGlobalSchedulerV2()
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
DWARFExpression::Operation Op
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
DenseMap< const MachineInstr *, UseDef_t > MIUseDef_t
bool operator<=(int64_t V1, const APSInt &V2)
Definition APSInt.h:358
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58