LLVM 24.0.0git
EarlyIfConversion.cpp
Go to the documentation of this file.
1//===-- EarlyIfConversion.cpp - If-conversion on SSA form machine code ----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Early if-conversion is for out-of-order CPUs that don't have a lot of
10// predicable instructions. The goal is to eliminate conditional branches that
11// may mispredict.
12//
13// Instructions from both sides of the branch are executed specutatively, and a
14// cmov instruction selects the result.
15//
16//===----------------------------------------------------------------------===//
17
19#include "llvm/ADT/BitVector.h"
20#include "llvm/ADT/DenseMap.h"
23#include "llvm/ADT/SparseSet.h"
24#include "llvm/ADT/Statistic.h"
45#include "llvm/Support/Debug.h"
47
48using namespace llvm;
49
50#define DEBUG_TYPE "early-ifcvt"
51
52// Absolute maximum number of instructions allowed per speculated block.
53// This bypasses all other heuristics, so it should be set fairly high.
55BlockInstrLimit("early-ifcvt-limit", cl::init(30), cl::Hidden,
56 cl::desc("Maximum number of instructions per speculated block."));
57
58// Stress testing mode - disable heuristics.
59static cl::opt<bool> Stress("stress-early-ifcvt", cl::Hidden,
60 cl::desc("Turn all knobs to 11"));
61
62// Enable analysis of data dependent branches (conditions derived from loads).
64 "enable-early-ifcvt-data-dependent", cl::Hidden, cl::init(false),
65 cl::desc("Enable hard-to-predict branch analysis for if-conversion"));
66
67// Limit the number steps we take when searching conditions that depend on
68// values recently loaded from memory.
70 MaxNumSteps("early-ifcvt-max-steps", cl::Hidden, cl::init(16),
71 cl::desc("Limit the number of steps taken when searching for a "
72 "recently loaded value"));
73
74// Limit the work done when looking for calls between a load and the condition
75// it feeds.
77 "early-ifcvt-max-region-instrs", cl::Hidden, cl::init(64),
78 cl::desc("Limit the number of blocks and instructions examined when "
79 "searching for calls between a load and the condition it feeds"));
80
82 "early-ifcvt-cold-edge-threshold", cl::Hidden, cl::init(1),
83 cl::desc("Cold edge probability threshold in percent for using no "
84 "critical-path extension budget (0 disables the threshold)"));
85
86STATISTIC(NumDiamondsSeen, "Number of diamonds");
87STATISTIC(NumDiamondsConv, "Number of diamonds converted");
88STATISTIC(NumTrianglesSeen, "Number of triangles");
89STATISTIC(NumTrianglesConv, "Number of triangles converted");
90STATISTIC(NumDataDependant,
91 "Number of data dependent conditional branches encountered");
92STATISTIC(NumLikelyBiased, "Number of branches with a hot path encountered");
93STATISTIC(NumStronglyBiased,
94 "Number of branches with reduced critical-path budget");
95
96//===----------------------------------------------------------------------===//
97// SSAIfConv
98//===----------------------------------------------------------------------===//
99//
100// The SSAIfConv class performs if-conversion on SSA form machine code after
101// determining if it is possible. The class contains no heuristics; external
102// code should be used to determine when if-conversion is a good idea.
103//
104// SSAIfConv can convert both triangles and diamonds:
105//
106// Triangle: Head Diamond: Head
107// | \ / \_
108// | \ / |
109// | [TF]BB FBB TBB
110// | / \ /
111// | / \ /
112// Tail Tail
113//
114// Instructions in the conditional blocks TBB and/or FBB are spliced into the
115// Head block, and phis in the Tail block are converted to select instructions.
116//
117namespace {
118class SSAIfConv {
119 const TargetInstrInfo *TII;
120 const TargetRegisterInfo *TRI;
122
123public:
124 /// The block containing the conditional branch.
125 MachineBasicBlock *Head;
126
127 /// The block containing phis after the if-then-else.
128 MachineBasicBlock *Tail;
129
130 /// The 'true' conditional block as determined by analyzeBranch.
132
133 /// The 'false' conditional block as determined by analyzeBranch.
135
136 /// isTriangle - When there is no 'else' block, either TBB or FBB will be
137 /// equal to Tail.
138 bool isTriangle() const { return TBB == Tail || FBB == Tail; }
139
140 /// Returns the Tail predecessor for the True side.
141 MachineBasicBlock *getTPred() const { return TBB == Tail ? Head : TBB; }
142
143 /// Returns the Tail predecessor for the False side.
144 MachineBasicBlock *getFPred() const { return FBB == Tail ? Head : FBB; }
145
146 /// Information about each phi in the Tail block.
147 struct PHIInfo {
148 MachineInstr *PHI;
149 Register TReg, FReg;
150 /// Description of the select that will replace this phi.
151 TargetInstrInfo::SelectExpansion Select;
152
153 PHIInfo(MachineInstr *phi) : PHI(phi) {}
154 };
155
157
158 /// The branch condition determined by analyzeBranch.
159 SmallVector<MachineOperand, 4> Cond;
160
161private:
162 /// Instructions in Head that define values used by the conditional blocks.
163 /// The hoisted instructions must be inserted after these instructions.
164 SmallPtrSet<MachineInstr*, 8> InsertAfter;
165
166 /// Register units clobbered by the conditional blocks.
167 BitVector ClobberedRegUnits;
168
169 // Scratch pad for findInsertionPoint.
170 SparseSet<MCRegUnit, MCRegUnit, MCRegUnitToIndex> LiveRegUnits;
171
172 /// Insertion point in Head for speculatively executed instructions form TBB
173 /// and FBB.
174 MachineBasicBlock::iterator InsertionPoint;
175
176 /// Return true if all non-terminator instructions in MBB can be safely
177 /// speculated.
178 bool canSpeculateInstrs(MachineBasicBlock *MBB);
179
180 /// Return true if all non-terminator instructions in MBB can be safely
181 /// predicated.
182 bool canPredicateInstrs(MachineBasicBlock *MBB);
183
184 /// Scan through instruction dependencies and update InsertAfter array.
185 /// Return false if any dependency is incompatible with if conversion.
186 bool InstrDependenciesAllowIfConv(MachineInstr *I);
187
188 /// Predicate all instructions of the basic block with current condition
189 /// except for terminators. Reverse the condition if ReversePredicate is set.
190 void PredicateBlock(MachineBasicBlock *MBB, bool ReversePredicate);
191
192 /// Find a valid insertion point in Head.
193 bool findInsertionPoint();
194
195 /// Replace PHI instructions in Tail with selects.
196 void replacePHIInstrs();
197
198 /// Insert selects and rewrite PHI operands to use them.
199 void rewritePHIOperands();
200
201public:
202 /// init - Initialize per-function data structures.
203 void init(MachineFunction &MF) {
204 TII = MF.getSubtarget().getInstrInfo();
205 TRI = MF.getSubtarget().getRegisterInfo();
206 MRI = &MF.getRegInfo();
207 LiveRegUnits.clear();
208 LiveRegUnits.setUniverse(TRI->getNumRegUnits());
209 ClobberedRegUnits.clear();
210 ClobberedRegUnits.resize(TRI->getNumRegUnits());
211 }
212
213 /// canConvertIf - If the sub-CFG headed by MBB can be if-converted,
214 /// initialize the internal state, and return true.
215 /// If predicate is set try to predicate the block otherwise try to
216 /// speculatively execute it.
217 bool canConvertIf(MachineBasicBlock *MBB, bool Predicate = false);
218
219 /// convertIf - If-convert the last block passed to canConvertIf(), assuming
220 /// it is possible. Add any blocks that are to be erased to RemoveBlocks.
221 void convertIf(SmallVectorImpl<MachineBasicBlock *> &RemoveBlocks,
222 bool Predicate = false);
223};
224} // end anonymous namespace
225
226/// canSpeculateInstrs - Returns true if all the instructions in MBB can safely
227/// be speculated. The terminators are not considered.
228///
229/// If instructions use any values that are defined in the head basic block,
230/// the defining instructions are added to InsertAfter.
231///
232/// Any clobbered regunits are added to ClobberedRegUnits.
233///
234bool SSAIfConv::canSpeculateInstrs(MachineBasicBlock *MBB) {
235 // Reject any live-in physregs. It's probably CPSR/EFLAGS, and very hard to
236 // get right.
237 if (!MBB->livein_empty()) {
238 LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << " has live-ins.\n");
239 return false;
240 }
241
242 unsigned InstrCount = 0;
243
244 // Check all instructions, except the terminators. It is assumed that
245 // terminators never have side effects or define any used register values.
246 for (MachineInstr &MI :
248 if (MI.isDebugInstr())
249 continue;
250
251 if (++InstrCount > BlockInstrLimit && !Stress) {
252 LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << " has more than "
253 << BlockInstrLimit << " instructions.\n");
254 return false;
255 }
256
257 // There shouldn't normally be any phis in a single-predecessor block.
258 if (MI.isPHI()) {
259 LLVM_DEBUG(dbgs() << "Can't hoist: " << MI);
260 return false;
261 }
262
263 // Don't speculate loads. Note that it may be possible and desirable to
264 // speculate GOT or constant pool loads that are guaranteed not to trap,
265 // but we don't support that for now.
266 if (MI.mayLoad()) {
267 LLVM_DEBUG(dbgs() << "Won't speculate load: " << MI);
268 return false;
269 }
270
271 // We never speculate stores, so an AA pointer isn't necessary.
272 bool DontMoveAcrossStore = true;
273 if (!MI.isSafeToMove(DontMoveAcrossStore)) {
274 LLVM_DEBUG(dbgs() << "Can't speculate: " << MI);
275 return false;
276 }
277
278 // Check for any dependencies on Head instructions.
279 if (!InstrDependenciesAllowIfConv(&MI))
280 return false;
281 }
282 return true;
283}
284
285/// Check that there is no dependencies preventing if conversion.
286///
287/// If instruction uses any values that are defined in the head basic block,
288/// the defining instructions are added to InsertAfter.
289bool SSAIfConv::InstrDependenciesAllowIfConv(MachineInstr *I) {
290 for (const MachineOperand &MO : I->operands()) {
291 if (MO.isRegMask()) {
292 LLVM_DEBUG(dbgs() << "Won't speculate regmask: " << *I);
293 return false;
294 }
295 if (!MO.isReg())
296 continue;
297 Register Reg = MO.getReg();
298
299 // Remember clobbered regunits.
300 if (MO.isDef() && Reg.isPhysical())
301 for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg()))
302 ClobberedRegUnits.set(static_cast<unsigned>(Unit));
303
304 if (!MO.readsReg() || !Reg.isVirtual())
305 continue;
306 MachineInstr *DefMI = MRI->getVRegDef(Reg);
307 if (!DefMI || DefMI->getParent() != Head)
308 continue;
309 if (InsertAfter.insert(DefMI).second)
310 LLVM_DEBUG(dbgs() << printMBBReference(*I->getParent()) << " depends on "
311 << *DefMI);
312 if (DefMI->isTerminator()) {
313 LLVM_DEBUG(dbgs() << "Can't insert instructions below terminator.\n");
314 return false;
315 }
316 }
317 return true;
318}
319
320/// canPredicateInstrs - Returns true if all the instructions in MBB can safely
321/// be predicates. The terminators are not considered.
322///
323/// If instructions use any values that are defined in the head basic block,
324/// the defining instructions are added to InsertAfter.
325///
326/// Any clobbered regunits are added to ClobberedRegUnits.
327///
328bool SSAIfConv::canPredicateInstrs(MachineBasicBlock *MBB) {
329 // Reject any live-in physregs. It's probably CPSR/EFLAGS, and very hard to
330 // get right.
331 if (!MBB->livein_empty()) {
332 LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << " has live-ins.\n");
333 return false;
334 }
335
336 unsigned InstrCount = 0;
337
338 // Check all instructions, except the terminators. It is assumed that
339 // terminators never have side effects or define any used register values.
342 I != E; ++I) {
343 if (I->isDebugInstr())
344 continue;
345
346 if (++InstrCount > BlockInstrLimit && !Stress) {
347 LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << " has more than "
348 << BlockInstrLimit << " instructions.\n");
349 return false;
350 }
351
352 // There shouldn't normally be any phis in a single-predecessor block.
353 if (I->isPHI()) {
354 LLVM_DEBUG(dbgs() << "Can't predicate: " << *I);
355 return false;
356 }
357
358 // Check that instruction is predicable
359 if (!TII->isPredicable(*I)) {
360 LLVM_DEBUG(dbgs() << "Isn't predicable: " << *I);
361 return false;
362 }
363
364 // Check that instruction is not already predicated.
365 if (TII->isPredicated(*I) && !TII->canPredicatePredicatedInstr(*I)) {
366 LLVM_DEBUG(dbgs() << "Is already predicated: " << *I);
367 return false;
368 }
369
370 // Check for any dependencies on Head instructions.
371 if (!InstrDependenciesAllowIfConv(&(*I)))
372 return false;
373 }
374 return true;
375}
376
377// Apply predicate to all instructions in the machine block.
378void SSAIfConv::PredicateBlock(MachineBasicBlock *MBB, bool ReversePredicate) {
379 auto Condition = Cond;
380 if (ReversePredicate) {
381 bool CanRevCond = !TII->reverseBranchCondition(Condition);
382 assert(CanRevCond && "Reversed predicate is not supported");
383 (void)CanRevCond;
384 }
385 // Terminators don't need to be predicated as they will be removed.
388 I != E; ++I) {
389 if (I->isDebugInstr())
390 continue;
391 TII->PredicateInstruction(*I, Condition);
392 }
393}
394
395/// Find an insertion point in Head for the speculated instructions. The
396/// insertion point must be:
397///
398/// 1. Before any terminators.
399/// 2. After any instructions in InsertAfter.
400/// 3. Not have any clobbered regunits live.
401///
402/// This function sets InsertionPoint and returns true when successful, it
403/// returns false if no valid insertion point could be found.
404///
405bool SSAIfConv::findInsertionPoint() {
406 // Keep track of live regunits before the current position.
407 // Only track RegUnits that are also in ClobberedRegUnits.
408 LiveRegUnits.clear();
413 while (I != B) {
414 --I;
415 // Some of the conditional code depends in I.
416 if (InsertAfter.count(&*I)) {
417 LLVM_DEBUG(dbgs() << "Can't insert code after " << *I);
418 return false;
419 }
420
421 // Update live regunits.
422 for (const MachineOperand &MO : I->operands()) {
423 // We're ignoring regmask operands. That is conservatively correct.
424 if (!MO.isReg())
425 continue;
426 Register Reg = MO.getReg();
427 if (!Reg.isPhysical())
428 continue;
429 // I clobbers Reg, so it isn't live before I.
430 if (MO.isDef())
431 for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg()))
432 LiveRegUnits.erase(Unit);
433 // Unless I reads Reg.
434 if (MO.readsReg())
435 Reads.push_back(Reg.asMCReg());
436 }
437 // Anything read by I is live before I.
438 while (!Reads.empty())
439 for (MCRegUnit Unit : TRI->regunits(Reads.pop_back_val()))
440 if (ClobberedRegUnits.test(static_cast<unsigned>(Unit)))
441 LiveRegUnits.insert(Unit);
442
443 // We can't insert before a terminator.
444 if (I != FirstTerm && I->isTerminator())
445 continue;
446
447 // Some of the clobbered registers are live before I, not a valid insertion
448 // point.
449 if (!LiveRegUnits.empty()) {
450 LLVM_DEBUG({
451 dbgs() << "Would clobber";
452 for (MCRegUnit LRU : LiveRegUnits)
453 dbgs() << ' ' << printRegUnit(LRU, TRI);
454 dbgs() << " live before " << *I;
455 });
456 continue;
457 }
458
459 // This is a valid insertion point.
460 InsertionPoint = I;
461 LLVM_DEBUG(dbgs() << "Can insert before " << *I);
462 return true;
463 }
464 LLVM_DEBUG(dbgs() << "No legal insertion point found.\n");
465 return false;
466}
467
468
469
470/// canConvertIf - analyze the sub-cfg rooted in MBB, and return true if it is
471/// a potential candidate for if-conversion. Fill out the internal state.
472///
473bool SSAIfConv::canConvertIf(MachineBasicBlock *MBB, bool Predicate) {
474 Head = MBB;
475 TBB = FBB = Tail = nullptr;
476
477 if (Head->succ_size() != 2)
478 return false;
479 MachineBasicBlock *Succ0 = Head->succ_begin()[0];
480 MachineBasicBlock *Succ1 = Head->succ_begin()[1];
481
482 // Canonicalize so Succ0 has MBB as its single predecessor.
483 if (Succ0->pred_size() != 1)
484 std::swap(Succ0, Succ1);
485
486 if (Succ0->pred_size() != 1 || Succ0->succ_size() != 1)
487 return false;
488
489 Tail = Succ0->succ_begin()[0];
490
491 // This is not a triangle.
492 if (Tail != Succ1) {
493 // Check for a diamond. We won't deal with any critical edges.
494 if (Succ1->pred_size() != 1 || Succ1->succ_size() != 1 ||
495 Succ1->succ_begin()[0] != Tail)
496 return false;
497 LLVM_DEBUG(dbgs() << "\nDiamond: " << printMBBReference(*Head) << " -> "
498 << printMBBReference(*Succ0) << "/"
499 << printMBBReference(*Succ1) << " -> "
500 << printMBBReference(*Tail) << '\n');
501
502 // Live-in physregs are tricky to get right when speculating code.
503 if (!Tail->livein_empty()) {
504 LLVM_DEBUG(dbgs() << "Tail has live-ins.\n");
505 return false;
506 }
507 } else {
508 LLVM_DEBUG(dbgs() << "\nTriangle: " << printMBBReference(*Head) << " -> "
509 << printMBBReference(*Succ0) << " -> "
510 << printMBBReference(*Tail) << '\n');
511 }
512
513 // This is a triangle or a diamond.
514 // Skip if we cannot predicate and there are no phis skip as there must be
515 // side effects that can only be handled with predication.
516 if (!Predicate && (Tail->empty() || !Tail->front().isPHI())) {
517 LLVM_DEBUG(dbgs() << "No phis in tail.\n");
518 return false;
519 }
520
521 // The branch we're looking to eliminate must be analyzable.
522 Cond.clear();
523 if (TII->analyzeBranch(*Head, TBB, FBB, Cond)) {
524 LLVM_DEBUG(dbgs() << "Branch not analyzable.\n");
525 return false;
526 }
527
528 // This is weird, probably some sort of degenerate CFG.
529 if (!TBB) {
530 LLVM_DEBUG(dbgs() << "analyzeBranch didn't find conditional branch.\n");
531 return false;
532 }
533
534 // Make sure the analyzed branch is conditional; one of the successors
535 // could be a landing pad. (Empty landing pads can be generated on Windows.)
536 if (Cond.empty()) {
537 LLVM_DEBUG(dbgs() << "analyzeBranch found an unconditional branch.\n");
538 return false;
539 }
540
541 // analyzeBranch doesn't set FBB on a fall-through branch.
542 // Make sure it is always set.
543 FBB = TBB == Succ0 ? Succ1 : Succ0;
544
545 // Any phis in the tail block must be convertible to selects.
546 PHIs.clear();
547 MachineBasicBlock *TPred = getTPred();
548 MachineBasicBlock *FPred = getFPred();
549 for (MachineBasicBlock::iterator I = Tail->begin(), E = Tail->end();
550 I != E && I->isPHI(); ++I) {
551 PHIs.push_back(&*I);
552 PHIInfo &PI = PHIs.back();
553 // Find PHI operands corresponding to TPred and FPred.
554 for (unsigned i = 1; i != PI.PHI->getNumOperands(); i += 2) {
555 if (PI.PHI->getOperand(i+1).getMBB() == TPred)
556 PI.TReg = PI.PHI->getOperand(i).getReg();
557 if (PI.PHI->getOperand(i+1).getMBB() == FPred)
558 PI.FReg = PI.PHI->getOperand(i).getReg();
559 }
560 assert(PI.TReg.isVirtual() && "Bad PHI");
561 assert(PI.FReg.isVirtual() && "Bad PHI");
562
563 // Get target information.
564 if (!TII->canInsertSelect(*Head, Cond, PI.PHI->getOperand(0).getReg(),
565 PI.TReg, PI.FReg, PI.Select)) {
566 LLVM_DEBUG(dbgs() << "Can't convert: " << *PI.PHI);
567 return false;
568 }
569 }
570
571 // Check that the conditional instructions can be speculated.
572 InsertAfter.clear();
573 ClobberedRegUnits.reset();
574 if (Predicate) {
575 if (TBB != Tail && !canPredicateInstrs(TBB))
576 return false;
577 if (FBB != Tail && !canPredicateInstrs(FBB))
578 return false;
579 } else {
580 if (TBB != Tail && !canSpeculateInstrs(TBB))
581 return false;
582 if (FBB != Tail && !canSpeculateInstrs(FBB))
583 return false;
584 }
585
586 // Try to find a valid insertion point for the speculated instructions in the
587 // head basic block.
588 if (!findInsertionPoint())
589 return false;
590
591 if (isTriangle())
592 ++NumTrianglesSeen;
593 else
594 ++NumDiamondsSeen;
595 return true;
596}
597
598/// \return true iff the two registers are known to have the same value.
600 const TargetInstrInfo *TII, Register TReg,
601 Register FReg) {
602 if (TReg == FReg)
603 return true;
604
605 if (!TReg.isVirtual() || !FReg.isVirtual())
606 return false;
607
608 const MachineInstr *TDef = MRI.getUniqueVRegDef(TReg);
609 const MachineInstr *FDef = MRI.getUniqueVRegDef(FReg);
610 if (!TDef || !FDef)
611 return false;
612
613 // If there are side-effects, all bets are off.
614 if (TDef->hasUnmodeledSideEffects())
615 return false;
616
617 // If the instruction could modify memory, or there may be some intervening
618 // store between the two, we can't consider them to be equal.
619 if (TDef->mayLoadOrStore() && !TDef->isDereferenceableInvariantLoad())
620 return false;
621
622 // We also can't guarantee that they are the same if, for example, the
623 // instructions are both a copy from a physical reg, because some other
624 // instruction may have modified the value in that reg between the two
625 // defining insts.
626 if (any_of(TDef->uses(), [](const MachineOperand &MO) {
627 return MO.isReg() && MO.getReg().isPhysical();
628 }))
629 return false;
630
631 // Check whether the two defining instructions produce the same value(s).
632 if (!TII->produceSameValue(*TDef, *FDef, &MRI))
633 return false;
634
635 // Further, check that the two defs come from corresponding operands.
636 int TIdx = TDef->findRegisterDefOperandIdx(TReg, /*TRI=*/nullptr);
637 int FIdx = FDef->findRegisterDefOperandIdx(FReg, /*TRI=*/nullptr);
638 if (TIdx == -1 || FIdx == -1)
639 return false;
640
641 return TIdx == FIdx;
642}
643
644/// replacePHIInstrs - Completely replace PHI instructions with selects.
645/// This is possible when the only Tail predecessors are the if-converted
646/// blocks.
647void SSAIfConv::replacePHIInstrs() {
648 assert(Tail->pred_size() == 2 && "Cannot replace PHIs");
650 assert(FirstTerm != Head->end() && "No terminators");
651 DebugLoc HeadDL = FirstTerm->getDebugLoc();
652
653 // Convert all PHIs to select instructions inserted before FirstTerm.
654 for (PHIInfo &PI : PHIs) {
655 LLVM_DEBUG(dbgs() << "If-converting " << *PI.PHI);
656 Register DstReg = PI.PHI->getOperand(0).getReg();
657 if (hasSameValue(*MRI, TII, PI.TReg, PI.FReg)) {
658 // We do not need the select instruction if both incoming values are
659 // equal, but we do need a COPY.
660 BuildMI(*Head, FirstTerm, HeadDL, TII->get(TargetOpcode::COPY), DstReg)
661 .addReg(PI.TReg);
662 } else {
663 TII->insertSelect(*Head, FirstTerm, HeadDL, DstReg, Cond, PI.TReg,
664 PI.FReg);
665 }
666 LLVM_DEBUG(dbgs() << " --> " << *std::prev(FirstTerm));
667 PI.PHI->eraseFromParent();
668 PI.PHI = nullptr;
669 }
670}
671
672/// rewritePHIOperands - When there are additional Tail predecessors, insert
673/// select instructions in Head and rewrite PHI operands to use the selects.
674/// Keep the PHI instructions in Tail to handle the other predecessors.
675void SSAIfConv::rewritePHIOperands() {
677 assert(FirstTerm != Head->end() && "No terminators");
678 DebugLoc HeadDL = FirstTerm->getDebugLoc();
679
680 // Convert all PHIs to select instructions inserted before FirstTerm.
681 for (PHIInfo &PI : PHIs) {
682 Register DstReg;
683
684 LLVM_DEBUG(dbgs() << "If-converting " << *PI.PHI);
685 if (hasSameValue(*MRI, TII, PI.TReg, PI.FReg)) {
686 // We do not need the select instruction if both incoming values are
687 // equal.
688 DstReg = PI.TReg;
689 } else {
690 Register PHIDst = PI.PHI->getOperand(0).getReg();
691 DstReg = MRI->createVirtualRegister(MRI->getRegClass(PHIDst));
692 TII->insertSelect(*Head, FirstTerm, HeadDL,
693 DstReg, Cond, PI.TReg, PI.FReg);
694 LLVM_DEBUG(dbgs() << " --> " << *std::prev(FirstTerm));
695 }
696
697 // Rewrite PHI operands TPred -> (DstReg, Head), remove FPred.
698 for (unsigned i = PI.PHI->getNumOperands(); i != 1; i -= 2) {
699 MachineBasicBlock *MBB = PI.PHI->getOperand(i-1).getMBB();
700 if (MBB == getTPred()) {
701 PI.PHI->getOperand(i-1).setMBB(Head);
702 PI.PHI->getOperand(i-2).setReg(DstReg);
703 } else if (MBB == getFPred()) {
704 PI.PHI->removeOperand(i-1);
705 PI.PHI->removeOperand(i-2);
706 }
707 }
708 LLVM_DEBUG(dbgs() << " --> " << *PI.PHI);
709 }
710}
711
712/// convertIf - Execute the if conversion after canConvertIf has determined the
713/// feasibility.
714///
715/// Any basic blocks that need to be erased will be added to RemoveBlocks.
716///
717void SSAIfConv::convertIf(SmallVectorImpl<MachineBasicBlock *> &RemoveBlocks,
718 bool Predicate) {
719 assert(Head && Tail && TBB && FBB && "Call canConvertIf first.");
720
721 // Update statistics.
722 if (isTriangle())
723 ++NumTrianglesConv;
724 else
725 ++NumDiamondsConv;
726
727 // Move all instructions into Head, except for the terminators.
728 if (TBB != Tail) {
729 if (Predicate)
730 PredicateBlock(TBB, /*ReversePredicate=*/false);
731 Head->splice(InsertionPoint, TBB, TBB->begin(), TBB->getFirstTerminator());
732 }
733 if (FBB != Tail) {
734 if (Predicate)
735 PredicateBlock(FBB, /*ReversePredicate=*/true);
736 Head->splice(InsertionPoint, FBB, FBB->begin(), FBB->getFirstTerminator());
737 }
738 // Are there extra Tail predecessors?
739 bool ExtraPreds = Tail->pred_size() != 2;
740 if (ExtraPreds)
741 rewritePHIOperands();
742 else
743 replacePHIInstrs();
744
745 // Fix up the CFG, temporarily leave Head without any successors.
746 Head->removeSuccessor(TBB);
747 Head->removeSuccessor(FBB, true);
748 if (TBB != Tail)
749 TBB->removeSuccessor(Tail, true);
750 if (FBB != Tail)
751 FBB->removeSuccessor(Tail, true);
752
753 // Fix up Head's terminators.
754 // It should become a single branch or a fallthrough.
755 DebugLoc HeadDL = Head->getFirstTerminator()->getDebugLoc();
756 TII->removeBranch(*Head);
757
758 // Mark the now empty conditional blocks for removal and move them to the end.
759 // It is likely that Head can fall
760 // through to Tail, and we can join the two blocks.
761 if (TBB != Tail) {
762 RemoveBlocks.push_back(TBB);
763 if (TBB != &TBB->getParent()->back())
764 TBB->moveAfter(&TBB->getParent()->back());
765 }
766 if (FBB != Tail) {
767 RemoveBlocks.push_back(FBB);
768 if (FBB != &FBB->getParent()->back())
769 FBB->moveAfter(&FBB->getParent()->back());
770 }
771
772 assert(Head->succ_empty() && "Additional head successors?");
773 if (!ExtraPreds && Head->isLayoutSuccessor(Tail)) {
774 // Splice Tail onto the end of Head.
775 LLVM_DEBUG(dbgs() << "Joining tail " << printMBBReference(*Tail)
776 << " into head " << printMBBReference(*Head) << '\n');
777 Head->splice(Head->end(), Tail,
778 Tail->begin(), Tail->end());
780 RemoveBlocks.push_back(Tail);
781 if (Tail != &Tail->getParent()->back())
782 Tail->moveAfter(&Tail->getParent()->back());
783 } else {
784 // We need a branch to Tail, let code placement work it out later.
785 LLVM_DEBUG(dbgs() << "Converting to unconditional branch.\n");
787 TII->insertBranch(*Head, Tail, nullptr, EmptyCond, HeadDL);
788 Head->addSuccessor(Tail);
789 }
790 LLVM_DEBUG(dbgs() << *Head);
791}
792
793//===----------------------------------------------------------------------===//
794// EarlyIfConverter Pass
795//===----------------------------------------------------------------------===//
796
797namespace {
798class EarlyIfConverter {
799 const TargetInstrInfo *TII = nullptr;
800 const TargetRegisterInfo *TRI = nullptr;
801 const TargetSubtargetInfo *STI = nullptr;
802 MachineRegisterInfo *MRI = nullptr;
803 MachineDominatorTree *DomTree = nullptr;
804 MachineLoopInfo *Loops = nullptr;
805 MachineTraceMetrics *Traces = nullptr;
806 MachineTraceMetrics::Ensemble *MinInstr = nullptr;
807 MachineBranchProbabilityInfo &MBPI;
808 SSAIfConv IfConv;
809
810 /// Cache of basic blocks verified to contain no call instructions, mapping
811 /// each block to the number of instructions scanned in it.
812 DenseMap<const MachineBasicBlock *, unsigned> NoCallBlocksCache;
813
814public:
815 EarlyIfConverter(MachineDominatorTree &DT, MachineLoopInfo &LI,
816 MachineTraceMetrics &MTM, MachineBranchProbabilityInfo &MBPI)
817 : DomTree(&DT), Loops(&LI), Traces(&MTM), MBPI(MBPI) {}
818 EarlyIfConverter() = delete;
819
820 bool run(MachineFunction &MF);
821
822private:
823 bool tryConvertIf(MachineBasicBlock *);
824 void invalidateTraces();
825 bool shouldConvertIf();
826 bool isConditionDataDependent();
827 bool doOperandsComeFromMemory(const MachineInstr *ConditionDef);
828 bool hasCallOrLoopInRange(const MachineInstr *From, const MachineInstr *To);
829};
830
831class EarlyIfConverterLegacy : public MachineFunctionPass {
832public:
833 static char ID;
834 EarlyIfConverterLegacy() : MachineFunctionPass(ID) {}
835 void getAnalysisUsage(AnalysisUsage &AU) const override;
836 bool runOnMachineFunction(MachineFunction &MF) override;
837 StringRef getPassName() const override { return "Early If-Conversion"; }
838};
839} // end anonymous namespace
840
841char EarlyIfConverterLegacy::ID = 0;
842char &llvm::EarlyIfConverterLegacyID = EarlyIfConverterLegacy::ID;
843
844INITIALIZE_PASS_BEGIN(EarlyIfConverterLegacy, DEBUG_TYPE, "Early If Converter",
845 false, false)
849INITIALIZE_PASS_END(EarlyIfConverterLegacy, DEBUG_TYPE, "Early If Converter",
851
852void EarlyIfConverterLegacy::getAnalysisUsage(AnalysisUsage &AU) const {
853 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
855 AU.addRequired<MachineDominatorTreeWrapperPass>();
856 AU.addPreserved<MachineDominatorTreeWrapperPass>();
857 AU.addRequired<MachineLoopInfoWrapperPass>();
858 AU.addPreserved<MachineLoopInfoWrapperPass>();
859 AU.addRequired<MachineTraceMetricsWrapperPass>();
860 AU.addPreserved<MachineTraceMetricsWrapperPass>();
862}
863
864namespace {
865/// Update the dominator tree after if-conversion erased some blocks.
866void updateDomTree(MachineDominatorTree *DomTree, const SSAIfConv &IfConv,
868 // convertIf can remove TBB, FBB, and Tail can be merged into Head.
869 // TBB and FBB should not dominate any blocks.
870 // Tail children should be transferred to Head.
871 MachineDomTreeNode *HeadNode = DomTree->getNode(IfConv.Head);
872 for (auto *B : Removed) {
873 MachineDomTreeNode *Node = DomTree->getNode(B);
874 assert(Node != HeadNode && "Cannot erase the head node");
875 while (!Node->isLeaf()) {
876 assert(Node->getBlock() == IfConv.Tail && "Unexpected children");
877 DomTree->changeImmediateDominator(*Node->begin(), HeadNode);
878 }
879 DomTree->eraseNode(B);
880 }
881}
882
883/// Update LoopInfo after if-conversion.
884void updateLoops(MachineLoopInfo *Loops,
886 // If-conversion doesn't change loop structure, and it doesn't mess with back
887 // edges, so updating LoopInfo is simply removing the dead blocks.
888 for (auto *B : Removed)
889 Loops->removeBlock(B);
890}
891} // namespace
892
893/// Invalidate MachineTraceMetrics before if-conversion.
894void EarlyIfConverter::invalidateTraces() {
895 Traces->verifyAnalysis();
896 Traces->invalidate(IfConv.Head);
897 Traces->invalidate(IfConv.Tail);
898 Traces->invalidate(IfConv.TBB);
899 Traces->invalidate(IfConv.FBB);
900 Traces->verifyAnalysis();
901}
902
903static bool isConstantPoolLoad(const MachineInstr *MI) {
904 return MI->mayLoad() && any_of(MI->memoperands(), [](MachineMemOperand *MOp) {
905 const PseudoSourceValue *PSV = MOp->getPseudoValue();
906 return PSV && PSV->isConstantPool();
907 });
908}
909
910/// Check whether the load in From and the condition in To are far apart, i.e.
911/// whether a call or a loop can be executed between them. This is done by first
912/// scanning the instructions within From and To MBBs. If no call is found, we
913/// then scan all blocks which are dominated by From (the load) and can reach To
914/// (the condition), looking for calls and for blocks belonging to a loop the
915/// condition is not part of.
916bool EarlyIfConverter::hasCallOrLoopInRange(const MachineInstr *From,
917 const MachineInstr *To) {
918 if (From == To)
919 return false;
920
921 LLVM_DEBUG(dbgs() << " checking for a call or loop between " << *From
922 << " and " << *To);
923 assert(DomTree->dominates(From, To) && "From is expected to dominate To");
924
925 const MachineBasicBlock *FromBB = From->getParent();
926 const MachineBasicBlock *ToBB = To->getParent();
927
928 unsigned NumScanned = 0;
929 auto HitSearchLimit = [&](unsigned N) {
930 NumScanned += N;
931 if (NumScanned <= MaxRegionInstrs)
932 return false;
933 LLVM_DEBUG(dbgs() << " hasCallOrLoopInRange scanned more than "
934 << MaxRegionInstrs << " instructions\n");
935 return true;
936 };
937 auto FoundCall = [](const MachineInstr &MI) {
938 LLVM_DEBUG(dbgs() << " found a call before the condition: " << MI);
939 return true;
940 };
941 auto IsCallOrHitSearchLimit = [&](const MachineInstr &MI) {
942 if (HitSearchLimit(1))
943 return true;
944 if (!MI.isCall())
945 return false;
946 return FoundCall(MI);
947 };
948
949 // If From and To are in the same block, just check (From, To).
950 if (FromBB == ToBB) {
951 for (const MachineInstr &MI : instructionsWithoutDebug(
952 std::next(From->getIterator()), To->getIterator(),
953 /*SkipPseudoOp=*/false))
954 if (IsCallOrHitSearchLimit(MI))
955 return true;
956 return false;
957 }
958
959 // Check (From, end of From's block] and [start of To's block, To).
960 for (const MachineInstr &MI : instructionsWithoutDebug(
961 std::next(From->getIterator()), FromBB->instr_end(),
962 /*SkipPseudoOp=*/false))
963 if (IsCallOrHitSearchLimit(MI))
964 return true;
965 for (const MachineInstr &MI :
967 /*SkipPseudoOp=*/false))
968 if (IsCallOrHitSearchLimit(MI))
969 return true;
970
971 // Enqueued guards the traversal: the endpoint blocks are traversed through
972 // but their instructions were already handled above.
973 SmallPtrSet<const MachineBasicBlock *, 16> Enqueued = {FromBB, ToBB};
975 auto Enqueue = [&](const MachineBasicBlock *BB) {
976 if (DomTree->dominates(FromBB, BB) && Enqueued.insert(BB).second)
977 Worklist.push_back(BB);
978 };
979
980 for (const MachineBasicBlock *Pred : ToBB->predecessors())
981 Enqueue(Pred);
982
983 while (!Worklist.empty()) {
984 const MachineBasicBlock *BB = Worklist.pop_back_val();
985
986 // If the block belongs to a loop containing neither the load nor the
987 // condition, that loop is executed entirely between the two, so consider
988 // them far apart.
989 if (const MachineLoop *BBLoop = Loops->getLoopFor(BB)) {
990 if (!BBLoop->contains(ToBB) && !BBLoop->contains(FromBB)) {
991 LLVM_DEBUG(dbgs() << " found a loop before the condition in "
992 << printMBBReference(*BB) << '\n');
993 return true;
994 }
995 }
996
997 // Next check for calls in the block.
998 auto CacheIt = NoCallBlocksCache.find(BB);
999 if (CacheIt != NoCallBlocksCache.end()) {
1000 if (HitSearchLimit(CacheIt->second))
1001 return true;
1002 } else {
1003 unsigned NumBlockInstrs = 0;
1004 for (const MachineInstr &MI :
1006 /*SkipPseudoOp=*/false)) {
1007 ++NumBlockInstrs;
1008 if (IsCallOrHitSearchLimit(MI))
1009 return true;
1010 }
1011 NoCallBlocksCache[BB] = NumBlockInstrs;
1012 }
1013
1014 for (const MachineBasicBlock *Pred : BB->predecessors())
1015 Enqueue(Pred);
1016 }
1017
1018 return false;
1019}
1020
1021/// Check if a register's value comes from a memory load by walking the
1022/// def-use chain. We want to prioritize converting branches which
1023/// depend on values loaded from memory (unless they are loop invariant,
1024/// or come from a constant pool). The walk starts from the definition of
1025/// ConditionDef's first operand, which is not ConditionDef itself for
1026/// instructions such as FCMPSrr, where that operand is a use.
1027bool EarlyIfConverter::doOperandsComeFromMemory(
1028 const MachineInstr *ConditionDef) {
1029 Register Reg = ConditionDef->getOperand(0).getReg();
1030 if (!Reg.isVirtual())
1031 return false;
1032
1033 LLVM_DEBUG(dbgs() << " doOperandsComeFromMemory starting from reg "
1034 << printReg(Reg) << "\n");
1035
1036 // The condition is consumed by the branch terminating Head, so this is the
1037 // end of the interval a load has to survive without a call in between.
1038 const MachineInstr *Br = &*IfConv.Head->getFirstTerminator();
1039 MachineLoop *IfConvLoop = Loops->getLoopFor(IfConv.Head);
1040
1041 // Walk the def-use chain.
1042 SmallPtrSet<const MachineInstr *, 8> VisitedInstrs;
1043 SmallVector<const MachineInstr *> Worklist;
1044
1045 MachineInstr *DefMI = MRI->getVRegDef(Reg);
1046 // The operand is defined outside of the function - it does not
1047 // come from memory access.
1048 if (!DefMI)
1049 return false;
1050
1051 Worklist.push_back(DefMI);
1052
1053 while (!Worklist.empty() && VisitedInstrs.size() < MaxNumSteps) {
1054 const MachineInstr *MI = Worklist.pop_back_val();
1055 if (!VisitedInstrs.insert(MI).second)
1056 continue;
1057
1058 // Don't walk through PHIs: a value arriving on a back edge is loaded in a
1059 // previous iteration, so the interval between the load and the branch is
1060 // not the one hasCallOrLoopInRange measures.
1061 if (MI->isPHI())
1062 continue;
1063
1064 const MachineBasicBlock *Parent = MI->getParent();
1065 MachineLoop *ParentLoop = Loops->getLoopFor(Parent);
1066
1067 // If the instruction is outside the loop, skip it (loop-invariant).
1068 if (IfConvLoop && ParentLoop != IfConvLoop)
1069 continue;
1070
1071 // Check if this instruction is a load, and there are no calls or loops
1072 // between the load and the condition (which would break the "close in
1073 // time" assumption).
1074 if (MI->mayLoad() && !isConstantPoolLoad(MI) &&
1075 !MI->isDereferenceableInvariantLoad()) {
1076 // If the load doesn't dominate the branch (e.g., comes after it in
1077 // the same block via a loop back-edge), it can't affect this iteration.
1078 // If not - check if there is a call or a loop between the load
1079 // instruction and the branch.
1080 if (!DomTree->dominates(MI, Br) || hasCallOrLoopInRange(MI, Br))
1081 continue;
1082
1083 return true;
1084 }
1085
1086 // Walk through all register use operands and find their definitions.
1087 for (const MachineOperand &MO : MI->operands()) {
1088 if (!MO.isReg() || !MO.isUse())
1089 continue;
1090 Register UseReg = MO.getReg();
1091 if (!UseReg.isVirtual())
1092 continue;
1093
1094 if (MachineInstr *UseDef = MRI->getVRegDef(UseReg)) {
1095 if (!VisitedInstrs.count(UseDef)) {
1096 Worklist.push_back(UseDef);
1097 }
1098 }
1099 }
1100 }
1101
1102 return false;
1103}
1104
1105/// Check if the branch condition is data-dependent (comes from memory loads).
1106bool EarlyIfConverter::isConditionDataDependent() {
1107 TargetInstrInfo::MachineBranchPredicate MBP;
1108 if (TII->analyzeBranchPredicate(*IfConv.Head, MBP, /*AllowModify=*/false))
1109 return false;
1110
1111 if (!MBP.ConditionDef)
1112 return false;
1113
1114 // If the branch is biased (not 50/50), don't consider it data dependent.
1115 // This is to prevent converting unprofitable checks such as
1116 // `x[i] != 0;`
1117 auto TBBProb = MBPI.getEdgeProbability(IfConv.Head, IfConv.TBB);
1118 auto FBBProb = MBPI.getEdgeProbability(IfConv.Head, IfConv.FBB);
1119 if (TBBProb != FBBProb) {
1120 ++NumLikelyBiased;
1121 return false;
1122 }
1123
1124 // Check if operands used to compute the branch condition were loaded recently
1125 // from memory, starting by the ConditionDef itself and walking up the use-def
1126 // chain.
1127 if (doOperandsComeFromMemory(MBP.ConditionDef)) {
1128 ++NumDataDependant;
1129 return true;
1130 }
1131
1132 return false;
1133}
1134
1135// Adjust cycles with downward saturation.
1136static unsigned adjCycles(unsigned Cyc, int Delta) {
1137 if (Delta < 0 && Cyc + Delta > Cyc)
1138 return 0;
1139 return Cyc + Delta;
1140}
1141
1142namespace {
1143/// Helper class to simplify emission of cycle counts into optimization remarks.
1144struct Cycles {
1145 const char *Key;
1146 unsigned Value;
1147};
1148template <typename Remark> Remark &operator<<(Remark &R, Cycles C) {
1149 return R << ore::NV(C.Key, C.Value) << (C.Value == 1 ? " cycle" : " cycles");
1150}
1151} // anonymous namespace
1152
1153/// Apply cost model and heuristics to the if-conversion in IfConv.
1154/// Return true if the conversion is a good idea.
1155///
1156bool EarlyIfConverter::shouldConvertIf() {
1157 // Stress testing mode disables all cost considerations.
1158 if (Stress)
1159 return true;
1160
1161 // Do not try to if-convert if the condition has a high chance of being
1162 // predictable.
1163 MachineLoop *CurrentLoop = Loops->getLoopFor(IfConv.Head);
1164 // If the condition is in a loop, consider it predictable if the condition
1165 // itself or all its operands are loop-invariant. E.g. this considers a load
1166 // from a loop-invariant address predictable; we were unable to prove that it
1167 // doesn't alias any of the memory-writes in the loop, but it is likely to
1168 // read to same value multiple times.
1169 if (CurrentLoop && any_of(IfConv.Cond, [&](MachineOperand &MO) {
1170 if (!MO.isReg() || !MO.isUse())
1171 return false;
1172 Register Reg = MO.getReg();
1173 if (Reg.isPhysical())
1174 return false;
1175
1176 MachineInstr *Def = MRI->getVRegDef(Reg);
1177 return CurrentLoop->isLoopInvariant(*Def) ||
1178 all_of(Def->operands(), [&](MachineOperand &Op) {
1179 if (Op.isImm())
1180 return true;
1181 if (!Op.isReg() || !Op.isUse())
1182 return true;
1183 Register Reg = Op.getReg();
1184 if (Reg.isPhysical())
1185 return false;
1186
1187 MachineInstr *Def = MRI->getVRegDef(Reg);
1188 return CurrentLoop->isLoopInvariant(*Def);
1189 });
1190 }))
1191 return false;
1192
1193 if (!MinInstr)
1194 MinInstr = Traces->getEnsemble(MachineTraceStrategy::TS_MinInstrCount);
1195
1196 MachineTraceMetrics::Trace TBBTrace = MinInstr->getTrace(IfConv.getTPred());
1197 MachineTraceMetrics::Trace FBBTrace = MinInstr->getTrace(IfConv.getFPred());
1198 LLVM_DEBUG(dbgs() << "TBB: " << TBBTrace << "FBB: " << FBBTrace);
1199 unsigned MinCrit = std::min(TBBTrace.getCriticalPath(),
1200 FBBTrace.getCriticalPath());
1201
1202 // Set a somewhat arbitrary limit on the critical path extension we accept.
1203 // Use the full misprediction penalty for data-dependent branches and half
1204 // for others. A branch with a cold edge below ColdEdgeThreshold gets no
1205 // extending the critical path: it is unlikely to mispredict often enough
1206 // to recover the extra latency from if-conversion.
1207 bool DataDependent = false;
1209 DataDependent = isConditionDataDependent();
1210
1211 const unsigned MispredictPenalty = STI->getMispredictionPenalty();
1212 unsigned CritLimit =
1213 DataDependent ? MispredictPenalty : MispredictPenalty / 2;
1214 const BranchProbability ColdProb =
1215 std::min(MBPI.getEdgeProbability(IfConv.Head, IfConv.TBB),
1216 MBPI.getEdgeProbability(IfConv.Head, IfConv.FBB));
1217 const unsigned ColdEdgePercent = std::min(ColdEdgeThreshold.getValue(), 50U);
1218 const bool StronglyBiased =
1219 ColdProb < BranchProbability(ColdEdgePercent, 100);
1220 if (StronglyBiased) {
1221 CritLimit = 0;
1222 ++NumStronglyBiased;
1223 }
1224
1225 MachineBasicBlock &MBB = *IfConv.Head;
1226 MachineOptimizationRemarkEmitter MORE(*MBB.getParent(), nullptr);
1227
1228 LLVM_DEBUG(dbgs() << "Cold edge probability: " << ColdProb
1229 << ", critical-path budget: " << CritLimit << " cycles\n");
1230 if (StronglyBiased) {
1231 MORE.emit([&]() {
1232 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE,
1233 "StronglyBiasedBranch",
1234 MBB.back().getDebugLoc(), &MBB)
1235 << "branch has a cold edge below "
1236 << ore::NV("ColdEdgeThreshold", ColdEdgePercent)
1237 << "%, using a critical-path "
1238 "extension budget of "
1239 << ore::NV("CritLimit", CritLimit) << " cycles";
1240 });
1241 }
1242
1243 // Emit analysis remark about data-dependent condition.
1244 if (DataDependent) {
1245 MORE.emit([&]() {
1246 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE,
1247 "DataDependentCondition",
1248 MBB.back().getDebugLoc(), &MBB)
1249 << "branch condition is data-dependent (from memory load), "
1250 << "using higher CritLimit of " << ore::NV("CritLimit", CritLimit)
1251 << " cycles";
1252 });
1253 }
1254
1255 // If-conversion only makes sense when there is unexploited ILP. Compute the
1256 // maximum-ILP resource length of the trace after if-conversion. Compare it
1257 // to the shortest critical path.
1259 if (IfConv.TBB != IfConv.Tail)
1260 ExtraBlocks.push_back(IfConv.TBB);
1261 unsigned ResLength = FBBTrace.getResourceLength(ExtraBlocks);
1262 LLVM_DEBUG(dbgs() << "Resource length " << ResLength
1263 << ", minimal critical path " << MinCrit << '\n');
1264 if (ResLength > MinCrit + CritLimit) {
1265 LLVM_DEBUG(dbgs() << "Not enough available ILP.\n");
1266 MORE.emit([&]() {
1267 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "IfConversion",
1268 MBB.findDebugLoc(MBB.back()), &MBB);
1269 R << "did not if-convert branch: the resulting critical path ("
1270 << Cycles{"ResLength", ResLength}
1271 << ") would extend the shorter leg's critical path ("
1272 << Cycles{"MinCrit", MinCrit} << ") by more than the threshold of "
1273 << Cycles{"CritLimit", CritLimit}
1274 << ", which cannot be hidden by available ILP.";
1275 return R;
1276 });
1277 return false;
1278 }
1279
1280 // Assume that the depth of the first head terminator will also be the depth
1281 // of the select instruction inserted, as determined by the flag dependency.
1282 // TBB / FBB data dependencies may delay the select even more.
1283 MachineTraceMetrics::Trace HeadTrace = MinInstr->getTrace(IfConv.Head);
1284 unsigned BranchDepth =
1285 HeadTrace.getInstrCycles(*IfConv.Head->getFirstTerminator()).Depth;
1286 LLVM_DEBUG(dbgs() << "Branch depth: " << BranchDepth << '\n');
1287
1288 // Look at all the tail phis, and compute the critical path extension caused
1289 // by inserting select instructions.
1290 MachineTraceMetrics::Trace TailTrace = MinInstr->getTrace(IfConv.Tail);
1291 struct CriticalPathInfo {
1292 unsigned Extra; // Count of extra cycles that the component adds.
1293 unsigned Depth; // Absolute depth of the component in cycles.
1294 };
1295 CriticalPathInfo Cond{};
1296 CriticalPathInfo TBlock{};
1297 CriticalPathInfo FBlock{};
1298 bool ShouldConvert = true;
1299 for (SSAIfConv::PHIInfo &PI : IfConv.PHIs) {
1300 unsigned Slack = TailTrace.getInstrSlack(*PI.PHI);
1301 unsigned MaxDepth = Slack + TailTrace.getInstrCycles(*PI.PHI).Depth;
1302 LLVM_DEBUG(dbgs() << "Slack " << Slack << ":\t" << *PI.PHI);
1303
1304 // The condition is pulled into the critical path.
1305 unsigned CondDepth = adjCycles(BranchDepth, PI.Select.CondCycles);
1306 if (CondDepth > MaxDepth) {
1307 unsigned Extra = CondDepth - MaxDepth;
1308 LLVM_DEBUG(dbgs() << "Condition adds " << Extra << " cycles.\n");
1309 if (Extra > Cond.Extra)
1310 Cond = {Extra, CondDepth};
1311 if (Extra > CritLimit) {
1312 LLVM_DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
1313 ShouldConvert = false;
1314 }
1315 }
1316
1317 // The TBB value is pulled into the critical path.
1318 unsigned TDepth =
1319 adjCycles(TBBTrace.getPHIDepth(*PI.PHI), PI.Select.TrueCycles);
1320 if (TDepth > MaxDepth) {
1321 unsigned Extra = TDepth - MaxDepth;
1322 LLVM_DEBUG(dbgs() << "TBB data adds " << Extra << " cycles.\n");
1323 if (Extra > TBlock.Extra)
1324 TBlock = {Extra, TDepth};
1325 if (Extra > CritLimit) {
1326 LLVM_DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
1327 ShouldConvert = false;
1328 }
1329 }
1330
1331 // The FBB value is pulled into the critical path.
1332 unsigned FDepth =
1333 adjCycles(FBBTrace.getPHIDepth(*PI.PHI), PI.Select.FalseCycles);
1334 if (FDepth > MaxDepth) {
1335 unsigned Extra = FDepth - MaxDepth;
1336 LLVM_DEBUG(dbgs() << "FBB data adds " << Extra << " cycles.\n");
1337 if (Extra > FBlock.Extra)
1338 FBlock = {Extra, FDepth};
1339 if (Extra > CritLimit) {
1340 LLVM_DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
1341 ShouldConvert = false;
1342 }
1343 }
1344 }
1345
1346 // Organize by "short" and "long" legs, since the diagnostics get confusing
1347 // when referring to the "true" and "false" sides of the branch, given that
1348 // those don't always correlate with what the user wrote in source-terms.
1349 const CriticalPathInfo Short = TBlock.Extra > FBlock.Extra ? FBlock : TBlock;
1350 const CriticalPathInfo Long = TBlock.Extra > FBlock.Extra ? TBlock : FBlock;
1351
1352 if (ShouldConvert) {
1353 MORE.emit([&]() {
1354 MachineOptimizationRemark R(DEBUG_TYPE, "IfConversion",
1355 MBB.back().getDebugLoc(), &MBB);
1356 R << "performing if-conversion on branch: the condition adds "
1357 << Cycles{"CondCycles", Cond.Extra} << " to the critical path";
1358 if (Short.Extra > 0)
1359 R << ", and the short leg adds another "
1360 << Cycles{"ShortCycles", Short.Extra};
1361 if (Long.Extra > 0)
1362 R << ", and the long leg adds another "
1363 << Cycles{"LongCycles", Long.Extra};
1364 R << ", each staying under the threshold of "
1365 << Cycles{"CritLimit", CritLimit} << ".";
1366 return R;
1367 });
1368 } else {
1369 MORE.emit([&]() {
1370 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "IfConversion",
1371 MBB.back().getDebugLoc(), &MBB);
1372 R << "did not if-convert branch: the condition would add "
1373 << Cycles{"CondCycles", Cond.Extra} << " to the critical path";
1374 if (Cond.Extra > CritLimit)
1375 R << " exceeding the limit of " << Cycles{"CritLimit", CritLimit};
1376 if (Short.Extra > 0) {
1377 R << ", and the short leg would add another "
1378 << Cycles{"ShortCycles", Short.Extra};
1379 if (Short.Extra > CritLimit)
1380 R << " exceeding the limit of " << Cycles{"CritLimit", CritLimit};
1381 }
1382 if (Long.Extra > 0) {
1383 R << ", and the long leg would add another "
1384 << Cycles{"LongCycles", Long.Extra};
1385 if (Long.Extra > CritLimit)
1386 R << " exceeding the limit of " << Cycles{"CritLimit", CritLimit};
1387 }
1388 R << ".";
1389 return R;
1390 });
1391 }
1392
1393 return ShouldConvert;
1394}
1395
1396/// Attempt repeated if-conversion on MBB, return true if successful.
1397///
1398bool EarlyIfConverter::tryConvertIf(MachineBasicBlock *MBB) {
1399 bool Changed = false;
1400 while (IfConv.canConvertIf(MBB) && shouldConvertIf()) {
1401 // If-convert MBB and update analyses.
1402 invalidateTraces();
1403 SmallVector<MachineBasicBlock *, 4> RemoveBlocks;
1404 IfConv.convertIf(RemoveBlocks);
1405 Changed = true;
1406 updateDomTree(DomTree, IfConv, RemoveBlocks);
1407 updateLoops(Loops, RemoveBlocks);
1408 // Head absorbs the instructions of the removed blocks, including any calls,
1409 // so a Head cached as call-free may no longer be.
1410 NoCallBlocksCache.erase(IfConv.Head);
1411 for (MachineBasicBlock *MBB : RemoveBlocks) {
1412 NoCallBlocksCache.erase(MBB);
1414 }
1415 }
1416 return Changed;
1417}
1418
1419bool EarlyIfConverter::run(MachineFunction &MF) {
1420 LLVM_DEBUG(dbgs() << "********** EARLY IF-CONVERSION **********\n"
1421 << "********** Function: " << MF.getName() << '\n');
1422
1423 STI = &MF.getSubtarget();
1424 // Only run if conversion if the target wants it.
1425 if (!STI->enableEarlyIfConversion())
1426 return false;
1427
1428 TII = STI->getInstrInfo();
1429 TRI = STI->getRegisterInfo();
1430 MRI = &MF.getRegInfo();
1431 MinInstr = nullptr;
1432
1433 bool Changed = false;
1434 IfConv.init(MF);
1435
1436 // Visit blocks in dominator tree post-order. The post-order enables nested
1437 // if-conversion in a single pass. The tryConvertIf() function may erase
1438 // blocks, but only blocks dominated by the head block. This makes it safe to
1439 // update the dominator tree while the post-order iterator is still active.
1440 for (auto *DomNode : post_order(DomTree))
1441 if (tryConvertIf(DomNode->getBlock()))
1442 Changed = true;
1443
1444 return Changed;
1445}
1446
1447PreservedAnalyses
1455
1456 EarlyIfConverter Impl(MDT, LI, MTM, MBPI);
1457 bool Changed = Impl.run(MF);
1458 if (!Changed)
1459 return PreservedAnalyses::all();
1460
1462 PA.preserve<MachineDominatorTreeAnalysis>();
1463 PA.preserve<MachineLoopAnalysis>();
1464 PA.preserve<MachineTraceMetricsAnalysis>();
1465 return PA;
1466}
1467
1468bool EarlyIfConverterLegacy::runOnMachineFunction(MachineFunction &MF) {
1469 if (skipFunction(MF.getFunction()))
1470 return false;
1471
1473 getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
1474 MachineLoopInfo &LI = getAnalysis<MachineLoopInfoWrapperPass>().getLI();
1475 MachineTraceMetrics &MTM =
1476 getAnalysis<MachineTraceMetricsWrapperPass>().getMTM();
1478 getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI();
1479
1480 return EarlyIfConverter(MDT, LI, MTM, MBPI).run(MF);
1481}
1482
1483//===----------------------------------------------------------------------===//
1484// EarlyIfPredicator Pass
1485//===----------------------------------------------------------------------===//
1486
1487namespace {
1488class EarlyIfPredicator : public MachineFunctionPass {
1489 const TargetInstrInfo *TII = nullptr;
1490 const TargetRegisterInfo *TRI = nullptr;
1491 TargetSchedModel SchedModel;
1492 MachineRegisterInfo *MRI = nullptr;
1493 MachineDominatorTree *DomTree = nullptr;
1494 MachineBranchProbabilityInfo *MBPI = nullptr;
1495 MachineLoopInfo *Loops = nullptr;
1496 SSAIfConv IfConv;
1497
1498public:
1499 static char ID;
1500 EarlyIfPredicator() : MachineFunctionPass(ID) {}
1501 void getAnalysisUsage(AnalysisUsage &AU) const override;
1502 bool runOnMachineFunction(MachineFunction &MF) override;
1503 StringRef getPassName() const override { return "Early If-predicator"; }
1504
1505protected:
1506 bool tryConvertIf(MachineBasicBlock *);
1507 bool shouldConvertIf();
1508};
1509} // end anonymous namespace
1510
1511#undef DEBUG_TYPE
1512#define DEBUG_TYPE "early-if-predicator"
1513
1514char EarlyIfPredicator::ID = 0;
1515char &llvm::EarlyIfPredicatorID = EarlyIfPredicator::ID;
1516
1517INITIALIZE_PASS_BEGIN(EarlyIfPredicator, DEBUG_TYPE, "Early If Predicator",
1518 false, false)
1521INITIALIZE_PASS_END(EarlyIfPredicator, DEBUG_TYPE, "Early If Predicator", false,
1522 false)
1523
1524void EarlyIfPredicator::getAnalysisUsage(AnalysisUsage &AU) const {
1526 AU.addRequired<MachineDominatorTreeWrapperPass>();
1527 AU.addPreserved<MachineDominatorTreeWrapperPass>();
1528 AU.addRequired<MachineLoopInfoWrapperPass>();
1529 AU.addPreserved<MachineLoopInfoWrapperPass>();
1531}
1532
1533/// Apply the target heuristic to decide if the transformation is profitable.
1534bool EarlyIfPredicator::shouldConvertIf() {
1535 auto TrueProbability = MBPI->getEdgeProbability(IfConv.Head, IfConv.TBB);
1536 if (IfConv.isTriangle()) {
1537 MachineBasicBlock &IfBlock =
1538 (IfConv.TBB == IfConv.Tail) ? *IfConv.FBB : *IfConv.TBB;
1539
1540 unsigned ExtraPredCost = 0;
1541 unsigned Cycles = 0;
1542 for (MachineInstr &I : IfBlock) {
1543 unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
1544 if (NumCycles > 1)
1545 Cycles += NumCycles - 1;
1546 ExtraPredCost += TII->getPredicationCost(I);
1547 }
1548
1549 return TII->isProfitableToIfCvt(IfBlock, Cycles, ExtraPredCost,
1550 TrueProbability);
1551 }
1552 unsigned TExtra = 0;
1553 unsigned FExtra = 0;
1554 unsigned TCycle = 0;
1555 unsigned FCycle = 0;
1556 for (MachineInstr &I : *IfConv.TBB) {
1557 unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
1558 if (NumCycles > 1)
1559 TCycle += NumCycles - 1;
1560 TExtra += TII->getPredicationCost(I);
1561 }
1562 for (MachineInstr &I : *IfConv.FBB) {
1563 unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
1564 if (NumCycles > 1)
1565 FCycle += NumCycles - 1;
1566 FExtra += TII->getPredicationCost(I);
1567 }
1568 return TII->isProfitableToIfCvt(*IfConv.TBB, TCycle, TExtra, *IfConv.FBB,
1569 FCycle, FExtra, TrueProbability);
1570}
1571
1572/// Attempt repeated if-conversion on MBB, return true if successful.
1573///
1574bool EarlyIfPredicator::tryConvertIf(MachineBasicBlock *MBB) {
1575 bool Changed = false;
1576 while (IfConv.canConvertIf(MBB, /*Predicate*/ true) && shouldConvertIf()) {
1577 // If-convert MBB and update analyses.
1578 SmallVector<MachineBasicBlock *, 4> RemoveBlocks;
1579 IfConv.convertIf(RemoveBlocks, /*Predicate*/ true);
1580 Changed = true;
1581 updateDomTree(DomTree, IfConv, RemoveBlocks);
1582 updateLoops(Loops, RemoveBlocks);
1583 for (MachineBasicBlock *MBB : RemoveBlocks)
1585 }
1586 return Changed;
1587}
1588
1589bool EarlyIfPredicator::runOnMachineFunction(MachineFunction &MF) {
1590 LLVM_DEBUG(dbgs() << "********** EARLY IF-PREDICATOR **********\n"
1591 << "********** Function: " << MF.getName() << '\n');
1592 if (skipFunction(MF.getFunction()))
1593 return false;
1594
1595 const TargetSubtargetInfo &STI = MF.getSubtarget();
1596 TII = STI.getInstrInfo();
1597 TRI = STI.getRegisterInfo();
1598 MRI = &MF.getRegInfo();
1599 SchedModel.init(&STI);
1600 DomTree = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
1601 Loops = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
1602 MBPI = &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI();
1603
1604 bool Changed = false;
1605 IfConv.init(MF);
1606
1607 // Visit blocks in dominator tree post-order. The post-order enables nested
1608 // if-conversion in a single pass. The tryConvertIf() function may erase
1609 // blocks, but only blocks dominated by the head block. This makes it safe to
1610 // update the dominator tree while the post-order iterator is still active.
1611 for (auto *DomNode : post_order(DomTree))
1612 if (tryConvertIf(DomNode->getBlock()))
1613 Changed = true;
1614
1615 return Changed;
1616}
MachineInstrBuilder MachineInstrBuilder & DefMI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
This file implements the BitVector class.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static unsigned InstrCount
This file defines the DenseMap class.
static cl::opt< unsigned > MaxRegionInstrs("early-ifcvt-max-region-instrs", cl::Hidden, cl::init(64), cl::desc("Limit the number of blocks and instructions examined when " "searching for calls between a load and the condition it feeds"))
static cl::opt< unsigned > MaxNumSteps("early-ifcvt-max-steps", cl::Hidden, cl::init(16), cl::desc("Limit the number of steps taken when searching for a " "recently loaded value"))
static cl::opt< unsigned > ColdEdgeThreshold("early-ifcvt-cold-edge-threshold", cl::Hidden, cl::init(1), cl::desc("Cold edge probability threshold in percent for using no " "critical-path extension budget (0 disables the threshold)"))
static bool hasSameValue(const MachineRegisterInfo &MRI, const TargetInstrInfo *TII, Register TReg, Register FReg)
static unsigned adjCycles(unsigned Cyc, int Delta)
static cl::opt< bool > Stress("stress-early-ifcvt", cl::Hidden, cl::desc("Turn all knobs to 11"))
static cl::opt< unsigned > BlockInstrLimit("early-ifcvt-limit", cl::init(30), cl::Hidden, cl::desc("Maximum number of instructions per speculated block."))
static bool isConstantPoolLoad(const MachineInstr *MI)
static cl::opt< bool > EnableDataDependentBranchAnalysis("enable-early-ifcvt-data-dependent", cl::Hidden, cl::init(false), cl::desc("Enable hard-to-predict branch analysis for if-conversion"))
#define DEBUG_TYPE
static Register UseReg(const MachineOperand &MO)
const HexagonInstrInfo * TII
Hexagon Hardware Loops
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
===- MachineOptimizationRemarkEmitter.h - Opt Diagnostics -*- C++ -*-—===//
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#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
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
SmallVector< MachineOperand, 4 > Cond
MachineRegisterInfo & MRI
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
This file defines the SmallPtrSet class.
This file defines the SparseSet class derived from the version described in Briggs,...
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
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:482
BitVector & reset()
Reset all bits in the bitvector.
Definition BitVector.h:409
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:366
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
void eraseNode(NodeT *BB)
eraseNode - Removes a node from the dominator tree.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
unsigned removeBranch(MachineBasicBlock &MBB, int *BytesRemoved=nullptr) const override
Remove the branching code at the end of the specific MBB.
bool isPredicated(const MachineInstr &MI) const override
Returns true if the instruction is already predicated.
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 reverseBranchCondition(SmallVectorImpl< MachineOperand > &Cond) const override
Reverses the branch condition of the specified condition list, returning false on success and true if...
unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB, ArrayRef< MachineOperand > Cond, const DebugLoc &DL, int *BytesAdded=nullptr) const override
Insert branch code into the end of the specified MachineBasicBlock.
bool isProfitableToIfCvt(MachineBasicBlock &MBB, unsigned NumCycles, unsigned ExtraPredCycles, BranchProbability Probability) const override
Return true if it's profitable to predicate instructions with accumulated instruction latency of "Num...
bool PredicateInstruction(MachineInstr &MI, ArrayRef< MachineOperand > Cond) const override
Convert the instruction into a predicated instruction.
bool isPredicable(const MachineInstr &MI) const override
Return true if the specified instruction can be predicated.
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
LLVM_ABI void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
LLVM_ABI DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
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.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< pred_iterator > predecessors()
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI void moveAfter(MachineBasicBlock *NewBefore)
LLVM_ABI BranchProbability getEdgeProbability(const MachineBasicBlock *Src, const MachineBasicBlock *Dst) const
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
bool dominates(const MachineInstr *A, const MachineInstr *B) const
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.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineBasicBlock & back() const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
bool isTerminator(QueryType Type=AnyInBundle) const
Returns true if this instruction part of the terminator for a basic block.
bool mayLoadOrStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read or modify memory.
const MachineBasicBlock * getParent() const
LLVM_ABI bool isDereferenceableInvariantLoad() const
Return true if this load instruction never traps and points to a memory location whose value doesn't ...
LLVM_ABI bool hasUnmodeledSideEffects() const
Return true if this instruction has side effects that are not modeled by mayLoad / mayStore,...
mop_range uses()
Returns all operands which may be register uses.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
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.
Analysis pass that exposes the MachineLoopInfo for a machine function.
A description of a memory reference used in the backend.
MachineOperand class - Representation of each machine instruction operand.
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
LLVM_ABI unsigned getResourceLength(ArrayRef< const MachineBasicBlock * > Extrablocks={}, ArrayRef< const MCSchedClassDesc * > ExtraInstrs={}, ArrayRef< const MCSchedClassDesc * > RemoveInstrs={}) const
Return the resource length of the trace.
InstrCycles getInstrCycles(const MachineInstr &MI) const
Return the depth and height of MI.
LLVM_ABI unsigned getInstrSlack(const MachineInstr &MI) const
Return the slack of MI.
unsigned getCriticalPath() const
Return the length of the (data dependency) critical path through the trace.
LLVM_ABI unsigned getPHIDepth(const MachineInstr &PHI) const
Return the Depth of a PHI instruction in a trace center block successor.
LLVM_ABI void verifyAnalysis() const
LLVM_ABI void invalidate(const MachineBasicBlock *MBB)
Invalidate cached information about MBB.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Wrapper class representing virtual and physical registers.
Definition Register.h:20
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:107
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
size_type size() const
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void push_back(const T &Elt)
iterator erase(iterator I)
erase - Erases an existing element identified by a valid iterator.
Definition SparseSet.h:288
void clear()
clear - Clears the set.
Definition SparseSet.h:191
std::pair< iterator, bool > insert(const ValueT &Val)
insert - Attempts to insert a new element.
Definition SparseSet.h:254
bool empty() const
empty - Returns true if the set is empty.
Definition SparseSet.h:180
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
Provide an instruction scheduling machine model to CodeGen passes.
LLVM_ABI void init(const TargetSubtargetInfo *TSInfo, bool EnableSModel=true, bool EnableSItins=true)
Initialize the machine model for instruction scheduling.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
virtual bool enableEarlyIfConversion() const
Enable the use of the early if conversion pass.
self_iterator getIterator()
Definition ilist_node.h:123
@ 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)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
constexpr double phi
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI Printable printRegUnit(MCRegUnit Unit, const TargetRegisterInfo *TRI)
Create Printable object to print register units on a raw_ostream.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI char & EarlyIfConverterLegacyID
EarlyIfConverter - This pass performs if-conversion on SSA form by inserting cmov instructions.
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
auto post_order(const T &G)
Post-order traversal of a graph.
auto instructionsWithoutDebug(IterT It, IterT End, bool SkipPseudoOp=true)
Construct a range iterator which begins at It and moves forwards until End is reached,...
LLVM_ABI char & EarlyIfPredicatorID
EarlyIfPredicator - This pass performs if-conversion on SSA form by predicating if/else block and ins...
DomTreeNodeBase< MachineBasicBlock > MachineDomTreeNode
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
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.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
#define MORE()
Definition regcomp.c:247
unsigned Depth
Earliest issue cycle as determined by data dependencies and instruction latencies from the beginning ...