blob: f7b69406fd892f5ad17f3b1698e4b072041f3ddc [file] [log] [blame]
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +00001//===--- HexagonEarlyIfConv.cpp -------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This implements a Hexagon-specific if-conversion pass that runs on the
11// SSA form.
12// In SSA it is not straightforward to represent instructions that condi-
13// tionally define registers, since a conditionally-defined register may
14// only be used under the same condition on which the definition was based.
15// To avoid complications of this nature, this patch will only generate
16// predicated stores, and speculate other instructions from the "if-conver-
17// ted" block.
18// The code will recognize CFG patterns where a block with a conditional
19// branch "splits" into a "true block" and a "false block". Either of these
20// could be omitted (in case of a triangle, for example).
21// If after conversion of the side block(s) the CFG allows it, the resul-
22// ting blocks may be merged. If the "join" block contained PHI nodes, they
23// will be replaced with MUX (or MUX-like) instructions to maintain the
24// semantics of the PHI.
25//
26// Example:
27//
28// %vreg40<def> = L2_loadrub_io %vreg39<kill>, 1
29// %vreg41<def> = S2_tstbit_i %vreg40<kill>, 0
30// J2_jumpt %vreg41<kill>, <BB#5>, %PC<imp-def,dead>
31// J2_jump <BB#4>, %PC<imp-def,dead>
32// Successors according to CFG: BB#4(62) BB#5(62)
33//
34// BB#4: derived from LLVM BB %if.then
35// Predecessors according to CFG: BB#3
36// %vreg11<def> = A2_addp %vreg6, %vreg10
37// S2_storerd_io %vreg32, 16, %vreg11
38// Successors according to CFG: BB#5
39//
40// BB#5: derived from LLVM BB %if.end
41// Predecessors according to CFG: BB#3 BB#4
42// %vreg12<def> = PHI %vreg6, <BB#3>, %vreg11, <BB#4>
43// %vreg13<def> = A2_addp %vreg7, %vreg12
44// %vreg42<def> = C2_cmpeqi %vreg9, 10
45// J2_jumpf %vreg42<kill>, <BB#3>, %PC<imp-def,dead>
46// J2_jump <BB#6>, %PC<imp-def,dead>
47// Successors according to CFG: BB#6(4) BB#3(124)
48//
49// would become:
50//
51// %vreg40<def> = L2_loadrub_io %vreg39<kill>, 1
52// %vreg41<def> = S2_tstbit_i %vreg40<kill>, 0
53// spec-> %vreg11<def> = A2_addp %vreg6, %vreg10
54// pred-> S2_pstorerdf_io %vreg41, %vreg32, 16, %vreg11
55// %vreg46<def> = MUX64_rr %vreg41, %vreg6, %vreg11
56// %vreg13<def> = A2_addp %vreg7, %vreg46
57// %vreg42<def> = C2_cmpeqi %vreg9, 10
58// J2_jumpf %vreg42<kill>, <BB#3>, %PC<imp-def,dead>
59// J2_jump <BB#6>, %PC<imp-def,dead>
60// Successors according to CFG: BB#6 BB#3
61
62#define DEBUG_TYPE "hexagon-eif"
63
64#include "llvm/ADT/DenseSet.h"
65#include "llvm/ADT/SetVector.h"
66#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
67#include "llvm/CodeGen/MachineDominators.h"
68#include "llvm/CodeGen/MachineFunctionPass.h"
69#include "llvm/CodeGen/MachineInstrBuilder.h"
70#include "llvm/CodeGen/MachineLoopInfo.h"
71#include "llvm/CodeGen/MachineRegisterInfo.h"
72#include "llvm/CodeGen/Passes.h"
73#include "llvm/Support/CommandLine.h"
74#include "llvm/Support/Debug.h"
75#include "llvm/Support/raw_ostream.h"
76#include "llvm/Target/TargetInstrInfo.h"
77#include "llvm/Target/TargetMachine.h"
78#include "HexagonTargetMachine.h"
79
80#include <functional>
81#include <set>
82#include <vector>
83
84using namespace llvm;
85
86static cl::opt<bool> EnableHexagonBP("enable-hexagon-br-prob", cl::Hidden,
87 cl::init(false), cl::ZeroOrMore, cl::desc("Enable branch probability info"));
88
89namespace llvm {
90 FunctionPass *createHexagonEarlyIfConversion();
91 void initializeHexagonEarlyIfConversionPass(PassRegistry& Registry);
92}
93
94namespace {
95 cl::opt<unsigned> SizeLimit("eif-limit", cl::init(6), cl::Hidden,
96 cl::ZeroOrMore, cl::desc("Size limit in Hexagon early if-conversion"));
97
98 struct PrintMB {
99 PrintMB(const MachineBasicBlock *B) : MB(B) {}
100 const MachineBasicBlock *MB;
101 };
102 raw_ostream &operator<< (raw_ostream &OS, const PrintMB &P) {
103 if (!P.MB)
104 return OS << "<none>";
105 return OS << '#' << P.MB->getNumber();
106 }
107
108 struct FlowPattern {
109 FlowPattern() : SplitB(0), TrueB(0), FalseB(0), JoinB(0), PredR(0) {}
110 FlowPattern(MachineBasicBlock *B, unsigned PR, MachineBasicBlock *TB,
111 MachineBasicBlock *FB, MachineBasicBlock *JB)
112 : SplitB(B), TrueB(TB), FalseB(FB), JoinB(JB), PredR(PR) {}
113
114 MachineBasicBlock *SplitB;
115 MachineBasicBlock *TrueB, *FalseB, *JoinB;
116 unsigned PredR;
117 };
118 struct PrintFP {
119 PrintFP(const FlowPattern &P, const TargetRegisterInfo &T)
120 : FP(P), TRI(T) {}
121 const FlowPattern &FP;
122 const TargetRegisterInfo &TRI;
123 friend raw_ostream &operator<< (raw_ostream &OS, const PrintFP &P);
124 };
125 raw_ostream &operator<<(raw_ostream &OS,
126 const PrintFP &P) LLVM_ATTRIBUTE_UNUSED;
127 raw_ostream &operator<<(raw_ostream &OS, const PrintFP &P) {
128 OS << "{ SplitB:" << PrintMB(P.FP.SplitB)
129 << ", PredR:" << PrintReg(P.FP.PredR, &P.TRI)
130 << ", TrueB:" << PrintMB(P.FP.TrueB) << ", FalseB:"
131 << PrintMB(P.FP.FalseB)
132 << ", JoinB:" << PrintMB(P.FP.JoinB) << " }";
133 return OS;
134 }
135
136 class HexagonEarlyIfConversion : public MachineFunctionPass {
137 public:
138 static char ID;
139 HexagonEarlyIfConversion() : MachineFunctionPass(ID),
140 TII(0), TRI(0), MFN(0), MRI(0), MDT(0), MLI(0) {
141 initializeHexagonEarlyIfConversionPass(*PassRegistry::getPassRegistry());
142 }
143 const char *getPassName() const override {
144 return "Hexagon early if conversion";
145 }
146 void getAnalysisUsage(AnalysisUsage &AU) const override {
147 AU.addRequired<MachineBranchProbabilityInfo>();
148 AU.addRequired<MachineDominatorTree>();
149 AU.addPreserved<MachineDominatorTree>();
150 AU.addRequired<MachineLoopInfo>();
151 MachineFunctionPass::getAnalysisUsage(AU);
152 }
153 bool runOnMachineFunction(MachineFunction &MF) override;
154
155 private:
156 typedef DenseSet<MachineBasicBlock*> BlockSetType;
157
158 bool isPreheader(const MachineBasicBlock *B) const;
159 bool matchFlowPattern(MachineBasicBlock *B, MachineLoop *L,
160 FlowPattern &FP);
161 bool visitBlock(MachineBasicBlock *B, MachineLoop *L);
162 bool visitLoop(MachineLoop *L);
163
164 bool hasEHLabel(const MachineBasicBlock *B) const;
165 bool hasUncondBranch(const MachineBasicBlock *B) const;
166 bool isValidCandidate(const MachineBasicBlock *B) const;
167 bool usesUndefVReg(const MachineInstr *MI) const;
168 bool isValid(const FlowPattern &FP) const;
169 unsigned countPredicateDefs(const MachineBasicBlock *B) const;
170 unsigned computePhiCost(MachineBasicBlock *B) const;
171 bool isProfitable(const FlowPattern &FP) const;
172 bool isPredicableStore(const MachineInstr *MI) const;
173 bool isSafeToSpeculate(const MachineInstr *MI) const;
174
175 unsigned getCondStoreOpcode(unsigned Opc, bool IfTrue) const;
176 void predicateInstr(MachineBasicBlock *ToB, MachineBasicBlock::iterator At,
177 MachineInstr *MI, unsigned PredR, bool IfTrue);
178 void predicateBlockNB(MachineBasicBlock *ToB,
179 MachineBasicBlock::iterator At, MachineBasicBlock *FromB,
180 unsigned PredR, bool IfTrue);
181
182 void updatePhiNodes(MachineBasicBlock *WhereB, const FlowPattern &FP);
183 void convert(const FlowPattern &FP);
184
185 void removeBlock(MachineBasicBlock *B);
186 void eliminatePhis(MachineBasicBlock *B);
187 void replacePhiEdges(MachineBasicBlock *OldB, MachineBasicBlock *NewB);
188 void mergeBlocks(MachineBasicBlock *PredB, MachineBasicBlock *SuccB);
189 void simplifyFlowGraph(const FlowPattern &FP);
190
191 const TargetInstrInfo *TII;
192 const TargetRegisterInfo *TRI;
193 MachineFunction *MFN;
194 MachineRegisterInfo *MRI;
195 MachineDominatorTree *MDT;
196 MachineLoopInfo *MLI;
197 BlockSetType Deleted;
198 const MachineBranchProbabilityInfo *MBPI;
199 };
200
201 char HexagonEarlyIfConversion::ID = 0;
202}
203
204INITIALIZE_PASS(HexagonEarlyIfConversion, "hexagon-eif",
205 "Hexagon early if conversion", false, false)
206
207bool HexagonEarlyIfConversion::isPreheader(const MachineBasicBlock *B) const {
208 if (B->succ_size() != 1)
209 return false;
210 MachineBasicBlock *SB = *B->succ_begin();
211 MachineLoop *L = MLI->getLoopFor(SB);
212 return L && SB == L->getHeader();
213}
214
215
216bool HexagonEarlyIfConversion::matchFlowPattern(MachineBasicBlock *B,
217 MachineLoop *L, FlowPattern &FP) {
218 DEBUG(dbgs() << "Checking flow pattern at BB#" << B->getNumber() << "\n");
219
220 // Interested only in conditional branches, no .new, no new-value, etc.
221 // Check the terminators directly, it's easier than handling all responses
222 // from AnalyzeBranch.
223 MachineBasicBlock *TB = 0, *FB = 0;
224 MachineBasicBlock::const_iterator T1I = B->getFirstTerminator();
225 if (T1I == B->end())
226 return false;
227 unsigned Opc = T1I->getOpcode();
228 if (Opc != Hexagon::J2_jumpt && Opc != Hexagon::J2_jumpf)
229 return false;
230 unsigned PredR = T1I->getOperand(0).getReg();
231
232 // Get the layout successor, or 0 if B does not have one.
233 MachineFunction::iterator NextBI = std::next(MachineFunction::iterator(B));
234 MachineBasicBlock *NextB = (NextBI != MFN->end()) ? &*NextBI : 0;
235
236 MachineBasicBlock *T1B = T1I->getOperand(1).getMBB();
237 MachineBasicBlock::const_iterator T2I = std::next(T1I);
238 // The second terminator should be an unconditional branch.
239 assert(T2I == B->end() || T2I->getOpcode() == Hexagon::J2_jump);
240 MachineBasicBlock *T2B = (T2I == B->end()) ? NextB
241 : T2I->getOperand(0).getMBB();
242 if (T1B == T2B) {
243 // XXX merge if T1B == NextB, or convert branch to unconditional.
244 // mark as diamond with both sides equal?
245 return false;
246 }
247 // Loop could be null for both.
248 if (MLI->getLoopFor(T1B) != L || MLI->getLoopFor(T2B) != L)
249 return false;
250
251 // Record the true/false blocks in such a way that "true" means "if (PredR)",
252 // and "false" means "if (!PredR)".
253 if (Opc == Hexagon::J2_jumpt)
254 TB = T1B, FB = T2B;
255 else
256 TB = T2B, FB = T1B;
257
258 if (!MDT->properlyDominates(B, TB) || !MDT->properlyDominates(B, FB))
259 return false;
260
261 // Detect triangle first. In case of a triangle, one of the blocks TB/FB
262 // can fall through into the other, in other words, it will be executed
263 // in both cases. We only want to predicate the block that is executed
264 // conditionally.
265 unsigned TNP = TB->pred_size(), FNP = FB->pred_size();
266 unsigned TNS = TB->succ_size(), FNS = FB->succ_size();
267
268 // A block is predicable if it has one predecessor (it must be B), and
269 // it has a single successor. In fact, the block has to end either with
270 // an unconditional branch (which can be predicated), or with a fall-
271 // through.
272 bool TOk = (TNP == 1) && (TNS == 1);
273 bool FOk = (FNP == 1) && (FNS == 1);
274
275 // If neither is predicable, there is nothing interesting.
276 if (!TOk && !FOk)
277 return false;
278
279 MachineBasicBlock *TSB = (TNS > 0) ? *TB->succ_begin() : 0;
280 MachineBasicBlock *FSB = (FNS > 0) ? *FB->succ_begin() : 0;
281 MachineBasicBlock *JB = 0;
282
283 if (TOk) {
284 if (FOk) {
285 if (TSB == FSB)
286 JB = TSB;
287 // Diamond: "if (P) then TB; else FB;".
288 } else {
289 // TOk && !FOk
290 if (TSB == FB) {
291 JB = FB;
292 FB = 0;
293 }
294 }
295 } else {
296 // !TOk && FOk (at least one must be true by now).
297 if (FSB == TB) {
298 JB = TB;
299 TB = 0;
300 }
301 }
302 // Don't try to predicate loop preheaders.
303 if ((TB && isPreheader(TB)) || (FB && isPreheader(FB))) {
304 DEBUG(dbgs() << "One of blocks " << PrintMB(TB) << ", " << PrintMB(FB)
305 << " is a loop preheader. Skipping.\n");
306 return false;
307 }
308
309 FP = FlowPattern(B, PredR, TB, FB, JB);
310 DEBUG(dbgs() << "Detected " << PrintFP(FP, *TRI) << "\n");
311 return true;
312}
313
314
315// KLUDGE: HexagonInstrInfo::AnalyzeBranch won't work on a block that
316// contains EH_LABEL.
317bool HexagonEarlyIfConversion::hasEHLabel(const MachineBasicBlock *B) const {
318 for (auto &I : *B)
319 if (I.isEHLabel())
320 return true;
321 return false;
322}
323
324
325// KLUDGE: HexagonInstrInfo::AnalyzeBranch may be unable to recognize
326// that a block can never fall-through.
327bool HexagonEarlyIfConversion::hasUncondBranch(const MachineBasicBlock *B)
328 const {
329 MachineBasicBlock::const_iterator I = B->getFirstTerminator(), E = B->end();
330 while (I != E) {
331 if (I->isBarrier())
332 return true;
333 ++I;
334 }
335 return false;
336}
337
338
339bool HexagonEarlyIfConversion::isValidCandidate(const MachineBasicBlock *B)
340 const {
341 if (!B)
342 return true;
343 if (B->isEHPad() || B->hasAddressTaken())
344 return false;
345 if (B->succ_size() == 0)
346 return false;
347
348 for (auto &MI : *B) {
349 if (MI.isDebugValue())
350 continue;
351 if (MI.isConditionalBranch())
352 return false;
353 unsigned Opc = MI.getOpcode();
354 bool IsJMP = (Opc == Hexagon::J2_jump);
355 if (!isPredicableStore(&MI) && !IsJMP && !isSafeToSpeculate(&MI))
356 return false;
357 // Look for predicate registers defined by this instruction. It's ok
358 // to speculate such an instruction, but the predicate register cannot
359 // be used outside of this block (or else it won't be possible to
360 // update the use of it after predication). PHI uses will be updated
361 // to use a result of a MUX, and a MUX cannot be created for predicate
362 // registers.
363 for (ConstMIOperands MO(&MI); MO.isValid(); ++MO) {
364 if (!MO->isReg() || !MO->isDef())
365 continue;
366 unsigned R = MO->getReg();
367 if (!TargetRegisterInfo::isVirtualRegister(R))
368 continue;
369 if (MRI->getRegClass(R) != &Hexagon::PredRegsRegClass)
370 continue;
371 for (auto U = MRI->use_begin(R); U != MRI->use_end(); ++U)
372 if (U->getParent()->isPHI())
373 return false;
374 }
375 }
376 return true;
377}
378
379
380bool HexagonEarlyIfConversion::usesUndefVReg(const MachineInstr *MI) const {
381 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
382 if (!MO->isReg() || !MO->isUse())
383 continue;
384 unsigned R = MO->getReg();
385 if (!TargetRegisterInfo::isVirtualRegister(R))
386 continue;
387 const MachineInstr *DefI = MRI->getVRegDef(R);
388 // "Undefined" virtual registers are actually defined via IMPLICIT_DEF.
389 assert(DefI && "Expecting a reaching def in MRI");
390 if (DefI->isImplicitDef())
391 return true;
392 }
393 return false;
394}
395
396
397bool HexagonEarlyIfConversion::isValid(const FlowPattern &FP) const {
398 if (hasEHLabel(FP.SplitB)) // KLUDGE: see function definition
399 return false;
400 if (FP.TrueB && !isValidCandidate(FP.TrueB))
401 return false;
402 if (FP.FalseB && !isValidCandidate(FP.FalseB))
403 return false;
404 // Check the PHIs in the join block. If any of them use a register
405 // that is defined as IMPLICIT_DEF, do not convert this. This can
406 // legitimately happen if one side of the split never executes, but
407 // the compiler is unable to prove it. That side may then seem to
408 // provide an "undef" value to the join block, however it will never
409 // execute at run-time. If we convert this case, the "undef" will
410 // be used in a MUX instruction, and that may seem like actually
411 // using an undefined value to other optimizations. This could lead
412 // to trouble further down the optimization stream, cause assertions
413 // to fail, etc.
414 if (FP.JoinB) {
415 const MachineBasicBlock &B = *FP.JoinB;
416 for (auto &MI : B) {
417 if (!MI.isPHI())
418 break;
419 if (usesUndefVReg(&MI))
420 return false;
421 unsigned DefR = MI.getOperand(0).getReg();
422 const TargetRegisterClass *RC = MRI->getRegClass(DefR);
423 if (RC == &Hexagon::PredRegsRegClass)
424 return false;
425 }
426 }
427 return true;
428}
429
430
431unsigned HexagonEarlyIfConversion::computePhiCost(MachineBasicBlock *B) const {
432 assert(B->pred_size() <= 2);
433 if (B->pred_size() < 2)
434 return 0;
435
436 unsigned Cost = 0;
437 MachineBasicBlock::const_iterator I, E = B->getFirstNonPHI();
438 for (I = B->begin(); I != E; ++I) {
439 const MachineOperand &RO1 = I->getOperand(1);
440 const MachineOperand &RO3 = I->getOperand(3);
441 assert(RO1.isReg() && RO3.isReg());
442 // Must have a MUX if the phi uses a subregister.
443 if (RO1.getSubReg() != 0 || RO3.getSubReg() != 0) {
444 Cost++;
445 continue;
446 }
447 MachineInstr *Def1 = MRI->getVRegDef(RO1.getReg());
448 MachineInstr *Def3 = MRI->getVRegDef(RO3.getReg());
449 if (!TII->isPredicable(Def1) || !TII->isPredicable(Def3))
450 Cost++;
451 }
452 return Cost;
453}
454
455
456unsigned HexagonEarlyIfConversion::countPredicateDefs(
457 const MachineBasicBlock *B) const {
458 unsigned PredDefs = 0;
459 for (auto &MI : *B) {
460 for (ConstMIOperands MO(&MI); MO.isValid(); ++MO) {
461 if (!MO->isReg() || !MO->isDef())
462 continue;
463 unsigned R = MO->getReg();
464 if (!TargetRegisterInfo::isVirtualRegister(R))
465 continue;
466 if (MRI->getRegClass(R) == &Hexagon::PredRegsRegClass)
467 PredDefs++;
468 }
469 }
470 return PredDefs;
471}
472
473
474bool HexagonEarlyIfConversion::isProfitable(const FlowPattern &FP) const {
475 if (FP.TrueB && FP.FalseB) {
476
477 // Do not IfCovert if the branch is one sided.
478 if (MBPI) {
479 BranchProbability Prob(9, 10);
480 if (MBPI->getEdgeProbability(FP.SplitB, FP.TrueB) > Prob)
481 return false;
482 if (MBPI->getEdgeProbability(FP.SplitB, FP.FalseB) > Prob)
483 return false;
484 }
485
486 // If both sides are predicable, convert them if they join, and the
487 // join block has no other predecessors.
488 MachineBasicBlock *TSB = *FP.TrueB->succ_begin();
489 MachineBasicBlock *FSB = *FP.FalseB->succ_begin();
490 if (TSB != FSB)
491 return false;
492 if (TSB->pred_size() != 2)
493 return false;
494 }
495
496 // Calculate the total size of the predicated blocks.
497 // Assume instruction counts without branches to be the approximation of
498 // the code size. If the predicated blocks are smaller than a packet size,
499 // approximate the spare room in the packet that could be filled with the
500 // predicated/speculated instructions.
501 unsigned TS = 0, FS = 0, Spare = 0;
502 if (FP.TrueB) {
503 TS = std::distance(FP.TrueB->begin(), FP.TrueB->getFirstTerminator());
504 if (TS < HEXAGON_PACKET_SIZE)
505 Spare += HEXAGON_PACKET_SIZE-TS;
506 }
507 if (FP.FalseB) {
508 FS = std::distance(FP.FalseB->begin(), FP.FalseB->getFirstTerminator());
509 if (FS < HEXAGON_PACKET_SIZE)
510 Spare += HEXAGON_PACKET_SIZE-TS;
511 }
512 unsigned TotalIn = TS+FS;
513 DEBUG(dbgs() << "Total number of instructions to be predicated/speculated: "
514 << TotalIn << ", spare room: " << Spare << "\n");
515 if (TotalIn >= SizeLimit+Spare)
516 return false;
517
518 // Count the number of PHI nodes that will need to be updated (converted
519 // to MUX). Those can be later converted to predicated instructions, so
520 // they aren't always adding extra cost.
521 // KLUDGE: Also, count the number of predicate register definitions in
522 // each block. The scheduler may increase the pressure of these and cause
523 // expensive spills (e.g. bitmnp01).
524 unsigned TotalPh = 0;
525 unsigned PredDefs = countPredicateDefs(FP.SplitB);
526 if (FP.JoinB) {
527 TotalPh = computePhiCost(FP.JoinB);
528 PredDefs += countPredicateDefs(FP.JoinB);
529 } else {
530 if (FP.TrueB && FP.TrueB->succ_size() > 0) {
531 MachineBasicBlock *SB = *FP.TrueB->succ_begin();
532 TotalPh += computePhiCost(SB);
533 PredDefs += countPredicateDefs(SB);
534 }
535 if (FP.FalseB && FP.FalseB->succ_size() > 0) {
536 MachineBasicBlock *SB = *FP.FalseB->succ_begin();
537 TotalPh += computePhiCost(SB);
538 PredDefs += countPredicateDefs(SB);
539 }
540 }
541 DEBUG(dbgs() << "Total number of extra muxes from converted phis: "
542 << TotalPh << "\n");
543 if (TotalIn+TotalPh >= SizeLimit+Spare)
544 return false;
545
546 DEBUG(dbgs() << "Total number of predicate registers: " << PredDefs << "\n");
547 if (PredDefs > 4)
548 return false;
549
550 return true;
551}
552
553
554bool HexagonEarlyIfConversion::visitBlock(MachineBasicBlock *B,
555 MachineLoop *L) {
556 bool Changed = false;
557
558 // Visit all dominated blocks from the same loop first, then process B.
559 MachineDomTreeNode *N = MDT->getNode(B);
560 typedef GraphTraits<MachineDomTreeNode*> GTN;
561 // We will change CFG/DT during this traversal, so take precautions to
562 // avoid problems related to invalidated iterators. In fact, processing
563 // a child C of B cannot cause another child to be removed, but it can
564 // cause a new child to be added (which was a child of C before C itself
565 // was removed. This new child C, however, would have been processed
566 // prior to processing B, so there is no need to process it again.
567 // Simply keep a list of children of B, and traverse that list.
568 typedef SmallVector<MachineDomTreeNode*,4> DTNodeVectType;
569 DTNodeVectType Cn(GTN::child_begin(N), GTN::child_end(N));
570 for (DTNodeVectType::iterator I = Cn.begin(), E = Cn.end(); I != E; ++I) {
571 MachineBasicBlock *SB = (*I)->getBlock();
572 if (!Deleted.count(SB))
573 Changed |= visitBlock(SB, L);
574 }
575 // When walking down the dominator tree, we want to traverse through
576 // blocks from nested (other) loops, because they can dominate blocks
577 // that are in L. Skip the non-L blocks only after the tree traversal.
578 if (MLI->getLoopFor(B) != L)
579 return Changed;
580
581 FlowPattern FP;
582 if (!matchFlowPattern(B, L, FP))
583 return Changed;
584
585 if (!isValid(FP)) {
586 DEBUG(dbgs() << "Conversion is not valid\n");
587 return Changed;
588 }
589 if (!isProfitable(FP)) {
590 DEBUG(dbgs() << "Conversion is not profitable\n");
591 return Changed;
592 }
593
594 convert(FP);
595 simplifyFlowGraph(FP);
596 return true;
597}
598
599
600bool HexagonEarlyIfConversion::visitLoop(MachineLoop *L) {
601 MachineBasicBlock *HB = L ? L->getHeader() : 0;
602 DEBUG((L ? dbgs() << "Visiting loop H:" << PrintMB(HB)
603 : dbgs() << "Visiting function") << "\n");
604 bool Changed = false;
605 if (L) {
606 for (MachineLoop::iterator I = L->begin(), E = L->end(); I != E; ++I)
607 Changed |= visitLoop(*I);
608 }
609
610 MachineBasicBlock *EntryB = GraphTraits<MachineFunction*>::getEntryNode(MFN);
611 Changed |= visitBlock(L ? HB : EntryB, L);
612 return Changed;
613}
614
615
616bool HexagonEarlyIfConversion::isPredicableStore(const MachineInstr *MI)
617 const {
618 // Exclude post-increment stores. Those return a value, so we cannot
619 // predicate them.
620 unsigned Opc = MI->getOpcode();
621 using namespace Hexagon;
622 switch (Opc) {
623 // Store byte:
624 case S2_storerb_io: case S4_storerb_rr:
625 case S2_storerbabs: case S4_storeirb_io: case S2_storerbgp:
626 // Store halfword:
627 case S2_storerh_io: case S4_storerh_rr:
628 case S2_storerhabs: case S4_storeirh_io: case S2_storerhgp:
629 // Store upper halfword:
630 case S2_storerf_io: case S4_storerf_rr:
631 case S2_storerfabs: case S2_storerfgp:
632 // Store word:
633 case S2_storeri_io: case S4_storeri_rr:
634 case S2_storeriabs: case S4_storeiri_io: case S2_storerigp:
635 // Store doubleword:
636 case S2_storerd_io: case S4_storerd_rr:
637 case S2_storerdabs: case S2_storerdgp:
638 return true;
639 }
640 return false;
641}
642
643
644bool HexagonEarlyIfConversion::isSafeToSpeculate(const MachineInstr *MI)
645 const {
646 if (MI->mayLoad() || MI->mayStore())
647 return false;
648 if (MI->isCall() || MI->isBarrier() || MI->isBranch())
649 return false;
650 if (MI->hasUnmodeledSideEffects())
651 return false;
652
653 return true;
654}
655
656
657unsigned HexagonEarlyIfConversion::getCondStoreOpcode(unsigned Opc,
658 bool IfTrue) const {
659 // Exclude post-increment stores.
660 using namespace Hexagon;
661 switch (Opc) {
662 case S2_storerb_io:
663 return IfTrue ? S2_pstorerbt_io : S2_pstorerbf_io;
664 case S4_storerb_rr:
665 return IfTrue ? S4_pstorerbt_rr : S4_pstorerbf_rr;
666 case S2_storerbabs:
667 case S2_storerbgp:
668 return IfTrue ? S4_pstorerbt_abs : S4_pstorerbf_abs;
669 case S4_storeirb_io:
670 return IfTrue ? S4_storeirbt_io : S4_storeirbf_io;
671 case S2_storerh_io:
672 return IfTrue ? S2_pstorerht_io : S2_pstorerhf_io;
673 case S4_storerh_rr:
674 return IfTrue ? S4_pstorerht_rr : S4_pstorerhf_rr;
675 case S2_storerhabs:
676 case S2_storerhgp:
677 return IfTrue ? S4_pstorerht_abs : S4_pstorerhf_abs;
678 case S2_storerf_io:
679 return IfTrue ? S2_pstorerft_io : S2_pstorerff_io;
680 case S4_storerf_rr:
681 return IfTrue ? S4_pstorerft_rr : S4_pstorerff_rr;
682 case S2_storerfabs:
683 case S2_storerfgp:
684 return IfTrue ? S4_pstorerft_abs : S4_pstorerff_abs;
685 case S4_storeirh_io:
686 return IfTrue ? S4_storeirht_io : S4_storeirhf_io;
687 case S2_storeri_io:
688 return IfTrue ? S2_pstorerit_io : S2_pstorerif_io;
689 case S4_storeri_rr:
690 return IfTrue ? S4_pstorerit_rr : S4_pstorerif_rr;
691 case S2_storeriabs:
692 case S2_storerigp:
693 return IfTrue ? S4_pstorerit_abs : S4_pstorerif_abs;
694 case S4_storeiri_io:
695 return IfTrue ? S4_storeirit_io : S4_storeirif_io;
696 case S2_storerd_io:
697 return IfTrue ? S2_pstorerdt_io : S2_pstorerdf_io;
698 case S4_storerd_rr:
699 return IfTrue ? S4_pstorerdt_rr : S4_pstorerdf_rr;
700 case S2_storerdabs:
701 case S2_storerdgp:
702 return IfTrue ? S4_pstorerdt_abs : S4_pstorerdf_abs;
703 }
704 llvm_unreachable("Unexpected opcode");
705 return 0;
706}
707
708
709void HexagonEarlyIfConversion::predicateInstr(MachineBasicBlock *ToB,
710 MachineBasicBlock::iterator At, MachineInstr *MI,
711 unsigned PredR, bool IfTrue) {
712 DebugLoc DL;
713 if (At != ToB->end())
714 DL = At->getDebugLoc();
715 else if (!ToB->empty())
716 DL = ToB->back().getDebugLoc();
717
718 unsigned Opc = MI->getOpcode();
719
720 if (isPredicableStore(MI)) {
721 unsigned COpc = getCondStoreOpcode(Opc, IfTrue);
722 assert(COpc);
723 MachineInstrBuilder MIB = BuildMI(*ToB, At, DL, TII->get(COpc))
724 .addReg(PredR);
725 for (MIOperands MO(MI); MO.isValid(); ++MO)
726 MIB.addOperand(*MO);
727
728 // Set memory references.
729 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
730 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
731 MIB.setMemRefs(MMOBegin, MMOEnd);
732
733 MI->eraseFromParent();
734 return;
735 }
736
737 if (Opc == Hexagon::J2_jump) {
738 MachineBasicBlock *TB = MI->getOperand(0).getMBB();
739 const MCInstrDesc &D = TII->get(IfTrue ? Hexagon::J2_jumpt
740 : Hexagon::J2_jumpf);
741 BuildMI(*ToB, At, DL, D)
742 .addReg(PredR)
743 .addMBB(TB);
744 MI->eraseFromParent();
745 return;
746 }
747
748 // Print the offending instruction unconditionally as we are about to
749 // abort.
750 dbgs() << *MI;
751 llvm_unreachable("Unexpected instruction");
752}
753
754
755// Predicate/speculate non-branch instructions from FromB into block ToB.
756// Leave the branches alone, they will be handled later. Btw, at this point
757// FromB should have at most one branch, and it should be unconditional.
758void HexagonEarlyIfConversion::predicateBlockNB(MachineBasicBlock *ToB,
759 MachineBasicBlock::iterator At, MachineBasicBlock *FromB,
760 unsigned PredR, bool IfTrue) {
761 DEBUG(dbgs() << "Predicating block " << PrintMB(FromB) << "\n");
762 MachineBasicBlock::iterator End = FromB->getFirstTerminator();
763 MachineBasicBlock::iterator I, NextI;
764
765 for (I = FromB->begin(); I != End; I = NextI) {
766 assert(!I->isPHI());
767 NextI = std::next(I);
768 if (isSafeToSpeculate(&*I))
769 ToB->splice(At, FromB, I);
770 else
771 predicateInstr(ToB, At, &*I, PredR, IfTrue);
772 }
773}
774
775
776void HexagonEarlyIfConversion::updatePhiNodes(MachineBasicBlock *WhereB,
777 const FlowPattern &FP) {
778 // Visit all PHI nodes in the WhereB block and generate MUX instructions
779 // in the split block. Update the PHI nodes with the values of the MUX.
780 auto NonPHI = WhereB->getFirstNonPHI();
781 for (auto I = WhereB->begin(); I != NonPHI; ++I) {
782 MachineInstr *PN = &*I;
783 // Registers and subregisters corresponding to TrueB, FalseB and SplitB.
784 unsigned TR = 0, TSR = 0, FR = 0, FSR = 0, SR = 0, SSR = 0;
785 for (int i = PN->getNumOperands()-2; i > 0; i -= 2) {
786 const MachineOperand &RO = PN->getOperand(i), &BO = PN->getOperand(i+1);
787 if (BO.getMBB() == FP.SplitB)
788 SR = RO.getReg(), SSR = RO.getSubReg();
789 else if (BO.getMBB() == FP.TrueB)
790 TR = RO.getReg(), TSR = RO.getSubReg();
791 else if (BO.getMBB() == FP.FalseB)
792 FR = RO.getReg(), FSR = RO.getSubReg();
793 else
794 continue;
795 PN->RemoveOperand(i+1);
796 PN->RemoveOperand(i);
797 }
798 if (TR == 0)
799 TR = SR, TSR = SSR;
800 else if (FR == 0)
801 FR = SR, FSR = SSR;
802 assert(TR && FR);
803
804 using namespace Hexagon;
805 unsigned DR = PN->getOperand(0).getReg();
806 const TargetRegisterClass *RC = MRI->getRegClass(DR);
807 const MCInstrDesc &D = RC == &IntRegsRegClass ? TII->get(C2_mux)
808 : TII->get(MUX64_rr);
809
810 MachineBasicBlock::iterator MuxAt = FP.SplitB->getFirstTerminator();
811 DebugLoc DL;
812 if (MuxAt != FP.SplitB->end())
813 DL = MuxAt->getDebugLoc();
814 unsigned MuxR = MRI->createVirtualRegister(RC);
815 BuildMI(*FP.SplitB, MuxAt, DL, D, MuxR)
816 .addReg(FP.PredR)
817 .addReg(TR, 0, TSR)
818 .addReg(FR, 0, FSR);
819
820 PN->addOperand(MachineOperand::CreateReg(MuxR, false));
821 PN->addOperand(MachineOperand::CreateMBB(FP.SplitB));
822 }
823}
824
825
826void HexagonEarlyIfConversion::convert(const FlowPattern &FP) {
827 MachineBasicBlock *TSB = 0, *FSB = 0;
828 MachineBasicBlock::iterator OldTI = FP.SplitB->getFirstTerminator();
829 assert(OldTI != FP.SplitB->end());
830 DebugLoc DL = OldTI->getDebugLoc();
831
832 if (FP.TrueB) {
833 TSB = *FP.TrueB->succ_begin();
834 predicateBlockNB(FP.SplitB, OldTI, FP.TrueB, FP.PredR, true);
835 }
836 if (FP.FalseB) {
837 FSB = *FP.FalseB->succ_begin();
838 MachineBasicBlock::iterator At = FP.SplitB->getFirstTerminator();
839 predicateBlockNB(FP.SplitB, At, FP.FalseB, FP.PredR, false);
840 }
841
842 // Regenerate new terminators in the split block and update the successors.
843 // First, remember any information that may be needed later and remove the
844 // existing terminators/successors from the split block.
845 MachineBasicBlock *SSB = 0;
846 FP.SplitB->erase(OldTI, FP.SplitB->end());
847 while (FP.SplitB->succ_size() > 0) {
848 MachineBasicBlock *T = *FP.SplitB->succ_begin();
849 // It's possible that the split block had a successor that is not a pre-
850 // dicated block. This could only happen if there was only one block to
851 // be predicated. Example:
852 // split_b:
853 // if (p) jump true_b
854 // jump unrelated2_b
855 // unrelated1_b:
856 // ...
857 // unrelated2_b: ; can have other predecessors, so it's not "false_b"
858 // jump other_b
859 // true_b: ; only reachable from split_b, can be predicated
860 // ...
861 //
862 // Find this successor (SSB) if it exists.
863 if (T != FP.TrueB && T != FP.FalseB) {
864 assert(!SSB);
865 SSB = T;
866 }
867 FP.SplitB->removeSuccessor(FP.SplitB->succ_begin());
868 }
869
870 // Insert new branches and update the successors of the split block. This
871 // may create unconditional branches to the layout successor, etc., but
872 // that will be cleaned up later. For now, make sure that correct code is
873 // generated.
874 if (FP.JoinB) {
875 assert(!SSB || SSB == FP.JoinB);
876 BuildMI(*FP.SplitB, FP.SplitB->end(), DL, TII->get(Hexagon::J2_jump))
877 .addMBB(FP.JoinB);
878 FP.SplitB->addSuccessor(FP.JoinB);
879 } else {
880 bool HasBranch = false;
881 if (TSB) {
882 BuildMI(*FP.SplitB, FP.SplitB->end(), DL, TII->get(Hexagon::J2_jumpt))
883 .addReg(FP.PredR)
884 .addMBB(TSB);
885 FP.SplitB->addSuccessor(TSB);
886 HasBranch = true;
887 }
888 if (FSB) {
889 const MCInstrDesc &D = HasBranch ? TII->get(Hexagon::J2_jump)
890 : TII->get(Hexagon::J2_jumpf);
891 MachineInstrBuilder MIB = BuildMI(*FP.SplitB, FP.SplitB->end(), DL, D);
892 if (!HasBranch)
893 MIB.addReg(FP.PredR);
894 MIB.addMBB(FSB);
895 FP.SplitB->addSuccessor(FSB);
896 }
897 if (SSB) {
898 // This cannot happen if both TSB and FSB are set. [TF]SB are the
899 // successor blocks of the TrueB and FalseB (or null of the TrueB
900 // or FalseB block is null). SSB is the potential successor block
901 // of the SplitB that is neither TrueB nor FalseB.
902 BuildMI(*FP.SplitB, FP.SplitB->end(), DL, TII->get(Hexagon::J2_jump))
903 .addMBB(SSB);
904 FP.SplitB->addSuccessor(SSB);
905 }
906 }
907
908 // What is left to do is to update the PHI nodes that could have entries
909 // referring to predicated blocks.
910 if (FP.JoinB) {
911 updatePhiNodes(FP.JoinB, FP);
912 } else {
913 if (TSB)
914 updatePhiNodes(TSB, FP);
915 if (FSB)
916 updatePhiNodes(FSB, FP);
917 // Nothing to update in SSB, since SSB's predecessors haven't changed.
918 }
919}
920
921
922void HexagonEarlyIfConversion::removeBlock(MachineBasicBlock *B) {
923 DEBUG(dbgs() << "Removing block " << PrintMB(B) << "\n");
924
925 // Transfer the immediate dominator information from B to its descendants.
926 MachineDomTreeNode *N = MDT->getNode(B);
927 MachineDomTreeNode *IDN = N->getIDom();
928 if (IDN) {
929 MachineBasicBlock *IDB = IDN->getBlock();
930 typedef GraphTraits<MachineDomTreeNode*> GTN;
931 typedef SmallVector<MachineDomTreeNode*,4> DTNodeVectType;
932 DTNodeVectType Cn(GTN::child_begin(N), GTN::child_end(N));
933 for (DTNodeVectType::iterator I = Cn.begin(), E = Cn.end(); I != E; ++I) {
934 MachineBasicBlock *SB = (*I)->getBlock();
935 MDT->changeImmediateDominator(SB, IDB);
936 }
937 }
938
939 while (B->succ_size() > 0)
940 B->removeSuccessor(B->succ_begin());
941
942 for (auto I = B->pred_begin(), E = B->pred_end(); I != E; ++I)
943 (*I)->removeSuccessor(B);
944
945 Deleted.insert(B);
946 MDT->eraseNode(B);
947 MachineFunction::iterator BI = B;
948 MFN->erase(BI);
949}
950
951
952void HexagonEarlyIfConversion::eliminatePhis(MachineBasicBlock *B) {
953 DEBUG(dbgs() << "Removing phi nodes from block " << PrintMB(B) << "\n");
954 MachineBasicBlock::iterator I, NextI, NonPHI = B->getFirstNonPHI();
955 for (I = B->begin(); I != NonPHI; I = NextI) {
956 NextI = std::next(I);
957 MachineInstr *PN = &*I;
958 assert(PN->getNumOperands() == 3 && "Invalid phi node");
959 MachineOperand &UO = PN->getOperand(1);
960 unsigned UseR = UO.getReg(), UseSR = UO.getSubReg();
961 unsigned DefR = PN->getOperand(0).getReg();
962 unsigned NewR = UseR;
963 if (UseSR) {
964 // MRI.replaceVregUsesWith does not allow to update the subregister,
965 // so instead of doing the use-iteration here, create a copy into a
966 // "non-subregistered" register.
967 DebugLoc DL = PN->getDebugLoc();
968 const TargetRegisterClass *RC = MRI->getRegClass(DefR);
969 NewR = MRI->createVirtualRegister(RC);
970 NonPHI = BuildMI(*B, NonPHI, DL, TII->get(TargetOpcode::COPY), NewR)
971 .addReg(UseR, 0, UseSR);
972 }
973 MRI->replaceRegWith(DefR, NewR);
974 B->erase(I);
975 }
976}
977
978
979void HexagonEarlyIfConversion::replacePhiEdges(MachineBasicBlock *OldB,
980 MachineBasicBlock *NewB) {
981 for (auto I = OldB->succ_begin(), E = OldB->succ_end(); I != E; ++I) {
982 MachineBasicBlock *SB = *I;
983 MachineBasicBlock::iterator P, N = SB->getFirstNonPHI();
984 for (P = SB->begin(); P != N; ++P) {
985 MachineInstr *PN = &*P;
986 for (MIOperands MO(PN); MO.isValid(); ++MO)
987 if (MO->isMBB() && MO->getMBB() == OldB)
988 MO->setMBB(NewB);
989 }
990 }
991}
992
993
994void HexagonEarlyIfConversion::mergeBlocks(MachineBasicBlock *PredB,
995 MachineBasicBlock *SuccB) {
996 DEBUG(dbgs() << "Merging blocks " << PrintMB(PredB) << " and "
997 << PrintMB(SuccB) << "\n");
998 bool TermOk = hasUncondBranch(SuccB);
999 eliminatePhis(SuccB);
1000 TII->RemoveBranch(*PredB);
1001 PredB->removeSuccessor(SuccB);
1002 PredB->splice(PredB->end(), SuccB, SuccB->begin(), SuccB->end());
1003 MachineBasicBlock::succ_iterator I, E = SuccB->succ_end();
1004 for (I = SuccB->succ_begin(); I != E; ++I)
1005 PredB->addSuccessor(*I);
1006 replacePhiEdges(SuccB, PredB);
1007 removeBlock(SuccB);
1008 if (!TermOk)
1009 PredB->updateTerminator();
1010}
1011
1012
1013void HexagonEarlyIfConversion::simplifyFlowGraph(const FlowPattern &FP) {
1014 if (FP.TrueB)
1015 removeBlock(FP.TrueB);
1016 if (FP.FalseB)
1017 removeBlock(FP.FalseB);
1018
1019 FP.SplitB->updateTerminator();
1020 if (FP.SplitB->succ_size() != 1)
1021 return;
1022
1023 MachineBasicBlock *SB = *FP.SplitB->succ_begin();
1024 if (SB->pred_size() != 1)
1025 return;
1026
1027 // By now, the split block has only one successor (SB), and SB has only
1028 // one predecessor. We can try to merge them. We will need to update ter-
1029 // minators in FP.Split+SB, and that requires working AnalyzeBranch, which
1030 // fails on Hexagon for blocks that have EH_LABELs. However, if SB ends
1031 // with an unconditional branch, we won't need to touch the terminators.
1032 if (!hasEHLabel(SB) || hasUncondBranch(SB))
1033 mergeBlocks(FP.SplitB, SB);
1034}
1035
1036
1037bool HexagonEarlyIfConversion::runOnMachineFunction(MachineFunction &MF) {
1038 auto &ST = MF.getSubtarget();
1039 TII = ST.getInstrInfo();
1040 TRI = ST.getRegisterInfo();
1041 MFN = &MF;
1042 MRI = &MF.getRegInfo();
1043 MDT = &getAnalysis<MachineDominatorTree>();
1044 MLI = &getAnalysis<MachineLoopInfo>();
1045 MBPI = EnableHexagonBP ? &getAnalysis<MachineBranchProbabilityInfo>() :
1046 nullptr;
1047
1048 Deleted.clear();
1049 bool Changed = false;
1050
1051 for (MachineLoopInfo::iterator I = MLI->begin(), E = MLI->end(); I != E; ++I)
1052 Changed |= visitLoop(*I);
1053 Changed |= visitLoop(0);
1054
1055 return Changed;
1056}
1057
1058//===----------------------------------------------------------------------===//
1059// Public Constructor Functions
1060//===----------------------------------------------------------------------===//
1061FunctionPass *llvm::createHexagonEarlyIfConversion() {
1062 return new HexagonEarlyIfConversion();
1063}
1064