LLVM 24.0.0git
HexagonGlobalScheduler.cpp
Go to the documentation of this file.
1
2//===----- HexagonGlobalScheduler.cpp - Global Scheduler ------------------===//
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9//
10// Basic infrastructure for the global scheduling + Hexagon pull-up pass.
11// Currently run at the very end of code generation for Hexagon, cleans
12// up lost scheduling opportunities. Currently breaks liveness, so no passes
13// that rely on liveness info should run afterwards. Will be fixed in future
14// versions.
15//
16//===----------------------------------------------------------------------===//
17#include "Hexagon.h"
18#include "HexagonGlobalRegion.h"
19#include "HexagonRegisterInfo.h"
20#include "HexagonSubtarget.h"
22#include "llvm/ADT/DenseMap.h"
23#include "llvm/ADT/SmallSet.h"
24#include "llvm/ADT/Statistic.h"
37#include "llvm/CodeGen/Passes.h"
46#include "llvm/Support/Debug.h"
49
50#include <list>
51#include <map>
52
53#define DEBUG_TYPE "global_sched"
54
55using namespace llvm;
56
57STATISTIC(HexagonNumPullUps, "Number of instructions pull-ups");
58STATISTIC(HexagonNumDualJumps, "Number of dual jumps formed");
59
60static cl::opt<bool> DisablePullUp("disable-pull-up", cl::Hidden,
61 cl::desc("Disable Hexagon pull-up pass"));
62
64 "enable-speculative-pull-up", cl::Hidden,
65 cl::desc("Enable speculation during Hexagon pull-up pass"));
66
68 "enable-local-pull-up", cl::Hidden, cl::init(true),
69 cl::desc("Enable same BB pull during Hexagon pull-up pass"));
70
72 "speculate-loads-on-pull-up", cl::Hidden, cl::init(true),
73 cl::desc("Allow speculative loads during Hexagon pull-up pass"));
74
76 "cmp-branch-loads-pull-up", cl::Hidden, cl::init(true),
77 cl::desc("Allow compare-branch loads during Hexagon pull-up pass"));
78
79static cl::opt<bool> AllowUnlikelyPath("unlikely-path-pull-up", cl::Hidden,
80 cl::init(true),
81 cl::desc("Allow unlikely path pull up"));
82
83static cl::opt<bool>
84 PerformDualJumps("dual-jump-in-pull-up", cl::Hidden, cl::init(true),
85 cl::desc("Perform dual jump formation during pull up"));
86
88 "enable-dependent-pull-up", cl::Hidden, cl::init(true),
89 cl::desc("Perform dual jump formation during pull up"));
90
91static cl::opt<bool>
92 AllowBBPeelPullUp("enable-bb-peel-pull-up", cl::Hidden, cl::init(true),
93 cl::desc("Peel a reg copy out of a BBloop"));
94
96 "prevent-compound-separation", cl::Hidden,
97 cl::desc("Do not destroy existing compounds during pull up"));
98
100 "prevent-duplex-separation", cl::Hidden, cl::init(true),
101 cl::desc("Do not destroy existing duplexes during pull up"));
102
103static cl::opt<unsigned> MainCandidateQueueSize("pull-up-main-queue-size",
104 cl::Hidden, cl::init(8));
105
106static cl::opt<unsigned> SecondaryCandidateQueueSize("pull-up-sec-queue-size",
107 cl::Hidden, cl::init(2));
108
110 "post-pull-up-opt", cl::Hidden, cl::init(true),
111 cl::desc("Enable opt. exposed by pull-up e.g., remove redundant jumps"));
112
114 "speculate-non-pred-insn", cl::Hidden, cl::init(true),
115 cl::desc("Speculate non-predicable instructions in parent BB"));
116
117static cl::opt<bool>
118 DisableCheckBundles("disable-hexagon-check-bundles", cl::Hidden,
119 cl::init(true),
120 cl::desc("Disable Hexagon check bundles pass"));
121
122static cl::opt<bool>
123 WarnOnBundleSize("warn-on-bundle-size", cl::Hidden,
124 cl::desc("Hexagon check bundles and warn on size"));
125
126static cl::opt<bool>
127 ForceNoopHazards("force-noop-hazards", cl::Hidden, cl::init(false),
128 cl::desc("Force noop hazards in scheduler"));
130 "enable-def-use-same-packet", cl::Hidden, cl::init(true),
131 cl::desc(
132 "Allow moving an instruction out of a packet that redefines one of "
133 "its source registers"));
136
137namespace llvm {
140} // namespace llvm
141
142namespace {
143class HexagonGlobalSchedulerImpl;
144
145// MIa = existing bundle sibling; MIb = candidate being moved.
146// WAR_SameBundle: MIa defs a reg MIb uses, same bundle, ISA-safe forwarding.
147enum class DepKind { Independent, WAR_SameBundle, Dependent };
148
149class HexagonGlobalScheduler : public MachineFunctionPass {
150public:
151 static char ID;
152 HexagonGlobalScheduler() : MachineFunctionPass(ID) {
154 }
155
156 void getAnalysisUsage(AnalysisUsage &AU) const override {
158 AU.addRequired<MachineLoopInfoWrapperPass>();
159 AU.addRequired<AAResultsWrapperPass>();
160 AU.addRequired<MachineBranchProbabilityInfoWrapperPass>();
161 AU.addRequired<MachineBlockFrequencyInfoWrapperPass>();
162 AU.addRequired<MachineDominatorTreeWrapperPass>();
164 }
165
166 StringRef getPassName() const override { return "Hexagon Global Scheduler"; }
167
168 bool runOnMachineFunction(MachineFunction &Fn) override;
169};
170char HexagonGlobalScheduler::ID = 0;
171
172// Describes a single pull-up candidate.
173class PullUpCandidate {
174 MachineBasicBlock::instr_iterator CandidateLocation;
176 bool DependentOp;
177 signed BenefitCost;
178 std::vector<MachineInstr *> Backtrack;
179
180public:
181 PullUpCandidate(MachineBasicBlock::instr_iterator MII) {
182 CandidateLocation = MII;
183 BenefitCost = 0;
184 }
185
186 PullUpCandidate(MachineBasicBlock::instr_iterator MII,
188 std::vector<MachineInstr *> &backtrack, bool DependentOp,
189 signed Cost)
190 : CandidateLocation(MII), HomeBundle(HomeBundle),
191 DependentOp(DependentOp), BenefitCost(Cost) {
192 // Copy of the backtrack.
193 Backtrack = backtrack;
194 }
195
196 void populate(MachineBasicBlock::instr_iterator &MII,
198 std::vector<MachineInstr *> &backtrack, bool &dependentOp) {
199 MII = CandidateLocation;
200 WorkPoint = HomeBundle;
201 backtrack = Backtrack;
202 dependentOp = DependentOp;
203 }
204
205 signed getCost() { return BenefitCost; }
206
207 MachineInstr *getCandidate() { return &*CandidateLocation; }
208
209 void dump() {
210 dbgs() << "Cost(" << BenefitCost;
211 dbgs() << ") Dependent(" << DependentOp;
212 dbgs() << ") backtrack size(" << Backtrack.size() << ")\t";
213 CandidateLocation->dump();
214 }
215};
216
217/// PullUpCandidateSorter - A Sort utility for pull-up candidates.
218struct PullUpCandidateSorter {
219 PullUpCandidateSorter() {}
220 bool operator()(PullUpCandidate *LHS, PullUpCandidate *RHS) {
221 return LHS->getCost() > RHS->getCost();
222 }
223};
224
225// Describes a single pull-up opportunity: location to which
226// pull-up is possible with additional information about it.
227// Also contains a list of pull-up candidates for this location.
228class PullUpState {
229 friend class HexagonGlobalSchedulerImpl;
230 // Available opportunity for pull-up.
231 // FAIAP a bundle with an empty slot.
232 MachineBasicBlock::iterator HomeLocation;
233 // Home bundle copy. This is here for speed of iteration.
235 // Multiple candidates for the Home location.
236 SmallVector<PullUpCandidate *, 8> PullUpCandidates;
237
238 const HexagonInstrInfo *QII;
239
240public:
241 PullUpState(const HexagonInstrInfo *QII) : HomeLocation(NULL), QII(QII) {}
242
243 ~PullUpState() { reset(); }
244
245 void addPullUpCandidate(MachineBasicBlock::instr_iterator MII,
247 std::vector<MachineInstr *> &backtrack,
248 bool DependentOp, signed Cost) {
249 LLVM_DEBUG(dbgs() << "\t[addPullUpCandidate]: "; (*MII).dump());
250 PullUpCandidate *PUI =
251 new PullUpCandidate(MII, HomeBundle, backtrack, DependentOp, Cost);
252 PullUpCandidates.push_back(PUI);
253 }
254
255 void dump() {
256 unsigned element = 0;
257 for (unsigned i = 0; i < HomeBundle.size(); i++) {
258 dbgs() << "[" << element++;
259 dbgs() << "] Home Duplex("
260 << QII->getDuplexCandidateGroup(*HomeBundle[i]);
261 dbgs() << ") Compound (" << QII->getCompoundCandidateGroup(*HomeBundle[i])
262 << ") ";
263 HomeBundle[i]->dump();
264 }
265 dbgs() << "\n";
266 element = 0;
267 for (SmallVector<PullUpCandidate *, 4>::iterator
268 I = PullUpCandidates.begin(),
269 E = PullUpCandidates.end();
270 I != E; ++I) {
271 dbgs() << "[" << element++ << "] Cand: Compound(";
272 dbgs() << QII->getCompoundCandidateGroup(*(*I)->getCandidate()) << ") ";
273 (*I)->dump();
274 }
275 }
276
277 void reset() {
278 HomeLocation = NULL;
279 for (SmallVector<PullUpCandidate *, 4>::iterator
280 I = PullUpCandidates.begin(),
281 E = PullUpCandidates.end();
282 I != E; ++I)
283 delete *I;
284 PullUpCandidates.clear();
285 HomeBundle.clear();
286 }
287
288 void addHomeLocation(MachineBasicBlock::iterator WorkPoint) {
289 reset();
290 HomeLocation = WorkPoint;
291 }
292
293 unsigned haveCandidates() { return PullUpCandidates.size(); }
294};
295
296class HexagonGlobalSchedulerImpl : public HexagonPacketizerList {
297 // List of PullUp regions for this function.
298 std::vector<BasicBlockRegion *> PullUpRegions;
299 // Map of approximate distance for each BB from the
300 // function base.
301 DenseMap<MachineBasicBlock *, unsigned> BlockToInstOffset;
302 // Keep track of multiple pull-up candidates.
303 PullUpState CurrentState;
304 // Empty basic blocks as a result of pull-up.
305 std::vector<MachineBasicBlock *> EmptyBBs;
306 // Save all the Speculated MachineInstr that were moved
307 // FROM MachineBasicBlock because we don't want to have
308 // more than one speculated instructions pulled into one packet.
309 // TODO: This can be removed once we have a use-def dependency chain
310 // for all the instructions in a function.
311 std::map<MachineInstr *, MachineBasicBlock *> SpeculatedIns;
312 // All the regs and their aliases used by an instruction.
313 std::map<MachineInstr *, std::vector<unsigned>> MIUseSet;
314 // All the regs and their aliases defined by an instruction.
315 std::map<MachineInstr *, std::vector<unsigned>> MIDefSet;
316
317 AliasAnalysis *AA;
318 const MachineBranchProbabilityInfo *MBPI;
319 const MachineBlockFrequencyInfo *MBFI;
320 const MachineRegisterInfo *MRI;
321 const MachineFrameInfo &MFI;
322 const HexagonRegisterInfo *QRI;
323 const HexagonInstrInfo *QII;
324 MachineLoopInfo &MLI;
325 MachineDominatorTree &MDT;
326 MachineInstrBuilder Ext;
327 MachineInstrBuilder Nop;
328 const unsigned PacketSize;
329 TargetSchedModel TSchedModel;
330
331public:
332 // Ctor.
333 HexagonGlobalSchedulerImpl(MachineFunction &MF, MachineLoopInfo &MLI,
334 MachineDominatorTree &MDT, AliasAnalysis *AA,
335 const MachineBranchProbabilityInfo *MBPI,
336 const MachineBlockFrequencyInfo *MBFI,
337 const MachineRegisterInfo *MRI,
338 const MachineFrameInfo &MFI,
339 const HexagonRegisterInfo *QRI);
340 HexagonGlobalSchedulerImpl(const HexagonGlobalSchedulerImpl &) = delete;
341 HexagonGlobalSchedulerImpl &
342 operator=(const HexagonGlobalSchedulerImpl &) = delete;
343
344 ~HexagonGlobalSchedulerImpl() {
345 // Free regions.
346 for (std::vector<BasicBlockRegion *>::iterator I = PullUpRegions.begin(),
347 E = PullUpRegions.end();
348 I != E; ++I)
349 delete *I;
350 MF.deleteMachineInstr(Ext);
351 MF.deleteMachineInstr(Nop);
352 }
353
354 // initPacketizerState - initialize some internal flags.
355 void initPacketizerState() override;
356
357 // ignorePseudoInstruction - Ignore bundling of pseudo instructions.
358 bool ignoreInstruction(MachineInstr *MI);
359
360 // isSoloInstruction - return true if instruction MI can not be packetized
361 // with any other instruction, which means that MI itself is a packet.
362 bool isSoloInstruction(const MachineInstr &MI) override;
363
364 // Add MI to packetizer state. Returns false if it cannot fit in the packet.
365 bool incrementalAddToPacket(MachineInstr &MI);
366
367 // formPullUpRegions - Top level call to form regions.
368 bool formPullUpRegions(MachineFunction &Fn);
369
370 // performPullUp - Top level call for pull-up.
371 bool performPullUp();
372
373 // performPullUpCFG - Top level call for pull-up CFG.
374 bool performPullUpCFG(MachineFunction &Fn);
375
376 // performExposedOptimizations -
377 // Look for optimization opportunities after pullup.
378 bool performExposedOptimizations(MachineFunction &Fn);
379
380 // optimizeBranching -
381 // 1. A conditional-jump transfers control to a BB with
382 // jump as the only instruction.
383 // if(p0) jump t1
384 // // ...
385 // t1: jump t2
386 // 2. When a BB with a single conditional jump, jumps to succ-of-succ and
387 // falls-through BB with only jump instruction.
388 // { if(p0) jump t1 }
389 // { jump t2 }
390 // t1: { ... }
391 MachineBasicBlock *optimizeBranches(MachineBasicBlock *MBB,
392 MachineBasicBlock *TBB,
393 MachineInstr *FirstTerm,
394 MachineBasicBlock *FBB);
395
396 // removeRedundantBranches -
397 // 1. Remove jump to the layout successor.
398 // 2. Remove multiple (dual) jump to the same target.
399 bool removeRedundantBranches(MachineBasicBlock *MBB, MachineBasicBlock *TBB,
400 MachineInstr *FirstTerm, MachineBasicBlock *FBB,
401 MachineInstr *SecondTerm);
402
403 // optimizeDualJumps - optimize dual jumps in a packet
404 // For now: Replace dual jump by single jump in case of a fall through.
405 bool optimizeDualJumps(MachineBasicBlock *MBB, MachineBasicBlock *TBB,
406 MachineInstr *FirstTerm, MachineBasicBlock *FBB,
407 MachineInstr *SecondTerm);
408
409 void GenUseDefChain(MachineFunction &Fn);
410
411 // Return region pointer or null if none found.
412 BasicBlockRegion *getRegionForMBB(std::vector<BasicBlockRegion *> &Regions,
413 MachineBasicBlock *MBB);
414
415 // Saves all the used-regs and their aliases in Uses.
416 // Saves all the defined-regs and their aliases in Defs.
417 void MIUseDefSet(MachineInstr *MI, std::vector<unsigned> &Defs,
418 std::vector<unsigned> &Uses);
419
420 // This is a very useful debug utility.
421 unsigned countCompounds(MachineFunction &Fn);
422
423 // Check bundle counts
424 void checkBundleCounts(MachineFunction &Fn);
425
426private:
427 // Get next BB to be included into the region.
428 MachineBasicBlock *getNextPURBB(MachineBasicBlock *MBB, bool SecondBest);
429
430 void setUsedRegs(BitVector &Set, unsigned Reg);
431 bool AliasingRegs(unsigned RegA, unsigned RegB);
432
433 // Test is true if the two MIs cannot be safely reordered.
434 bool ReorderDependencyTest(MachineInstr *MIa, MachineInstr *MIb) {
435 return analyzeDependence(MIa, MIb) != DepKind::Independent;
436 }
437 DepKind analyzeDependence(MachineInstr *MIa, MachineInstr *MIb);
438
439 bool canAddMIToThisPacket(
440 MachineInstr *MI,
442
443 bool pullUpPeelBBLoop(MachineBasicBlock *PredBB, MachineBasicBlock *LoopBB);
444
445 MachineInstr *findBundleAndBranch(MachineBasicBlock *BB,
447
448 // Does this bundle have any slots left?
449 bool ResourcesAvailableInBundle(BasicBlockRegion *CurrentRegion,
450 MachineBasicBlock::iterator &TargetPacket);
451
452 // Perform the actual move.
453 MachineInstr *MoveAndUpdateLiveness(
454 BasicBlockRegion *CurrentRegion, MachineBasicBlock *HomeBB,
455 MachineInstr *InstrToMove, bool NeedToNewify, unsigned DepReg,
456 bool MovingDependentOp, MachineBasicBlock *OriginBB,
457 MachineInstr *OriginalInstruction, SmallVector<MachineOperand, 4> &Cond,
458 MachineBasicBlock::iterator &SourceLocation,
459 MachineBasicBlock::iterator &TargetPacket,
461 std::vector<MachineInstr *> &backtrack);
462
463 // Updates incremental kill patterns along the backtrack.
464 void updateKillAlongThePath(MachineBasicBlock *HomeBB,
465 MachineBasicBlock *OriginBB,
468 MachineBasicBlock::iterator &SourcePacket,
469 MachineBasicBlock::iterator &TargetPacket,
470 std::vector<MachineInstr *> &backtrack);
471
472 // Gather list of pull-up candidates.
473 bool findPullUpCandidates(MachineBasicBlock::iterator &WorkPoint,
475 std::vector<MachineInstr *> &backtrack,
476 unsigned MaxCandidates);
477
478 // See if the instruction could be pulled up.
479 bool tryMultipleInstructions(
480 MachineBasicBlock::iterator &RetVal, /* output parameter */
481 std::vector<BasicBlockRegion *>::iterator &CurrentRegion,
483 MachineBasicBlock::iterator &ToThisBBEnd,
484 MachineBasicBlock::iterator &FromThisBBEnd, bool PathInRegion = true);
485
486 // Try to move MI into existing bundle.
487 bool MoveMItoBundle(BasicBlockRegion *CurrentRegion,
490 MachineBasicBlock::iterator &TargetPacket,
491 MachineBasicBlock::iterator &SourceLocation,
492 std::vector<MachineInstr *> &backtrack,
493 bool MovingDependentOp, bool PathInRegion);
494
495 // Insert temporary MI copy into MBB.
497 insertTempCopy(MachineBasicBlock *MBB,
498 MachineBasicBlock::iterator &TargetPacket, MachineInstr *MI,
499 bool DeleteOldCopy);
500
502 findInsertPositionInBundle(MachineBasicBlock::iterator &Bundle,
503 MachineInstr *MI, bool &LastInBundle);
504
505 bool NeedToNewify(MachineBasicBlock::instr_iterator NewMI, unsigned *DepReg,
506 MachineInstr *TargetPacket);
507
508 bool CanNewifiedBeUsedInBundle(MachineBasicBlock::instr_iterator NewMI,
509 unsigned DepReg, MachineInstr *TargetPacket);
510
511 void addInstructionToExistingBundle(MachineBasicBlock *HomeBB,
515 MachineBasicBlock::iterator &TargetPacket,
517 std::vector<MachineInstr *> &backtrack);
518
519 void removeInstructionFromExistingBundle(
520 MachineBasicBlock *HomeBB, MachineBasicBlock::instr_iterator &Head,
522 MachineBasicBlock::iterator &SourceLocation,
523 MachineBasicBlock::iterator &NextMI, bool MovingDependentOp,
524 std::vector<MachineInstr *> &backtrack);
525
526 // Check for conditional register operaton.
527 bool MIsCondAssign(MachineInstr *BMI, MachineInstr *MI,
528 SmallVector<unsigned, 4> &Defs);
529
530 // Test all the conditions required for instruction to be
531 // speculative. These are just required conditions, cost
532 // or benefit should be computed elsewhere.
533 bool canMIBeSpeculated(MachineInstr *MI, MachineBasicBlock *ToBB,
534 MachineBasicBlock *FromBB,
535 std::vector<MachineInstr *> &backtrack);
536
537 // See if this branch target belongs to the current region.
538 bool isBranchWithinRegion(BasicBlockRegion *CurrentRegion, MachineInstr *MI);
539
540 // A collection of low level utilities.
541 bool MIsAreDependent(MachineInstr *MIa, MachineInstr *MIb);
542 bool MIsHaveTrueDependency(MachineInstr *MIa, MachineInstr *MIb);
543 bool canReorderMIs(MachineInstr *MIa, MachineInstr *MIb);
544 bool canCauseStall(MachineInstr *MI, MachineInstr *MJ);
545 bool canThisMIBeMoved(MachineInstr *MI,
547 bool &MovingDependentOp, int &Cost);
548 bool MIisDualJumpCandidate(MachineInstr *MI,
549 MachineBasicBlock::iterator &WorkPoint);
550 bool DemoteToDotOld(MachineInstr *MI);
551 bool isNewifiable(MachineBasicBlock::instr_iterator MII, unsigned DepReg,
552 MachineInstr *TargetPacket);
553 bool IsNewifyStore(MachineInstr *MI);
554 bool isJumpOutOfRange(MachineInstr *MI);
555 bool IsDualJumpFirstCandidate(MachineInstr *MI);
556 bool IsDualJumpFirstCandidate(MachineBasicBlock *MBB);
557 bool IsDualJumpFirstCandidate(MachineBasicBlock::iterator &TargetPacket);
558 bool IsNotDualJumpFirstCandidate(MachineInstr *MI);
559 bool isJumpOutOfRange(MachineInstr *UnCond, MachineInstr *Cond);
560 bool IsDualJumpSecondCandidate(MachineInstr *MI);
561 bool tryAllocateResourcesForConstExt(MachineInstr *MI, bool UpdateState);
562 bool isCompoundPair(MachineInstr *MIa, MachineInstr *MIb);
563 bool doesMIDefinesPredicate(MachineInstr *MI, SmallVector<unsigned, 4> &Defs);
564 bool AnalyzeBBBranches(MachineBasicBlock *MBB, MachineBasicBlock *&TBB,
565 MachineInstr *&FirstTerm, MachineBasicBlock *&FBB,
566 MachineInstr *&SecondTerm);
567 inline bool multipleBranchesFromToBB(MachineBasicBlock *BB) const;
568};
569} // namespace
570
571INITIALIZE_PASS_BEGIN(HexagonGlobalScheduler, "global-sched",
572 "Hexagon Global Scheduler", false, false)
578INITIALIZE_PASS_END(HexagonGlobalScheduler, "global-sched",
579 "Hexagon Global Scheduler", false, false)
580
581/// HexagonGlobalSchedulerImpl Ctor.
582HexagonGlobalSchedulerImpl::HexagonGlobalSchedulerImpl(
587 : HexagonPacketizerList(MF, MLI, AA, nullptr, false), PullUpRegions(0),
588 CurrentState((const HexagonInstrInfo *)TII), AA(AA), MBPI(MBPI),
589 MBFI(MBFI), MRI(MRI), MFI(MFI), QRI(QRI), MLI(MLI), MDT(MDT),
590 PacketSize(MF.getSubtarget().getSchedModel().IssueWidth) {
591 QII = (const HexagonInstrInfo *)TII;
592 Ext = BuildMI(MF, DebugLoc(), QII->get(Hexagon::A4_ext));
593 Nop = BuildMI(MF, DebugLoc(), QII->get(Hexagon::A2_nop));
594 TSchedModel.init(&MF.getSubtarget());
595}
596
597// Return bundle size without debug instructions.
598static unsigned nonDbgBundleSize(MachineBasicBlock::iterator &TargetPacket) {
600 MachineBasicBlock::instr_iterator End = MII->getParent()->instr_end();
601 unsigned count = 0;
602 for (++MII; MII != End && MII->isInsideBundle(); ++MII) {
603 if (MII->isDebugInstr())
604 continue;
605 count++;
606 }
607 return count;
608}
609
610/// The pass main entry point.
611bool HexagonGlobalScheduler::runOnMachineFunction(MachineFunction &Fn) {
612 auto &HST = Fn.getSubtarget<HexagonSubtarget>();
613 if (DisablePullUp || !HST.usePackets() || skipFunction(Fn.getFunction()))
614 return false;
615
616 const MachineRegisterInfo *MRI = &Fn.getRegInfo();
617 const MachineFrameInfo &MFI = Fn.getFrameInfo();
618 const HexagonRegisterInfo *QRI = HST.getRegisterInfo();
619 MachineLoopInfo &MLI = getAnalysis<MachineLoopInfoWrapperPass>().getLI();
620 MachineDominatorTree &MDT =
621 getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
622 const MachineBranchProbabilityInfo *MBPI =
623 &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI();
624 const MachineBlockFrequencyInfo *MBFI =
625 &getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI();
626 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
627
628 // Preserve comounds if Opt Size.
629 const Function &F = Fn.getFunction();
630 if (F.hasOptSize() && PreventCompoundSeparation.getNumOccurrences() == 0)
632
633 // Instantiate the Scheduler.
634 HexagonGlobalSchedulerImpl GlobalSchedulerState(Fn, MLI, MDT, AA, MBPI, MBFI,
635 MRI, MFI, QRI);
636
637 // DFA state table should not be empty.
638 assert(GlobalSchedulerState.getResourceTracker() && "Empty DFA table!");
639
640 // Loop over all of the basic blocks.
641 // PullUp regions are basically traces with no side entrances.
642 // Might want to traverse BB by frequency.
643 GlobalSchedulerState.checkBundleCounts(Fn);
644
645 // Pullup does not handle hazards yet.
647 return true;
648
649 LLVM_DEBUG(GlobalSchedulerState.countCompounds(Fn));
650 GlobalSchedulerState.GenUseDefChain(Fn);
651 GlobalSchedulerState.formPullUpRegions(Fn);
652 GlobalSchedulerState.performPullUp();
653 GlobalSchedulerState.performPullUpCFG(Fn);
654 if (PostPullUpOpt) {
655 GlobalSchedulerState.formPullUpRegions(Fn);
656 GlobalSchedulerState.performExposedOptimizations(Fn);
657 }
658 LLVM_DEBUG(GlobalSchedulerState.countCompounds(Fn));
659
660 return true;
661}
662
663/// Allocate resources (i.e. 4 bytes) for constant extender. If succeess, return
664/// true, otherwise, return false.
665bool HexagonGlobalSchedulerImpl::tryAllocateResourcesForConstExt(
666 MachineInstr *MI, bool UpdateState = true) {
667 if (ResourceTracker->canReserveResources(*Ext)) {
668 // We do not always want to change the state of ResourceTracker.
669 // When we do not want to change it, we need to test for additional
670 // corner cases.
671 if (UpdateState)
672 ResourceTracker->reserveResources(*Ext);
673 else if (CurrentPacketMIs.size() >= PacketSize - 1)
674 return false;
675 return true;
676 }
677
678 return false;
679}
680
681static bool IsSchedBarrier(const MachineInstr *MI) {
682 return MI->getOpcode() == Hexagon::Y2_barrier;
683}
684
685static bool IsIndirectCall(const MachineInstr *MI) {
686 return MI->getOpcode() == Hexagon::J2_callr;
687}
688
689#ifndef NDEBUG
691 if (MI->isBundledWithPred())
692 dbgs() << "^";
693 else
694 dbgs() << " ";
695 if (MI->isBundledWithSucc())
696 dbgs() << "v";
697 else
698 dbgs() << " ";
699 MI->dump();
700}
701
704 dbgs() << "\tNULL\n";
705 return;
706 }
707 MachineInstr *MI = &*MII;
708 MachineBasicBlock *MBB = MI->getParent();
709 // Uninserted instruction.
710 if (!MBB) {
711 dbgs() << "\tUnattached: ";
712 DumpLinked(MI);
713 return;
714 }
715 dbgs() << "\t";
716 DumpLinked(MI);
717 if (MI->isBundle()) {
718 MachineBasicBlock::instr_iterator MIE = MI->getParent()->instr_end();
719 for (++MII; MII != MIE && MII->isInsideBundle() && !MII->isBundle();
720 ++MII) {
721 dbgs() << "\t\t*";
722 DumpLinked(&*MII);
723 }
724 }
725}
726
729 if (MII == BBEnd) {
730 dbgs() << "\tBBEnd\n";
731 return;
732 }
733
734 DumpPacket(MII);
735}
736#endif
737
738static bool isBranch(MachineInstr *MI) {
739 if (MI->isBundle()) {
740 MachineBasicBlock::instr_iterator MII = MI->getIterator();
741 MachineBasicBlock::instr_iterator MIE = MI->getParent()->instr_end();
742 for (++MII; MII != MIE && MII->isInsideBundle() && !MII->isBundle();
743 ++MII) {
744 if (MII->isBranch())
745 return true;
746 }
747 } else
748 return MI->isBranch();
749 return false;
750}
751
752/// Any of those must not be first dual jump. Everything else is OK.
753bool HexagonGlobalSchedulerImpl::IsNotDualJumpFirstCandidate(MachineInstr *MI) {
754 if (MI->isCall() || (MI->isBranch() && !QII->isPredicated(*MI)) ||
755 MI->isReturn() || QII->isEndLoopN(MI->getOpcode()))
756 return true;
757 return false;
758}
759
760/// These four functions clearly belong in HexagonInstrInfo.cpp.
761/// Is this MI could be first dual jump instruction?
762bool HexagonGlobalSchedulerImpl::IsDualJumpFirstCandidate(MachineInstr *MI) {
763 if (!PerformDualJumps)
764 return false;
765 if (MI->isBranch() && QII->isPredicated(*MI) && !QII->isNewValueJump(*MI) &&
766 !MI->isIndirectBranch() && !QII->isEndLoopN(MI->getOpcode()))
767 return true;
768 // Missing loopN here, but not sure if there will be any benefit from it.
769 return false;
770}
771
772/// This version covers the whole packet.
773bool HexagonGlobalSchedulerImpl::IsDualJumpFirstCandidate(
774 MachineBasicBlock::iterator &TargetPacket) {
775 if (!PerformDualJumps)
776 return false;
777 MachineInstr *MI = &*TargetPacket;
778
779 if (MI->isBundle()) {
780 // If this is a bundle, it must be the last bundle in BB.
781 if (&(*MI->getParent()->rbegin()) != MI)
782 return false;
783
784 MachineBasicBlock::instr_iterator MII = MI->getIterator();
785 MachineBasicBlock::instr_iterator BBEnd = MI->getParent()->instr_end();
786 // If there is a control flow op in this packet, this is the case
787 // we look for, even if they are dependent on other members.
788 for (++MII; MII != BBEnd && MII->isInsideBundle() && !MII->isBundle();
789 ++MII)
790 if (IsNotDualJumpFirstCandidate(&*MII))
791 return false;
792 } else
793 return IsDualJumpFirstCandidate(MI);
794
795 return true;
796}
797
798/// This version cover whole BB. There could be a BB
799/// with no control flow in it. In this case we can still pull-up a jump
800/// into it. Negative proof.
801bool HexagonGlobalSchedulerImpl::IsDualJumpFirstCandidate(
802 MachineBasicBlock *MBB) {
803 if (!PerformDualJumps)
804 return false;
805
807 MBBEnd = MBB->instr_end();
808 MII != MBBEnd; ++MII) {
809 MachineInstr *MI = &*MII;
810 if (MI->isDebugInstr())
811 continue;
812 if (!MI->isBundle() && IsNotDualJumpFirstCandidate(MI))
813 return false;
814 }
815 return true;
816}
817
818/// Is this MI could be second dual jump instruction?
819bool HexagonGlobalSchedulerImpl::IsDualJumpSecondCandidate(MachineInstr *MI) {
820 if (!PerformDualJumps)
821 return false;
822 if ((MI->isBranch() && !QII->isNewValueJump(*MI) && !MI->isIndirectBranch() &&
823 !QII->isEndLoopN(MI->getOpcode())) ||
824 (MI->isCall() && !IsIndirectCall(MI)))
825 return true;
826 return false;
827}
828
829// Since we have no exact knowledge of code layout,
830// allow some safety buffer for jump target.
831// This is measured in bytes.
832static const unsigned SafetyBuffer = 200;
833
836 MachineBasicBlock::instr_iterator MIB = MBB->instr_begin();
837 MachineBasicBlock::instr_iterator MIE = MBB->instr_end();
839 while (MII != MIE) {
840 if (!MII->isBundle() && MII->isTerminator())
841 return MII;
842 ++MII;
843 }
844 return MIE;
845}
846
847/// Check if a given instruction is:
848/// - a jump to a distant target
849/// - that exceeds its immediate range
850/// If both conditions are true, it requires constant extension.
851bool HexagonGlobalSchedulerImpl::isJumpOutOfRange(MachineInstr *MI) {
852 if (!MI || !MI->isBranch())
853 return false;
854 MachineBasicBlock *MBB = MI->getParent();
855 auto FirstTerm = getHexagonFirstInstrTerminator(MBB);
856 if (FirstTerm == MBB->instr_end())
857 return false;
858
859 unsigned InstOffset = BlockToInstOffset[MBB];
860 unsigned Distance = 0;
861 MachineBasicBlock::instr_iterator FTMII = FirstTerm;
862
863 // To save time, estimate exact position of a branch instruction
864 // as one at the end of the MBB.
865 // Number of instructions times typical instruction size.
866 InstOffset += (QII->nonDbgBBSize(MBB) * HEXAGON_INSTR_SIZE);
867
868 MachineBasicBlock *TBB = NULL, *FBB = NULL;
869 SmallVector<MachineOperand, 4> Cond;
870
871 // Try to analyze this branch.
872 if (QII->analyzeBranch(*MBB, TBB, FBB, Cond, false)) {
873 // Could not analyze it. See if this is something we can recognize.
874 // If it is a NVJ, it should always have its target in
875 // a fixed location.
876 if (QII->isNewValueJump(*FirstTerm))
877 TBB = FirstTerm->getOperand(QII->getCExtOpNum(*FirstTerm)).getMBB();
878 }
879 if (TBB && (MI == &*FirstTerm)) {
880 Distance =
881 (unsigned)std::abs((long long)InstOffset - BlockToInstOffset[TBB]) +
883 LLVM_DEBUG(dbgs() << "\tFirst term offset(" << Distance << "): ";
884 FirstTerm->dump());
885 return !QII->isJumpWithinBranchRange(*FirstTerm, Distance);
886 }
887 if (FBB) {
888 // Look for second terminator.
889 FTMII++;
890 MachineInstr *SecondTerm = &*FTMII;
891 assert(FTMII != MBB->instr_end() &&
892 (SecondTerm->isBranch() || SecondTerm->isCall()) &&
893 "Bad second terminator");
894 if (MI != SecondTerm)
895 return false;
896 // Analyze the second branch in the BB.
897 Distance =
898 (unsigned)std::abs((long long)InstOffset - BlockToInstOffset[FBB]) +
900 LLVM_DEBUG(dbgs() << "\tSecond term offset(" << Distance << "): ";
901 FirstTerm->dump());
902 return !QII->isJumpWithinBranchRange(*SecondTerm, Distance);
903 }
904 return false;
905}
906
907/// Returns true if an instruction can be promoted to .new predicate
908/// or new-value store.
909/// Performs implicit version checking.
910bool HexagonGlobalSchedulerImpl::isNewifiable(
911 MachineBasicBlock::instr_iterator MII, unsigned DepReg,
912 MachineInstr *TargetPacket) {
913 MachineInstr *MI = &*MII;
914 if (QII->isDotNewInst(*MI) ||
915 !CanNewifiedBeUsedInBundle(MII, DepReg, TargetPacket))
916 return false;
917 return (QII->isPredicated(*MI) && QII->getDotNewPredOp(*MI, nullptr) > 0) ||
918 QII->mayBeNewStore(*MI);
919}
920
921bool HexagonGlobalSchedulerImpl::DemoteToDotOld(MachineInstr *MI) {
922 int NewOpcode = QII->getDotOldOp(*MI);
923 MI->setDesc(QII->get(NewOpcode));
924 return true;
925}
926
927// initPacketizerState - Initialize packetizer flags
928void HexagonGlobalSchedulerImpl::initPacketizerState(void) {
929 CurrentPacketMIs.clear();
930 return;
931}
932
933// ignorePseudoInstruction - Ignore bundling of pseudo instructions.
934bool HexagonGlobalSchedulerImpl::ignoreInstruction(MachineInstr *MI) {
935 if (MI->isDebugInstr())
936 return true;
937
938 // We must print out inline assembly
939 if (MI->isInlineAsm())
940 return false;
941
942 // We check if MI has any functional units mapped to it.
943 // If it doesn't, we ignore the instruction.
944 const MCInstrDesc &TID = MI->getDesc();
945 unsigned SchedClass = TID.getSchedClass();
946 const InstrStage *IS =
947 ResourceTracker->getInstrItins()->beginStage(SchedClass);
948 unsigned FuncUnits = IS->getUnits();
949 return !FuncUnits;
950}
951
952// isSoloInstruction: - Returns true for instructions that must be
953// scheduled in their own packet.
954bool HexagonGlobalSchedulerImpl::isSoloInstruction(const MachineInstr &MI) {
955 if (MI.isInlineAsm())
956 return true;
957
958 if (MI.isEHLabel())
959 return true;
960
961 // From Hexagon V4 Programmer's Reference Manual 3.4.4 Grouping constraints:
962 // trap, pause, barrier, icinva, isync, and syncht are solo instructions.
963 // They must not be grouped with other instructions in a packet.
964 if (IsSchedBarrier(&MI))
965 return true;
966
967 if (MI.getOpcode() == Hexagon::A2_nop)
968 return true;
969
970 return false;
971}
972
973/// Return region ptr or null if non found.
974BasicBlockRegion *HexagonGlobalSchedulerImpl::getRegionForMBB(
975 std::vector<BasicBlockRegion *> &Regions, MachineBasicBlock *MBB) {
976 for (std::vector<BasicBlockRegion *>::iterator I = Regions.begin(),
977 E = Regions.end();
978 I != E; ++I) {
979 if ((*I)->findMBB(MBB))
980 return *I;
981 }
982 return NULL;
983}
984
985/// Select best candidate to form regions.
986static inline bool selectBestBB(BlockFrequency &BBaFreq, unsigned BBaSize,
987 BlockFrequency &BBbFreq, unsigned BBbSize) {
988 if (BBaFreq.getFrequency() > BBbFreq.getFrequency())
989 return true;
990 // TODO: This needs fine tuning.
991 // if (BBaSize < BBbSize)
992 // return true;
993 if (BBaFreq.getFrequency() == BBbFreq.getFrequency())
994 return true;
995 return false;
996}
997
998/// Returns BB pointer if one of MBB successors should be added to the
999/// current PullUp Region, NULL otherwise.
1000/// If SecondBest is defined, get next one after Best match.
1001/// Most of the time, since we practically always have only two successors,
1002/// this is "the other" BB successor which still matches original
1003/// selection criterion.
1004MachineBasicBlock *
1005HexagonGlobalSchedulerImpl::getNextPURBB(MachineBasicBlock *MBB,
1006 bool SecondBest = false) {
1007 if (!MBB)
1008 return NULL;
1009
1010 BlockFrequency BestBlockFreq = BlockFrequency(0);
1011 unsigned BestBlockSize = 0;
1012 MachineBasicBlock *BestBB = NULL;
1013 MachineBasicBlock *SecondBestBB = NULL;
1014
1015 // Catch single BB loops.
1016 for (MachineBasicBlock *Succ : MBB->successors())
1017 if (Succ == MBB)
1018 return NULL;
1019
1020 // Iterate through successors to MBB.
1021 for (MachineBasicBlock *Succ : MBB->successors()) {
1022 BlockFrequency BlockFreq = MBFI->getBlockFreq(Succ);
1023
1024 LLVM_DEBUG(dbgs() << "\tsucc BB(" << Succ->getNumber() << ") freq("
1025 << BlockFreq.getFrequency() << ")");
1026
1027 if (!SecondBest && getRegionForMBB(PullUpRegions, Succ))
1028 continue;
1029
1030 // If there is more then one predecessor to this block, do not include it.
1031 // It means there is a side entrance to it.
1032 if (Succ->pred_size() > 1)
1033 continue;
1034
1035 // If this block is a target of an indirect branch, it should
1036 // also not be included.
1037 if (Succ->isEHPad() || Succ->hasAddressTaken())
1038 continue;
1039
1040 // Get BB edge frequency.
1041 BlockFrequency EdgeFreq = BlockFreq * MBPI->getEdgeProbability(MBB, Succ);
1042 LLVM_DEBUG(dbgs() << "\tedge with freq(" << EdgeFreq.getFrequency()
1043 << ")\n");
1044
1045 if (selectBestBB(EdgeFreq, QII->nonDbgBBSize(Succ), BestBlockFreq,
1046 BestBlockSize)) {
1047 BestBlockFreq = EdgeFreq;
1048 BestBlockSize = QII->nonDbgBBSize(Succ);
1049 SecondBestBB = BestBB;
1050 BestBB = Succ;
1051 } else if (!SecondBestBB) {
1052 SecondBestBB = Succ;
1053 }
1054 }
1055 if (SecondBest)
1056 return SecondBestBB;
1057 else
1058 return BestBB;
1059}
1060
1061/// Form region to perform pull-up.
1062bool HexagonGlobalSchedulerImpl::formPullUpRegions(MachineFunction &Fn) {
1063 const Function &F = Fn.getFunction();
1064 // Check for single-block functions and skip them.
1065 if (std::next(F.begin()) == F.end())
1066 return false;
1067
1068 // Compute map for BB distances.
1069 // Offset of the current instruction from the start.
1070 unsigned InstOffset = 0;
1071
1072 LLVM_DEBUG(dbgs() << "****** Form PullUpRegions **************\n");
1073 // Loop over all basic blocks.
1074 // PullUp regions are basically traces with no side entrances.
1075 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end(); MBB != MBBe;
1076 ++MBB) {
1077 if (MBB->getAlignment() > llvm::Align(1)) {
1078 // Although we don't know the exact layout of the final code, we need
1079 // to account for alignment padding somehow. This heuristic pads each
1080 // aligned basic block according to the alignment value.
1081 int ByteAlign = MBB->getAlignment().value() - 1;
1082 InstOffset = (InstOffset + ByteAlign) & ~(ByteAlign);
1083 }
1084 // Remember BB layout offset.
1085 BlockToInstOffset[&*MBB] = InstOffset;
1087 MIE = MBB->instr_end();
1088 MII != MIE; ++MII)
1089 if (!MII->isBundle())
1090 InstOffset += QII->getSize(*MII);
1091
1092 // If this BB is already in a region, move on.
1093 if (getRegionForMBB(PullUpRegions, &*MBB))
1094 continue;
1095
1096 LLVM_DEBUG(dbgs() << "\nRoot BB(" << MBB->getNumber() << ") name("
1097 << MBB->getName() << ") size(" << QII->nonDbgBBSize(&*MBB)
1098 << ") freq(" << printBlockFreq(*MBFI, *MBB)
1099 << ") pred_size(" << MBB->pred_size() << ") in_func("
1100 << MBB->getParent()->getFunction().getName() << ")\n");
1101
1102 BasicBlockRegion *PUR = new BasicBlockRegion(TII, QRI, &*MBB);
1103 PullUpRegions.push_back(PUR);
1104
1105 for (MachineBasicBlock *MBBR = getNextPURBB(&*MBB); MBBR;
1106 MBBR = getNextPURBB(MBBR)) {
1107 LLVM_DEBUG(dbgs() << "Add BB(" << MBBR->getNumber() << ") name("
1108 << MBBR->getName() << ") size("
1109 << QII->nonDbgBBSize(MBBR) << ") freq("
1110 << printBlockFreq(*MBFI, *MBBR) << ") in_func("
1111 << MBBR->getParent()->getFunction().getName() << ")\n");
1112 PUR->addBBtoRegion(MBBR);
1113 }
1114 }
1115 return true;
1116}
1117
1118/// Return true if MI is an instruction we are unable to reason about
1119/// (like something with unmodeled memory side effects).
1121 if (MI->hasUnmodeledSideEffects() || MI->hasOrderedMemoryRef() ||
1122 MI->isCall() ||
1123 (MI->getOpcode() == Hexagon::J2_jump && !MI->getOperand(0).isMBB()))
1124 return true;
1125 return false;
1126}
1127
1128/// Gather register def/uses from MI.
1129/// This treats possible (predicated) defs
1130/// as actually happening ones (conservatively).
1131static inline void parseOperands(MachineInstr *MI,
1134 Defs.clear();
1135 Uses.clear();
1136
1137 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1138 const MachineOperand &MO = MI->getOperand(i);
1139
1140 if (MO.isReg()) {
1141 unsigned Reg = MO.getReg();
1142 if (!Reg)
1143 continue;
1145 if (MO.isUse())
1146 Uses.push_back(MO.getReg());
1147 if (MO.isDef())
1148 Defs.push_back(MO.getReg());
1149 } else if (MO.isRegMask()) {
1150 for (unsigned R = 1, NR = Hexagon::NUM_TARGET_REGS; R != NR; ++R)
1151 if (MO.clobbersPhysReg(R))
1152 Defs.push_back(R);
1153 }
1154 }
1155}
1156
1157void HexagonGlobalSchedulerImpl::MIUseDefSet(MachineInstr *MI,
1158 std::vector<unsigned> &Defs,
1159 std::vector<unsigned> &Uses) {
1160 Defs.clear();
1161 Uses.clear();
1162 assert(!MI->isBundle() && "Cannot parse regs of a bundle.");
1163 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1164 const MachineOperand &MO = MI->getOperand(i);
1165
1166 if (MO.isReg()) {
1167 unsigned Reg = MO.getReg();
1168 if (!Reg)
1169 continue;
1170 assert(Register::isPhysicalRegister(Reg));
1171 std::vector<unsigned> &Refs = MO.isUse() ? Uses : Defs;
1172 for (MCRegAliasIterator AI(MO.getReg(), QRI, true); AI.isValid(); ++AI)
1173 Refs.push_back(*AI);
1174 } else if (MO.isRegMask()) {
1175 for (unsigned R = 1, NR = Hexagon::NUM_TARGET_REGS; R != NR; ++R)
1176 if (MO.clobbersPhysReg(R))
1177 Defs.push_back(R);
1178 }
1179 }
1180}
1181
1182/// Some apparent dependencies are not actually restricting us since there
1183/// is a delay between assignment and actual usage, like in case of a call.
1184/// There could be more cases here, but this one seems the most obvious.
1186 if (MIa->isCall() && !MIb->isCall())
1187 return true;
1188 if (!MIa->isCall() && MIb->isCall())
1189 return true;
1190 return false;
1191}
1192
1193/// This is a check for resources availability and dependency
1194/// for an MI being tried for an existing bundle.
1195/// This is needed because we can:
1196/// - save time by filtering out trivial cases
1197/// - we want to reuse infrastructure that does not really knows
1198/// how to deal with parallel semantics of a bundle that already
1199/// exists. For instance, the following case:
1200/// SI %R6<def> = L2_ploadrif_io %P0<kill>, %R7, 4;
1201/// SJ %R6<def> = A2_tfr %R0;
1202/// will be happily allowed by isLegalToPacketizeTogether since in serial
1203/// semantics it never happens, and even if it does, it is legal. Not so
1204/// for when we __speculatively__ trying and MI for a bundle.
1205///
1206/// Note: This is not equivalent to MIsAreDependent().
1207/// MIsAreDependent only understands serial semantics.
1208/// These are OK to packetize together:
1209/// %R0<def> = L2_loadri_io %R18, 76; mem:LD4[%sunkaddr226](tbaa=!"int")
1210/// %R2<def> = ASL %R0<kill>, 3; flags: Inside bundle
1211///
1212bool HexagonGlobalSchedulerImpl::canAddMIToThisPacket(
1213 MachineInstr *MI,
1215 if (!MI)
1216 return false;
1217 LLVM_DEBUG(dbgs() << "\n\t[canAddMIToThisPacket]: "; MI->dump());
1218
1219 // Const extenders need custom resource checking...
1220 // Should be OK if we can update the check everywhere.
1221 if ((QII->isConstExtended(*MI) || QII->isExtended(*MI) ||
1222 isJumpOutOfRange(MI)) &&
1223 !tryAllocateResourcesForConstExt(MI, false))
1224 return false;
1225
1226 // Ask DFA if machine resource is available for MI.
1227 if (!ResourceTracker->canReserveResources(*MI) || !shouldAddToPacket(*MI)) {
1228 LLVM_DEBUG(dbgs() << "\tNo DFA resources.\n");
1229 return false;
1230 }
1231
1232 SmallVector<unsigned, 4> BundleDefs;
1233 SmallVector<unsigned, 8> BundleUses;
1234 SmallVector<unsigned, 4> Defs;
1235 SmallVector<unsigned, 8> Uses;
1236 MachineInstr *FirstCompound = NULL, *SecondCompound = NULL;
1237 MachineInstr *FirstDuplex = NULL, *SecondDuplex = NULL;
1238
1239 parseOperands(MI, Defs, Uses);
1240 for (SmallVector<MachineInstr *, HEXAGON_PACKET_SIZE>::iterator
1241 BI = Bundle.begin(),
1242 BE = Bundle.end();
1243 BI != BE; ++BI) {
1244 BundleDefs.clear();
1245 BundleUses.clear();
1246 parseOperands(*BI, BundleDefs, BundleUses);
1247
1248 MachineInstr *Inst1 = *BI;
1249 MachineInstr *Inst2 = MI;
1250
1251 if (Inst1->getParent() && OneFloatPerPacket && QII->isFloat(*Inst1) &&
1252 QII->isFloat(*Inst2))
1253 return false;
1254
1255 if (Inst1->getParent() && OneComplexPerPacket && QII->isComplex(*Inst1) &&
1256 QII->isComplex(*Inst2))
1257 return false;
1258
1260 if (QII->getCompoundCandidateGroup(**BI)) {
1261 if (!FirstCompound)
1262 FirstCompound = *BI;
1263 else {
1264 SecondCompound = *BI;
1265 if (isCompoundPair(FirstCompound, SecondCompound)) {
1266 if (MI->mayLoad() || MI->mayStore()) {
1267 LLVM_DEBUG(dbgs() << "\tPrevent compound destruction.\n");
1268 return false;
1269 }
1270 }
1271 }
1272 }
1274 if (QII->getDuplexCandidateGroup(**BI)) {
1275 if (!FirstDuplex)
1276 FirstDuplex = *BI;
1277 else {
1278 SecondDuplex = *BI;
1279 if (QII->isDuplexPair(*FirstDuplex, *SecondDuplex)) {
1280 if (MI->mayLoad() || MI->mayStore()) {
1281 LLVM_DEBUG(dbgs() << "\tPrevent duplex destruction.\n");
1282 return false;
1283 }
1284 }
1285 }
1286 }
1287
1288 for (unsigned i = 0; i < Defs.size(); i++) {
1289 // Check for multiple definitions in the same packet.
1290 for (unsigned j = 0; j < BundleDefs.size(); j++)
1291 // Multiple defs in the same packet.
1292 // Calls are OK here.
1293 // Also if we have multiple defs of PC, this simply means we are
1294 // dealing with dual jumps.
1295 if (AliasingRegs(Defs[i], BundleDefs[j]) &&
1296 !isDelayedUseException(MI, *BI) &&
1297 !(IsDualJumpFirstCandidate(*BI) && IsDualJumpSecondCandidate(MI))) {
1298 LLVM_DEBUG(dbgs() << "\tMultiple defs.\n\t"; MI->dump();
1299 dbgs() << "\t"; (*BI)->dump());
1300 return false;
1301 }
1302
1303 // See if we are creating a swap case as we go, and disallow
1304 // it for now.
1305 // Also, this is not OK:
1306 // if (!p0) r7 = r5
1307 // if (!p0) r5 = #0
1308 // But this is fine:
1309 // if (!p0) r7 = r5
1310 // if (p0) r5 = #0
1311 // Aslo - this is not a swap, but an opportunity to newify:
1312 // %P1<def> = C2_cmpeqi %R0, 0; flags:
1313 // %R0<def> = L2_ploadrif_io %P1<kill>, %R29, 8;
1314 // TODO: Handle this.
1315 for (unsigned j = 0; j < BundleUses.size(); j++)
1316 if (AliasingRegs(Defs[i], BundleUses[j])) {
1317 for (unsigned k = 0; k < BundleDefs.size(); k++)
1318 for (unsigned l = 0; l < Uses.size(); l++) {
1319 if (AliasingRegs(BundleDefs[k], Uses[l]) &&
1320 !isDelayedUseException(MI, *BI)) {
1321 LLVM_DEBUG(dbgs() << "\tSwap detected:\n\t"; MI->dump();
1322 dbgs() << "\t"; (*BI)->dump());
1323 return false;
1324 }
1325 }
1326 }
1327 }
1328
1329 for (unsigned i = 0; i < Uses.size(); i++) {
1330 // Check for true data dependency.
1331 for (unsigned j = 0; j < BundleDefs.size(); j++)
1332 if (AliasingRegs(Uses[i], BundleDefs[j]) &&
1333 !isDelayedUseException(MI, *BI)) {
1334 LLVM_DEBUG(dbgs() << "\tImmediate Use detected on reg("
1335 << printReg(Uses[i], QRI) << ")\n\t";
1336 MI->dump(); dbgs() << "\t"; (*BI)->dump());
1337 // TODO: This could be an opportunity for newifying:
1338 // %P0<def> = C2_cmpeqi %R26, 0
1339 // %R26<def> = A2_tfr %R0<kill>
1340 // if (CanPromoteToDotNew(MI, Uses[i]))
1341 // LLVM_DEBUG(dbgs() << "\tCan promoto to .new form.\n");
1342 // else
1343 return false;
1344 }
1345 }
1346
1347 // For calls we also check callee save regs.
1348 if ((*BI)->isCall()) {
1349 for (const uint16_t *I = QRI->getCalleeSavedRegs(&MF); *I; ++I) {
1350 for (unsigned i = 0; i < Defs.size(); i++) {
1351 if (AliasingRegs(Defs[i], *I)) {
1352 LLVM_DEBUG(dbgs() << "\tAlias with call.\n");
1353 return false;
1354 }
1355 }
1356 }
1357 }
1358
1359 // If this is return, we are probably speculating (otherwise
1360 // we could not pull in there) and will not win from pulling
1361 // into this location anyhow.
1362 // Example: a side exit.
1363 // if (!p0) dealloc_return
1364 // TODO: Can check that we do not overwrite return value
1365 // and proceed.
1366 if ((*BI)->isBarrier()) {
1367 LLVM_DEBUG(dbgs() << "\tBarrier interference.\n");
1368 return false;
1369 }
1370
1371 // \ref-manual (7.3.4) A loop setup packet in loopN or spNloop0 cannot
1372 // contain a speculative indirect jump,
1373 // a new-value compare jump or a dealloc_return.
1374 // Speculative indirect jumps (predicate + .new + indirect):
1375 // if ([!]Ps.new) jumpr:t Rs
1376 // if ([!]Ps.new) jumpr:nt Rs
1377 // @note: We don't want to pull across a call to be on the safe side.
1378 if (QII->isLoopN(*MI) &&
1379 ((QII->isPredicated(**BI) && QII->isPredicatedNew(**BI) &&
1380 QII->isJumpR(**BI)) ||
1381 QII->isNewValueJump(**BI) || QII->isDeallocRet(**BI) ||
1382 (*BI)->isCall())) {
1383 LLVM_DEBUG(dbgs() << "\tLoopN pull interference.\n");
1384 return false;
1385 }
1386
1387 // The opposite is also true.
1388 if (QII->isLoopN(**BI) &&
1389 ((QII->isPredicated(*MI) && QII->isPredicatedNew(*MI) &&
1390 QII->isJumpR(*MI)) ||
1391 QII->isNewValueJump(*MI) || QII->isDeallocRet(*MI) || MI->isCall())) {
1392 LLVM_DEBUG(dbgs() << "\tResident LoopN.\n");
1393 return false;
1394 }
1395
1396 // @todo \ref-manual 7.6.1
1397 // Presence of NVJ adds more restrictions.
1398 if (QII->isNewValueJump(**BI) &&
1399 (MI->mayStore() || MI->getOpcode() == Hexagon::S2_allocframe ||
1400 MI->isCall())) {
1401 LLVM_DEBUG(dbgs() << "\tNew val Jump.\n");
1402 return false;
1403 }
1404
1405 // For memory operations, check aliasing.
1406 // First, be conservative on these objects. Might be overly constraining,
1407 // so recheck.
1409 // Currently it catches things like this:
1410 // S2_storerinew_io %R29, 32, %R16
1411 // S2_storeri_io %R29, 68, %R0
1412 // which we can reason about.
1413 // TODO: revisit.
1414 return false;
1415
1416 // If packet has a new-value store, MI can't be a store instruction.
1417 if (QII->isNewValueStore(**BI) && MI->mayStore()) {
1418 LLVM_DEBUG(dbgs() << "\tNew Value Store to store.\n");
1419 return false;
1420 }
1421
1422 if ((QII->isMemOp(**BI) && MI->mayStore()) ||
1423 (QII->isMemOp(*MI) && (*BI)->mayStore())) {
1424 LLVM_DEBUG(
1425 dbgs() << "\tSlot 0 not available for store because of memop.\n");
1426 return false;
1427 }
1428
1429 // If any of these is true, check aliasing.
1430 if ((MI->mayLoad() && (*BI)->mayStore()) ||
1431 (MI->mayStore() && (*BI)->mayLoad()) ||
1432 (MI->mayStore() && (*BI)->mayStore())) {
1433 if (QII->areMemAccessesDependent(AA, MI, *BI)) {
1434 LLVM_DEBUG(dbgs() << "\tAliasing detected:\n\t"; MI->dump();
1435 dbgs() << "\t"; (*BI)->dump());
1436 return false;
1437 }
1438 }
1439 // Do not move an instruction to this packet if this packet
1440 // already contains a speculated instruction.
1441 std::map<MachineInstr *, MachineBasicBlock *>::iterator MIMoved;
1442 MIMoved = SpeculatedIns.find(*BI);
1443 if ((MIMoved != SpeculatedIns.end()) &&
1444 (MIMoved->second != (*BI)->getParent())) {
1445 LLVM_DEBUG(
1446 dbgs() << "This packet already contains a speculated instruction";
1447 (*BI)->dump(););
1448 return false;
1449 }
1450 }
1451
1452 // Do not pull-up vector instructions because these instructions have
1453 // multi-cycle latencies, and the pull-up pass doesn't correctly account
1454 // for instructions that stall for more than one cycle.
1455 if (QII->isHVXVec(*MI))
1456 return false;
1457
1458 return true;
1459}
1460
1461/// Classify the dependence between \p MIa (an instruction resident in the
1462/// bundle) and \p MIb (the instruction being moved): DepKind::Dependent if
1463/// they cannot share a packet, Independent if freely reorderable, or
1464/// WAR_SameBundle for a def/use pair legal only when \p MIb joins \p MIa's
1465/// packet.
1466///
1467/// Anti-symmetric: the WAR_SameBundle carve-out applies only when \p MIa
1468/// *defines* a register \p MIb *uses*; the reverse is always Dependent. So
1469/// argument order matters: always pass the instruction being moved as \p MIb.
1470DepKind HexagonGlobalSchedulerImpl::analyzeDependence(MachineInstr *MIa,
1471 MachineInstr *MIb) {
1472 if (MIa == MIb)
1473 return DepKind::Independent;
1474
1475 bool sameBundle =
1476 MIa->isBundled() && MIb->isBundled() &&
1478 bool foundBundleWAR = false;
1479
1480 SmallVector<unsigned, 4> DefsA;
1481 SmallVector<unsigned, 4> DefsB;
1482 SmallVector<unsigned, 8> UsesA;
1483 SmallVector<unsigned, 8> UsesB;
1484
1485 parseOperands(MIa, DefsA, UsesA);
1486 parseOperands(MIb, DefsB, UsesB);
1487
1488 for (SmallVector<unsigned, 4>::iterator IDA = DefsA.begin(),
1489 IDAE = DefsA.end();
1490 IDA != IDAE; ++IDA) {
1491 for (SmallVector<unsigned, 8>::iterator IUB = UsesB.begin(),
1492 IUBE = UsesB.end();
1493 IUB != IUBE; ++IUB)
1494 // MIa defines a register that MIb reads. In one packet MIb reads the old
1495 // value, so moving MIb out of the packet may be safe.
1496 if (AliasingRegs(*IDA, *IUB)) {
1497 if (sameBundle && EnableDefUseSamePacket) {
1498 int DefIdx = MIa->findRegisterDefOperandIdx(*IDA, QRI);
1499 int UseIdx = MIb->findRegisterUseOperandIdx(*IUB, QRI);
1500 // DefIdx < 0 means *IDA has no explicit def operand: parseOperands
1501 // surfaced it from a regmask clobber, which never forwards a value.
1502 bool DefViaRegMask = DefIdx < 0;
1503 if (UseIdx >= 0 && QII->isSafeInBundleWAR(
1504 *MIa, DefViaRegMask ? 0 : DefIdx, *MIb, UseIdx,
1505 /*IsPullDown=*/false, DefViaRegMask)) {
1506 foundBundleWAR = true;
1507 continue;
1508 }
1509 }
1510 return DepKind::Dependent;
1511 }
1512
1513 for (SmallVector<unsigned, 4>::iterator IDB = DefsB.begin(),
1514 IDBE = DefsB.end();
1515 IDB != IDBE; ++IDB)
1516 // Output dependency.
1517 if (AliasingRegs(*IDA, *IDB))
1518 return DepKind::Dependent;
1519 }
1520
1521 for (SmallVector<unsigned, 4>::iterator IDB = DefsB.begin(),
1522 IDBE = DefsB.end();
1523 IDB != IDBE; ++IDB) {
1524 for (SmallVector<unsigned, 8>::iterator IUA = UsesA.begin(),
1525 IUAE = UsesA.end();
1526 IUA != IUAE; ++IUA)
1527 // WAR: MIb defs, MIa uses.
1528 if (AliasingRegs(*IDB, *IUA))
1529 return DepKind::Dependent;
1530 }
1531
1532 // Do not reorder two calls...
1533 if (MIa->isCall() && MIb->isCall())
1534 return DepKind::Dependent;
1535
1536 // For calls we also check callee save regs.
1537 if (MIa->isCall())
1538 for (const uint16_t *I = QRI->getCalleeSavedRegs(&MF); *I; ++I) {
1539 for (unsigned i = 0; i < DefsB.size(); i++) {
1540 if (AliasingRegs(DefsB[i], *I))
1541 return DepKind::Dependent;
1542 }
1543 }
1544
1545 if (MIb->isCall())
1546 for (const uint16_t *I = QRI->getCalleeSavedRegs(&MF); *I; ++I) {
1547 for (unsigned i = 0; i < DefsA.size(); i++) {
1548 if (AliasingRegs(DefsA[i], *I))
1549 return DepKind::Dependent;
1550 }
1551 }
1552
1553 // For memory operations, check aliasing.
1554 // First, be conservative on these objects.
1555 // Might be overly constraining, so recheck.
1556 if ((isGlobalMemoryObject(MIa)) || (isGlobalMemoryObject(MIb)))
1557 return DepKind::Dependent;
1558
1559 // If any of these is true, check aliasing.
1560 if (((MIa->mayLoad() && MIb->mayStore()) ||
1561 (MIa->mayStore() && MIb->mayLoad()) ||
1562 (MIa->mayStore() && MIb->mayStore())) &&
1563 QII->areMemAccessesDependent(AA, MIa, MIb))
1564 return DepKind::Dependent;
1565
1566 return foundBundleWAR ? DepKind::WAR_SameBundle : DepKind::Independent;
1567}
1568
1569/// Serial semantics.
1570bool HexagonGlobalSchedulerImpl::MIsAreDependent(MachineInstr *MIa,
1571 MachineInstr *MIb) {
1572 if (MIa == MIb)
1573 return false;
1574
1575 if (ReorderDependencyTest(MIa, MIb)) {
1576 LLVM_DEBUG(dbgs() << "\t\t[MIsAreDependent]:\n\t\t"; MIa->dump();
1577 dbgs() << "\t\t"; MIb->dump());
1578 return true;
1579 }
1580 return false;
1581}
1582
1583/// Serial semantics.
1584bool HexagonGlobalSchedulerImpl::MIsHaveTrueDependency(MachineInstr *MIa,
1585 MachineInstr *MIb) {
1586 if (MIa == MIb)
1587 return false;
1588
1589 SmallVector<unsigned, 4> DefsA;
1590 SmallVector<unsigned, 4> DefsB;
1591 SmallVector<unsigned, 8> UsesA;
1592 SmallVector<unsigned, 8> UsesB;
1593
1594 parseOperands(MIa, DefsA, UsesA);
1595 parseOperands(MIb, DefsB, UsesB);
1596
1597 for (SmallVector<unsigned, 4>::iterator IDA = DefsA.begin(),
1598 IDAE = DefsA.end();
1599 IDA != IDAE; ++IDA) {
1600 for (SmallVector<unsigned, 8>::iterator IUB = UsesB.begin(),
1601 IUBE = UsesB.end();
1602 IUB != IUBE; ++IUB)
1603 // True data dependency.
1604 if (AliasingRegs(*IDA, *IUB))
1605 return true;
1606 }
1607 return false;
1608}
1609
1610/// Sequential semantics. Can these two MIs be reordered?
1611/// Moving MIa from "behind" to "in front" of MIb.
1612bool HexagonGlobalSchedulerImpl::canReorderMIs(MachineInstr *MIa,
1613 MachineInstr *MIb) {
1614 if (!MIa || !MIb)
1615 return false;
1616
1617 // Within bundle semantics are parallel.
1618 if (MIa->isBundle()) {
1619 // WAR_SameBundle = ISA-safe in-bundle def/use pair; treat as reorderable.
1622 for (++MII; MII != MIIE && MII->isInsideBundle(); ++MII) {
1623 if (MII->isDebugInstr())
1624 continue;
1625 DepKind dk = analyzeDependence(&*MII, MIb);
1626 if (dk == DepKind::Independent)
1627 continue;
1628 LLVM_DEBUG(dbgs() << "\t\t[MIsAreDependent]:\n\t\t"; (*MII).dump();
1629 dbgs() << "\t\t"; MIb->dump());
1630 if (dk == DepKind::WAR_SameBundle) {
1631 LLVM_DEBUG(dbgs() << "\t\t[canReorderMIs] WAR_SameBundle, allow.\n");
1632 continue;
1633 }
1634 return false;
1635 }
1636 return true;
1637 }
1638 return !MIsAreDependent(MIa, MIb);
1639}
1640
1642 if (MI->isInlineAsm() || MI->isEHLabel() || IsSchedBarrier(MI))
1643 return true;
1644 return false;
1645}
1646
1648 if (MI->isBranch() || MI->isReturn() || MI->isCall() || MI->isBarrier() ||
1649 MI->isTerminator() || MIMustNotBePulledUp(MI))
1650 return true;
1651 return false;
1652}
1653
1654// Only approve dual jump candidate:
1655// It is a branch, and we move it to last packet of the target location.
1656bool HexagonGlobalSchedulerImpl::MIisDualJumpCandidate(
1657 MachineInstr *MI, MachineBasicBlock::iterator &WorkPoint) {
1658 if (!PerformDualJumps || !IsDualJumpSecondCandidate(MI) ||
1659 MIMustNotBePulledUp(MI) || ignoreInstruction(MI))
1660 return false;
1661
1662 MachineBasicBlock *FromThisBB = MI->getParent();
1663 MachineBasicBlock *ToThisBB = WorkPoint->getParent();
1664
1665 LLVM_DEBUG(dbgs() << "\t\t[MIisDualJumpCandidate] To BB("
1666 << ToThisBB->getNumber() << ") From BB("
1667 << FromThisBB->getNumber() << ")\n");
1668 // If the question is about the same BB, we do not want to get
1669 // dual jump involved - it is a different case.
1670 if (FromThisBB == ToThisBB)
1671 return false;
1672
1673 // Dual jump could only be done on neigboring BBs.
1674 // The FromThisBB must only have one predecessor - the basic
1675 // block we are trying to merge.
1676 if ((*(FromThisBB->pred_begin()) != ToThisBB) ||
1677 (std::next(FromThisBB->pred_begin()) != FromThisBB->pred_end()))
1678 return false;
1679
1680 // If this block is a target of an indirect branch, it should
1681 // also not be included.
1682 if (FromThisBB->isEHPad() || FromThisBB->hasAddressTaken())
1683 return false;
1684
1685 // Now we must preserve original fall through paths. In fact we
1686 // might be dealing with 3way branching.
1687 MachineBasicBlock *ToTBB = NULL, *ToFBB = NULL;
1688
1689 if (ToThisBB->succ_size() == 2) {
1690 // Check the branch from target block.
1691 // If we have two successors, we must understand the branch.
1692 SmallVector<MachineOperand, 4> ToCond;
1693 if (!QII->analyzeBranch(*ToThisBB, ToTBB, ToFBB, ToCond, false)) {
1694 // Have the branch. Check the topology.
1695 LLVM_DEBUG(dbgs() << "\t\tToThisBB has two successors: TBB("
1696 << ToTBB->getNumber() << ") and FBB(";
1697 if (ToFBB) dbgs() << ToFBB->getNumber() << ").\n";
1698 else dbgs() << "None"
1699 << ").\n";);
1700 if (ToTBB == FromThisBB) {
1701 // If the from BB is not the fall through, we can only handle case
1702 // when second branch is unconditional jump.
1703 return false;
1704 } else if (ToFBB == FromThisBB || !ToFBB) {
1705 // If the fall through path of ToBB is our FromBB, we have more freedom
1706 // of operation.
1707 LLVM_DEBUG(dbgs() << "\t\tFall through jump target.\n");
1708 }
1709 } else {
1710 LLVM_DEBUG(dbgs() << "\t\tUnable to analyze first branch.\n");
1711 return false;
1712 }
1713 } else if (ToThisBB->succ_size() == 1) {
1714 ToFBB = *ToThisBB->succ_begin();
1715 assert(ToFBB == FromThisBB && "Bad CFG layout");
1716 } else
1717 return false;
1718
1719 // First unbundled control flow instruction in the BB.
1720 if (!MI->isBundled() && MI == &*FromThisBB->getFirstNonDebugInstr())
1721 return IsDualJumpFirstCandidate(WorkPoint);
1722
1723 return false;
1724}
1725
1726// Check whether moving MI to MJ's packet would cause a stall from a previous
1727// packet.
1728bool HexagonGlobalSchedulerImpl::canCauseStall(MachineInstr *MI,
1729 MachineInstr *MJ) {
1730 SmallVector<unsigned, 4> DefsMJI;
1731 SmallVector<unsigned, 8> UsesMJI;
1732 SmallVector<unsigned, 4> DefsMI;
1733 SmallVector<unsigned, 8> UsesMI;
1734 parseOperands(MI, DefsMI, UsesMI);
1735
1736 for (auto Use : UsesMI) {
1737 int UseIdx = MI->findRegisterUseOperandIdx(Use, /*TRI=*/nullptr);
1738 if (UseIdx == -1)
1739 continue;
1740 bool ShouldBreak = false;
1741 int BundleCount = 0;
1743 Begin = MJ->getParent()->instr_begin(),
1744 MJI = MJ->getIterator();
1745 MJI != Begin; --MJI) {
1746 if (MJI->isBundle()) {
1747 ++BundleCount;
1748 continue;
1749 }
1750 parseOperands(&*MJI, DefsMJI, UsesMJI);
1751 for (auto Def : DefsMJI) {
1752 if (Def == Use || AliasingRegs(Def, Use)) {
1753 int DefIdx = MJI->findRegisterDefOperandIdx(Def, /*TRI=*/nullptr);
1754 if (DefIdx >= 0) {
1755 int Latency =
1756 TSchedModel.computeOperandLatency(&*MJI, DefIdx, MI, UseIdx);
1757 Latency = MF.getSubtarget<HexagonSubtarget>().updateLatency(
1758 *MJI, *MI, false, Latency);
1759 if (Latency > BundleCount)
1760 // There will be a stall if MI is moved to MJ's packet.
1761 return true;
1762 // We found the def for the use and it does not cause a stall.
1763 // Continue checking the next use for a potential stall.
1764 ShouldBreak = true;
1765 break;
1766 }
1767 }
1768 }
1769 if (ShouldBreak)
1770 break;
1771 if (!MJI->isBundled() && !MJI->isDebugInstr())
1772 ++BundleCount;
1773 }
1774 }
1775 return false;
1776}
1777
1778/// Analyze this instruction. If this is an unbundled instruction, see
1779/// if it in theory could be packetized.
1780/// If it is already part of a packet, see if it has internal
1781/// dependencies to this packet.
1782bool HexagonGlobalSchedulerImpl::canThisMIBeMoved(
1783 MachineInstr *MI, MachineBasicBlock::iterator &WorkPoint,
1784 bool &MovingDependentOp, int &Cost) {
1785 if (!MI)
1786 return false;
1787 // By default, it is a normal move.
1788 MovingDependentOp = false;
1789 Cost = 0;
1790 // If MI is a 'formed' compound not potential compound, bail out.
1791 if (QII->isCompoundBranchInstr(*MI))
1792 return false;
1793 // See if we can potentially break potential compound candidates,
1794 // and do not do it.
1795 if (PreventCompoundSeparation && MI->isBundled()) {
1797 if (MICG != HexagonII::HCG_None) {
1798 // Check internal dependencies in the bundle.
1799 // First, find the bundle header.
1800 MachineBasicBlock::instr_iterator MII = MI->getIterator();
1801 for (--MII; MII->isBundled(); --MII)
1802 if (MII->isBundle())
1803 break;
1804
1805 MachineBasicBlock::instr_iterator BBEnd = MI->getParent()->instr_end();
1806 for (++MII; MII != BBEnd && MII->isInsideBundle() && !MII->isBundle();
1807 ++MII) {
1808 if (&(*MII) == MI)
1809 continue;
1810 if (isCompoundPair(&*MII, MI)) {
1811 LLVM_DEBUG(dbgs() << "\tPrevent Compound separation.\n");
1812 return false;
1813 }
1814 }
1815 }
1816 }
1817 // Same thing for duplex candidates.
1818 if (PreventDuplexSeparation && MI->isBundled()) {
1820 // Check internal dependencies in the bundle.
1821 // First, find the bundle header.
1822 MachineBasicBlock::instr_iterator MII = MI->getIterator();
1823 for (--MII; MII->isBundled(); --MII)
1824 if (MII->isBundle())
1825 break;
1826
1827 MachineBasicBlock::instr_iterator BBEnd = MI->getParent()->instr_end();
1828 for (++MII; MII != BBEnd && MII->isInsideBundle() && !MII->isBundle();
1829 ++MII) {
1830 if ((&(*MII) != MI) && QII->isDuplexPair(*MII, *MI)) {
1831 LLVM_DEBUG(dbgs() << "\tPrevent Duplex separation.\n");
1832 return false;
1833 }
1834 }
1835 }
1836 }
1837
1838 // If we perform dual jump formation during the pull-up,
1839 // then we want to consider several additional situations.
1840 // a) Allow moving of dependent instruction from a packet
1841 // b) Allow moving some control flow instructions if they meet
1842 // dual jump criteria.
1843 if (MIisDualJumpCandidate(MI, WorkPoint)) {
1844 LLVM_DEBUG(dbgs() << "\t\tDual jump candidate:\t"; MI->dump());
1845 // Here we are breaking our general assumption about not moving dependent
1846 // instructions. To save us two more expensive checks down the line,
1847 // propagate the information directly.
1848 MovingDependentOp = true;
1849 return true;
1850 }
1851
1852 // Any of these should not even be tried.
1853 if (MIShouldNotBePulledUp(MI) || ignoreInstruction(MI))
1854 return false;
1855 // Pulling up these instructions could put them
1856 // out of jump range/offset size.
1857 if (QII->isLoopN(*MI)) {
1858 unsigned dist_looplabel =
1859 BlockToInstOffset.find(MI->getOperand(0).getMBB())->second;
1860 unsigned dist_newloop0 =
1861 BlockToInstOffset.find(WorkPoint->getParent())->second;
1862 // Check if the jump in the last instruction is within range.
1863 unsigned Distance =
1864 (unsigned)std::abs((long long)dist_looplabel - dist_newloop0) +
1865 QII->nonDbgBBSize(WorkPoint->getParent()) * 4 + SafetyBuffer;
1866 const HexagonInstrInfo *HII = (const HexagonInstrInfo *)TII;
1867 if (!HII->isJumpWithinBranchRange(*MI, Distance)) {
1868 LLVM_DEBUG(dbgs() << "\nloopN cannot be moved since Distance: "
1869 << Distance << " outside branch range.";);
1870 return false;
1871 }
1872 LLVM_DEBUG(dbgs() << "\nloopN can be moved since Distance: " << Distance
1873 << " within branch range.";);
1874 }
1875 // If the def-set of an MI is one of the live-ins then MI should
1876 // kill that reg and no instruction before MI should use it.
1877 // For simplicity, allow only if MI is the first instruction in the MBB.
1878 std::map<MachineInstr *, std::vector<unsigned>>::const_iterator DefIter =
1879 MIDefSet.find(MI);
1880 MachineBasicBlock *MBB = MI->getParent();
1881 for (unsigned i = 0; DefIter != MIDefSet.end() && i < DefIter->second.size();
1882 ++i) {
1883 if (MBB->isLiveIn(DefIter->second[i]) &&
1885 return false;
1886 }
1887 // If it is part of a bundle, analyze it.
1888 if (MI->isBundled()) {
1889 // Cannot move bundle header itself. This function is about
1890 // individual MI move.
1891 if (MI->isBundle())
1892 return false;
1893
1894 // Check internal dependencies in the bundle.
1895 // First, find the bundle header.
1896 MachineBasicBlock::instr_iterator MII = MI->getIterator();
1897 for (--MII; MII->isBundled(); --MII)
1898 if (MII->isBundle())
1899 break;
1900
1901 MachineBasicBlock::instr_iterator BBEnd = MI->getParent()->instr_end();
1902 for (++MII; MII != BBEnd && MII->isInsideBundle() && !MII->isBundle();
1903 ++MII) {
1904 if (MII->isDebugInstr())
1905 continue;
1906 DepKind dk = analyzeDependence(&*MII, MI);
1907 if (dk == DepKind::Independent)
1908 continue;
1909 LLVM_DEBUG(dbgs() << "\t\t[MIsAreDependent]:\n\t\t"; (*MII).dump();
1910 dbgs() << "\t\t"; MI->dump());
1911 if (dk == DepKind::WAR_SameBundle) {
1912 LLVM_DEBUG(dbgs() << "\t\t[canThisMIBeMoved] WAR_SameBundle, allow.\n");
1913 continue;
1914 }
1915 if (!AllowDependentPullUp) {
1916 LLVM_DEBUG(dbgs() << "\t\tDependent.\n");
1917 return false;
1918 } else {
1919 // There are a few cases that we can safely move a dependent
1920 // instruction away from this packet.
1921 // One example is an instruction setting a call operands.
1922 if ((MII->isCall() && !IsIndirectCall(&*MII)) ||
1923 IsDualJumpSecondCandidate(&*MII) || MI->isBranch()) {
1924 LLVM_DEBUG(dbgs() << "\t\tDependent, but allow to move.\n");
1925 MovingDependentOp = true;
1926 Cost -= 10;
1927 continue;
1928 } else {
1929 LLVM_DEBUG(dbgs() << "\t\tDependent, and do not allow for now.\n");
1930 return false;
1931 }
1932 }
1933 }
1934 }
1935 return true;
1936}
1937
1938/// Return true if MI defines a predicate and parse all defs.
1939bool HexagonGlobalSchedulerImpl::doesMIDefinesPredicate(
1940 MachineInstr *MI, SmallVector<unsigned, 4> &Defs) {
1941 bool defsPredicate = false;
1942 Defs.clear();
1943
1944 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1945 const MachineOperand &MO = MI->getOperand(i);
1946
1947 // Regmasks are considered "implicit".
1948 if (!MO.isReg())
1949 continue;
1950 unsigned Reg = MO.getReg();
1951
1952 if (!Reg || QRI->isFakeReg(Reg))
1953 continue;
1954
1955 assert(Register::isPhysicalRegister(Reg));
1956
1957 if (MO.isDef() && !MO.isImplicit()) {
1958 const TargetRegisterClass *RC = QRI->getMinimalPhysRegClass(Reg);
1959 if (RC == &Hexagon::PredRegsRegClass) {
1960 defsPredicate = true;
1961 Defs.push_back(MO.getReg());
1962 }
1963 }
1964 }
1965 return defsPredicate;
1966}
1967
1968/// We have just tentatively added a predicated MI to an existing packet.
1969/// Now we need to determine if it needs to be changed to .new form.
1970/// It only handles compare/predicate right now.
1971/// TODO - clean this logic up.
1972/// TODO - generalize to handle any .new
1973bool HexagonGlobalSchedulerImpl::NeedToNewify(
1974 MachineBasicBlock::instr_iterator NewMI, unsigned *DepReg,
1975 MachineInstr *TargetPacket = NULL) {
1977 SmallVector<unsigned, 4> DefsA;
1978 SmallVector<unsigned, 4> DefsB;
1979 SmallVector<unsigned, 8> UsesB;
1980
1981 // If this is not a normal bundle, we are probably
1982 // trying to size two lonesome instructions together,
1983 // and trying to say if one of them will need to be
1984 // newified. In this is the case we have something like this:
1985 // BB#5:
1986 // %P0<def> = CMPGEri %R4, 2
1987 // S2_pstorerif_io %P0<kill>, %R29, 16, %R21<kill>
1988 // BUNDLE %R7<imp-def>, %R4<imp-def>, %R7<imp-use>
1989 parseOperands(&*NewMI, DefsB, UsesB);
1990 if (TargetPacket && !TargetPacket->isBundled()) {
1991 if (doesMIDefinesPredicate(TargetPacket, DefsA)) {
1992 for (SmallVector<unsigned, 4>::iterator IA = DefsA.begin(),
1993 IAE = DefsA.end();
1994 IA != IAE; ++IA)
1995 for (SmallVector<unsigned, 8>::iterator IB = UsesB.begin(),
1996 IBE = UsesB.end();
1997 IB != IBE; ++IB)
1998 if (*IA == *IB) {
1999 *DepReg = *IA;
2000 return true;
2001 }
2002 }
2003 return false;
2004 }
2005
2006 // Find bundle header.
2007 for (--MII; MII->isBundled(); --MII)
2008 if (MII->isBundle())
2009 break;
2010
2011 // Iterate down, if there is data dependent cmp found, need to .newify.
2012 // Also, we can have the following:
2013 // {
2014 // p0 = r7
2015 // if (!p0.new) jump:t .LBB4_18
2016 // if (p0.new) r8 = zxth(r12)
2017 // }
2018 MachineBasicBlock::instr_iterator BBEnd = MII->getParent()->instr_end();
2019 for (++MII; MII != BBEnd && MII->isBundled() && !MII->isBundle(); ++MII) {
2020 if (MII == NewMI)
2021 continue;
2022 if (doesMIDefinesPredicate(&*MII, DefsA)) {
2023 for (SmallVector<unsigned, 4>::iterator IA = DefsA.begin(),
2024 IAE = DefsA.end();
2025 IA != IAE; ++IA)
2026 for (SmallVector<unsigned, 8>::iterator IB = UsesB.begin(),
2027 IBE = UsesB.end();
2028 IB != IBE; ++IB)
2029 // We do not have multiple predicate regs defined in any instruction,
2030 // if we ever will, this needs to be generalized.
2031 if (*IA == *IB) {
2032 *DepReg = *IA;
2033 return true;
2034 }
2035 DefsA.clear();
2036 }
2037 }
2038 LLVM_DEBUG(dbgs() << "\nNo need to newify:"; NewMI->dump());
2039 return false;
2040}
2041
2042/// We know this instruction needs to be newified to be added to the packet,
2043/// but not all combinations are legal.
2044/// It is a complimentary check to NeedToNewify().
2045/// The packet actually contains the new instruction during the check.
2046bool HexagonGlobalSchedulerImpl::CanNewifiedBeUsedInBundle(
2047 MachineBasicBlock::instr_iterator NewMI, unsigned DepReg,
2048 MachineInstr *TargetPacket) {
2050 if (!TargetPacket || !TargetPacket->isBundled())
2051 return true;
2052
2053 // Find the bundle header.
2054 for (--MII; MII->isBundled(); --MII)
2055 if (MII->isBundle())
2056 break;
2057
2058 MachineBasicBlock::instr_iterator BBEnd = MII->getParent()->instr_end();
2059 for (++MII; MII != BBEnd && MII->isBundled() && !MII->isBundle(); ++MII) {
2060 // Effectively we look for the case of late predicates.
2061 // No additional checks at the time.
2062 if (MII == NewMI || !QII->isPredicateLate(MII->getOpcode()))
2063 continue;
2064 SmallVector<unsigned, 4> DefsA;
2065 if (!doesMIDefinesPredicate(&*MII, DefsA))
2066 continue;
2067 for (auto &IA : DefsA)
2068 if (IA == DepReg)
2069 return false;
2070 }
2071 return true;
2072}
2073
2074/// setUsed - Set the register and its sub-registers as being used.
2075/// Similar to RegScavenger::setUsed().
2076void HexagonGlobalSchedulerImpl::setUsedRegs(BitVector &Set, unsigned Reg) {
2077 Set.reset(Reg);
2078 for (MCSubRegIterator SubRegs(Reg, QRI); SubRegs.isValid(); ++SubRegs)
2079 Set.reset(*SubRegs);
2080}
2081
2082/// Are these two registers overlaping?
2083bool HexagonGlobalSchedulerImpl::AliasingRegs(unsigned RegA, unsigned RegB) {
2084 if (RegA == RegB)
2085 return true;
2086
2087 for (MCSubRegIterator SubRegs(RegA, QRI); SubRegs.isValid(); ++SubRegs)
2088 if (RegB == *SubRegs)
2089 return true;
2090
2091 for (MCSubRegIterator SubRegs(RegB, QRI); SubRegs.isValid(); ++SubRegs)
2092 if (RegA == *SubRegs)
2093 return true;
2094
2095 return false;
2096}
2097
2098/// Find use with this reg, and unmark the kill flag.
2099static inline void unmarkKillReg(MachineInstr *MI, unsigned Reg) {
2100 if (MI->isDebugInstr())
2101 return;
2102
2103 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2104 MachineOperand &MO = MI->getOperand(i);
2105
2106 if (!MO.isReg())
2107 continue;
2108
2109 if (MO.isKill() && (MO.getReg() == Reg))
2110 MO.setIsKill(false);
2111 }
2112}
2113
2114/// Find use with this reg, and unmark the kill flag.
2115static inline void markKillReg(MachineInstr *MI, unsigned Reg) {
2116 if (MI->isDebugInstr())
2117 return;
2118
2119 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2120 MachineOperand &MO = MI->getOperand(i);
2121
2122 if (!MO.isReg())
2123 continue;
2124
2125 if (MO.isUse() && (MO.getReg() == Reg))
2126 MO.setIsKill(true);
2127 }
2128}
2129
2130/// We have just moved an instruction that could have changed kill patterns
2131/// along the path it was moved. We need to update it.
2132void HexagonGlobalSchedulerImpl::updateKillAlongThePath(
2133 MachineBasicBlock *HomeBB, MachineBasicBlock *OriginBB,
2136 MachineBasicBlock::iterator &SourcePacket,
2137 MachineBasicBlock::iterator &TargetPacket,
2138 std::vector<MachineInstr *> &backtrack) {
2139 // This is the instruction being moved.
2140 MachineInstr *MI = &*Head;
2141 MachineBasicBlock *CurrentBB = OriginBB;
2142 SmallSet<unsigned, 8> KilledUseSet;
2143
2144 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2145 const MachineOperand &MO = MI->getOperand(i);
2146 if (!MO.isReg())
2147 continue;
2148 unsigned Reg = MO.getReg();
2149 if (!Reg)
2150 continue;
2151
2152 if (MO.isKill())
2153 KilledUseSet.insert(Reg);
2154 }
2155
2156 // If there are no kills here, we are done.
2157 if (KilledUseSet.empty())
2158 return;
2159
2160 LLVM_DEBUG(dbgs() << "\n[updateKillAlongThePath]\n");
2161 LLVM_DEBUG(dbgs() << "\t\tInstrToMove :\t"; MI->dump());
2162 LLVM_DEBUG(dbgs() << "\t\tSourceLocation:\n";
2163 DumpPacket(SourcePacket.getInstrIterator()));
2164 LLVM_DEBUG(dbgs() << "\t\tTargetPacket :\n";
2165 DumpPacket(TargetPacket.getInstrIterator()));
2166 LLVM_DEBUG(dbgs() << "\tUpdate Kills. Need to update (" << KilledUseSet.size()
2167 << ")kills. From BB (" << OriginBB->getNumber() << ")\n");
2168 LLVM_DEBUG(dbgs() << "\tMove path:\n");
2169 assert(!backtrack.empty() && "Empty back track");
2170
2171 // We have pulled up an instruction, with one of its uses marked as kill.
2172 // If there is any other use of the same register along the move path,
2173 // and there are no side exits with killed register live-in along them,
2174 // we need to mark last use of that reg as kill.
2175 for (signed i = backtrack.size() - 1; i >= 0; --i) {
2176 LLVM_DEBUG(dbgs() << "\t\t[" << i << "]BB("
2177 << backtrack[i]->getParent()->getNumber() << ")\t";
2178 backtrack[i]->dump());
2179 if (CurrentBB != backtrack[i]->getParent()) {
2180 LLVM_DEBUG(dbgs() << "\t\tChange BB from (" << CurrentBB->getNumber()
2181 << ") to(" << backtrack[i]->getParent()->getNumber()
2182 << ")\n");
2184 SI = backtrack[i]->getParent()->succ_begin(),
2185 SE = backtrack[i]->getParent()->succ_end();
2186 SI != SE; ++SI) {
2187 if (*SI == CurrentBB)
2188 continue;
2189
2190 LLVM_DEBUG(dbgs() << "\t\tSide Exit:\n\t"; (*SI)->dump());
2191 // If any reg kill is live along this side exit, it is not
2192 // a kill any more.
2193 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
2194 E = (*SI)->livein_end();
2195 I != E; ++I) {
2196 if (KilledUseSet.count((*I).PhysReg)) {
2197 LLVM_DEBUG(dbgs() << "\t\tReg (" << printReg((*I).PhysReg, QRI)
2198 << ") is LiveIn along side exit.\n");
2199 KilledUseSet.erase((*I).PhysReg);
2200 unmarkKillReg(MI, (*I).PhysReg);
2201 }
2202 if (KilledUseSet.empty())
2203 return;
2204 }
2205 }
2206 CurrentBB = backtrack[i]->getParent();
2207 }
2208
2209 // Done with the whole path.
2210 if (backtrack[i] == &*TargetPacket)
2211 return;
2212
2213 // Starting the tracking. Do not update source bundle.
2214 // If TargetPacket == SourcePacket we have returned
2215 // in the previous check.
2216 if (backtrack[i] == &*SourcePacket)
2217 continue;
2218
2219 // Ignore DBG_VALUE.
2220 if (backtrack[i]->isDebugInstr())
2221 continue;
2222
2223 // Encountered an intermediary bundle. Process it.
2224 // Beware, sometimes check for backtrack[i] == TargetPacket
2225 // does not work, so this instruction could be one from the target bundle.
2226 SmallVector<unsigned, 4> Defs;
2227 SmallVector<unsigned, 8> Uses;
2228 MachineInstr *MIU = backtrack[i];
2229 parseOperands(MIU, Defs, Uses);
2230
2231 for (SmallVector<unsigned, 8>::iterator IA = Uses.begin(), IAE = Uses.end();
2232 IA != IAE; ++IA) {
2233 if (KilledUseSet.count(*IA)) {
2234 // Now this is new kill point for this Reg.
2235 // Update the bundle, and any local uses.
2236 markKillReg(MIU, *IA);
2237
2238 // Unmark the current MI.
2239 unmarkKillReg(MI, *IA);
2240
2241 if (MIU->isBundle()) {
2242 // TODO: Can do this cleaner and faster.
2245 for (++MII; MII != End && MII->isInsideBundle(); ++MII)
2246 markKillReg(&*MII, *IA);
2247 }
2248
2249 // We have updated this kill reg, if there are more, keep on going.
2250 KilledUseSet.erase(*IA);
2251
2252 // If the set is exhausted, just leave.
2253 if (KilledUseSet.empty())
2254 return;
2255 }
2256 }
2257 }
2258}
2259
2260/// This is houskeeping for bundle with instruction just added to it.
2261void HexagonGlobalSchedulerImpl::addInstructionToExistingBundle(
2262 MachineBasicBlock *HomeBB, MachineBasicBlock::instr_iterator &Head,
2265 MachineBasicBlock::iterator &TargetPacket,
2267 std::vector<MachineInstr *> &backtrack) {
2268 Tail = getBundleEnd(Head);
2269 LLVM_DEBUG(dbgs() << "\t\t\t[Add] Head home: "; DumpPacket(Head));
2270
2271 // Old header to be deleted shortly.
2272 MachineBasicBlock::instr_iterator Outcast = Head;
2273 // Unbundle old header.
2274 if (Outcast->isBundle() && Outcast->isBundledWithSucc())
2275 Outcast->unbundleFromSucc();
2276
2277 bool memShufDisabled = QII->getBundleNoShuf(*Outcast);
2278
2279 // Create new bundle header and update MI flags.
2280 finalizeBundle(*HomeBB, ++Head, Tail);
2281 MachineBasicBlock::instr_iterator BundleMII = std::prev(Head);
2282 if (memShufDisabled)
2283 QII->setBundleNoShuf(BundleMII);
2284 --Head;
2285
2286 LLVM_DEBUG(dbgs() << "\t\t\t[Add] New Head : "; DumpPacket(Head));
2287
2288 // The old header could be listed in the back tracking,
2289 // so if it is, we need to update it.
2290 for (unsigned i = 0; i < backtrack.size(); ++i)
2291 if (backtrack[i] == &*Outcast)
2292 backtrack[i] = &*Head;
2293
2294 // Same for top MI iterator.
2295 if (NextMI == Outcast)
2296 NextMI = Head;
2297
2298 TargetPacket = Head;
2299 HomeBB->erase(Outcast);
2300}
2301
2302/// This handles houskeeping for bundle with instruction just deleted from it.
2303/// We do not see the original moved instruction in here.
2304void HexagonGlobalSchedulerImpl::removeInstructionFromExistingBundle(
2305 MachineBasicBlock *HomeBB, MachineBasicBlock::instr_iterator &Head,
2307 MachineBasicBlock::iterator &SourceLocation,
2308 MachineBasicBlock::iterator &NextMI, bool MovingDependentOp,
2309 std::vector<MachineInstr *> &backtrack) {
2310 // Empty BBs will be deleted shortly.
2311 if (HomeBB->empty()) {
2314 return;
2315 }
2316
2317 if (!SourceLocation->isBundle()) {
2318 LLVM_DEBUG(dbgs() << "\t\t\tOriginal instruction was not bundled.\n\t\t\t";
2319 SourceLocation->dump());
2320 // If original instruction was not bundled, and we have moved it
2321 // and it is in the back track, we probably want to remove it from there.
2322 LLVM_DEBUG(dbgs() << "\t\t\t[Rem] New head: "; backtrack.back()->dump());
2323
2324 for (unsigned i = 0; i < backtrack.size(); ++i) {
2325 if (backtrack[i] == &*SourceLocation) {
2326 // By definition, this should be the last instruction in the backtrack.
2327 assert((backtrack[i] == backtrack.back()) && "Lost back track");
2328 backtrack.pop_back();
2329 }
2330 // Point the main iterator to the next instruction.
2331 if (NextMI == SourceLocation)
2332 NextMI++;
2333 }
2334 SourceLocation = MachineBasicBlock::iterator();
2337 return;
2338 }
2339
2340 // The old header, soon to be deleted.
2341 MachineBasicBlock::instr_iterator Outcast = SourceLocation.getInstrIterator();
2342 LLVM_DEBUG(dbgs() << "\t\t\t[Rem] SourceLocation after bundle update: ";
2343 DumpPacket(Outcast));
2344
2345 // If bundle has been already destroyed. BB->splat seems to do it some times
2346 // but not the other.
2347 // We already know that SourceLocation is bundle header.
2348 if (!SourceLocation->isBundledWithSucc()) {
2349 assert(!Head->isBundledWithSucc() && !Head->isBundledWithPred() &&
2350 "Bad bundle");
2351 } else {
2352 Head = SourceLocation.getInstrIterator();
2353 Tail = getBundleEnd(Head);
2354 unsigned Size = 0;
2355 unsigned BBSizeWithDbg = 0;
2357 MachineBasicBlock::const_instr_iterator E = Head->getParent()->instr_end();
2358
2359 for (++I; I != E && I->isBundledWithPred(); ++I) {
2360 ++BBSizeWithDbg;
2361 if (!I->isDebugInstr())
2362 ++Size;
2363 }
2364
2365 LLVM_DEBUG(dbgs() << "\t\t\t[Rem] Size(" << Size << ") Head orig: ";
2366 DumpPacket(Head));
2367 // The old header, soon to be deleted.
2368 Outcast = Head;
2369
2370 // The old Header is still counted here.
2371 if (Size > 1) {
2372 if (Outcast->isBundle() && Outcast->isBundledWithSucc())
2373 Outcast->unbundleFromSucc();
2374
2375 bool memShufDisabled = QII->getBundleNoShuf(*Outcast);
2376 // The finalizeBundle() assumes that "original" sequence
2377 // it is finalizing is sequentially correct. That basically
2378 // means that swap case might not be handled properly.
2379 // I find insert point for the pull-up instruction myself,
2380 // and I should try to catch that swap case there, and refuse
2381 // to insert if I cannot guarantee correct serial semantics.
2382 // In the future, I need my own incremental "inserToBundle"
2383 // function.
2384 finalizeBundle(*HomeBB, ++Head, Tail);
2385 MachineBasicBlock::instr_iterator BundleMII = std::prev(Head);
2386 if (memShufDisabled)
2387 QII->setBundleNoShuf(BundleMII);
2388
2389 --Head;
2390 } else if (Size == 1) {
2391 // There is only one non-debug instruction in the bundle.
2392 if (BBSizeWithDbg > 1) {
2393 // There are some debug instructions that should be unbundled too.
2395 MachineBasicBlock::instr_iterator E = Head->getParent()->instr_end();
2396 for (++I; I != E && I->isBundledWithPred(); ++I) {
2397 I->unbundleFromPred();
2398 // Set Head to the non-debug instruction.
2399 if (!I->isDebugInstr())
2400 Head = I;
2401 }
2402 } else {
2403 // This means that only one original instruction is
2404 // left in the bundle. We need to "unbundle" it because the
2405 // rest of API will not like it.
2406 ++Head;
2407 if (Head->isBundledWithPred())
2408 Head->unbundleFromPred();
2409 if (Head->isBundledWithSucc())
2410 Head->unbundleFromSucc();
2411 }
2412 // Head is no longer bundled, so none of its reads are internal.
2413 for (MachineOperand &MO : Head->all_uses())
2414 MO.setIsInternalRead(false);
2415 } else
2416 llvm_unreachable("Corrupt bundle");
2417 }
2418
2419 LLVM_DEBUG(dbgs() << "\t\t\t[Rem] New Head : "; DumpPacket(Head));
2420 SourceLocation = Head;
2421
2422 // The old header could be listed in the back tracking,
2423 // so if it is, we need to update it.
2424 for (unsigned i = 0; i < backtrack.size(); ++i)
2425 if (backtrack[i] == &*Outcast)
2426 backtrack[i] = &*Head;
2427
2428 // Same for top MI iterator.
2429 if (NextMI == Outcast)
2430 NextMI = Head;
2431
2432 HomeBB->erase(Outcast);
2433}
2434
2435#ifndef NDEBUG
2437 const TargetRegisterInfo *TRI) {
2438 LLVM_DEBUG(dbgs() << "\tLiveness for BB:\n"; MBB->dump());
2439 for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(),
2440 SE = MBB->succ_end();
2441 SI != SE; ++SI) {
2442 LLVM_DEBUG(dbgs() << "\tSuccessor BB (" << (*SI)->getNumber() << "):");
2443 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
2444 E = (*SI)->livein_end();
2445 I != E; ++I)
2446 LLVM_DEBUG(dbgs() << "\t" << printReg((*I).PhysReg, TRI));
2447 LLVM_DEBUG(dbgs() << "\n");
2448 }
2449}
2450#endif
2451
2452// Blocks should be considered empty if they contain only debug info;
2453// else the debug info would affect codegen.
2455 if (MBB->empty())
2456 return true;
2457 for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
2458 MBBI != MBBE; ++MBBI) {
2459 if (!MBBI->isDebugInstr())
2460 return false;
2461 }
2462 return true;
2463}
2464
2465/// Treat given instruction as a branch, go through its operands
2466/// and see if any of them is a BB address. If so, return it.
2467/// Return NULL otherwise.
2469 if (!MI || !MI->isBranch() || MI->isBundle())
2470 return NULL;
2471
2472 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2473 const MachineOperand &MO = MI->getOperand(i);
2474 if (MO.isMBB())
2475 return MO.getMBB();
2476 }
2477 return NULL;
2478}
2479
2480/// Similar to HexagonInstrInfo::analyzeBranch but handles
2481/// serveral more general cases including parsing empty BBs when possible.
2482bool HexagonGlobalSchedulerImpl::AnalyzeBBBranches(MachineBasicBlock *MBB,
2483 MachineBasicBlock *&TBB,
2484 MachineInstr *&FirstTerm,
2485 MachineBasicBlock *&FBB,
2486 MachineInstr *&SecondTerm) {
2487 // Hexagon allowes up to two jumps in MBB.
2488 FirstTerm = NULL;
2489 SecondTerm = NULL;
2490
2491 LLVM_DEBUG(dbgs() << "\n\t\tAnalyze Branches in BB(" << MBB->getNumber()
2492 << ")\n");
2493 if (MBB->succ_size() == 0) {
2494 LLVM_DEBUG(dbgs() << "\n\t\tBlock has no successors.\n");
2495 return true;
2496 }
2497 // Find both jumps.
2498 // We largely rely on implied assumption that BB branching always
2499 // looks like this:
2500 // J2_jumpf %P0, <BB#60>, %PC<imp-def>;
2501 // J2_jump <BB#49>
2502 // Branches also could be in different packets.
2506
2507 if (QII->nonDbgBBSize(MBB) == 1) {
2509 if (MII->isBranch())
2510 FirstTerm = &*MII;
2511 } else {
2512 // We have already eliminated the case when MIB == MIE.
2513 while (MII != MIE) {
2514 if (!MII->isBundle() && MII->isBranch()) {
2515 if (!FirstTerm)
2516 FirstTerm = &*MII;
2517 else
2518 SecondTerm = &*MII;
2519 }
2520 ++MII;
2521 }
2522 }
2523 if ((FirstTerm && FirstTerm->isIndirectBranch()) ||
2524 (SecondTerm && SecondTerm->isIndirectBranch())) {
2525 LLVM_DEBUG(dbgs() << "\n\t\tCannot analyze BB with indirect branch.");
2526 return true;
2527 }
2528 if ((FirstTerm && FirstTerm->getOpcode() == Hexagon::J2_jump &&
2529 !FirstTerm->getOperand(0).isMBB()) ||
2530 (SecondTerm && SecondTerm->getOpcode() == Hexagon::J2_jump &&
2531 !SecondTerm->getOperand(0).isMBB())) {
2532 LLVM_DEBUG(
2533 dbgs() << "\n\t\tCannot analyze BB with a branch out of function.");
2534 return true;
2535 }
2536
2537 // Now try to analyze this branch.
2538 SmallVector<MachineOperand, 4> Cond;
2539 if (QII->analyzeBranch(*MBB, TBB, FBB, Cond, false)) {
2540 LLVM_DEBUG(dbgs() << "\t\tFail to analyze with analyzeBranch.\n");
2541 LLVM_DEBUG(dbgs() << "\t\tFirst term: "; if (FirstTerm) FirstTerm->dump();
2542 else dbgs() << "None\n";);
2543 // Could not analyze it. See if this is something we can recognize.
2544 TBB = getBranchDestination(FirstTerm);
2545 }
2546 // There are several cases not handled by HexagonInstrInfo::analyzeBranch.
2547 if (!TBB) {
2548 LLVM_DEBUG(dbgs() << "\t\tMissing TBB.\n");
2549 // There is a branch, but TBB is not found.
2550 // The BB could also be empty at this point. See if it is a trivial
2551 // layout case.
2552 if (MBB->succ_size() == 1) {
2553 TBB = *MBB->succ_begin();
2554 LLVM_DEBUG(dbgs() << "\t\tFall through TBB(" << TBB->getNumber()
2555 << ").\n");
2556 return false;
2557 } else if (MBB->succ_size() == 2) {
2558 // This should cover majority of remaining cases.
2559 if (FirstTerm && SecondTerm &&
2560 (QII->isPredicated(*FirstTerm) || QII->isNewValueJump(*FirstTerm)) &&
2561 !QII->isPredicated(*SecondTerm)) {
2562 TBB = getBranchDestination(FirstTerm);
2563 FBB = getBranchDestination(SecondTerm);
2564 LLVM_DEBUG(dbgs() << "\t\tCanonical dual jump layout: TBB("
2565 << TBB->getNumber() << ") FBB(" << FBB->getNumber()
2566 << ").\n");
2567 return false;
2568 } else if (SecondTerm && SecondTerm->getOpcode() == Hexagon::J2_jump &&
2569 SecondTerm->getOperand(0).isMBB()) {
2570 // Look at the second term if I know it, to find out what is the fall
2571 // through for this BB.
2572 FBB = SecondTerm->getOperand(0).getMBB();
2573 assert(MBB->succ_size() == 2 && "Expected exactly 2 successors");
2574 MachineBasicBlock *Succ0 = *MBB->succ_begin();
2575 MachineBasicBlock *Succ1 = *std::next(MBB->succ_begin());
2576 if (FBB == Succ0)
2577 TBB = Succ1;
2578 else
2579 TBB = Succ0;
2580 LLVM_DEBUG(dbgs() << "\t\tSecond br is J2_jump TBB(" << TBB->getNumber()
2581 << ") FBB(" << FBB->getNumber() << ").\n");
2582 return false;
2583 } else {
2584 // This might be an empty BB but still with two
2585 // successors set. Try to use CFG layout to sort it out.
2586 // This could happen when last jump was pulled up from a BB, and
2587 // CFG is being updated. At that point this method is called and
2588 // returns best guess possible for TBB/FBB. Fortunately order of those
2589 // is irrelevant, and rather used a worklist for CFG update.
2591 MachineFunction &MF = *MBB->getParent();
2592 (void)MF; // supress compiler warning
2593 // If there are no other clues, assume next sequential BB
2594 // in CFG as FBB.
2595 ++MBBIter;
2596 assert(MBBIter != MF.end() && "I give up.");
2597 FBB = &(*MBBIter);
2598 assert(MBB->succ_size() == 2 && "Expected exactly 2 successors");
2599 MachineBasicBlock *S0 = *MBB->succ_begin();
2600 MachineBasicBlock *S1 = *std::next(MBB->succ_begin());
2601 if (FBB == S0)
2602 TBB = S1;
2603 else if (FBB == S1) {
2604 TBB = S0;
2605 } else {
2606 // This case can arise when the layout successor basic block (++IMBB)
2607 // got empty during pull-up.
2608 // As a result, ++IMBB is not one of MBB's successors.
2609 MBBIter = MF.begin();
2610 while (!MBB->isSuccessor(&*MBBIter) && (MBBIter != MF.end()))
2611 ++MBBIter;
2612 assert(MBBIter != MF.end() && "Malformed BB with invalid successors");
2613 FBB = &*MBBIter;
2614 if (FBB == S0)
2615 TBB = S1;
2616 else
2617 TBB = S0;
2618 }
2619 LLVM_DEBUG(dbgs() << "\t\tUse layout TBB(" << TBB->getNumber()
2620 << ") FBB(" << FBB->getNumber() << ").\n");
2621 return false;
2622 }
2623 }
2624 assert(!FirstTerm && "Bad BB");
2625 return true;
2626 }
2627 // Ok, we have TBB, but maybe missing FBB.
2628 if (!FBB && SecondTerm) {
2629 LLVM_DEBUG(dbgs() << "\t\tMissing FBB.\n");
2630 // analyzeBranch could lie to us, ignore it in this case.
2631 // For the canonical case simply take known branch targets.
2632 if ((QII->isPredicated(*FirstTerm) || QII->isNewValueJump(*FirstTerm)) &&
2633 !QII->isPredicated(*SecondTerm)) {
2634 FBB = getBranchDestination(SecondTerm);
2635 } else {
2636 // Second term is also predicated.
2637 // Use CFG layout. Assign layout successor as FBB.
2638 for (MachineBasicBlock *Succ : MBB->successors()) {
2639 if (MBB->isLayoutSuccessor(Succ))
2640 FBB = Succ;
2641 }
2642 if (FBB == NULL) {
2643 LLVM_DEBUG(dbgs() << "\nNo layout successor found.");
2644 LLVM_DEBUG(dbgs() << "Possibly the layout successor is an empty BB");
2645 return true;
2646 }
2647 if (TBB == FBB)
2648 LLVM_DEBUG(dbgs() << "Malformed branch with useless branch condition";);
2649 }
2650 LLVM_DEBUG(dbgs() << "\t\tSecond term: "; SecondTerm->dump());
2651 } else if (TBB && !FBB) {
2652 // If BB ends in endloop, and it is a single BB hw loop,
2653 // we will have a single terminator, but we can figure FBB
2654 // easily from CFG.
2655 if (MBB->succ_size() == 2) {
2656 MachineBasicBlock *S0 = *MBB->succ_begin();
2657 MachineBasicBlock *S1 = *std::next(MBB->succ_begin());
2658 if (TBB == S0)
2659 FBB = S1;
2660 else
2661 FBB = S0;
2662 }
2663 }
2664
2665 LLVM_DEBUG(dbgs() << "\t\tFinal TBB(" << TBB->getNumber() << ").\n";
2666 if (FBB) dbgs() << "\t\tFinal FBB(" << FBB->getNumber() << ").\n";
2667 else dbgs() << "\t\tFinal FBB(None)\n";);
2668 return false;
2669}
2670
2671/// updateBranches - Updates all branches to \p From in the basic block \p
2672/// InBlock to branches to \p To.
2674 MachineBasicBlock *To) {
2675 for (MachineBasicBlock::instr_iterator BI = InBlock.instr_begin(),
2676 E = InBlock.instr_end();
2677 BI != E; ++BI) {
2678 MachineInstr *Inst = &*BI;
2679 // Ignore anything that is not a branch.
2680 if (!Inst->isBranch())
2681 continue;
2683 OE = Inst->operands_end();
2684 OI != OE; ++OI) {
2685 MachineOperand &Opd = *OI;
2686 // Look for basic block "From".
2687 if (!Opd.isMBB() || Opd.getMBB() != From)
2688 continue;
2689 // Update it.
2690 Opd.setMBB(To);
2691 }
2692 }
2693}
2694
2695/// Rewrite all predecessors of the old block to go to the fallthrough
2696/// instead.
2697/// NB: Collect predecessors into a snapshot vector before iterating to
2698/// avoid iterator invalidation on MBB's predecessor list. Each call to
2699/// ReplaceUsesOfBlockWith modifies both the successor list of Pred and
2700/// the predecessor list of MBB, which invalidates debug-mode iterators
2701/// (detected by _GLIBCXX_DEBUG).
2703 MachineBasicBlock *MFBB) {
2704 MachineFunction &MF = *MBB.getParent();
2705
2706 if (MFBB->getIterator() == MF.end())
2707 return;
2708
2709 // Snapshot the predecessor list to avoid iterator invalidation.
2710 SmallVector<MachineBasicBlock *, 4> Preds(MBB.pred_begin(), MBB.pred_end());
2711 for (MachineBasicBlock *Pred : Preds) {
2712 if (!Pred->isSuccessor(&MBB))
2713 continue;
2714 Pred->ReplaceUsesOfBlockWith(&MBB, MFBB);
2715 updateBranches(*Pred, &MBB, MFBB);
2716 }
2717}
2718
2719static void UpdateCFG(MachineBasicBlock *HomeBB, MachineBasicBlock *OriginBB,
2720 MachineInstr *MII, MachineBasicBlock *HomeTBB,
2721 MachineBasicBlock *HomeFBB, MachineInstr *FTA,
2722 MachineInstr *STA,
2723 const MachineBranchProbabilityInfo *MBPI) {
2724 MachineBasicBlock *S2Add = NULL, *S2Remove = NULL;
2725 bool RemoveLSIfPresent = false;
2726 if ((&*MII == FTA) && MII->isConditionalBranch()) {
2727 LLVM_DEBUG(dbgs() << "\nNew firstterm conditional jump added to HomeBB";);
2728 S2Add = HomeTBB;
2729 S2Remove = HomeTBB;
2730 } else if ((&*MII == STA) && MII->isConditionalBranch()) {
2731 LLVM_DEBUG(dbgs() << "\nNew secondterm conditional jump added to HomeBB";);
2732 // AnalyzeBBBranches might not give correct information in this case.
2733 // The branch destination may be a symbol, not necessarily a block.
2734 if (MachineBasicBlock *Dest = getBranchDestination(MII)) {
2735 LLVM_DEBUG(dbgs() << "\nBranch destination for pulled instruction is BB#"
2736 << Dest->getNumber(););
2737 S2Add = Dest;
2738 S2Remove = Dest;
2739 }
2740 } else if ((&*MII == FTA) && MII->isUnconditionalBranch()) {
2741 LLVM_DEBUG(dbgs() << "\nNew firstterm unconditional jump added to HomeBB";);
2742 S2Add = HomeTBB;
2743 S2Remove = HomeTBB;
2744 RemoveLSIfPresent = true;
2745 } else if ((&*MII == STA) && MII->isUnconditionalBranch()) {
2746 LLVM_DEBUG(
2747 dbgs() << "\nNew secondterm unconditional jump added to HomeBB";);
2748 S2Add = HomeFBB;
2749 S2Remove = HomeFBB;
2750 RemoveLSIfPresent = true;
2751 }
2752 if (S2Add && !HomeBB->isSuccessor(S2Add)) {
2753 HomeBB->addSuccessor(S2Add, MBPI->getEdgeProbability(OriginBB, S2Add));
2754 }
2755 if (S2Remove)
2756 OriginBB->removeSuccessor(S2Remove);
2757 if (RemoveLSIfPresent) {
2758 MachineFunction::iterator HomeBBLS = HomeBB->getIterator();
2759 ++HomeBBLS;
2760 if (HomeBBLS != HomeBB->getParent()->end() &&
2761 HomeBB->isLayoutSuccessor(&*HomeBBLS)) {
2762 LLVM_DEBUG(dbgs() << "\nRemoving LayoutSucc BB#" << HomeBBLS->getNumber()
2763 << "from list of successors";);
2764 HomeBB->removeSuccessor(&*HomeBBLS);
2765 }
2766 }
2767}
2768
2769/// Move instruction from/to BB, Update liveness info,
2770/// return pointer to the newly inserted and modified
2771/// instruction.
2772MachineInstr *HexagonGlobalSchedulerImpl::MoveAndUpdateLiveness(
2773 BasicBlockRegion *CurrentRegion, MachineBasicBlock *HomeBB,
2774 MachineInstr *InstrToMove, bool NeedToNewify, unsigned DepReg,
2775 bool MovingDependentOp, MachineBasicBlock *OriginBB,
2776 MachineInstr *OriginalInstruction, SmallVector<MachineOperand, 4> &Cond,
2777 MachineBasicBlock::iterator &SourceLocation,
2778 MachineBasicBlock::iterator &TargetPacket,
2780 std::vector<MachineInstr *> &backtrack) {
2781 LLVM_DEBUG(
2782 dbgs() << "\n...............[MoveAndUpdateLiveness]..............\n");
2783 LLVM_DEBUG(dbgs() << "\t\tInstrToMove :\t"; InstrToMove->dump());
2784 LLVM_DEBUG(dbgs() << "\t\tOriginalInstruction:\t";
2785 OriginalInstruction->dump());
2786 LLVM_DEBUG(dbgs() << "\t\tSourceLocation :\t";
2787 DumpPacket(SourceLocation.getInstrIterator()));
2788 LLVM_DEBUG(dbgs() << "\t\tTargetPacket :\t";
2789 DumpPacket(TargetPacket.getInstrIterator()));
2790
2792 SourceLocation.getInstrIterator();
2793 MachineBasicBlock::instr_iterator OriginalTail = getBundleEnd(OriginalHead);
2795 OriginalInstruction->getIterator();
2796
2797 // Remove our temporary instruction.
2798 MachineBasicBlock::instr_iterator kill_it(InstrToMove);
2799 HomeBB->erase(kill_it);
2800
2801 MachineBasicBlock::instr_iterator TargetHead(TargetPacket.getInstrIterator());
2802 MachineBasicBlock::instr_iterator TargetTail = getBundleEnd(TargetHead);
2803
2804 LLVM_DEBUG(dbgs() << "\n\tTo BB before:\n"; debugLivenessForBB(HomeBB, QRI));
2805 LLVM_DEBUG(dbgs() << "\n\tFrom BB before:\n";
2806 debugLivenessForBB(OriginBB, QRI));
2807
2808 // Before we perform the move, we need to collect the worklist
2809 // of BBs for liveness updated.
2810 std::list<MachineBasicBlock *> WorkList;
2811
2812 // Insert into the work list all BBs along the backtrace.
2813 for (std::vector<MachineInstr *>::iterator RI = backtrack.begin(),
2814 RIE = backtrack.end();
2815 RI != RIE; RI++)
2816 WorkList.push_back((*RI)->getParent());
2817
2818 // Only keep unique entries.
2819 // TODO: Use a different container here.
2820 WorkList.unique();
2821
2822 // Move the original instruction.
2823 // If this instruction is inside a bundle, update the bundle.
2825 TargetHead->getParent()->instr_end();
2826 bool LastInstructionInBundle = false;
2827 MachineBasicBlock::instr_iterator MII = findInsertPositionInBundle(
2828 TargetPacket, &*OutcastFrom, LastInstructionInBundle);
2829
2830 (void)BBEnd;
2831 LLVM_DEBUG(dbgs() << "\n\t\t\tHead target : "; DumpPacket(TargetHead));
2832 LLVM_DEBUG(dbgs() << "\t\t\tTail target : ";
2833 DumpPacket(TargetTail, BBEnd));
2834 LLVM_DEBUG(dbgs() << "\t\t\tInsert right before: "; DumpPacket(MII, BBEnd));
2835
2836 MIBundleBuilder Bundle(&*TargetHead);
2837
2838 // Actual move. One day liveness might be updated here.
2839 if (OriginalInstruction->isBundled()) {
2840 Bundle.insert(MII, OriginalInstruction->removeFromBundle());
2841 --MII;
2842 } else {
2843 // This is one case currently unhandled by Bundle.insert
2844 // and needs to be fixed upstream. Meanwhile use old way to handle
2845 // this odd case.
2846 if (OriginalInstruction->getIterator() == TargetTail) {
2847 LLVM_DEBUG(dbgs() << "\t\t\tSpecial case move.\n");
2848 MachineBasicBlock::instr_iterator MIIToPred = MII;
2849 --MIIToPred;
2850 LLVM_DEBUG(dbgs() << "\t\t\tInser after : ";
2851 DumpPacket(MIIToPred, BBEnd));
2852 // Unbundle it in its current location.
2853 if (OutcastFrom->isBundledWithSucc()) {
2854 OutcastFrom->clearFlag(MachineInstr::BundledSucc);
2855 OutcastFrom->clearFlag(MachineInstr::BundledPred);
2856 } else if (OutcastFrom->isBundledWithPred()) {
2857 OutcastFrom->unbundleFromPred();
2858 }
2859 HomeBB->splice(MII, OriginBB, OutcastFrom);
2860 if (!MII->isBundledWithPred())
2861 MII->bundleWithPred();
2862 if (!LastInstructionInBundle && !MII->isBundledWithSucc())
2863 MII->bundleWithSucc();
2864 // This is the instruction after which we have inserted.
2865 if (!MIIToPred->isBundledWithSucc())
2866 MIIToPred->bundleWithSucc();
2867 } else {
2868 Bundle.insert(MII, OriginalInstruction->removeFromParent());
2869 --MII;
2870 }
2871 }
2872 // Source location bundle is updated later in the
2873 // removeInstructionFromExistingBundle().
2874
2875 LLVM_DEBUG(dbgs() << "\t\t\tNew packet head: "; DumpPacket(TargetHead));
2876 LLVM_DEBUG(dbgs() << "\t\t\tInserted op : "; MII->dump());
2877 LLVM_DEBUG(dbgs() << "\n\tTo BB after move:\n";
2878 debugLivenessForBB(HomeBB, QRI));
2879 LLVM_DEBUG(dbgs() << "\n\tFrom BB after:\n";
2880 debugLivenessForBB(OriginBB, QRI));
2881
2882 // Update kill patterns. Do it before we have predicated the moved
2883 // instruction.
2884 updateKillAlongThePath(HomeBB, OriginBB, MII, TargetTail, SourceLocation,
2885 TargetPacket, backtrack);
2886 // I need to know:
2887 // - true/false predication
2888 // - do I need to .new it?
2889 // - do I need to .old it?
2890 // If the original instruction used new value operands,
2891 // it might need to be changed to the generic form
2892 // before further processing.
2893 if (QII->isDotNewInst(*MII)) {
2894 DemoteToDotOld(&*MII);
2895 LLVM_DEBUG(dbgs() << "\t\t\tDemoted to .old\t:"; MII->dump());
2896 }
2897
2898 // We have previously checked whether this instruction could
2899 // be placed in this packet, including all possible transformations
2900 // it might need, so if any request will fail now, something is wrong.
2901 //
2902 // Need for predication and the exact condition is determined by
2903 // the path between original and current instruction location.
2904 if (!Cond.empty()) { // To be predicated
2905 LLVM_DEBUG(dbgs() << "\t\t\tPredicating:"; MII->dump());
2906 assert(TII->isPredicable(*MII) && "MII is not predicable");
2908 if (NeedToNewify) {
2909 assert((DepReg < std::numeric_limits<unsigned>::max()) &&
2910 "Invalid pred reg value");
2911 LLVM_DEBUG(dbgs() << "\t\t\tNeeds to NEWify on Reg("
2912 << printReg(DepReg, QRI) << ").\n");
2913 int NewOpcode = QII->getDotNewPredOp(*MII, MBPI);
2914 MII->setDesc(QII->get(NewOpcode));
2915
2916 // Now we need to mark newly created predicate operand as
2917 // internal read.
2918 // TODO: Better look for predicate operand.
2919 for (unsigned i = 0, e = MII->getNumOperands(); i != e; ++i) {
2920 MachineOperand &MO = MII->getOperand(i);
2921 if (!MO.isReg())
2922 continue;
2923 if (MO.isDef())
2924 continue;
2925 if (DepReg == MO.getReg())
2926 MO.setIsInternalRead();
2927 }
2928 }
2929 LLVM_DEBUG(dbgs() << "\t\t\tNew predicated form:\t"; MII->dump());
2930 // If the predicate has changed kill pattern, now we need to propagate
2931 // that again. This is important for liveness computation.
2932 updateKillAlongThePath(HomeBB, OriginBB, MII, TargetTail, SourceLocation,
2933 TargetPacket, backtrack);
2934 }
2935
2936 // Create new bundle header, remove the old one.
2937 addInstructionToExistingBundle(HomeBB, TargetHead, TargetTail, MII,
2938 TargetPacket, NextMI, backtrack);
2939
2940 // If moved instruction was inside a bundle, update that bundle.
2941 removeInstructionFromExistingBundle(OriginBB, ++OriginalHead, OriginalTail,
2942 SourceLocation, NextMI, MovingDependentOp,
2943 backtrack);
2944
2945 // If removed instruction could have been dependent on any
2946 // of the remaining ops, we need to oldify possible affected ones.
2947 LLVM_DEBUG(dbgs() << "\t\tTargetHead:\t"; DumpPacket(TargetHead, BBEnd));
2948 LLVM_DEBUG(dbgs() << "\t\tOriginalHead:\t"; DumpPacket(OriginalHead, BBEnd));
2949 LLVM_DEBUG(dbgs() << "\t\tOriginalInstruction:\t";
2950 DumpPacket(OriginalInstruction->getIterator(), BBEnd));
2951 LLVM_DEBUG(dbgs() << "\t\tOutcastFrom:\t"; DumpPacket(OutcastFrom, BBEnd));
2952
2953 // Clean up the original source bundle on a global scope.
2954 if (OriginalHead != MachineBasicBlock::instr_iterator() &&
2955 QII->isEndLoopN(OriginalHead->getOpcode())) {
2956 // Single endloop left. Since it is not a real instruction,
2957 // we can simply add it to a non empty previous bundle, if one exist,
2958 // or let assembler to produce a fake bundle for it.
2959 LLVM_DEBUG(dbgs() << "\t\tOnly endloop in packet.\n");
2961 if (OriginBB->begin() != I) {
2962 --I;
2963 if (I->isBundled()) {
2964 if (!I->isBundledWithSucc())
2965 I->bundleWithSucc();
2966 if (!OriginalHead->isBundledWithPred())
2967 OriginalHead->bundleWithPred();
2968 }
2969 // else we probably need to create a new bundle here.
2970 // SourceLocation = NULL;
2971 }
2972 } else if (MovingDependentOp &&
2973 OriginalHead != MachineBasicBlock::instr_iterator()) {
2974 if (OriginalHead->isBundled()) {
2975 for (MachineBasicBlock::instr_iterator J = ++OriginalHead;
2976 J != OriginalTail && J->isInsideBundle() && !J->isBundle(); ++J) {
2977 // Need to oldify it.
2978 if (MIsHaveTrueDependency(OriginalInstruction, &*J) &&
2979 QII->isDotNewInst(*J)) {
2980 LLVM_DEBUG(dbgs() << "\t\tDemoting to .old:\t"; J->dump());
2981 DemoteToDotOld(&*J);
2982 }
2983 }
2984 } else {
2985 // Single instruction left.
2986 if (MIsHaveTrueDependency(OriginalInstruction, &*OriginalHead) &&
2987 QII->isDotNewInst(*OriginalHead)) {
2988 LLVM_DEBUG(dbgs() << "\t\tDemoting to .old op:\t";
2989 OriginalHead->dump());
2990 DemoteToDotOld(&*OriginalHead);
2991 }
2992 }
2993 }
2994
2995 // Now we need to update liveness to all BBs involved
2996 // including those we might have "passed" through on the way here.
2997 LLVM_DEBUG(dbgs() << "\n\tTo BB after bundle update:\n"; HomeBB->dump());
2998 LLVM_DEBUG(dbgs() << "\n\n\tFrom BB after bundle update:\n";
2999 OriginBB->dump());
3000
3001 // Update global liveness.
3002 LLVM_DEBUG(dbgs() << "\n\tWorkList:\t");
3003 for (std::list<MachineBasicBlock *>::iterator BBI = WorkList.begin(),
3004 BBIE = WorkList.end();
3005 BBI != BBIE; BBI++) {
3006 LLVM_DEBUG(dbgs() << "BB#" << (*BBI)->getNumber() << " ");
3007 }
3008 LLVM_DEBUG(dbgs() << "\n");
3009
3010 do {
3011 MachineBasicBlock *BB = WorkList.back();
3012 WorkList.pop_back();
3013 CurrentRegion->getLivenessInfoForBB(BB)->UpdateLiveness(BB);
3014 } while (!WorkList.empty());
3015
3016 // No need to analyze for empty BB or update CFG for same BB pullup.
3017 if (OriginBB == HomeBB)
3018 return &*TargetHead;
3019 // If the instruction moved was a branch we need to update the
3020 // successor/predecessor of OriginBB and HomeBB accordingly.
3021 MachineBasicBlock *HomeTBB, *HomeFBB;
3022 MachineInstr *FTA = NULL, *STA = NULL;
3023 bool HomeBBAnalyzed = !AnalyzeBBBranches(HomeBB, HomeTBB, FTA, HomeFBB, STA);
3024 if (MII->isBranch()) {
3025 if (HomeBBAnalyzed) {
3026 UpdateCFG(HomeBB, OriginBB, &*MII, HomeTBB, HomeFBB, FTA, STA, MBPI);
3027 } else {
3028 llvm_unreachable("Underimplememted AnalyzeBBBranches");
3029 }
3030 }
3031 // If we have exhausted the OriginBB clean it up.
3032 // Beware that we could have created dual conditional jumps, which
3033 // ultimately means we can have three way jumps.
3034 if (IsEmptyBlock(OriginBB) && !OriginBB->isEHPad() &&
3035 !OriginBB->hasAddressTaken() && !OriginBB->succ_empty()) {
3036 // Dead block? Unlikely, but check.
3037 LLVM_DEBUG(dbgs() << "Empty BB(" << OriginBB->getNumber() << ").\n");
3038 // Update region map.
3039 CurrentRegion->RemoveBBFromRegion(OriginBB);
3040 // Keep the list of empty basic blocks to be freed later.
3041 EmptyBBs.push_back(OriginBB);
3042 if (OriginBB->pred_empty() || OriginBB->succ_empty())
3043 return &*TargetHead;
3044
3045 if (OriginBB->succ_size() == 1) {
3046 // Find empty block's successor.
3047 MachineBasicBlock *CommonFBB = *OriginBB->succ_begin();
3048 updatePredecessors(*OriginBB, CommonFBB);
3049 // Remove the only successor entry for empty BB.
3050 OriginBB->removeSuccessor(CommonFBB);
3051 } else {
3052 // Three way branching is not yet fully supported.
3053 assert((OriginBB->succ_size() == 2) && "Underimplemented 3way branch.");
3054 MachineBasicBlock *OriginTBB, *OriginFBB;
3055 MachineInstr *FTB = NULL, *STB = NULL;
3056
3057 LLVM_DEBUG(dbgs() << "\tComplex case.\n");
3058 if (HomeBBAnalyzed &&
3059 !AnalyzeBBBranches(OriginBB, OriginTBB, FTB, OriginFBB, STB)) {
3060 assert(OriginFBB && "Missing Origin FBB");
3061 if (HomeFBB == OriginBB) {
3062 // OriginBB is FBB for HomeBB.
3063 if (HomeTBB == OriginTBB) {
3064 // Shared TBB target, common FBB.
3065 updatePredecessors(*OriginBB, OriginFBB);
3066 } else if (HomeTBB == OriginFBB) {
3067 // Shared TBB target, common FBB.
3068 updatePredecessors(*OriginBB, OriginTBB);
3069 } else {
3070 // Three way branch. Add new successor to HomeBB.
3071 updatePredecessors(*OriginBB, OriginFBB);
3072 // TODO: Update the weight as well.
3073 // Adding the successor to make updatePredecessor happy.
3074 HomeBB->addSuccessor(OriginBB);
3075 updatePredecessors(*OriginBB, OriginTBB);
3076 }
3077 } else if (HomeTBB == OriginBB) {
3078 // OriginBB is TBB for HomeBB.
3079 if (HomeFBB == OriginTBB) {
3080 // Shared TBB target, common FBB.
3081 updatePredecessors(*OriginBB, OriginFBB);
3082 } else if (HomeFBB == OriginFBB) {
3083 // Shared TBB target, common FBB.
3084 updatePredecessors(*OriginBB, OriginTBB);
3085 } else {
3086 // Three way branch. Add new successor to HomeBB.
3087 updatePredecessors(*OriginBB, OriginFBB);
3088 // TODO: Update the weight as well.
3089 // Adding the successor to make updatePredecessor happy.
3090 HomeBB->addSuccessor(OriginBB);
3091 updatePredecessors(*OriginBB, OriginTBB);
3092 }
3093 } else
3094 llvm_unreachable("CFG update failed");
3095 // The empty BB can now be relieved of its successors.
3096 OriginBB->removeSuccessor(OriginFBB);
3097 OriginBB->removeSuccessor(OriginTBB);
3098 } else
3099 llvm_unreachable("Underimplemented analyzeBranch");
3100 }
3101 LLVM_DEBUG(dbgs() << "Updated BB(" << HomeBB->getNumber() << ").\n";
3102 HomeBB->dump());
3103 }
3104 return &*TargetHead;
3105}
3106
3107// Find where inside a given bundle current instruction should be inserted.
3108// Instruction will be inserted _before_ this position.
3110HexagonGlobalSchedulerImpl::findInsertPositionInBundle(
3111 MachineBasicBlock::iterator &Bundle, MachineInstr *MI, bool &LastInBundle) {
3113 MachineBasicBlock *MBB = MII->getParent();
3115 MachineBasicBlock::instr_iterator FirstBranch = BBEnd;
3116 MachineBasicBlock::instr_iterator LastBundledInstruction = BBEnd;
3117 MachineBasicBlock::instr_iterator DualJumpFirstCandidate = BBEnd;
3118
3119 assert(MII->isBundle() && "Missing insert location");
3120 bool isDualJumpSecondCandidate = IsDualJumpSecondCandidate(MI);
3121 LastInBundle = false;
3122
3123 for (++MII; MII != BBEnd && MII->isInsideBundle() && !MII->isBundle();
3124 ++MII) {
3125 if (MII->isBranch() && (FirstBranch == BBEnd))
3126 FirstBranch = MII;
3127 // If what we insert is a dual jump, we need to find
3128 // first jump, and insert new instruction after it.
3129 if (isDualJumpSecondCandidate && IsDualJumpFirstCandidate(&*MII))
3130 DualJumpFirstCandidate = MII;
3131 LastBundledInstruction = MII;
3132 }
3133
3134 if (DualJumpFirstCandidate != BBEnd) {
3135 // First respect dual jumps.
3136 ++DualJumpFirstCandidate;
3137 if (DualJumpFirstCandidate == BBEnd ||
3138 DualJumpFirstCandidate == LastBundledInstruction)
3139 LastInBundle = true;
3140 return DualJumpFirstCandidate;
3141 } else if (FirstBranch != BBEnd) {
3142 // If we have no dual jumps, but do have a single
3143 // branch in the bundle, add our new instruction
3144 // right before it.
3145 return FirstBranch;
3146 } else if (LastBundledInstruction != BBEnd) {
3147 LastInBundle = true;
3148 return ++LastBundledInstruction;
3149 } else
3150 llvm_unreachable("Lost in bundle");
3151 return MBB->instr_begin();
3152}
3153
3154/// This function for now needs to try to insert new instruction
3155/// in correct serial semantics fashion - i.e. find "correct" insert
3156/// point for instruction as if inserting in serial sequence.
3157MachineBasicBlock::instr_iterator HexagonGlobalSchedulerImpl::insertTempCopy(
3158 MachineBasicBlock *MBB, MachineBasicBlock::iterator &TargetPacket,
3159 MachineInstr *MI, bool DeleteOldCopy) {
3161 MachineBasicBlock *CurrentBB = MI->getParent();
3162
3163 assert(CurrentBB && "Corrupt instruction");
3164 // Create a temporary copy of the instruction we are considering.
3165 // LLVM refuses to deal with an instruction which was not inserted
3166 // to any BB. We can visit multiple BBs on the way "up", so we
3167 // create a temp copy of the original instruction and delete it later.
3168 // It is way cheaper than using splice and then
3169 // needing to undo it most of the time.
3170 MachineInstr *NewMI = MI->getParent()->getParent()->CloneMachineInstr(MI);
3171 // Make sure all bundling flags are cleared.
3172 if (NewMI->isBundledWithPred())
3173 NewMI->unbundleFromPred();
3174 if (NewMI->isBundledWithSucc())
3175 NewMI->unbundleFromSucc();
3176
3177 if (DeleteOldCopy) {
3178 // Remove our temporary instruction.
3179 // MachineBasicBlock::erase method calls unbundleSingleMI()
3180 // prior to deletion, so we do not have to do it here.
3182 CurrentBB->erase(kill_it);
3183 }
3184
3185 // If the original instruction used new value operands,
3186 // it might need to be changed to generic form
3187 // before further processing.
3188 if (QII->isDotNewInst(*NewMI))
3189 DemoteToDotOld(NewMI);
3190
3191 // Insert new temporary instruction.
3192 // If this is the destination packet, insert the tmp after
3193 // its header. Otherwise, as second instr in BB.
3194 if (TargetPacket->getParent() == MBB) {
3195 MII = TargetPacket.getInstrIterator();
3196
3197 if (MII->isBundled()) {
3198 bool LastInBundle = false;
3200 findInsertPositionInBundle(TargetPacket, NewMI, LastInBundle);
3201 MIBundleBuilder Bundle(&*TargetPacket);
3202 Bundle.insert(InsertBefore, NewMI);
3203 } else
3204 MBB->insertAfter(MII, NewMI);
3205 } else {
3206 MII = MBB->instr_begin();
3207
3208 // Skip debug instructions.
3209 while (MII->isDebugInstr())
3210 MII++;
3211
3212 if (MII->isBundled()) {
3213 MIBundleBuilder Bundle(&*MII);
3214 Bundle.insert(++MII, NewMI);
3215 } else
3216 MBB->insertAfter(MII, NewMI);
3217 }
3218 return NewMI->getIterator();
3219}
3220
3221// Check for a conditionally assigned register within the block.
3222bool HexagonGlobalSchedulerImpl::MIsCondAssign(MachineInstr *BMI,
3223 MachineInstr *MI,
3224 SmallVector<unsigned, 4> &Defs) {
3225 if (!QII->isPredicated(*BMI))
3226 return false;
3227 // Its a conditional instruction, now is it the same registers as MI?
3228 SmallVector<unsigned, 4> CondDefs;
3229 SmallVector<unsigned, 8> CondUses;
3230 parseOperands(BMI, CondDefs, CondUses);
3231
3232 for (SmallVector<unsigned, 4>::iterator ID = Defs.begin(), IDE = Defs.end();
3233 ID != IDE; ++ID) {
3234 for (SmallVector<unsigned, 4>::iterator CID = CondDefs.begin(),
3235 CIDE = CondDefs.end();
3236 CID != CIDE; ++CID) {
3237 if (AliasingRegs(*CID, *ID)) {
3238 LLVM_DEBUG(dbgs() << "\tFound conditional def, can't move\n";
3239 BMI->dump());
3240 return true;
3241 }
3242 }
3243 }
3244 return false;
3245}
3246
3247// Returns the Union of all the elements in Set1 and
3248// Union of all the elements in Set2 separately.
3249// Constraints:
3250// Set1 and Set2 should contain an entry for each element in Range.
3251template <typename ElemType, typename IndexType>
3252void Unify(std::vector<ElemType> Range,
3253 std::map<ElemType, std::vector<IndexType>> &Set1,
3254 std::map<ElemType, std::vector<IndexType>> &Set2,
3255 std::pair<std::vector<IndexType>, std::vector<IndexType>> &UnionSet,
3256 unsigned union_size = 100) {
3257 typedef
3258 typename std::map<ElemType, std::vector<IndexType>>::iterator PosIter_t;
3259 typedef typename std::vector<IndexType>::iterator IndexIter_t;
3260 std::vector<IndexType> &Union1 = UnionSet.first;
3261 std::vector<IndexType> &Union2 = UnionSet.second;
3262 Union1.resize(union_size, 0);
3263 Union2.resize(union_size, 0);
3264 LLVM_DEBUG(dbgs() << "\n\t\tElements in the range:\n";);
3265 typename std::vector<ElemType>::iterator iter = Range.begin();
3266 while (iter != Range.end()) {
3267 if ((*iter)->isDebugInstr()) {
3268 ++iter;
3269 continue;
3270 }
3271 LLVM_DEBUG((*iter)->dump());
3272 PosIter_t set1_pos = Set1.find(*iter);
3273 assert(set1_pos != Set1.end() &&
3274 "Set1 should contain an entry for each element in Range.");
3275 IndexIter_t set1idx = set1_pos->second.begin();
3276 while (set1idx != set1_pos->second.end()) {
3277 Union1[*set1idx] = 1;
3278 ++set1idx;
3279 }
3280 PosIter_t set2_pos = Set2.find(*iter);
3281 assert(set2_pos != Set2.end() &&
3282 "Set2 should contain an entry for each element in Range.");
3283 IndexIter_t set2idx = set2_pos->second.begin();
3284 while (set2idx != set2_pos->second.end()) {
3285 Union2[*set2idx] = 1;
3286 ++set2idx;
3287 }
3288 ++iter;
3289 }
3290}
3291
3292static void UpdateBundle(MachineInstr *BundleHead) {
3293 assert(BundleHead->isBundle() && "Not a bundle header");
3294 if (!BundleHead)
3295 return;
3296 unsigned Size = BundleHead->getBundleSize();
3297 if (Size >= 2)
3298 return;
3299 if (Size == 1) {
3300 MachineBasicBlock::instr_iterator MIter = BundleHead->getIterator();
3301 MachineInstr *MI = &*(++MIter);
3302 MI->unbundleFromPred();
3303 }
3304 BundleHead->eraseFromParent();
3305}
3306
3307/// Gatekeeper for instruction speculation.
3308/// If all MI defs are dead (not live-in) to any other
3309/// BB but the one we are moving into, and it could not cause
3310/// exception by early execution, allow it to be pulled up.
3311bool HexagonGlobalSchedulerImpl::canMIBeSpeculated(
3312 MachineInstr *MI, MachineBasicBlock *ToBB, MachineBasicBlock *FromBB,
3313 std::vector<MachineInstr *> &backtrack) {
3314 // For now disallow memory accesses from speculation.
3315 // Generally we can check if they potentially may trap/cause an exception.
3316 if (!EnableSpeculativePullUp || !MI || MI->mayStore())
3317 return false;
3318
3319 LLVM_DEBUG(dbgs() << "\t[canMIBeSpeculated] From BB(" << FromBB->getNumber()
3320 << "):\t";
3321 MI->dump());
3322 LLVM_DEBUG(dbgs() << "\tTo this BB:\n"; ToBB->dump());
3323
3324 if (!ToBB->isSuccessor(FromBB))
3325 return false;
3326
3327 // This is a very tricky topic. Speculating arithmetic instructions with
3328 // results dead out of a loop more times then required by number of
3329 // iterations is safe, while speculating loads can cause an exception.
3330 // Simplest of checks is to not cross loop exit edge, or in our case
3331 // do not pull-in to a loop exit BB, but there are implications for
3332 // non-natural loops (not recognized by LLVM as loops) and multi-threaded
3333 // code.
3334 if (AllowSpeculateLoads && MI->mayLoad()) {
3335 // Invariant loads should always be safe.
3336 if (!MI->isDereferenceableInvariantLoad())
3337 return false;
3338 LLVM_DEBUG(dbgs() << "\tSpeculating a Load.\n");
3339 }
3340
3341 SmallVector<unsigned, 4> Defs;
3342 SmallVector<unsigned, 8> Uses;
3343 parseOperands(MI, Defs, Uses);
3344
3345 // Do not speculate instructions that modify reserved global registers.
3346 for (unsigned R : Defs)
3347 if (MRI->isReserved(R) && QRI->isGlobalReg(R))
3348 return false;
3349
3351 SE = ToBB->succ_end();
3352 SI != SE; ++SI) {
3353 // TODO: Allow an instruction (I) which 'defines' the live-in reg (R)
3354 // along the path when I is the first instruction to use the R.
3355 // i.e., I kills R before any other instruction in the BB uses it.
3356 // TODO: We have already parsed live sets - reuse them.
3357 if (*SI == FromBB)
3358 continue;
3359 LLVM_DEBUG(dbgs() << "\tTarget succesor BB to check:\n"; (*SI)->dump());
3360 LLVM_DEBUG(
3361 for (MachineBasicBlock::const_succ_iterator SII = (*SI)->succ_begin(),
3362 SIE = (*SI)->succ_end();
3363 SII != SIE; ++SII)(*SII)
3364 ->dump());
3365 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
3366 E = (*SI)->livein_end();
3367 I != E; ++I)
3368 for (SmallVector<unsigned, 4>::iterator ID = Defs.begin(),
3369 IDE = Defs.end();
3370 ID != IDE; ++ID) {
3371 if (AliasingRegs((*I).PhysReg, *ID))
3372 return false;
3373 }
3374
3375 // Check the successor blocks for conditional define.
3376 // TODO: We should really test the whole path here.
3377 for (MachineBasicBlock::instr_iterator BI = (*SI)->instr_begin(),
3378 E = (*SI)->instr_end();
3379 BI != E; ++BI) {
3380 if (BI->isBundle() || BI->isDebugInstr())
3381 continue;
3382 LLVM_DEBUG(dbgs() << "\t\tcheck against:\t"; BI->dump());
3383 if (MIsCondAssign(&*BI, MI, Defs))
3384 return false;
3385 }
3386 }
3387 // Taking a very conservative approach during speculation.
3388 // Traverse the path (FromBB, ToBB] and make sure
3389 // that the def-use set of the instruction to be moved
3390 // are not modified.
3391 std::vector<MachineBasicBlock *> PathBB;
3392 for (unsigned i = 0; i < backtrack.size(); ++i) {
3393 // Insert unique BB along the path but skip FromBB
3394 MachineBasicBlock *MBB = backtrack[i]->getParent();
3395 if ((MBB != FromBB) &&
3396 (std::find(PathBB.begin(), PathBB.end(), MBB) == PathBB.end()))
3397 PathBB.push_back(MBB);
3398 }
3399 bool WaitingForTargetPacket = true;
3401 std::vector<MachineInstr *> TraversalRange;
3402 LLVM_DEBUG(dbgs() << "\n\tElements in the range:");
3403 // TODO: Use just the backtrack to get TraversalRange because it
3404 // contains the path (only when speculated from a path in region).
3405 // Note: We check the dependency of instruction-to-move with
3406 // all the instructions (starting from backtrack[0]) in the parent BBs
3407 // because a BB might have a branching from in between due to packetization
3408 // and just checking packets in the backtrack won't be comprehensive.
3409 for (unsigned i = 0; i < PathBB.size(); ++i) {
3410 for (MII = PathBB[i]->instr_begin(); MII != PathBB[i]->instr_end(); ++MII) {
3411 // Skip instructions until the target packet is found.
3412 // although target packet is already checked for correctness,
3413 // it is good to check here to validate intermediate pullups.
3414 if (backtrack[0] == &*MII)
3415 WaitingForTargetPacket = false;
3416 if (WaitingForTargetPacket)
3417 continue;
3418 if (MII->isBundle())
3419 continue;
3420 // TODO: Ideally we should check that there is a `linear' control flow
3421 // in the TraversalRange in all possible manner. For e.g.,
3422 // BB0 { packet1: if(p0) indirect_jump BB1;
3423 // packet2: jump BB2 }
3424 // BB1 { i1 }. In this case we should not pull `i1' into packet2.
3425 if (MII->isCall() || MII->isReturn() ||
3426 (MII->getOpcode() == Hexagon::J2_jump && !MII->getOperand(0).isMBB()))
3427 return false;
3428 if (MI != &*MII) {
3429 TraversalRange.push_back(&*MII);
3430 LLVM_DEBUG(MII->dump(););
3431 }
3432 }
3433 }
3434 // Get the union of def/use set of all the instructions along TraversalRange.
3435 std::pair<std::vector<unsigned>, std::vector<unsigned>> RangeDefUse;
3436 Unify(TraversalRange, MIDefSet, MIUseSet, RangeDefUse, QRI->getNumRegs());
3437 // No instruction (along TraversalRange) should 'define' the use set of MI
3438 for (unsigned j = 0; j < Uses.size(); ++j)
3439 if (RangeDefUse.first[Uses[j]]) {
3440 LLVM_DEBUG(dbgs() << "\n\t\tUnresolved dependency along path to HOME for "
3441 << printReg(Uses[j], QRI););
3442 return false;
3443 }
3444 // No instruction (along TraversalRange) should 'define' or 'use'
3445 // the def set of MI
3446 for (unsigned j = 0; j < Defs.size(); ++j)
3447 if (RangeDefUse.first[Defs[j]] || RangeDefUse.second[Defs[j]]) {
3448 LLVM_DEBUG(dbgs() << "\n\t\tUnresolved dependency along path to HOME for "
3449 << printReg(Defs[j], QRI););
3450 return false;
3451 }
3452 return true;
3453}
3454
3455/// Try to move InstrToMove to TargetPacket using path stored in backtrack.
3456/// SourceLocation is current iterator point. It must be updated to the new
3457/// iteration location after all updates.
3458/// Alogrithm:
3459/// To move an instruction (I) from OriginBB through HomeBB via backtrack.
3460/// for each packet (i) in backtrack, analyzeBranch
3461/// case 1 (success)
3462/// case Pulling from conditional branch:
3463/// if I is predicable
3464/// Try to predicate on the branch condition
3465/// else
3466/// Try to speculate I to backtrack[i].
3467/// case Pulling from unconditional branch:
3468/// Just pullup. (TODO: Speculate here as well)
3469/// case 2 (fails)
3470/// Try to speculate I backtrack[i].
3471bool HexagonGlobalSchedulerImpl::MoveMItoBundle(
3472 BasicBlockRegion *CurrentRegion,
3475 MachineBasicBlock::iterator &TargetPacket,
3476 MachineBasicBlock::iterator &SourceLocation,
3477 std::vector<MachineInstr *> &backtrack, bool MovingDependentOp,
3478 bool PathInRegion) {
3479 MachineBasicBlock *HomeBB = TargetPacket->getParent();
3480 MachineBasicBlock *OriginBB = InstrToMove->getParent();
3481 MachineBasicBlock *CurrentBB = OriginBB;
3482 MachineBasicBlock *CleanupBB = OriginBB;
3483 MachineBasicBlock *PreviousBB = OriginBB;
3484 MachineInstr *OriginalInstructionToMove = &*InstrToMove;
3485
3486 assert(HomeBB && "Missing HomeBB");
3487 assert(OriginBB && "Missing OriginBB");
3488
3489 LLVM_DEBUG(dbgs() << "\n.........[MoveMItoBundle]..............\n");
3490 LLVM_DEBUG(dbgs() << "\t\tInstrToMove :\t"; InstrToMove->dump());
3491 LLVM_DEBUG(dbgs() << "\t\tTargetPacket :\t";
3492 DumpPacket(TargetPacket.getInstrIterator()));
3493 LLVM_DEBUG(dbgs() << "\t\tSourceLocation:\t";
3494 DumpPacket(SourceLocation.getInstrIterator()));
3495
3496 // We do not allow to move instructions in the same BB.
3497 if (HomeBB == OriginBB) {
3498 LLVM_DEBUG(dbgs() << "\t\tSame BB pull-up.\n");
3499 if (!EnableLocalPullUp)
3500 return false;
3501 }
3502
3503 if (OneFloatPerPacket && QII->isFloat(*TargetPacket) &&
3504 QII->isFloat(*InstrToMove))
3505 return false;
3506
3507 if (OneComplexPerPacket && QII->isComplex(*TargetPacket) &&
3508 QII->isComplex(*InstrToMove))
3509 return false;
3510
3511 LLVM_DEBUG(dbgs() << "\t\tWay home:\n");
3512 // Test integrity of the back track.
3513 for (unsigned i = 0; i < backtrack.size(); ++i) {
3514 assert(backtrack[i]->getParent() && "Messed back track.");
3515 LLVM_DEBUG(dbgs() << "\t\t[" << i << "] BB("
3516 << backtrack[i]->getParent()->getNumber() << ")\t";
3517 backtrack[i]->dump());
3518 }
3519 LLVM_DEBUG(dbgs() << "\n");
3520
3521 bool NeedCleanup = false;
3522 bool NeedToPredicate = false;
3523 bool MINeedToNewify = false;
3524 unsigned DepReg = std::numeric_limits<unsigned>::max();
3525 bool isDualJump = false;
3526 SmallVector<MachineOperand, 4> Cond;
3527 SmallVector<MachineOperand, 4> PredCond;
3528 std::vector<MachineInstr *> PullUpPath;
3529 if (PathInRegion)
3530 PullUpPath = backtrack;
3531 else {
3532 PullUpPath.push_back(&*TargetPacket);
3533 PullUpPath.push_back(&*InstrToMove);
3534 }
3535
3536 // Now start iterating over all instructions
3537 // preceeding the one we are trying to move,
3538 // and see if they could be reodered/bypassed.
3539 for (std::vector<MachineInstr *>::reverse_iterator RI = backtrack.rbegin(),
3540 RIE = backtrack.rend();
3541 RI < RIE; ++RI) {
3542 // Once most of debug will be gone, this will be a real assert.
3543 // assert((backtrack.front() == ToThisBundle) && "Lost my way home.");
3544 MachineInstr *MIWH = *RI;
3545 if (QII->isDotNewInst(*InstrToMove)) {
3546 LLVM_DEBUG(dbgs() << "Cannot move a dot new instruction:";
3547 InstrToMove->dump());
3548 if (NeedCleanup)
3549 CleanupBB->erase(InstrToMove);
3550 return false;
3551 }
3552 if (canCauseStall(&*InstrToMove, MIWH)) {
3553 if (NeedCleanup)
3554 CleanupBB->erase(InstrToMove);
3555 return false;
3556 }
3557 LLVM_DEBUG(dbgs() << "\t> Step home BB(" << MIWH->getParent()->getNumber()
3558 << "):\t";
3559 DumpPacket(MIWH->getIterator()));
3560
3561 // See if we cross a jump, and possibly change the form of instruction.
3562 // Passing through BBs with dual jumps in different packets
3563 // takes extra care.
3564 bool isBranchMIWH = isBranch(MIWH);
3565 if (((&*SourceLocation != MIWH) && isBranchMIWH) ||
3566 (CurrentBB != MIWH->getParent())) {
3567 LLVM_DEBUG(dbgs() << "\tChange BB from(" << CurrentBB->getNumber()
3568 << ") to (" << MIWH->getParent()->getNumber() << ")\n");
3569 PreviousBB = CurrentBB;
3570 CurrentBB = MIWH->getParent();
3571
3572 // See what kind of branch we are dealing with.
3573 MachineBasicBlock *PredTBB = NULL;
3574 MachineBasicBlock *PredFBB = NULL;
3575
3576 if (QII->analyzeBranch(*CurrentBB, PredTBB, PredFBB, Cond, false)) {
3577 // We currently do not handle NV jumps of this kind:
3578 // if (cmp.eq(r0.new, #0)) jump:t .LBB12_69
3579 // TODO: Need to handle them.
3580 LLVM_DEBUG(dbgs() << "\tCould not analyze branch.\n");
3581
3582 // This is the main point of lost performance.
3583 // We could try to speculate here, but for that we need accurate
3584 // liveness info, and it is not ready yet.
3585 if (!canMIBeSpeculated(&*InstrToMove, CurrentBB, PreviousBB,
3586 PullUpPath)) {
3587 if (NeedCleanup)
3588 CleanupBB->erase(InstrToMove);
3589 return false;
3590 } else {
3591 // Save speculated instruction moved.
3592 SpeculatedIns.insert(
3593 std::make_pair(OriginalInstructionToMove, OriginBB));
3594 LLVM_DEBUG(dbgs() << "\nSpeculatedInsToMove"; InstrToMove->dump());
3595 }
3596
3597 LLVM_DEBUG(dbgs() << "\tSpeculating.\n");
3598 // If we are speculating, we can come through a predication
3599 // into an unconditional branch...
3600 // For now simply bail out.
3601 // TODO: See if this ever happens.
3602 if (NeedToPredicate) {
3604 << "\tUnderimplemented pred for speculative move.\n");
3605 if (NeedCleanup)
3606 CleanupBB->erase(InstrToMove);
3607 return false;
3608 }
3609 InstrToMove =
3610 insertTempCopy(CurrentBB, TargetPacket, &*InstrToMove, NeedCleanup);
3611 NeedCleanup = true;
3612 NeedToPredicate = false;
3613 assert(!NeedToPredicate && "Need to handle predication for this case");
3614 CleanupBB = CurrentBB;
3615 // No need to recheck for resources - instruction did not change.
3616 LLVM_DEBUG(dbgs() << "\tUpdated BB:\n"; CurrentBB->dump());
3617 } else {
3618 bool LocalNeedPredication = true;
3619 // We were able to analyze the branch.
3620 if (!isBranchMIWH && !PredTBB) {
3621 LLVM_DEBUG(dbgs() << "\tDo not need predicate for this case.\n");
3622 LocalNeedPredication = false;
3623 }
3624 // First see if this is a potential dual jump situation.
3625 if (IsDualJumpSecondCandidate(&*InstrToMove) &&
3626 IsDualJumpFirstCandidate(TargetPacket)) {
3627 LLVM_DEBUG(dbgs() << "\tPerforming unrestricted dual jump.\n");
3628 isDualJump = true;
3629 } else if (LocalNeedPredication && (PredFBB != PreviousBB)) {
3630 // Predicate instruction based on condition feeding it.
3631 // This is generally a statefull pull-up path.
3632 // Can this insn be predicated? If so, try to do it.
3633 if (TII->isPredicable(*InstrToMove)) {
3634 if (PredTBB) {
3635 if (PreviousBB != PredTBB) {
3636 // If we "came" not from TBB, we need to invert condition.
3638 LLVM_DEBUG(dbgs() << "\tUnable to invert condition.\n");
3639 if (NeedCleanup)
3640 CleanupBB->erase(InstrToMove);
3641 return false;
3642 }
3643 }
3644 LLVM_DEBUG(dbgs() << "\tTBB(" << PredTBB->getNumber()
3645 << ")InvertCondition("
3646 << (PreviousBB != PredTBB) << ")\n");
3647 }
3648 // Create a new copy of the instruction we are trying to move.
3649 // It changes enough (new BB, predicated form) and untill we
3650 // reach home, we do not even know if it is going to work.
3651 InstrToMove = insertTempCopy(CurrentBB, TargetPacket, &*InstrToMove,
3652 NeedCleanup);
3653 NeedCleanup = true;
3654 NeedToPredicate = true;
3655 CleanupBB = CurrentBB;
3656
3657 if (PredCond.empty() && // If not already predicated.
3658 TII->PredicateInstruction(*InstrToMove, Cond)) {
3659 LLVM_DEBUG(dbgs() << "\tNew predicated insn:\t";
3660 InstrToMove->dump());
3661 // After predication some instruction could become const extended:
3662 // L2_loadrigp == "$dst=memw(#$global)"
3663 // L4_ploadrit_abs == "if ($src1) $dst=memw(##$global)"
3664 // Resource checking for those is different.
3665 if ((QII->isExtended(*InstrToMove) ||
3666 QII->isConstExtended(*InstrToMove) ||
3667 isJumpOutOfRange(&*InstrToMove)) &&
3668 !tryAllocateResourcesForConstExt(&*InstrToMove, false)) {
3669 // If we cannot, do not modify the state.
3671 << "\tEI Could not be added to the packet.\n");
3672 CleanupBB->erase(InstrToMove);
3673 return false;
3674 }
3675
3676 if (!ResourceTracker->canReserveResources(*InstrToMove) ||
3677 !shouldAddToPacket(*InstrToMove)) {
3678 // It will not fit in its new form...
3679 LLVM_DEBUG(dbgs() << "\tCould not be added in its new form.\n");
3680 CurrentBB->erase(InstrToMove);
3681 return false;
3682 }
3683
3684 // Need also verify that we can newify it if we want to.
3685 if (NeedToNewify(InstrToMove, &DepReg, &*TargetPacket)) {
3686 if (isNewifiable(InstrToMove, DepReg, &*TargetPacket)) {
3687 MINeedToNewify = true;
3688 LLVM_DEBUG(dbgs() << "\t\t\tNeeds to NEWify on Reg("
3689 << printReg(DepReg, QRI) << ").\n");
3690 } else {
3691 LLVM_DEBUG(dbgs() << "\tNon newifiable in this bundle: ";
3692 InstrToMove->dump());
3693 CleanupBB->erase(InstrToMove);
3694 return false;
3695 }
3696 }
3697
3698 LLVM_DEBUG(dbgs() << "\tUpdated BB:\n"; CurrentBB->dump());
3699 PredCond = Cond;
3700 // Now the instruction uses the pred-reg as well.
3701 if (!Cond.empty() && (Cond.size() == 2)) {
3702 MIUseSet[OriginalInstructionToMove].push_back(Cond[1].getReg());
3703 }
3704 assert(((Cond.size() <= 2) &&
3705 !(QII->isNewValueJump(Cond[0].getImm()))) &&
3706 "Update MIUseSet for new-value compare jumps");
3707 } else {
3708 LLVM_DEBUG(dbgs() << "\tCould not predicate it\n");
3709 LLVM_DEBUG(dbgs() << "\tTrying to speculate!\t";
3710 InstrToMove->dump());
3711 bool DistantSpeculation = false;
3712 std::vector<MachineInstr *> NonPredPullUpPath;
3713 unsigned btidx = 0;
3714 // Generate a backtrack path for instruction to be speculated.
3715 // Original backtrack may start from a different (ancestor)
3716 // target packet.
3717 while (btidx < backtrack.size()) {
3718 const MachineBasicBlock *btBB = backtrack[btidx]->getParent();
3719 if ((btBB == PreviousBB) || (btBB == CurrentBB))
3720 NonPredPullUpPath.push_back(backtrack[btidx]);
3721 ++btidx;
3722 }
3723 // Speculate only to immediate predecessor.
3724 if (PreviousBB != CurrentBB) {
3725 if (*(PreviousBB->pred_begin()) != CurrentBB) {
3726 // In a region there are no side entries.
3727 DistantSpeculation = true;
3729 << "\n\tMI not in immediate successor of BB#"
3730 << CurrentBB->getNumber() << ", MI is in BB#"
3731 << PreviousBB->getNumber(););
3732 }
3733 assert((PreviousBB->pred_size() < 2) &&
3734 "Region with a side entry");
3735 }
3736 // TODO: Speculate ins. when pulled from unlikely path.
3737 if (DistantSpeculation || /*!PathInRegion ||*/
3738 InstrToMove->mayLoad() || InstrToMove->mayStore() ||
3739 InstrToMove->hasUnmodeledSideEffects() ||
3740 !canMIBeSpeculated(&*InstrToMove, CurrentBB, PreviousBB,
3741 NonPredPullUpPath)) {
3742 CleanupBB->erase(InstrToMove);
3743 return false;
3744 } else {
3745 // Save speculated instruction moved.
3746 NeedToPredicate = false;
3747 SpeculatedIns.insert(
3748 std::make_pair(OriginalInstructionToMove, OriginBB));
3749 LLVM_DEBUG(dbgs() << "\nPredicable+SpeculatedInsToMove";
3750 InstrToMove->dump());
3751 }
3752 }
3753 } else {
3754 // This is a non-predicable instruction. We still can try to
3755 // speculate it here.
3756 LLVM_DEBUG(dbgs() << "\tNon predicable insn!\t";
3757 InstrToMove->dump());
3758 // TODO: Speculate ins. when pulled from unlikely path.
3759 if (!SpeculateNonPredInsn || !PathInRegion ||
3760 InstrToMove->mayLoad() || InstrToMove->mayStore() ||
3761 InstrToMove->hasUnmodeledSideEffects() ||
3762 !canMIBeSpeculated(&*InstrToMove, CurrentBB, PreviousBB,
3763 PullUpPath)) {
3764 if (NeedCleanup)
3765 CleanupBB->erase(InstrToMove);
3766 return false;
3767 } else {
3768 // Save speculated instruction moved.
3769 SpeculatedIns.insert(
3770 std::make_pair(OriginalInstructionToMove, OriginBB));
3771 LLVM_DEBUG(dbgs() << "\nNonPredicable+SpeculatedInsToMove";
3772 InstrToMove->dump());
3773 }
3774
3775 InstrToMove = insertTempCopy(CurrentBB, TargetPacket, &*InstrToMove,
3776 NeedCleanup);
3777 NeedCleanup = true;
3778 CleanupBB = CurrentBB;
3779 }
3780 } else {
3781 // No branch. Fall through.
3782 LLVM_DEBUG(dbgs() << "\tFall through BB.\n"
3783 << "\tCurrentBB:" << CurrentBB->getNumber()
3784 << "\tPreviousBB:" << PreviousBB->getNumber();
3785 if (PredFBB) dbgs()
3786 << "\tPredFBB:" << PredFBB->getNumber(););
3787 // Even though this is a fall though case, we still can
3788 // have a dual jump situation here with a CALL involved.
3789 // For now simply avoid it.
3790 if (IsDualJumpSecondCandidate(&*InstrToMove)) {
3791 llvm_unreachable("Dual jumps with known?");
3792 LLVM_DEBUG(dbgs() << "\tUnderimplemented dual jump formation.\n");
3793 if (NeedCleanup)
3794 CleanupBB->erase(InstrToMove);
3795 return false;
3796 }
3797
3798 if (!CurrentBB->isSuccessor(PreviousBB)) {
3799 LLVM_DEBUG(dbgs() << "\tNon-successor fall through.\n");
3800 if (NeedCleanup)
3801 CleanupBB->erase(InstrToMove);
3802 return false;
3803 }
3804 // Don't pull a predicated instruction above the def of its
3805 // predicate (which may live in PreviousBB), as that reads a stale
3806 // predicate. PredCond holds the predication; Cond was just clobbered
3807 // by analyzeBranch(CurrentBB).
3808 if (!PredCond.empty()) {
3809 for (const MachineOperand &CMO : PredCond) {
3810 if (!CMO.isReg())
3811 continue;
3812 Register PredReg = CMO.getReg();
3813 bool DefinedInPrev = false;
3814 for (MachineInstr &PMI : PreviousBB->instrs()) {
3815 if (PMI.isBundle())
3816 continue;
3817 if (PMI.definesRegister(PredReg, QRI)) {
3818 DefinedInPrev = true;
3819 break;
3820 }
3821 }
3822 if (DefinedInPrev) {
3824 << "\tFall-through would pull predicated insn above "
3825 "its predicate def; bailing out.\n");
3826 if (NeedCleanup)
3827 CleanupBB->erase(InstrToMove);
3828 return false;
3829 }
3830 }
3831 }
3832 SpeculatedIns.insert(
3833 std::make_pair(OriginalInstructionToMove, OriginBB));
3834 LLVM_DEBUG(dbgs() << "\nSpeculatedInsToMove+FallThroughBB";
3835 InstrToMove->dump());
3836 // Create a temp copy.
3837 InstrToMove = insertTempCopy(CurrentBB, TargetPacket, &*InstrToMove,
3838 NeedCleanup);
3839 NeedCleanup = true;
3840 NeedToPredicate = false;
3841 CleanupBB = CurrentBB;
3842 LLVM_DEBUG(dbgs() << "\tUpdated BB:\n"; CurrentBB->dump());
3843 }
3844 }
3845 }
3846 // If we have reached Home, great.
3847 // Original check should have verified that instruction could be added
3848 // to the target packet, so here we do nothing for deps.
3849 if (MIWH == backtrack.front()) {
3850 LLVM_DEBUG(dbgs() << "\tHOME!\n");
3851 break;
3852 }
3853
3854 // Test if we can reorder the two MIs.
3855 // The exception is when we are forming dual jumps - we can pull up
3856 // dependent instruction to the last bundle of an immediate predecesor
3857 // of the current BB if control flow permits it.
3858 // In this special case we also need to update the bundle we are moving
3859 // from.
3860 if (!(MovingDependentOp && (MIWH == &*SourceLocation)) &&
3861 !canReorderMIs(MIWH, &*InstrToMove)) {
3862 if (NeedCleanup)
3863 CleanupBB->erase(InstrToMove);
3864 return false;
3865 }
3866 }
3867 // We have previously tested this instruction, but has not updated the state
3868 // for it. Do it now.
3869 if (QII->isExtended(*InstrToMove) || QII->isConstExtended(*InstrToMove) ||
3870 isJumpOutOfRange(&*InstrToMove)) {
3871 if (!tryAllocateResourcesForConstExt(&*InstrToMove))
3872 llvm_unreachable("Missed dependency test");
3873 }
3874
3875 // Ok. We can safely move this instruction all the way up.
3876 // We also potentially have a slot for it.
3877 // During move original instruction could have changed (becoming predicated).
3878 // Now try to place the final instance of it into the current packet.
3879 LLVM_DEBUG(dbgs() << "\nWant to move ";
3880 if (MovingDependentOp) dbgs() << "dependent op"; dbgs() << ": ";
3881 InstrToMove->dump(); dbgs() << "To BB:\n"; HomeBB->dump();
3882 dbgs() << "From BB:\n"; OriginBB->dump());
3883
3884 // Keep these two statistics separately.
3885 if (!isDualJump)
3886 HexagonNumPullUps++;
3887 else
3888 HexagonNumDualJumps++;
3889
3890 // This means we have not yet inserted the temp copy of InstrToMove
3891 // in the target bundle. We are probably inside the same BB.
3892 if (!NeedCleanup) {
3893 InstrToMove =
3894 insertTempCopy(HomeBB, TargetPacket, &*InstrToMove, NeedCleanup);
3895 NeedCleanup = true;
3896 }
3897
3898 // No problems detected. Add it.
3899 // If we were adding InstrToMove to a single, not yet packetized
3900 // instruction, we need to create bundle header for it before proceeding.
3901 // Be carefull since endPacket also resets the DFA state.
3902 if (!TargetPacket->isBundle()) {
3903 LLVM_DEBUG(dbgs() << "\tForm a new bundle.\n");
3904 finalizeBundle(*HomeBB, TargetPacket.getInstrIterator(),
3905 std::next(InstrToMove));
3906 LLVM_DEBUG(HomeBB->dump());
3907 // Now we need to adjust pointer to the newly created packet header.
3909 MII--;
3910
3911 // Is it also on the way home?
3912 for (unsigned i = 0; i < backtrack.size(); ++i)
3913 if (backtrack[i] == &*TargetPacket)
3914 backtrack[i] = &*MII;
3915
3916 // Is it where our next MI is pointing?
3917 if (NextMI == TargetPacket)
3918 NextMI = MII;
3919 TargetPacket = MII;
3920 }
3921
3922 // Move and Update Liveness info.
3923 MoveAndUpdateLiveness(CurrentRegion, HomeBB, &*InstrToMove, MINeedToNewify,
3924 DepReg, MovingDependentOp, OriginBB,
3925 OriginalInstructionToMove, PredCond, SourceLocation,
3926 TargetPacket, NextMI, backtrack);
3927
3928 LLVM_DEBUG(dbgs() << "\n______Updated______\n"; HomeBB->dump();
3929 OriginBB->dump());
3930
3931 return true;
3932}
3933
3934/// Verify that we respect CFG layout during pull-up.
3935bool HexagonGlobalSchedulerImpl::isBranchWithinRegion(
3936 BasicBlockRegion *CurrentRegion, MachineInstr *MI) {
3937 assert(MI && MI->isBranch() && "Missing call info");
3938
3939 MachineBasicBlock *MBB = MI->getParent();
3940 LLVM_DEBUG(dbgs() << "\t[isBranchWithinRegion] BB(" << MBB->getNumber()
3941 << ") Branch instr:\t";
3942 MI->dump());
3943 // If there is only one successor, it is safe to pull.
3944 if (MBB->succ_size() <= 1)
3945 return true;
3946 // If there are multiple successors (jump table), we should
3947 // not allow pull up over this instruction.
3948 if (MBB->succ_size() > 2)
3949 return false;
3950
3951 MachineBasicBlock *NextRegionBB;
3952 MachineBasicBlock *TBB, *FBB;
3953 MachineInstr *FirstTerm = NULL;
3954 MachineInstr *SecondTerm = NULL;
3955
3956 if (AnalyzeBBBranches(MBB, TBB, FirstTerm, FBB, SecondTerm)) {
3957 LLVM_DEBUG(dbgs() << "\t\tAnalyzeBBBranches failed!\n");
3958 return false;
3959 }
3960
3961 // If there is no jump in this BB, it simply falls through.
3962 if (!FirstTerm) {
3963 LLVM_DEBUG(dbgs() << "\t\tNo FirstTerm\n");
3964 return true;
3965 } else if (QII->isEndLoopN(FirstTerm->getOpcode())) {
3966 // We can easily analyze where endloop would take us
3967 // but here it would be pointless either way since
3968 // the region will not cross it.
3969 LLVM_DEBUG(dbgs() << "\t\tEndloop terminator\n");
3970 return false;
3971 }
3972 // On some occasions we see code like this:
3973 // BB#142: derived from LLVM BB %init, Align 4 (16 bytes)
3974 // Live Ins: %R17 %R18
3975 // Predecessors according to CFG: BB#2
3976 // EH_LABEL <MCSym=.Ltmp35>
3977 // J2_jump <BB#3>, %PC<imp-def>
3978 // Successors according to CFG: BB#3(1048575) BB#138(1)
3979 // It breaks most assumptions about CFG layout, so untill we know
3980 // the source of it, let's have a safeguard.
3981 if (MBB->succ_size() > 1 && !TII->isPredicated(*FirstTerm) &&
3982 !QII->isNewValueJump(*FirstTerm)) {
3983 LLVM_DEBUG(dbgs() << "\t\tBadly formed BB.\n");
3984 return false;
3985 }
3986
3987 LLVM_DEBUG(dbgs() << "\t\tFirstTerm: "; FirstTerm->dump());
3988 LLVM_DEBUG(dbgs() << "\t\tSecondTerm: "; if (SecondTerm) SecondTerm->dump();
3989 else dbgs() << "None\n";);
3990
3991 // All cases where there is only one branch in BB are OK to proceed.
3992 if (!SecondTerm)
3993 return true;
3994
3995 assert(!QII->isEndLoopN(SecondTerm->getOpcode()) && "Found endloop.");
3996
3997 // Find next BB in this region - if there is none, we will likely
3998 // stop pulling in the next check outside of this function.
3999 // This largely is don't care.
4000 NextRegionBB = CurrentRegion->findNextMBB(MBB);
4001 if (!NextRegionBB) {
4002 LLVM_DEBUG(dbgs() << "\t\tNo next BB in the region...\n");
4003 return true;
4004 }
4005 LLVM_DEBUG(dbgs() << "\t\tNextRegionBB(" << NextRegionBB->getNumber()
4006 << ")\n");
4007 assert(TBB && "Corrupt BB layout");
4008 // This means we are trying to pull into a packet _before_ the first
4009 // branch in the MBB.
4010 if (MI == FirstTerm) {
4011 LLVM_DEBUG(dbgs() << "\t\tTBB(" << TBB->getNumber()
4012 << ") NextBB in the region(" << NextRegionBB->getNumber()
4013 << ")\n");
4014 return (TBB == NextRegionBB);
4015 }
4016 assert(FBB && "Corrupt BB layout");
4017 // This means we are trying to pull into the packet _after_ first branch,
4018 // and it is OK if we pull from the second branch target.
4019 // This pull is always speculative.
4020 if ((MI != SecondTerm)) {
4021 LLVM_DEBUG(dbgs() << "\t\tDual terminator not matching SecondTerm.\n");
4022 return false;
4023 }
4024 // Analyze the second branch in the BB.
4025 LLVM_DEBUG(dbgs() << "\t\tFBB(" << FBB->getNumber()
4026 << ") NextBB in the region(" << NextRegionBB->getNumber()
4027 << ")\n");
4028 return (FBB == NextRegionBB);
4029}
4030
4031/// Check if a given instruction is:
4032/// - a jump to a distant target
4033/// - that exceeds its immediate range
4034/// If both conditions are true, it requires constant extension.
4035bool HexagonGlobalSchedulerImpl::isJumpOutOfRange(MachineInstr *UnCond,
4036 MachineInstr *Cond) {
4037 if (!UnCond || !UnCond->isBranch())
4038 return false;
4039
4040 MachineBasicBlock *UnCondBB = UnCond->getParent();
4041 MachineBasicBlock *CondBB = Cond->getParent();
4042 MachineInstr *FirstTerm = &*(CondBB->getFirstInstrTerminator());
4043 // This might be worth an assert.
4044 if (FirstTerm == &*CondBB->instr_end())
4045 return false;
4046
4047 unsigned InstOffset = BlockToInstOffset[UnCondBB];
4048 unsigned Distance = 0;
4049
4050 // To save time, estimate exact position of a branch instruction
4051 // as one at the end of the UnCondBB.
4052 // Number of instructions times typical instruction size.
4053 InstOffset += (QII->nonDbgBBSize(UnCondBB) * HEXAGON_INSTR_SIZE);
4054
4055 MachineBasicBlock *TBB = NULL, *FBB = NULL;
4056 SmallVector<MachineOperand, 4> CondList;
4057
4058 // Find the target of the unconditional branch in UnCondBB, which is returned
4059 // in TBB. Then use the CondBB to extract the FirsTerm. We desire to replace
4060 // the branch target in FirstTerm with the branch location from the UnCondBB,
4061 // provided it is within the distance of the opcode in FirstTerm.
4062 if (QII->analyzeBranch(*UnCondBB, TBB, FBB, CondList, false))
4063 // Could not analyze it. give up.
4064 return false;
4065
4066 if (TBB && (Cond == FirstTerm)) {
4067 Distance =
4068 (unsigned)std::abs((long long)InstOffset - BlockToInstOffset[TBB]) +
4070 return !QII->isJumpWithinBranchRange(*FirstTerm, Distance);
4071 }
4072 return false;
4073}
4074
4075// findBundleAndBranch returns the branch instruction and the
4076// bundle which contains it. Null is returned if not found.
4077MachineInstr *HexagonGlobalSchedulerImpl::findBundleAndBranch(
4078 MachineBasicBlock *BB, MachineBasicBlock::iterator &Bundle) {
4079 // Find the conditional branch out of BB.
4080 if (!BB)
4081 return NULL;
4082 MachineInstr *CondBranch = NULL;
4083 Bundle = BB->end();
4085 MBBEnd = BB->instr_end();
4086 MII != MBBEnd; ++MII) {
4087 MachineInstr *MI = &*MII;
4088 if (MII->isConditionalBranch()) {
4089 CondBranch = MI;
4090 }
4091 }
4092 if (!CondBranch)
4093 return NULL;
4095 if (!MII->isBundled())
4096 return NULL;
4097 // Find bundle header.
4098 for (--MII; MII->isBundled(); --MII)
4099 if (MII->isBundle()) {
4100 Bundle = MII;
4101 break;
4102 }
4103 return CondBranch;
4104}
4105
4106// pullUpPeelBBLoop
4107// A single BB loop with a register copy at the beginning in its
4108// own bundle, benefits from eliminating the extra bundle. We do
4109// this by predicating the register copy in the predecessor BB, and
4110// again in the last bundle of the loop.
4111bool HexagonGlobalSchedulerImpl::pullUpPeelBBLoop(MachineBasicBlock *PredBB,
4112 MachineBasicBlock *LoopBB) {
4113 if (!AllowBBPeelPullUp)
4114 return false;
4115 if (!LoopBB || !PredBB)
4116 return false;
4117
4118 // We consider single BB loops only. Check for it here.
4119 if (LoopBB->isEHPad() || LoopBB->hasAddressTaken())
4120 return false;
4121 if (LoopBB->succ_size() != 2)
4122 return false;
4123 if (LoopBB->pred_size() != 2)
4124 return false;
4125 // Make sure one of the successors and one of the predecssors is to self.
4126 if (!(LoopBB->isSuccessor(LoopBB) && LoopBB->isPredecessor(LoopBB)))
4127 return false;
4128
4129 // Find the none self successor block. We know we only have 2 successors.
4130 MachineBasicBlock *SuccBB = NULL;
4131 for (MachineBasicBlock::succ_iterator SI = LoopBB->succ_begin(),
4132 SE = LoopBB->succ_end();
4133 SI != SE; ++SI)
4134 if (*SI != LoopBB) {
4135 SuccBB = *SI;
4136 break;
4137 }
4138 if (!SuccBB)
4139 return false;
4140
4141 // Find the conditional branch and its bundle inside PredBB.
4142 MachineBasicBlock::iterator PredBundle;
4143 MachineInstr *PredCondBranch = NULL;
4144 PredCondBranch = findBundleAndBranch(PredBB, PredBundle);
4145 if (!PredCondBranch)
4146 return false;
4147 if (PredBundle == PredBB->end())
4148 return false;
4149 LLVM_DEBUG(dbgs() << "PredBB's Branch: ");
4150 LLVM_DEBUG(dbgs() << *PredCondBranch);
4151
4152 // Look for leading reg copy as single bundle and make sure its live in.
4154 // Skip debug instructions.
4155 while (FMI->isDebugInstr())
4156 FMI++;
4157
4158 MachineInstr *RegMI = &*FMI;
4159 if (RegMI->isBundle())
4160 return false;
4161 if (RegMI->getOpcode() != Hexagon::A2_tfr)
4162 return false;
4163 if (!(RegMI->getOperand(0).isReg() && RegMI->getOperand(1).isReg()))
4164 return false;
4165 unsigned InLoopReg = RegMI->getOperand(1).getReg();
4166 if (!LoopBB->isLiveIn(InLoopReg))
4167 return false;
4168
4169 // Create a region to pass to ResourcesAvailableInBundle.
4170 BasicBlockRegion PUR(BasicBlockRegion(TII, QRI, PredBB));
4171 PUR.addBBtoRegion(LoopBB);
4172 PUR.addBBtoRegion(SuccBB);
4173
4174 // Make sure we have space in PredBB's last bundle.
4175 if (!ResourcesAvailableInBundle(&PUR, PredBundle))
4176 return false;
4178 CurrentState.HomeBundle);
4179
4180 // Find condition to use for predicating the reg copy into PredBB.
4181 MachineBasicBlock *TBB = NULL, *FBB = NULL;
4182 SmallVector<MachineOperand, 4> Cond;
4183 if (QII->analyzeBranch(*PredBB, TBB, FBB, Cond, false))
4184 return false;
4185 if (Cond.empty())
4186 return false;
4187
4188 // Find condition to use for predicating the reg copy at the end of LoopBB.
4189 MachineBasicBlock *LTBB = NULL, *LFBB = NULL;
4190 SmallVector<MachineOperand, 4> LCond;
4191 if (QII->analyzeBranch(*LoopBB, LTBB, LFBB, LCond, false))
4192 return false;
4193 if (LCond.empty())
4194 return false;
4195
4196 // Move predicated reg copy to previous BB's last bundle.
4197 if (!TII->isPredicable(*RegMI))
4198 return false;
4199 MachineInstr *InstrToMove =
4200 &*insertTempCopy(PredBB, PredBundle, RegMI, false);
4201 if (!canAddMIToThisPacket(InstrToMove, PredBundlePkt)) {
4202 PredBB->erase_instr(InstrToMove);
4203 return false;
4204 }
4205
4206 if (!TII->PredicateInstruction(*InstrToMove, Cond)) {
4207 // Failed to predicate the copy reg.
4208 PredBB->erase_instr(InstrToMove);
4209 return false;
4210 }
4211
4212 // Can we newify this instruction?
4213 unsigned DepReg = 0;
4214 if (NeedToNewify(InstrToMove->getIterator(), &DepReg, &*PredBundle) &&
4215 !isNewifiable(InstrToMove->getIterator(), DepReg, &*PredBundle)) {
4216 PredBB->erase_instr(InstrToMove);
4217 return false;
4218 }
4219 // Newify it, and then undo it if we determine we are using a .old.
4220 int NewOpcode = QII->getDotNewPredOp(*InstrToMove, MBPI);
4221 // Undo newify if we have a non .new predicated jump we are matching.
4222 if (!QII->isDotNewInst(*PredCondBranch))
4223 NewOpcode = QII->getDotOldOp(*InstrToMove);
4224 NewOpcode = QII->getInvertedPredicatedOpcode(NewOpcode);
4225 // Properly set the opcode on the new hoisted reg copy instruction.
4226 InstrToMove->setDesc(QII->get(NewOpcode));
4227 if (!incrementalAddToPacket(*InstrToMove)) {
4228 PredBB->erase_instr(InstrToMove);
4229 return false;
4230 }
4231
4232 // Find the conditional branch and its bundle for LoopBB.
4233 MachineBasicBlock::iterator LoopBundle;
4234 MachineInstr *LoopCondBranch = NULL;
4235 LoopCondBranch = findBundleAndBranch(LoopBB, LoopBundle);
4236 if (!LoopCondBranch)
4237 return false;
4238 if (LoopBundle == LoopBB->end())
4239 return false;
4240 LLVM_DEBUG(dbgs() << "LoopBB's Branch: ");
4241 LLVM_DEBUG(dbgs() << *LoopCondBranch);
4242
4243 // Make sure we have space in LoopBB's last bundle.
4244 if (!ResourcesAvailableInBundle(&PUR, LoopBundle))
4245 return false;
4247 CurrentState.HomeBundle);
4248
4249 // Move predicated reg copy to last bundle of LoopBB.
4250 MachineInstr *InstrToSink =
4251 &*insertTempCopy(LoopBB, LoopBundle, RegMI, false);
4252 if (!canAddMIToThisPacket(InstrToSink, LoopBundlePkt)) {
4253 // Get rid of previous instruction as well.
4254 PredBB->erase_instr(InstrToMove);
4255 LoopBB->erase_instr(InstrToSink);
4256 return false;
4257 }
4258
4259 if (!TII->PredicateInstruction(*InstrToSink, LCond)) {
4260 // Get rid of previous instruction as well.
4261 PredBB->erase_instr(InstrToMove);
4262 LoopBB->erase_instr(InstrToSink);
4263 return false;
4264 }
4265 // Can we newify this instruction?
4266 if (NeedToNewify(InstrToSink->getIterator(), &DepReg, &*LoopBundle) &&
4267 !isNewifiable(InstrToSink->getIterator(), DepReg, &*LoopBundle)) {
4268 // Get rid of previous instruction as well.
4269 PredBB->erase_instr(InstrToMove);
4270 PredBB->erase_instr(InstrToSink);
4271 return false;
4272 }
4273 NewOpcode = QII->getDotNewPredOp(*InstrToSink, MBPI);
4274 // Undo newify if we have a non .new predicated jump we are matching.
4275 if (!QII->isDotNewInst(*LoopCondBranch))
4276 NewOpcode = QII->getDotOldOp(*InstrToSink);
4277 InstrToSink->setDesc(QII->get(NewOpcode));
4278 if (!incrementalAddToPacket(*InstrToSink)) {
4279 // Get rid of previous instruction as well.
4280 PredBB->erase_instr(InstrToMove);
4281 LoopBB->erase_instr(InstrToSink);
4282 return false;
4283 }
4284
4285 // Remove old instruction.
4286 LoopBB->erase_instr(RegMI);
4287 // Set loop alignment to 32.
4288 LoopBB->setAlignment(llvm::Align(32));
4289
4290 LLVM_DEBUG(dbgs() << "Peeled Single BBLoop copy\n");
4291 LLVM_DEBUG(dbgs() << *InstrToMove);
4292 LLVM_DEBUG(dbgs() << *InstrToSink);
4293 LLVM_DEBUG(dbgs() << *PredBB);
4294 LLVM_DEBUG(dbgs() << *LoopBB);
4295 LLVM_DEBUG(dbgs() << *SuccBB);
4296 LLVM_DEBUG(dbgs() << "--- BBLoop ---\n\n");
4297 return true;
4298}
4299
4300bool HexagonGlobalSchedulerImpl::performPullUpCFG(MachineFunction &Fn) {
4301 const Function &F = Fn.getFunction();
4302 // Check for single-block functions and skip them.
4303 if (std::next(F.begin()) == F.end())
4304 return false;
4305 bool Changed = false;
4306 LLVM_DEBUG(dbgs() << "****** PullUpCFG **************\n");
4307
4308 // Loop over all basic blocks, asking if 3 consecutive blocks are
4309 // the jump opportunity.
4310 MachineBasicBlock *PrevBlock = NULL;
4311 MachineBasicBlock *JumpBlock = NULL;
4312 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end(); MBB != MBBe;
4313 ++MBB) {
4314 MachineBasicBlock *FallBlock = &*MBB;
4315 if (PrevBlock && JumpBlock) {
4316 Changed |= pullUpPeelBBLoop(PrevBlock, JumpBlock);
4317 }
4318 PrevBlock = JumpBlock;
4319 JumpBlock = FallBlock;
4320 }
4321 return Changed;
4322}
4323
4324void HexagonGlobalSchedulerImpl::GenUseDefChain(MachineFunction &Fn) {
4325 std::vector<unsigned> Defs;
4326 std::vector<unsigned> Uses;
4327 for (MachineFunction::iterator MBBIter = Fn.begin(); MBBIter != Fn.end();
4328 ++MBBIter) {
4329 for (MachineBasicBlock::instr_iterator MIter = MBBIter->instr_begin();
4330 MIter != MBBIter->instr_end(); ++MIter) {
4331 if (MIter->isBundle() || MIter->isDebugInstr())
4332 continue;
4333 LLVM_DEBUG(dbgs() << "\n\nInserted Ins:"; MIter->dump());
4334 MIUseDefSet(&*MIter, Defs, Uses);
4335 LLVM_DEBUG(dbgs() << "\n\tDefs:";
4336 for (unsigned i = 0; i < Defs.size(); ++i) dbgs()
4337 << printReg(Defs[i], QRI) << ",");
4338 LLVM_DEBUG(dbgs() << "\n\tUses:";
4339 for (unsigned i = 0; i < Uses.size(); ++i) dbgs()
4340 << printReg(Uses[i], QRI) << ",");
4341 MIDefSet[&*MIter] = Defs;
4342 MIUseSet[&*MIter] = Uses;
4343 }
4344 }
4345}
4346
4347// optimizeBranching -
4348// 1. A conditional-jump transfers control to a BB with
4349// jump as the only instruction.
4350// if(p0) jump t1
4351// // ...
4352// t1: jump t2
4353// 2. When a BB with a single conditional jump, jumps to succ-of-succ and
4354// falls-through BB with only jump instruction.
4355// { if(p0) jump t1 }
4356// { jump t2 }
4357// t1: { ... }
4358MachineBasicBlock *HexagonGlobalSchedulerImpl::optimizeBranches(
4359 MachineBasicBlock *MBB, MachineBasicBlock *TBB, MachineInstr *FirstTerm,
4360 MachineBasicBlock *FBB) {
4361 LLVM_DEBUG(dbgs() << "\n\t\t[optimizeBranching]\n");
4362 if ((TBB == MBB) || (FBB == MBB))
4363 LLVM_DEBUG(dbgs() << "Cannot deal with loops in BB#" << MBB->getNumber(););
4364
4365 // LLVM_DEBUG(dbgs() << "\n\t\tTBBMIb:"; MII->dump(););
4366 // { if(p) jump t1; }
4367 // t1: { jump t2; }
4368 // --> { if(p) jump t2
4369 // remove t1: { jump t2; }, if it's address is not taken/not a landing pad.
4370 if (QII->nonDbgBBSize(TBB) == 1) {
4371 MachineInstr *TBBMIb = &*TBB->getFirstNonDebugInstr();
4372 if (TBBMIb->getOpcode() == Hexagon::J2_jump &&
4373 TBBMIb->getOperand(0).isMBB()) {
4374 MachineBasicBlock *NewTarget = TBBMIb->getOperand(0).getMBB();
4375 if (TBB == NewTarget) // Infinite loop.
4376 return NULL;
4377
4378 LLVM_DEBUG(dbgs() << "\nSuboptimal branching in TBB");
4379 // Check if the jump in the last instruction is within range.
4380 int64_t InstOffset =
4381 BlockToInstOffset.find(MBB)->second + QII->nonDbgBBSize(MBB) * 4;
4382 unsigned Distance = (unsigned)std::abs(
4383 InstOffset - BlockToInstOffset.find(NewTarget)->second);
4384 if (!QII->isJumpWithinBranchRange(*FirstTerm, Distance)) {
4385 LLVM_DEBUG(dbgs() << "\nUnconditional jump target:" << Distance
4386 << " out of range.");
4387 return NULL;
4388 }
4389 // We need to make sure that the TBB is _not_ also a target for another
4390 // branch. This is suboptimal since theoretically we can update both
4391 // branches.
4392 if (!TBB->hasAddressTaken() && !TBB->isEHPad() && TBB->pred_size() == 1) {
4393 updatePredecessors(*TBB, NewTarget);
4394 // TBB has only one successor since only one J2_jump instr.
4395 TBB->removeSuccessor(TBB->succ_begin());
4396 TBBMIb->removeFromParent();
4397 if (!TBB->empty()) {
4398 // There are only debug instructions in TBB now. Move them to
4399 // the beginning of NewTarget.
4400 NewTarget->splice(NewTarget->getFirstNonPHI(), TBB, TBB->begin(),
4401 TBB->end());
4402 }
4403 return TBB;
4404 } else {
4405 MBB->ReplaceUsesOfBlockWith(TBB, NewTarget);
4406 return NULL;
4407 }
4408 }
4409 }
4410 // { if(p) jump t1; } may contain more instructions
4411 // { jump t2; } --only one instruction
4412 // t1: {...}
4413 // TBB is layout successor of FBB, then we can change the branch target
4414 // for conditional jump and invert the predicate to remove jump t2.
4415 // { if(!p) jump t2; }
4416 // t1: {...}
4417 if (QII->nonDbgBBSize(FBB) == 1) {
4418 MachineInstr *FBBMIb = &*FBB->getFirstNonDebugInstr();
4419 if (FBBMIb->getOpcode() == Hexagon::J2_jump &&
4420 FBBMIb->getOperand(0).isMBB()) {
4421 MachineBasicBlock *NewTarget = FBBMIb->getOperand(0).getMBB();
4422 if (FBB->hasAddressTaken() || FBB->isEHPad() ||
4423 !FBB->isLayoutSuccessor(TBB) || (FBB == NewTarget /*Infinite loop*/))
4424 return NULL;
4425
4426 LLVM_DEBUG(dbgs() << "\nSuboptimal branching in FBB");
4427 // Check if the jump in the last instruction is within range.
4428 int64_t InstOffset =
4429 BlockToInstOffset.find(MBB)->second + QII->nonDbgBBSize(MBB) * 4;
4430 unsigned Distance = (unsigned)std::abs(
4431 InstOffset - BlockToInstOffset.find(NewTarget)->second);
4432 if (!QII->isJumpWithinBranchRange(*FirstTerm, Distance)) {
4433 LLVM_DEBUG(dbgs() << "\nUnconditional jump target:" << Distance
4434 << " out of range.");
4435 return NULL;
4436 }
4437 if (!QII->invertAndChangeJumpTarget(*FirstTerm, NewTarget))
4438 return NULL;
4439 LLVM_DEBUG(dbgs() << "\nNew instruction:"; FirstTerm->dump(););
4440 updatePredecessors(*FBB, NewTarget);
4441 // Only one successor remains for FBB
4442 FBB->removeSuccessor(FBB->succ_begin());
4443 FBBMIb->removeFromParent();
4444 return FBB;
4445 }
4446 }
4447 return NULL;
4448}
4449
4450// performExposedOptimizations -
4451// look for optimization opportunities after pullup.
4452// e.g. jump to adjacent targets
4453bool HexagonGlobalSchedulerImpl::performExposedOptimizations(
4454 MachineFunction &Fn) {
4455 // Check for single-block functions and skip them.
4456 if (std::next(Fn.getFunction().begin()) == Fn.getFunction().end())
4457 return true;
4458 LLVM_DEBUG(dbgs() << "\n\t\t[performExposedOptimizations]\n");
4459 // Erasing the empty basic blocks formed during pullup.
4460 std::vector<MachineBasicBlock *>::iterator ebb = EmptyBBs.begin();
4461 while (ebb != EmptyBBs.end()) {
4462 assert(IsEmptyBlock(*ebb) && "Pullup inserted packets into an empty BB");
4463 LLVM_DEBUG(dbgs() << "Removing BB(" << (*ebb)->getNumber()
4464 << ") from parent.\n");
4465 (*ebb)->eraseFromParent();
4466 ++ebb;
4467 }
4468 MachineBasicBlock *TBB = NULL, *FBB = NULL;
4469 MachineInstr *FirstTerm = NULL, *SecondTerm = NULL;
4470
4471 SmallVector<MachineBasicBlock *, 4> Erase;
4472
4473 for (MachineBasicBlock &MBB : Fn) {
4474 if (MBB.succ_size() > 2 ||
4475 AnalyzeBBBranches(&MBB, TBB, FirstTerm, FBB, SecondTerm)) {
4476 LLVM_DEBUG(dbgs() << "\nAnalyzeBBBranches failed in BB#"
4477 << MBB.getNumber() << "\n";);
4478 continue;
4479 }
4480 if (FirstTerm && QII->isCompoundBranchInstr(*FirstTerm))
4481 continue;
4482 if (TBB && FirstTerm &&
4483 removeRedundantBranches(&MBB, TBB, FirstTerm, FBB, SecondTerm)) {
4484 LLVM_DEBUG(dbgs() << "\nRemoved redundant branches in BB#"
4485 << MBB.getNumber(););
4486 continue;
4487 }
4488 if (FirstTerm && SecondTerm &&
4489 optimizeDualJumps(&MBB, TBB, FirstTerm, FBB, SecondTerm)) {
4490 LLVM_DEBUG(dbgs() << "\nRemoved dual jumps in in BB#"
4491 << MBB.getNumber(););
4492 continue;
4493 }
4494 if (TBB && FBB && FirstTerm && !SecondTerm) {
4495 MachineBasicBlock *MBBToErase =
4496 optimizeBranches(&MBB, TBB, FirstTerm, FBB);
4497 if (MBBToErase) {
4498 assert(IsEmptyBlock(MBBToErase) && "Erasing non-empty BB");
4499 Erase.push_back(MBBToErase);
4500 LLVM_DEBUG(dbgs() << "\nOptimized jump from BB#" << MBB.getNumber());
4501 }
4502 }
4503 }
4504 for (MachineBasicBlock *MBB : Erase)
4506
4507 return false;
4508}
4509
4510// 1. Remove jump to the layout successor.
4511// 2. Remove multiple (dual) jump to the same target.
4512bool HexagonGlobalSchedulerImpl::removeRedundantBranches(
4513 MachineBasicBlock *MBB, MachineBasicBlock *TBB, MachineInstr *FirstTerm,
4514 MachineBasicBlock *FBB, MachineInstr *SecondTerm) {
4515 bool Analyzed = false;
4516 LLVM_DEBUG(dbgs() << "\n\t\t[removeRedundantBranches]\n");
4517 MachineInstr *Head = NULL, *ToErase = NULL;
4518 if (!FBB && (FirstTerm->getOpcode() == Hexagon::J2_jump) &&
4520 // Jmp layout_succ_basic_block <-- Remove
4521 LLVM_DEBUG(
4522 dbgs() << "\nRemoving Uncond. jump to the layout successor in BB#"
4523 << MBB->getNumber());
4524 ToErase = FirstTerm;
4525 } else if (SecondTerm && (TBB == FBB) &&
4526 (SecondTerm->getOpcode() == Hexagon::J2_jump)) {
4527 // If both branching instructions in same packet or are consecutive.
4528 // Jmp_c t1 <-- Remove
4529 // Jmp t1
4530 // @Note: If they are in different packets or if they are separated
4531 // by packet(s), this opt. cannot be done.
4532 MachineBasicBlock::instr_iterator FirstTermIter = FirstTerm->getIterator();
4533 MachineBasicBlock::instr_iterator SecondTermIter =
4534 SecondTerm->getIterator();
4535 if (++FirstTermIter == SecondTermIter) {
4536 LLVM_DEBUG(dbgs() << "\nRemoving multiple branching to same target in BB#"
4537 << MBB->getNumber());
4538 // TODO: This might make the `p' register assignment instruction dead.
4539 // and can be removed.
4540 ToErase = FirstTerm;
4541 }
4542 } else if (SecondTerm && (SecondTerm->getOpcode() == Hexagon::J2_jump) &&
4543 FBB && MBB->isLayoutSuccessor(FBB)) {
4544 // Jmp_c t1
4545 // Jmp layout_succ_basic_block <-- Remove
4546 LLVM_DEBUG(dbgs() << "\nRemoving fall through branch in BB#"
4547 << MBB->getNumber());
4548 ToErase = SecondTerm;
4549 } else if (SecondTerm && QII->PredOpcodeHasJMP_c(SecondTerm->getOpcode()) &&
4551 // Jmp_c t1
4552 // Jmp_c layout_succ_basic_block <-- Remove
4553 // In this case AnalyzeBBBranches might assign FBB to some other BB.
4554 // So using the jump target of SecondTerm to check.
4555 LLVM_DEBUG(dbgs() << "\nRemoving Cond. jump to the layout successor in BB#"
4556 << MBB->getNumber());
4557 ToErase = SecondTerm;
4558 }
4559 // Remove the instruction from the BB
4560 if (ToErase) {
4561 if (ToErase->isBundled()) {
4562 Head = &*getBundleStart(ToErase->getIterator());
4563 ToErase->eraseFromBundle();
4564 UpdateBundle(Head);
4565 } else
4566 ToErase->eraseFromParent();
4567 Analyzed = true;
4568 }
4569 return Analyzed;
4570}
4571
4572// ----- convert
4573// p = <expr>
4574// if(p) jump layout_succ_basic_block
4575// jump t
4576// ----- to
4577// p = <expr>
4578// if(!p) jump t
4579// for now only looking at the dual jump
4580bool HexagonGlobalSchedulerImpl::optimizeDualJumps(MachineBasicBlock *MBB,
4581 MachineBasicBlock *TBB,
4582 MachineInstr *FirstTerm,
4583 MachineBasicBlock *FBB,
4584 MachineInstr *SecondTerm) {
4585 LLVM_DEBUG(dbgs() << "\n******* optimizeDualJumps *******");
4586
4587 bool Analyzed = false;
4588
4589 if (QII->PredOpcodeHasJMP_c(FirstTerm->getOpcode()) &&
4590 (SecondTerm->getOpcode() == Hexagon::J2_jump)) {
4591
4592 if (TBB == FBB) {
4593 LLVM_DEBUG(dbgs() << "\nBoth successors are the same.");
4594 return Analyzed;
4595 }
4596
4597 // Do not optimize for dual jumps if this MBB
4598 // contains a speculatively pulled-up instruction.
4599 // A speculated instruction is more likely to be at the end of MBB.
4601 while (SII != MBB->instr_rend()) {
4602 MachineInstr *SI = &*SII;
4603 std::map<MachineInstr *, MachineBasicBlock *>::iterator MIMoved;
4604 MIMoved = SpeculatedIns.find(SI);
4605 if ((MIMoved != SpeculatedIns.end()) &&
4606 (MIMoved->second != SI->getParent())) {
4607 return Analyzed;
4608 }
4609 ++SII;
4610 }
4611
4612 LLVM_DEBUG(dbgs() << "\nCandidate for jump optimization in BB("
4613 << MBB->getNumber() << ").\n";);
4614
4615 // Predicated jump to layout successor followed by an unconditional jump.
4616 if (MBB->isLayoutSuccessor(TBB)) {
4617
4618 // Check if the jump in the last instruction is within range.
4619 int64_t InstOffset =
4620 BlockToInstOffset.find(&*MBB)->second + QII->nonDbgBBSize(MBB) * 4;
4621 unsigned Distance =
4622 (unsigned)std::abs(InstOffset - BlockToInstOffset.find(FBB)->second) +
4624 if (!QII->isJumpWithinBranchRange(*FirstTerm, Distance)) {
4625 LLVM_DEBUG(dbgs() << "\nUnconditional jump target:" << Distance
4626 << " out of range.");
4627 return Analyzed;
4628 }
4629
4630 // modify the second last -predicated- instruction (sense and target)
4631 LLVM_DEBUG(dbgs() << "\nFirst Instr:" << *FirstTerm;);
4632 LLVM_DEBUG(dbgs() << "\nSecond Instr:" << *SecondTerm;);
4633 LLVM_DEBUG(dbgs() << "\nOld Succ BB(" << TBB->getNumber() << ").";);
4634
4635 QII->invertAndChangeJumpTarget(*FirstTerm, FBB);
4636
4637 LLVM_DEBUG(dbgs() << "\nNew First Instruction:" << *FirstTerm;);
4638
4639 // unbundle if there is only one instruction left
4640 MachineInstr *SecondHead, *FirstHead;
4641 FirstHead = FirstTerm->isBundled()
4642 ? &*getBundleStart(FirstTerm->getIterator())
4643 : nullptr;
4644 SecondHead = SecondTerm->isBundled()
4645 ? &*getBundleStart(SecondTerm->getIterator())
4646 : nullptr;
4647
4648 // 1. Both unbundled, 2. FirstTerm inside bundle, second outside.
4649 if (!SecondHead)
4650 SecondTerm->eraseFromParent();
4651 else if (!FirstHead) {
4652 // 3. FirstHead outside, SecondHead inside.
4653 SecondTerm->eraseFromBundle();
4654 UpdateBundle(SecondHead);
4655 } else if (FirstHead == SecondHead) {
4656 // 4. Both are in the same bundle
4657 assert((FirstHead && SecondHead) && "Unbundled Instruction");
4658 SecondTerm->eraseFromBundle();
4659 if (SecondHead->getBundleSize() < 2)
4660 UpdateBundle(SecondHead);
4661 } else {
4662 // 5. Both are in different bundles
4663 SecondTerm->eraseFromBundle();
4664 UpdateBundle(SecondHead);
4665 }
4666 Analyzed = true;
4667 }
4668 }
4669 return Analyzed;
4670}
4671
4672/// Are there any resources left in this bundle?
4673bool HexagonGlobalSchedulerImpl::ResourcesAvailableInBundle(
4674 BasicBlockRegion *CurrentRegion,
4675 MachineBasicBlock::iterator &TargetPacket) {
4677
4678 // If this is a single instruction, form new packet around it.
4679 if (!TargetPacket->isBundle()) {
4680 if (ignoreInstruction(&*MII) || isSoloInstruction(*MII))
4681 return false;
4682
4683 // Before we begin, we need to make sure that we do not
4684 // look at an unconditional jump outside the current region.
4685 if (MII->isBranch() && !isBranchWithinRegion(CurrentRegion, &*MII))
4686 return false;
4687
4688 // Build up state for this new packet.
4689 // Note, we cannot create a bundle header for it,
4690 // so this "bundle" only exist in DFA state, and not in code.
4691 initPacketizerState();
4692 ResourceTracker->clearResources();
4693 CurrentState.addHomeLocation(MII);
4694 return incrementalAddToPacket(*MII);
4695 }
4696
4697 MachineBasicBlock::instr_iterator End = MII->getParent()->instr_end();
4698
4699 // Build up state for this packet.
4700 initPacketizerState();
4701 ResourceTracker->clearResources();
4702 CurrentState.addHomeLocation(MII);
4703
4704 for (++MII; MII != End && MII->isInsideBundle(); ++MII) {
4705 if (MII->getOpcode() == TargetOpcode::DBG_VALUE ||
4706 MII->getOpcode() == TargetOpcode::IMPLICIT_DEF ||
4707 MII->getOpcode() == TargetOpcode::CFI_INSTRUCTION || MII->isEHLabel())
4708 continue;
4709
4710 // Before we begin, we need to make sure that we do not
4711 // look at an unconditional jump outside the current region.
4712 // TODO: See if we can profit from handling this kind of cases:
4713 // B#15: derived from LLVM BB %if.then22
4714 // Predecessors according to CFG: BB#13
4715 // BUNDLE %PC<imp-def>, %P2<imp-use,kill>
4716 // * J2_jumpf %P2<kill,internal>, <BB#17>, %PC<imp-def>; flags:
4717 // * J2_jump <BB#18>, %PC<imp-def>; flags:
4718 // Successors according to CFG: BB#18(62) BB#17(62)
4719 // Curently we do not allow them.
4720 if (MII->isBranch() && !isBranchWithinRegion(CurrentRegion, &*MII))
4721 return false;
4722
4723 if (!incrementalAddToPacket(*MII))
4724 return false;
4725 }
4726 return ResourceTracker->canReserveResources(*Nop);
4727}
4728
4729/// Symmetrical. See if these two instructions are fit for compound pair.
4730bool HexagonGlobalSchedulerImpl::isCompoundPair(MachineInstr *MIa,
4731 MachineInstr *MIb) {
4733 MIbG = QII->getCompoundCandidateGroup(*MIb);
4734 // We have two candidates - check that this is the same register
4735 // we are talking about.
4736 unsigned Opcb = MIb->getOpcode();
4737 if (MIaG == HexagonII::HCG_C && MIbG == HexagonII::HCG_A &&
4738 (Opcb == Hexagon::A2_tfr || Opcb == Hexagon::A2_tfrsi))
4739 return true;
4740 unsigned Opca = MIa->getOpcode();
4741 if (MIbG == HexagonII::HCG_C && MIaG == HexagonII::HCG_A &&
4742 (Opca == Hexagon::A2_tfr || Opca == Hexagon::A2_tfrsi))
4743 return true;
4744 return (((MIaG == HexagonII::HCG_A && MIbG == HexagonII::HCG_B) ||
4745 (MIbG == HexagonII::HCG_A && MIaG == HexagonII::HCG_B)) &&
4746 (MIa->getOperand(0).getReg() == MIb->getOperand(0).getReg()));
4747}
4748
4749// This is a weird situation when BB conditionally branches + falls through
4750// to layout successor. \ref bug17792
4751inline bool HexagonGlobalSchedulerImpl::multipleBranchesFromToBB(
4752 MachineBasicBlock *BB) const {
4753 if (BB->succ_size() != 1)
4754 return false;
4755 SmallVector<MachineInstr *, 2> Jumpers = QII->getBranchingInstrs(*BB);
4756 return ((Jumpers.size() == 1) && !Jumpers[0]->isUnconditionalBranch());
4757}
4758
4759/// Gather a worklist of MaxCandidates pull-up candidates.
4760/// Compute relative cost.
4761bool HexagonGlobalSchedulerImpl::findPullUpCandidates(
4762 MachineBasicBlock::iterator &WorkPoint,
4764 std::vector<MachineInstr *> &backtrack, unsigned MaxCandidates = 1) {
4765
4766 const HexagonInstrInfo *QII = (const HexagonInstrInfo *)TII;
4767 MachineBasicBlock *FromThisBB = FromHere->getParent();
4768 bool MovingDependentOp = false;
4769 signed CostBenefit = 0;
4770
4771 // Do not collect more than that many candidates.
4772 if (CurrentState.haveCandidates() >= MaxCandidates)
4773 return false;
4774
4775 LLVM_DEBUG(dbgs() << "\n\tTry from BB(" << FromThisBB->getNumber() << "):\n";
4776 DumpPacket(FromHere.getInstrIterator()));
4777
4778 if (FromHere->isBundle()) {
4780 for (++MII; MII != FromThisBB->instr_end() && MII->isInsideBundle();
4781 ++MII) {
4782 if (MII->isDebugInstr())
4783 continue;
4784 LLVM_DEBUG(dbgs() << "\tCandidate from BB("
4785 << MII->getParent()->getNumber() << "): ";
4786 MII->dump());
4787
4788 // See if this instruction could be moved.
4789 if (!canThisMIBeMoved(&*MII, WorkPoint, MovingDependentOp, CostBenefit))
4790 continue;
4791
4792 MachineBasicBlock::instr_iterator InstrToMove = MII;
4793 if (canAddMIToThisPacket(&*InstrToMove, CurrentState.HomeBundle)) {
4794 CostBenefit -= (backtrack.size() * 4);
4795 // Prefer instructions in empty packets.
4796 CostBenefit += (PacketSize - nonDbgBundleSize(FromHere)) * 2;
4797 // Prefer Compares.
4798 if (MII->isCompare())
4799 CostBenefit += 10;
4800 // Check duplex conditions;
4801 for (unsigned i = 0; i < CurrentState.HomeBundle.size(); i++) {
4802 if (QII->isDuplexPair(*CurrentState.HomeBundle[i], *MII)) {
4803 LLVM_DEBUG(dbgs() << "\tGot real Duplex (bundle).\n");
4804 CostBenefit += 20;
4805 }
4806 if (isCompoundPair(CurrentState.HomeBundle[i], &*MII)) {
4807 LLVM_DEBUG(dbgs() << "\tGot compound (bundle).\n");
4808 CostBenefit += 40;
4809 }
4810 }
4811 // Create a record for this location.
4812 CurrentState.addPullUpCandidate(InstrToMove, WorkPoint, backtrack,
4813 MovingDependentOp, CostBenefit);
4814 } else
4815 LLVM_DEBUG(dbgs() << "\tNo resources in the target packet.\n");
4816 }
4817 }
4818 // This is a standalone instruction.
4819 // First see if this MI can even be moved. Cost model for a single instruction
4820 // should be rather different from moving something out of a bundle.
4821 else if (canThisMIBeMoved(&*FromHere, WorkPoint, MovingDependentOp,
4822 CostBenefit)) {
4823 MachineBasicBlock::instr_iterator InstrToMove = FromHere.getInstrIterator();
4824 if (canAddMIToThisPacket(&*InstrToMove, CurrentState.HomeBundle)) {
4825 CostBenefit -= (backtrack.size() * 4);
4826 // Prefer Compares.
4827 if (InstrToMove->isCompare())
4828 CostBenefit += 10;
4829 // It is better to pull a single instruction in to a bundle - save
4830 // a cycle immediately.
4831 CostBenefit += 10;
4832 // Search for duplex match.
4833 for (unsigned i = 0; i < CurrentState.HomeBundle.size(); i++) {
4834 if (QII->isDuplexPair(*CurrentState.HomeBundle[i], *InstrToMove)) {
4835 LLVM_DEBUG(dbgs() << "\tGot real Duplex (single).\n");
4836 CostBenefit += 30;
4837 }
4838 if (isCompoundPair(CurrentState.HomeBundle[i], &*InstrToMove)) {
4839 LLVM_DEBUG(dbgs() << "\tGot compound (single).\n");
4840 CostBenefit += 50;
4841 }
4842 }
4843 // Create a record for this location.
4844 CurrentState.addPullUpCandidate(InstrToMove, WorkPoint, backtrack,
4845 MovingDependentOp, CostBenefit);
4846 } else
4847 LLVM_DEBUG(dbgs() << "\tNo resources for single in the target packet.\n");
4848 }
4849 return true;
4850}
4851
4852/// Try to move a candidate MI.
4853/// The move can destroy all iterator system, so we have to drag them
4854/// around to keep them up to date.
4855bool HexagonGlobalSchedulerImpl::tryMultipleInstructions(
4856 MachineBasicBlock::iterator &RetVal, /* output parameter */
4857 std::vector<BasicBlockRegion *>::iterator &CurrentRegion,
4859 MachineBasicBlock::iterator &ToThisBBEnd,
4860 MachineBasicBlock::iterator &FromThisBBEnd, bool PathInRegion) {
4861
4864 bool MovingDependentOp = false;
4865 std::vector<MachineInstr *> backtrack;
4866
4867 LLVM_DEBUG(dbgs() << "\n\tTry Multiple candidates: \n");
4868
4869 std::sort(CurrentState.PullUpCandidates.begin(),
4870 CurrentState.PullUpCandidates.end(), PullUpCandidateSorter());
4871 LLVM_DEBUG(CurrentState.dump());
4872 // Iterate through candidates in sorted order.
4873 for (SmallVector<PullUpCandidate *, 4>::iterator
4874 I = CurrentState.PullUpCandidates.begin(),
4875 E = CurrentState.PullUpCandidates.end();
4876 I != E; ++I) {
4877 (*I)->populate(MII, WorkPoint, backtrack, MovingDependentOp);
4878
4879 MachineBasicBlock *FromThisBB = MII->getParent();
4880 MachineBasicBlock *ToThisBB = WorkPoint->getParent();
4881
4882 LLVM_DEBUG(dbgs() << "\n\tCandidate: "; MII->dump());
4883 LLVM_DEBUG(dbgs() << "\tDependent(" << MovingDependentOp << ") FromBB("
4884 << FromThisBB->getNumber() << ") ToBB("
4885 << ToThisBB->getNumber() << ") to this packet:\n";
4886 DumpPacket(WorkPoint.getInstrIterator()));
4887
4888 MachineBasicBlock::instr_iterator FromHereII = MII;
4889 if (MII->isInsideBundle()) {
4890 while (!FromHereII->isBundle())
4891 --FromHereII;
4892 LLVM_DEBUG(dbgs() << "\tFrom here:\n"; DumpPacket(FromHereII));
4893
4894 MachineBasicBlock::iterator FromHere(FromHereII);
4895 // We have instruction that could be moved from its current position.
4896 if (MoveMItoBundle(*CurrentRegion, MII, NextMI, WorkPoint, FromHere,
4897 backtrack, MovingDependentOp, PathInRegion)) {
4898 // If BB from which we pull is now empty, move on.
4899 if (IsEmptyBlock(FromThisBB)) {
4900 LLVM_DEBUG(dbgs() << "\n\tExhosted BB (bundle).\n");
4901 return false;
4902 }
4903 FromThisBBEnd = FromThisBB->end();
4904 ToThisBBEnd = ToThisBB->end();
4905
4906 LLVM_DEBUG(dbgs() << "\n\tAfter updates(bundle to bundle):\n");
4907 LLVM_DEBUG(dbgs() << "\t\tWorkPoint: ";
4908 DumpPacket(WorkPoint.getInstrIterator()));
4909
4910 // We should not increment current position,
4911 // but rather try one more time to pull from the same bundle.
4912 RetVal = WorkPoint;
4913 return true;
4914 } else
4915 LLVM_DEBUG(dbgs() << "\tCould not move packetized instr.\n");
4916 } else {
4917 MachineBasicBlock::iterator FromHere(FromHereII);
4918 if (MoveMItoBundle(*CurrentRegion, MII, NextMI, WorkPoint, FromHere,
4919 backtrack, MovingDependentOp, PathInRegion)) {
4920
4921 // If BB from which we pull is now empty, move on.
4922 if (IsEmptyBlock(FromThisBB)) {
4923 LLVM_DEBUG(dbgs() << "\n\tExhosted BB (single).\n");
4924 return false;
4925 }
4926 FromThisBBEnd = FromThisBB->end();
4927 ToThisBBEnd = ToThisBB->end();
4928
4929 LLVM_DEBUG(dbgs() << "\tAfter updates (single to bundle):\n");
4930 LLVM_DEBUG(dbgs() << "\t\tWorkPoint: ";
4931 DumpPacket(WorkPoint.getInstrIterator()));
4932 // We should not increment current position,
4933 // but rather try one more time to pull from the same bundle.
4934 RetVal = WorkPoint;
4935 return true;
4936 } else
4937 LLVM_DEBUG(dbgs() << "\tCould not move single.\n");
4938 }
4939 }
4940 LLVM_DEBUG(dbgs() << "\tNot a single candidate fit.\n");
4941 return false;
4942}
4943
4944/// Main function. Iterate all current regions one at a time,
4945/// and look for pull-up opportunities.
4946/// Pseudo sequence:
4947/// - for all bundles and single instructions in region:
4948/// - see if resources are available (in the same cycle) - this is HOME.
4949/// - Starting from next BB in region, find an instruction that could be:
4950/// - removed from its current location
4951/// - added to underutilized bundle (including bundles with only one op)
4952/// - If so, trace path back to HOME and check that candidate could be
4953/// reordered with all the intermediate instructions.
4954bool HexagonGlobalSchedulerImpl::performPullUp() {
4955 std::vector<MachineInstr *> backtrack;
4957 MachineBasicBlock::iterator FromThisBBEnd;
4958
4959 LLVM_DEBUG(dbgs() << "****** PullUpRegions ***********\n");
4960 // For all regions...
4961 for (std::vector<BasicBlockRegion *>::iterator
4962 CurrentRegion = PullUpRegions.begin(),
4963 E = PullUpRegions.end();
4964 CurrentRegion != E; ++CurrentRegion) {
4965
4966 LLVM_DEBUG(dbgs() << "\n\nRegion with(" << (*CurrentRegion)->size()
4967 << ")BBs\n");
4968
4969 if (!EnableLocalPullUp && (*CurrentRegion)->size() < 2)
4970 continue;
4971
4972 // For all MBB in the region... except the last one.
4973 // ...except when we want to allow local pull-up.
4974 for (auto ToThisBB = (*CurrentRegion)->getRootMBB(),
4975 LastBBInRegion = (*CurrentRegion)->getLastMBB();
4976 ToThisBB != LastBBInRegion; ++ToThisBB) {
4977 // If we do not want to allow same BB pull-up, take an early exit.
4978 if (!EnableLocalPullUp && (std::next(ToThisBB) == LastBBInRegion))
4979 break;
4980 if (multipleBranchesFromToBB(*ToThisBB))
4981 break;
4982
4983 auto FromThisBB = ToThisBB;
4984 MachineBasicBlock::iterator ToThisBBEnd = (*ToThisBB)->end();
4985 MachineBasicBlock::iterator MI = (*ToThisBB)->begin();
4986
4987 LLVM_DEBUG(dbgs() << "\n\tHome iterator moved to new BB("
4988 << (*ToThisBB)->getNumber() << ")\n";
4989 (*ToThisBB)->dump());
4990
4991 // For all instructions in the BB.
4992 while (MI != ToThisBBEnd) {
4993 MachineBasicBlock::iterator WorkPoint = MI;
4994 ++MI;
4995
4996 // Trivial check that there are unused resources
4997 // in the current location (cycle).
4998 while (ResourcesAvailableInBundle(*CurrentRegion, WorkPoint)) {
4999 LLVM_DEBUG(dbgs() << "\nxxxx Next Home in BB("
5000 << (*ToThisBB)->getNumber() << "):\n";
5001 DumpPacket(WorkPoint.getInstrIterator()));
5002 // Keep the path to the candidate.
5003 // It is the traveled path between home and work point.
5004 // Reset it for the new iteration.
5005 backtrack.clear();
5006
5007 // The point of pull-up source (WorkPoint) could begin from the
5008 // current BB, but only if we allow pull-up in the same BB.
5009 // At the moment we do not.
5010 // We also do not process last block in the region,
5011 // so it is safe to always begin with the next BB in the region.
5012 // Start from "next" BB in the region.
5013 if (EnableLocalPullUp) {
5014 FromThisBB = ToThisBB;
5015 FromHere = WorkPoint;
5016 ++FromHere;
5017 FromThisBBEnd = (*FromThisBB)->end();
5018
5019 // Initialize backtrack.
5020 // These are instructions between Home location
5021 // and the WorkPoint.
5022 for (MachineBasicBlock::iterator I = WorkPoint, IE = FromHere;
5023 I != IE; ++I)
5024 backtrack.push_back(&*I);
5025 } else {
5026 FromThisBB = ToThisBB;
5027 ++FromThisBB;
5028 FromHere = (*FromThisBB)->begin();
5029 FromThisBBEnd = (*FromThisBB)->end();
5030
5031 // Initialize backtrack.
5032 // These are instructions between Home location
5033 // and the end of the home BB.
5034 for (MachineBasicBlock::iterator I = WorkPoint, IE = ToThisBBEnd;
5035 I != IE; ++I)
5036 backtrack.push_back(&*I);
5037 }
5038
5039 // Search for pull-up candidate.
5040 while (true) {
5041 // If this BB is over, move onto the next one
5042 // in this region.
5043 if (FromHere == FromThisBBEnd) {
5044 ++FromThisBB;
5045 // Refresh LastBBInRegion in case tryMultipleInstructions modified
5046 // the regions Elements vector, invalidating the iterator.
5047 LastBBInRegion = (*CurrentRegion)->getLastMBB();
5048 if (FromThisBB == LastBBInRegion)
5049 break;
5050 else {
5051 LLVM_DEBUG(dbgs() << "\n\tNext BB in this region\n";
5052 (*FromThisBB)->dump());
5053 FromThisBBEnd = (*FromThisBB)->end();
5054 FromHere = (*FromThisBB)->begin();
5055 if (FromThisBBEnd == FromHere)
5056 break;
5057 }
5058 }
5059 if ((*FromHere).isDebugInstr()) {
5060 ++FromHere;
5061 continue;
5062 }
5063 // This is a step Home.
5064 backtrack.push_back(&*FromHere);
5065 if (!findPullUpCandidates(WorkPoint, FromHere, backtrack,
5067 break;
5068 ++FromHere;
5069 }
5070 // Try to pull-up one of the selected candidates.
5071 if (!tryMultipleInstructions(/*output*/ WorkPoint, CurrentRegion, MI,
5072 ToThisBBEnd, FromThisBBEnd))
5073 break;
5074 }
5075 }
5076 // Refresh LastBBInRegion after potential CFG modifications.
5077 LastBBInRegion = (*CurrentRegion)->getLastMBB();
5078 }
5079 // AllowUnlikelyPath is on by default,
5080 // if we wish to disable it, we can do so here.
5081 if (!AllowUnlikelyPath)
5082 continue;
5083
5084 // We have parsed the likely path through the region.
5085 // Now traverse the other (unlikely) path.
5086 //
5087 // Note: BasicBlockRegion uses a vector for MBB storage, so adding BBs to
5088 // the region while iterating could invalidate iterators. Collect the work
5089 // items first, then process them.
5090 std::vector<std::pair<MachineBasicBlock *, MachineBasicBlock *>>
5091 UnlikelyWork;
5092 UnlikelyWork.reserve((*CurrentRegion)->size());
5093 for (auto ToIt = (*CurrentRegion)->getRootMBB(),
5094 End = (*CurrentRegion)->getLastMBB();
5095 ToIt != End; ++ToIt) {
5096 MachineBasicBlock *ToBB = *ToIt;
5097 MachineBasicBlock *SecondBest = getNextPURBB(ToBB, true);
5098 if (SecondBest)
5099 UnlikelyWork.emplace_back(ToBB, SecondBest);
5100 }
5101
5102 for (auto [ToBB, SecondBest] : UnlikelyWork) {
5103 LLVM_DEBUG(dbgs() << "\tFor BB:\n"; ToBB->dump());
5104 LLVM_DEBUG(dbgs() << "\tHave SecondBest:\n"; SecondBest->dump());
5105 // Adding this BB to the region should not be done if we
5106 // plan to reuse it(the region) again. For now it is OK.
5107 (*CurrentRegion)->addBBtoRegion(SecondBest);
5108 LLVM_DEBUG(dbgs() << "\tHome iterator moved to new BB("
5109 << ToBB->getNumber() << ")\n";
5110 ToBB->dump());
5111 MachineBasicBlock::iterator ToThisBBEnd = ToBB->end();
5113
5114 // For all instructions in the BB.
5115 while (MI != ToThisBBEnd) {
5116 MachineBasicBlock::iterator WorkPoint = MI;
5117 ++MI;
5118
5119 // Trivial check that there are unused resources
5120 // in the current location (cycle).
5121 while (ResourcesAvailableInBundle(*CurrentRegion, WorkPoint)) {
5122 LLVM_DEBUG(dbgs() << "\nxxxx Second visit Home in BB("
5123 << ToBB->getNumber() << "):\n";
5124 DumpPacket(WorkPoint.getInstrIterator()));
5125
5126 FromHere = SecondBest->begin();
5127 FromThisBBEnd = SecondBest->end();
5128
5129 // Keep the path to the candidate.
5130 backtrack.clear();
5131
5132 // This is Home location.
5133 for (MachineBasicBlock::iterator I = WorkPoint, IE = ToThisBBEnd;
5134 I != IE; ++I)
5135 backtrack.push_back(&*I);
5136
5137 while (true) {
5138 // If this BB is over, move onto the next one
5139 // in this region.
5140 if (FromHere == FromThisBBEnd) {
5142 << "\tOnly do one successor for the second try\n");
5143 break;
5144 }
5145 if ((*FromHere).isDebugInstr()) {
5146 ++FromHere;
5147 continue;
5148 }
5149 // This is a step Home.
5150 backtrack.push_back(&*FromHere);
5151 if (!findPullUpCandidates(WorkPoint, FromHere, backtrack,
5153 break;
5154 ++FromHere;
5155 }
5156 // Try to pull-up one of selected candidate.
5157 if (!tryMultipleInstructions(/*output*/ WorkPoint, CurrentRegion, MI,
5158 ToThisBBEnd, FromThisBBEnd, false))
5159 break;
5160 }
5161 }
5162 }
5163 }
5164 return true;
5165}
5166
5167bool HexagonGlobalSchedulerImpl::incrementalAddToPacket(MachineInstr &MI) {
5168
5169 LLVM_DEBUG(dbgs() << "\t[AddToPacket] (" << CurrentPacketMIs.size()
5170 << ") adding:\t";
5171 MI.dump());
5172
5173 if (!ResourceTracker->canReserveResources(MI) || !shouldAddToPacket(MI))
5174 return false;
5175
5176 ResourceTracker->reserveResources(MI);
5177 CurrentPacketMIs.push_back(&MI);
5178 CurrentState.HomeBundle.push_back(&MI);
5179
5180 if (QII->isExtended(MI) || QII->isConstExtended(MI) ||
5181 isJumpOutOfRange(&MI)) {
5182 // If at this point of time we cannot reserve resources,
5183 // this might mean that the packet came into the pull-up
5184 // pass already in danger of overflowing.
5185 // Nevertheless, since this is only a possibility of overflow
5186 // no error should be issued here.
5187 if (ResourceTracker->canReserveResources(*Ext)) {
5188 ResourceTracker->reserveResources(*Ext);
5189 LLVM_DEBUG(dbgs() << "\t[AddToPacket] (" << CurrentPacketMIs.size()
5190 << ") adding:\t immext_i\n");
5191 CurrentPacketMIs.push_back(Ext);
5192 CurrentState.HomeBundle.push_back(Ext);
5193 return true;
5194 } else {
5195 LLVM_DEBUG(dbgs() << "\t Previous overflow possible.\n");
5196 return false;
5197 }
5198 }
5199 return true;
5200}
5201
5202void HexagonGlobalSchedulerImpl::checkBundleCounts(MachineFunction &Fn) {
5204 return;
5205
5206 unsigned BundleLimit = 4;
5207
5208 for (MachineFunction::iterator MBBi = Fn.begin(), MBBe = Fn.end();
5209 MBBi != MBBe; ++MBBi) {
5210
5211 for (MachineBasicBlock::iterator MI = MBBi->instr_begin(),
5212 ME = MBBi->instr_end();
5213 MI != ME; ++MI) {
5214 if (MI->isBundle()) {
5215 MachineBasicBlock::instr_iterator MII = MI.getInstrIterator();
5216 MachineBasicBlock::instr_iterator End = MII->getParent()->instr_end();
5217
5218 unsigned InstrCount = 0;
5219
5220 for (++MII; MII != End && MII->isInsideBundle(); ++MII) {
5221 if (MII->getOpcode() == TargetOpcode::DBG_VALUE ||
5222 MII->getOpcode() == TargetOpcode::IMPLICIT_DEF ||
5223 MII->getOpcode() == TargetOpcode::CFI_INSTRUCTION ||
5224 MII->isEHLabel() || QII->isEndLoopN(MII->getOpcode())) {
5225 continue;
5226 } else {
5227 InstrCount++;
5228 }
5229 }
5230 if (InstrCount > BundleLimit) {
5231 if (WarnOnBundleSize) {
5232 LLVM_DEBUG(dbgs() << "Warning bundle size exceeded " << *MI);
5233 } else {
5234 assert(0 && "Bundle size exceeded");
5235 }
5236 }
5237 }
5238 }
5239 }
5240}
5241
5242/// Debugging only. Count compound and duplex opportunities.
5243unsigned HexagonGlobalSchedulerImpl::countCompounds(MachineFunction &Fn) {
5244 unsigned CompoundCount = 0;
5245 [[maybe_unused]] unsigned DuplexCount = 0;
5246 [[maybe_unused]] unsigned InstOffset = 0;
5247
5248 // Loop over all basic blocks.
5249 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end(); MBB != MBBe;
5250 ++MBB) {
5251 LLVM_DEBUG(dbgs() << "\n BB#" << MBB->getNumber() << " " << MBB->getName()
5252 << " in_func "
5253 << MBB->getParent()->getFunction().getName() << " \n");
5255 ME = MBB->instr_end();
5256 MI != ME; ++MI) {
5257 if (MI->isDebugInstr())
5258 continue;
5259 if (MI->isBundle()) {
5260 MachineBasicBlock::instr_iterator MII = MI.getInstrIterator();
5261 MachineBasicBlock::instr_iterator MIE = MI->getParent()->instr_end();
5262 MachineInstr *FirstCompound = NULL, *SecondCompound = NULL;
5263 MachineInstr *FirstDuplex = NULL, *SecondDuplex = NULL;
5264 LLVM_DEBUG(dbgs() << "{\n");
5265
5266 for (++MII; MII != MIE && MII->isInsideBundle() && !MII->isBundle();
5267 ++MII) {
5268 if (MII->isDebugInstr())
5269 continue;
5270 LLVM_DEBUG(dbgs() << "(" << InstOffset << ")\t");
5271 InstOffset += QII->getSize(*MII);
5272 if (QII->getCompoundCandidateGroup(*MII)) {
5273 if (!FirstCompound) {
5274 FirstCompound = &*MII;
5275 LLVM_DEBUG(dbgs() << "XX ");
5276 } else {
5277 SecondCompound = &*MII;
5278 LLVM_DEBUG(dbgs() << "YY ");
5279 }
5280 }
5281 if (QII->getDuplexCandidateGroup(*MII)) {
5282 if (!FirstDuplex) {
5283 FirstDuplex = &*MII;
5284 LLVM_DEBUG(dbgs() << "AA ");
5285 } else {
5286 SecondDuplex = &*MII;
5287 LLVM_DEBUG(dbgs() << "VV ");
5288 }
5289 }
5290 LLVM_DEBUG(MII->dump());
5291 }
5292 LLVM_DEBUG(dbgs() << "}\n");
5293 if (SecondCompound) {
5294 if (isCompoundPair(FirstCompound, SecondCompound)) {
5295 LLVM_DEBUG(dbgs() << "Compound pair (" << CompoundCount << ")\n");
5296 CompoundCount++;
5297 }
5298 }
5299 if (SecondDuplex) {
5300 if (QII->isDuplexPair(*FirstDuplex, *SecondDuplex)) {
5301 LLVM_DEBUG(dbgs() << "Duplex pair (" << DuplexCount << ")\n");
5302 DuplexCount++;
5303 }
5304 }
5305 } else {
5306 LLVM_DEBUG(dbgs() << "(" << InstOffset << ")\t");
5307 if (QII->getCompoundCandidateGroup(*MI))
5308 LLVM_DEBUG(dbgs() << "XX ");
5309 if (QII->getDuplexCandidateGroup(*MI))
5310 LLVM_DEBUG(dbgs() << "AA ");
5311 InstOffset += QII->getSize(*MI);
5312 LLVM_DEBUG(MI->dump());
5313 }
5314 }
5315 }
5316 LLVM_DEBUG(dbgs() << "Total compound(" << CompoundCount << ") duplex("
5317 << DuplexCount << ")\n");
5318 return CompoundCount;
5319}
5320
5321//===----------------------------------------------------------------------===//
5322// Public Constructor Functions
5323//===----------------------------------------------------------------------===//
5324
5326 return new HexagonGlobalScheduler();
5327}
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
constexpr LLT S1
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator MBBI
static const Function * getParent(const Value *V)
bbsections Prepares for basic block by splitting functions into clusters of basic static false void updateBranches(MachineFunction &MF, const SmallVector< MachineBasicBlock * > &PreLayoutFallThroughs)
static bool IsEmptyBlock(MachineBasicBlock *MBB)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static InstructionCost getCost(const AnalysisOptions &Opts, Instruction &Inst, TTI::TargetCostKind CostKind, TargetTransformInfo &TTI)
Definition CostModel.cpp:33
static unsigned InstrCount
This file defines the DenseMap class.
const HexagonInstrInfo * TII
static void DumpLinked(MachineInstr *MI)
static bool IsSchedBarrier(const MachineInstr *MI)
static cl::opt< bool > EnableSpeculativePullUp("enable-speculative-pull-up", cl::Hidden, cl::desc("Enable speculation during Hexagon pull-up pass"))
static cl::opt< bool > ForceNoopHazards("force-noop-hazards", cl::Hidden, cl::init(false), cl::desc("Force noop hazards in scheduler"))
static MachineBasicBlock::instr_iterator getHexagonFirstInstrTerminator(MachineBasicBlock *MBB)
static void debugLivenessForBB(const MachineBasicBlock *MBB, const TargetRegisterInfo *TRI)
static void markKillReg(MachineInstr *MI, unsigned Reg)
Find use with this reg, and unmark the kill flag.
static MachineBasicBlock * getBranchDestination(MachineInstr *MI)
Treat given instruction as a branch, go through its operands and see if any of them is a BB address.
static cl::opt< bool > AllowBBPeelPullUp("enable-bb-peel-pull-up", cl::Hidden, cl::init(true), cl::desc("Peel a reg copy out of a BBloop"))
cl::opt< bool > OneComplexPerPacket
static void updatePredecessors(MachineBasicBlock &MBB, MachineBasicBlock *MFBB)
Rewrite all predecessors of the old block to go to the fallthrough instead.
static void parseOperands(MachineInstr *MI, SmallVector< unsigned, 4 > &Defs, SmallVector< unsigned, 8 > &Uses)
Gather register def/uses from MI.
static bool selectBestBB(BlockFrequency &BBaFreq, unsigned BBaSize, BlockFrequency &BBbFreq, unsigned BBbSize)
Select best candidate to form regions.
static bool MIMustNotBePulledUp(MachineInstr *MI)
static cl::opt< bool > PreventDuplexSeparation("prevent-duplex-separation", cl::Hidden, cl::init(true), cl::desc("Do not destroy existing duplexes during pull up"))
static cl::opt< bool > AllowCmpBranchLoads("cmp-branch-loads-pull-up", cl::Hidden, cl::init(true), cl::desc("Allow compare-branch loads during Hexagon pull-up pass"))
static void DumpPacket(MachineBasicBlock::instr_iterator MII)
static cl::opt< unsigned > SecondaryCandidateQueueSize("pull-up-sec-queue-size", cl::Hidden, cl::init(2))
static bool isDelayedUseException(MachineInstr *MIa, MachineInstr *MIb)
Some apparent dependencies are not actually restricting us since there is a delay between assignment ...
static cl::opt< bool > AllowUnlikelyPath("unlikely-path-pull-up", cl::Hidden, cl::init(true), cl::desc("Allow unlikely path pull up"))
static const unsigned SafetyBuffer
static cl::opt< bool > EnableLocalPullUp("enable-local-pull-up", cl::Hidden, cl::init(true), cl::desc("Enable same BB pull during Hexagon pull-up pass"))
static cl::opt< bool > SpeculateNonPredInsn("speculate-non-pred-insn", cl::Hidden, cl::init(true), cl::desc("Speculate non-predicable instructions in parent BB"))
static void UpdateCFG(MachineBasicBlock *HomeBB, MachineBasicBlock *OriginBB, MachineInstr *MII, MachineBasicBlock *HomeTBB, MachineBasicBlock *HomeFBB, MachineInstr *FTA, MachineInstr *STA, const MachineBranchProbabilityInfo *MBPI)
static cl::opt< bool > WarnOnBundleSize("warn-on-bundle-size", cl::Hidden, cl::desc("Hexagon check bundles and warn on size"))
static unsigned nonDbgBundleSize(MachineBasicBlock::iterator &TargetPacket)
static bool isGlobalMemoryObject(MachineInstr *MI)
Return true if MI is an instruction we are unable to reason about (like something with unmodeled memo...
void Unify(std::vector< ElemType > Range, std::map< ElemType, std::vector< IndexType > > &Set1, std::map< ElemType, std::vector< IndexType > > &Set2, std::pair< std::vector< IndexType >, std::vector< IndexType > > &UnionSet, unsigned union_size=100)
static cl::opt< bool > PreventCompoundSeparation("prevent-compound-separation", cl::Hidden, cl::desc("Do not destroy existing compounds during pull up"))
static cl::opt< bool > AllowDependentPullUp("enable-dependent-pull-up", cl::Hidden, cl::init(true), cl::desc("Perform dual jump formation during pull up"))
static cl::opt< unsigned > MainCandidateQueueSize("pull-up-main-queue-size", cl::Hidden, cl::init(8))
static cl::opt< bool > DisableCheckBundles("disable-hexagon-check-bundles", cl::Hidden, cl::init(true), cl::desc("Disable Hexagon check bundles pass"))
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"))
static cl::opt< bool > PerformDualJumps("dual-jump-in-pull-up", cl::Hidden, cl::init(true), cl::desc("Perform dual jump formation during pull up"))
static void UpdateBundle(MachineInstr *BundleHead)
static bool IsIndirectCall(const MachineInstr *MI)
static cl::opt< bool > DisablePullUp("disable-pull-up", cl::Hidden, cl::desc("Disable Hexagon pull-up pass"))
static cl::opt< bool > AllowSpeculateLoads("speculate-loads-on-pull-up", cl::Hidden, cl::init(true), cl::desc("Allow speculative loads during Hexagon pull-up pass"))
static void unmarkKillReg(MachineInstr *MI, unsigned Reg)
Find use with this reg, and unmark the kill flag.
static bool MIShouldNotBePulledUp(MachineInstr *MI)
static cl::opt< bool > PostPullUpOpt("post-pull-up-opt", cl::Hidden, cl::init(true), cl::desc("Enable opt. exposed by pull-up e.g., remove redundant jumps"))
cl::opt< bool > OneFloatPerPacket
#define HEXAGON_INSTR_SIZE
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
if(PassOpts->AAPipeline)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
static bool isBranch(unsigned Opcode)
SmallVector< MachineOperand, 4 > Cond
MachineRegisterInfo & MRI
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
Remove Loads Into Fake Uses
static bool InBlock(const Value *V, const BasicBlock *BB)
This file defines the SmallSet 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:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
Value * RHS
Value * LHS
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
LLVM_ABI AnalysisUsage & addRequiredID(const void *ID)
Definition Pass.cpp:294
AnalysisUsage & addRequired()
void RemoveBBFromRegion(MachineBasicBlock *MBB)
MachineBasicBlock * findNextMBB(MachineBasicBlock *MBB)
LivenessInfo * getLivenessInfoForBB(MachineBasicBlock *MBB)
void addBBtoRegion(MachineBasicBlock *MBB)
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
iterator begin()
Definition Function.h:847
iterator end()
Definition Function.h:849
bool isPredicated(const MachineInstr &MI) const override
Returns true if the instruction is already predicated.
bool isCompoundBranchInstr(const MachineInstr &MI) const
bool isDuplexPair(const MachineInstr &MIa, const MachineInstr &MIb) const
Symmetrical. See if these two instructions are fit for duplex pair.
bool isJumpR(const MachineInstr &MI) const
bool invertAndChangeJumpTarget(MachineInstr &MI, MachineBasicBlock *NewTarget) const
int getDotNewPredOp(const MachineInstr &MI, const MachineBranchProbabilityInfo *MBPI) const
unsigned getInvertedPredicatedOpcode(const int Opc) const
HexagonII::SubInstructionGroup getDuplexCandidateGroup(const MachineInstr &MI) 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
bool mayBeNewStore(const MachineInstr &MI) const
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 isConstExtended(const MachineInstr &MI) const
bool PredOpcodeHasJMP_c(unsigned Opcode) 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 isComplex(const MachineInstr &MI) const
void setBundleNoShuf(MachineBasicBlock::instr_iterator MIB) const
bool isMemOp(const MachineInstr &MI) const
int getDotOldOp(const MachineInstr &MI) const
bool isDeallocRet(const MachineInstr &MI) const
unsigned getCExtOpNum(const MachineInstr &MI) const
bool isDotNewInst(const MachineInstr &MI) const
unsigned getSize(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 getBundleNoShuf(const MachineInstr &MIB) const
bool isNewValueJump(const MachineInstr &MI) const
bool PredicateInstruction(MachineInstr &MI, ArrayRef< MachineOperand > Cond) const override
Convert the instruction into a predicated instruction.
bool isFloat(const MachineInstr &MI) const
unsigned nonDbgBBSize(const MachineBasicBlock *BB) const
getInstrTimingClassLatency - Compute the instruction latency of a given instruction using Timing Clas...
bool isEndLoopN(unsigned Opcode) const
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
const MCPhysReg * getCalleeSavedRegs(const MachineFunction *MF) const override
Code Generation virtual methods...
bool isFakeReg(MCPhysReg Reg) const
Returns true if the given reserved physical register Reg is live across function calls/returns.
bool isGlobalReg(MCPhysReg Reg) const
Returns true if the given reserved physical register is live across function calls/returns.
void UpdateLiveness(MachineBasicBlock *MBB)
unsigned getSchedClass() const
Return the scheduling class for this instruction.
bool isEHPad() const
Returns true if the block is a landing pad.
reverse_instr_iterator instr_rbegin()
instr_iterator erase_instr(MachineInstr *I)
Remove an instruction from the instruction list and delete it.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
SmallVectorImpl< MachineBasicBlock * >::const_iterator const_succ_iterator
LLVM_ABI iterator getFirstNonDebugInstr(bool SkipPseudoOp=true)
Returns an iterator to the first non-debug instruction in the basic block, or end().
LiveInVector::const_iterator livein_iterator
bool hasAddressTaken() const
Test whether this block is used as something other than the target of a terminator,...
void setAlignment(Align A)
Set alignment of the basic block.
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
LLVM_ABI void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
LLVM_ABI iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI bool isPredecessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a predecessor of this block.
reverse_instr_iterator instr_rend()
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...
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
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
iterator_range< succ_iterator > successors()
LLVM_ABI instr_iterator getFirstInstrTerminator()
Same getFirstTerminator but it ignores bundles and return an instr_iterator instead.
iterator insertAfter(iterator I, MachineInstr *MI)
Insert MI into the instruction list after I.
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 '...
Align getAlignment() const
Return alignment of the basic block.
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
LLVM_ABI bool isLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
Instructions::reverse_iterator reverse_instr_iterator
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
LLVM_ABI BlockFrequency getBlockFreq(const MachineBasicBlock *MBB) const
getblockFreq - Return block frequency.
LLVM_ABI BranchProbability getEdgeProbability(const MachineBasicBlock *Src, const MachineBasicBlock *Dst) const
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
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.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
Representation of each machine instruction.
mop_iterator operands_begin()
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
LLVM_ABI MachineInstr * removeFromParent()
Unlink 'this' from the containing basic block, and return it without deleting it.
const MachineBasicBlock * getParent() const
bool isCall(QueryType Type=AnyInBundle) const
bool isBundle() const
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 isBundledWithPred() const
Return true if this instruction is part of a bundle, and it is not the first instruction in the bundl...
LLVM_ABI void unbundleFromPred()
Break bundle above this instruction.
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
mop_iterator operands_end()
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.
bool isConditionalBranch(QueryType Type=AnyInBundle) const
Return true if this is a branch which may fall through to the next instruction or may transfer contro...
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.
MachineOperand * mop_iterator
iterator/begin/end - Iterate over all operands of a machine instruction.
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
LLVM_ABI void dump() const
bool isBundledWithSucc() const
Return true if this instruction is part of a bundle, and it is not the last instruction in the bundle...
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI void unbundleFromSucc()
Break bundle below this instruction.
LLVM_ABI int findRegisterDefOperandIdx(Register Reg, const TargetRegisterInfo *TRI, bool isDead=false, bool Overlap=false) const
Returns the operand index that is a def of the specified register or -1 if it is not found.
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
bool isIndirectBranch(QueryType Type=AnyInBundle) const
Return true if this is an indirect branch, such as a branch through a register.
bool isBundled() const
Return true if this instruction part of a bundle.
MachineOperand class - Representation of each machine instruction operand.
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
void setIsKill(bool Val=true)
void setMBB(MachineBasicBlock *MBB)
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.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
static constexpr bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
Definition Register.h:60
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
bool empty() const
Definition SmallSet.h:169
bool erase(const T &V)
Definition SmallSet.h:200
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
size_type size() const
Definition SmallSet.h:171
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
LLVM_ABI void init(const TargetSubtargetInfo *TSInfo, bool EnableSModel=true, bool EnableSItins=true)
Initialize the machine model for instruction scheduling.
LLVM_ABI unsigned computeOperandLatency(const MachineInstr *DefMI, unsigned DefOperIdx, const MachineInstr *UseMI, unsigned UseOperIdx) const
Compute operand latency based on the available machine model.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
int getNumOccurrences() const
unsigned getPosition() const
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:166
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
Definition CallingConv.h:76
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
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.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
InstructionCost Cost
LLVM_ABI char & MachineDominatorsID
MachineDominators - This pass is a machine dominators analysis pass.
void initializeHexagonGlobalSchedulerPass(PassRegistry &)
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.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
RNSuccIterator< NodeRef, BlockT, RegionT > succ_end(NodeRef Node)
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
LLVM_ABI Printable printBlockFreq(const BlockFrequencyInfo &BFI, BlockFrequency Freq)
Print the block frequency Freq relative to the current functions entry frequency.
@ 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.
FunctionPass * createHexagonGlobalScheduler()
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82