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