blob: 4418b57f6a060a9829d71d2f77c3ce0da140710f [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
Krzysztof Parzyszek258af192016-08-11 19:12:18 +000055// %vreg46<def> = PS_pselect %vreg41, %vreg6, %vreg11
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +000056// %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
Eugene Zelenkof9f8c682016-12-14 22:50:46 +000064#include "Hexagon.h"
65#include "HexagonInstrInfo.h"
66#include "HexagonSubtarget.h"
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +000067#include "llvm/ADT/DenseSet.h"
Eugene Zelenkof9f8c682016-12-14 22:50:46 +000068#include "llvm/ADT/iterator_range.h"
69#include "llvm/ADT/SmallVector.h"
70#include "llvm/ADT/StringRef.h"
71#include "llvm/CodeGen/MachineBasicBlock.h"
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +000072#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
73#include "llvm/CodeGen/MachineDominators.h"
Eugene Zelenkof9f8c682016-12-14 22:50:46 +000074#include "llvm/CodeGen/MachineFunction.h"
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +000075#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenkof9f8c682016-12-14 22:50:46 +000076#include "llvm/CodeGen/MachineInstr.h"
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +000077#include "llvm/CodeGen/MachineInstrBuilder.h"
78#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenkof9f8c682016-12-14 22:50:46 +000079#include "llvm/CodeGen/MachineOperand.h"
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +000080#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenkof9f8c682016-12-14 22:50:46 +000081#include "llvm/IR/DebugLoc.h"
82#include "llvm/Pass.h"
83#include "llvm/Support/BranchProbability.h"
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +000084#include "llvm/Support/CommandLine.h"
Eugene Zelenkof9f8c682016-12-14 22:50:46 +000085#include "llvm/Support/Compiler.h"
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +000086#include "llvm/Support/Debug.h"
Eugene Zelenkof9f8c682016-12-14 22:50:46 +000087#include "llvm/Support/ErrorHandling.h"
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +000088#include "llvm/Support/raw_ostream.h"
Eugene Zelenkof9f8c682016-12-14 22:50:46 +000089#include "llvm/Target/TargetRegisterInfo.h"
90#include <cassert>
91#include <iterator>
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +000092
93using namespace llvm;
94
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +000095namespace llvm {
Eugene Zelenkof9f8c682016-12-14 22:50:46 +000096
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +000097 FunctionPass *createHexagonEarlyIfConversion();
98 void initializeHexagonEarlyIfConversionPass(PassRegistry& Registry);
Eugene Zelenkof9f8c682016-12-14 22:50:46 +000099
100} // end namespace llvm
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000101
102namespace {
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000103
Krzysztof Parzyszek8d2b2cf2015-10-06 18:29:36 +0000104 cl::opt<bool> EnableHexagonBP("enable-hexagon-br-prob", cl::Hidden,
105 cl::init(false), cl::desc("Enable branch probability info"));
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000106 cl::opt<unsigned> SizeLimit("eif-limit", cl::init(6), cl::Hidden,
Krzysztof Parzyszek8d2b2cf2015-10-06 18:29:36 +0000107 cl::desc("Size limit in Hexagon early if-conversion"));
Krzysztof Parzyszek8a4c6012017-03-06 17:24:04 +0000108 cl::opt<bool> SkipExitBranches("eif-no-loop-exit", cl::init(false),
109 cl::Hidden, cl::desc("Do not convert branches that may exit the loop"));
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000110
111 struct PrintMB {
112 PrintMB(const MachineBasicBlock *B) : MB(B) {}
113 const MachineBasicBlock *MB;
114 };
115 raw_ostream &operator<< (raw_ostream &OS, const PrintMB &P) {
116 if (!P.MB)
117 return OS << "<none>";
118 return OS << '#' << P.MB->getNumber();
119 }
120
121 struct FlowPattern {
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000122 FlowPattern() = default;
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000123 FlowPattern(MachineBasicBlock *B, unsigned PR, MachineBasicBlock *TB,
124 MachineBasicBlock *FB, MachineBasicBlock *JB)
125 : SplitB(B), TrueB(TB), FalseB(FB), JoinB(JB), PredR(PR) {}
126
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000127 MachineBasicBlock *SplitB = nullptr;
128 MachineBasicBlock *TrueB = nullptr;
129 MachineBasicBlock *FalseB = nullptr;
130 MachineBasicBlock *JoinB = nullptr;
131 unsigned PredR = 0;
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000132 };
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000133
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000134 struct PrintFP {
135 PrintFP(const FlowPattern &P, const TargetRegisterInfo &T)
136 : FP(P), TRI(T) {}
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000137
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000138 const FlowPattern &FP;
139 const TargetRegisterInfo &TRI;
140 friend raw_ostream &operator<< (raw_ostream &OS, const PrintFP &P);
141 };
142 raw_ostream &operator<<(raw_ostream &OS,
143 const PrintFP &P) LLVM_ATTRIBUTE_UNUSED;
144 raw_ostream &operator<<(raw_ostream &OS, const PrintFP &P) {
145 OS << "{ SplitB:" << PrintMB(P.FP.SplitB)
146 << ", PredR:" << PrintReg(P.FP.PredR, &P.TRI)
Krzysztof Parzyszek8a4c6012017-03-06 17:24:04 +0000147 << ", TrueB:" << PrintMB(P.FP.TrueB)
148 << ", FalseB:" << PrintMB(P.FP.FalseB)
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000149 << ", JoinB:" << PrintMB(P.FP.JoinB) << " }";
150 return OS;
151 }
152
153 class HexagonEarlyIfConversion : public MachineFunctionPass {
154 public:
155 static char ID;
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000156
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000157 HexagonEarlyIfConversion() : MachineFunctionPass(ID),
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000158 HII(nullptr), TRI(nullptr), MFN(nullptr), MRI(nullptr), MDT(nullptr),
159 MLI(nullptr) {
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000160 initializeHexagonEarlyIfConversionPass(*PassRegistry::getPassRegistry());
161 }
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000162
Mehdi Amini117296c2016-10-01 02:56:57 +0000163 StringRef getPassName() const override {
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000164 return "Hexagon early if conversion";
165 }
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000166
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000167 void getAnalysisUsage(AnalysisUsage &AU) const override {
168 AU.addRequired<MachineBranchProbabilityInfo>();
169 AU.addRequired<MachineDominatorTree>();
170 AU.addPreserved<MachineDominatorTree>();
171 AU.addRequired<MachineLoopInfo>();
172 MachineFunctionPass::getAnalysisUsage(AU);
173 }
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000174
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000175 bool runOnMachineFunction(MachineFunction &MF) override;
176
177 private:
178 typedef DenseSet<MachineBasicBlock*> BlockSetType;
179
180 bool isPreheader(const MachineBasicBlock *B) const;
181 bool matchFlowPattern(MachineBasicBlock *B, MachineLoop *L,
182 FlowPattern &FP);
183 bool visitBlock(MachineBasicBlock *B, MachineLoop *L);
184 bool visitLoop(MachineLoop *L);
185
186 bool hasEHLabel(const MachineBasicBlock *B) const;
187 bool hasUncondBranch(const MachineBasicBlock *B) const;
188 bool isValidCandidate(const MachineBasicBlock *B) const;
189 bool usesUndefVReg(const MachineInstr *MI) const;
190 bool isValid(const FlowPattern &FP) const;
191 unsigned countPredicateDefs(const MachineBasicBlock *B) const;
Krzysztof Parzyszek8a4c6012017-03-06 17:24:04 +0000192 unsigned computePhiCost(const MachineBasicBlock *B,
193 const FlowPattern &FP) const;
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000194 bool isProfitable(const FlowPattern &FP) const;
195 bool isPredicableStore(const MachineInstr *MI) const;
196 bool isSafeToSpeculate(const MachineInstr *MI) const;
197
198 unsigned getCondStoreOpcode(unsigned Opc, bool IfTrue) const;
199 void predicateInstr(MachineBasicBlock *ToB, MachineBasicBlock::iterator At,
200 MachineInstr *MI, unsigned PredR, bool IfTrue);
201 void predicateBlockNB(MachineBasicBlock *ToB,
202 MachineBasicBlock::iterator At, MachineBasicBlock *FromB,
203 unsigned PredR, bool IfTrue);
204
Krzysztof Parzyszek8a4c6012017-03-06 17:24:04 +0000205 unsigned buildMux(MachineBasicBlock *B, MachineBasicBlock::iterator At,
206 const TargetRegisterClass *DRC, unsigned PredR, unsigned TR,
207 unsigned TSR, unsigned FR, unsigned FSR);
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000208 void updatePhiNodes(MachineBasicBlock *WhereB, const FlowPattern &FP);
209 void convert(const FlowPattern &FP);
210
211 void removeBlock(MachineBasicBlock *B);
212 void eliminatePhis(MachineBasicBlock *B);
213 void replacePhiEdges(MachineBasicBlock *OldB, MachineBasicBlock *NewB);
214 void mergeBlocks(MachineBasicBlock *PredB, MachineBasicBlock *SuccB);
215 void simplifyFlowGraph(const FlowPattern &FP);
216
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000217 const HexagonInstrInfo *HII;
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000218 const TargetRegisterInfo *TRI;
219 MachineFunction *MFN;
220 MachineRegisterInfo *MRI;
221 MachineDominatorTree *MDT;
222 MachineLoopInfo *MLI;
223 BlockSetType Deleted;
224 const MachineBranchProbabilityInfo *MBPI;
225 };
226
227 char HexagonEarlyIfConversion::ID = 0;
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000228
229} // end anonymous namespace
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000230
231INITIALIZE_PASS(HexagonEarlyIfConversion, "hexagon-eif",
232 "Hexagon early if conversion", false, false)
233
234bool HexagonEarlyIfConversion::isPreheader(const MachineBasicBlock *B) const {
235 if (B->succ_size() != 1)
236 return false;
237 MachineBasicBlock *SB = *B->succ_begin();
238 MachineLoop *L = MLI->getLoopFor(SB);
Krzysztof Parzyszek8a4c6012017-03-06 17:24:04 +0000239 return L && SB == L->getHeader() && MDT->dominates(B, SB);
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000240}
241
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000242bool HexagonEarlyIfConversion::matchFlowPattern(MachineBasicBlock *B,
243 MachineLoop *L, FlowPattern &FP) {
244 DEBUG(dbgs() << "Checking flow pattern at BB#" << B->getNumber() << "\n");
245
246 // Interested only in conditional branches, no .new, no new-value, etc.
247 // Check the terminators directly, it's easier than handling all responses
248 // from AnalyzeBranch.
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000249 MachineBasicBlock *TB = nullptr, *FB = nullptr;
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000250 MachineBasicBlock::const_iterator T1I = B->getFirstTerminator();
251 if (T1I == B->end())
252 return false;
253 unsigned Opc = T1I->getOpcode();
254 if (Opc != Hexagon::J2_jumpt && Opc != Hexagon::J2_jumpf)
255 return false;
256 unsigned PredR = T1I->getOperand(0).getReg();
257
258 // Get the layout successor, or 0 if B does not have one.
259 MachineFunction::iterator NextBI = std::next(MachineFunction::iterator(B));
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000260 MachineBasicBlock *NextB = (NextBI != MFN->end()) ? &*NextBI : nullptr;
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000261
262 MachineBasicBlock *T1B = T1I->getOperand(1).getMBB();
263 MachineBasicBlock::const_iterator T2I = std::next(T1I);
264 // The second terminator should be an unconditional branch.
265 assert(T2I == B->end() || T2I->getOpcode() == Hexagon::J2_jump);
266 MachineBasicBlock *T2B = (T2I == B->end()) ? NextB
267 : T2I->getOperand(0).getMBB();
268 if (T1B == T2B) {
269 // XXX merge if T1B == NextB, or convert branch to unconditional.
270 // mark as diamond with both sides equal?
271 return false;
272 }
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000273
274 // Record the true/false blocks in such a way that "true" means "if (PredR)",
275 // and "false" means "if (!PredR)".
276 if (Opc == Hexagon::J2_jumpt)
277 TB = T1B, FB = T2B;
278 else
279 TB = T2B, FB = T1B;
280
281 if (!MDT->properlyDominates(B, TB) || !MDT->properlyDominates(B, FB))
282 return false;
283
284 // Detect triangle first. In case of a triangle, one of the blocks TB/FB
285 // can fall through into the other, in other words, it will be executed
286 // in both cases. We only want to predicate the block that is executed
287 // conditionally.
288 unsigned TNP = TB->pred_size(), FNP = FB->pred_size();
289 unsigned TNS = TB->succ_size(), FNS = FB->succ_size();
290
291 // A block is predicable if it has one predecessor (it must be B), and
292 // it has a single successor. In fact, the block has to end either with
293 // an unconditional branch (which can be predicated), or with a fall-
294 // through.
Krzysztof Parzyszek8a4c6012017-03-06 17:24:04 +0000295 // Also, skip blocks that do not belong to the same loop.
296 bool TOk = (TNP == 1 && TNS == 1 && MLI->getLoopFor(TB) == L);
297 bool FOk = (FNP == 1 && FNS == 1 && MLI->getLoopFor(FB) == L);
298
299 // If requested (via an option), do not consider branches where the
300 // true and false targets do not belong to the same loop.
301 if (SkipExitBranches && MLI->getLoopFor(TB) != MLI->getLoopFor(FB))
302 return false;
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000303
304 // If neither is predicable, there is nothing interesting.
305 if (!TOk && !FOk)
306 return false;
307
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000308 MachineBasicBlock *TSB = (TNS > 0) ? *TB->succ_begin() : nullptr;
309 MachineBasicBlock *FSB = (FNS > 0) ? *FB->succ_begin() : nullptr;
310 MachineBasicBlock *JB = nullptr;
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000311
312 if (TOk) {
313 if (FOk) {
314 if (TSB == FSB)
315 JB = TSB;
316 // Diamond: "if (P) then TB; else FB;".
317 } else {
318 // TOk && !FOk
Krzysztof Parzyszek8a4c6012017-03-06 17:24:04 +0000319 if (TSB == FB)
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000320 JB = FB;
Krzysztof Parzyszek8a4c6012017-03-06 17:24:04 +0000321 FB = nullptr;
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000322 }
323 } else {
324 // !TOk && FOk (at least one must be true by now).
Krzysztof Parzyszek8a4c6012017-03-06 17:24:04 +0000325 if (FSB == TB)
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000326 JB = TB;
Krzysztof Parzyszek8a4c6012017-03-06 17:24:04 +0000327 TB = nullptr;
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000328 }
329 // Don't try to predicate loop preheaders.
330 if ((TB && isPreheader(TB)) || (FB && isPreheader(FB))) {
331 DEBUG(dbgs() << "One of blocks " << PrintMB(TB) << ", " << PrintMB(FB)
332 << " is a loop preheader. Skipping.\n");
333 return false;
334 }
335
336 FP = FlowPattern(B, PredR, TB, FB, JB);
337 DEBUG(dbgs() << "Detected " << PrintFP(FP, *TRI) << "\n");
338 return true;
339}
340
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000341// KLUDGE: HexagonInstrInfo::AnalyzeBranch won't work on a block that
342// contains EH_LABEL.
343bool HexagonEarlyIfConversion::hasEHLabel(const MachineBasicBlock *B) const {
344 for (auto &I : *B)
345 if (I.isEHLabel())
346 return true;
347 return false;
348}
349
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000350// KLUDGE: HexagonInstrInfo::AnalyzeBranch may be unable to recognize
351// that a block can never fall-through.
352bool HexagonEarlyIfConversion::hasUncondBranch(const MachineBasicBlock *B)
353 const {
354 MachineBasicBlock::const_iterator I = B->getFirstTerminator(), E = B->end();
355 while (I != E) {
356 if (I->isBarrier())
357 return true;
358 ++I;
359 }
360 return false;
361}
362
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000363bool HexagonEarlyIfConversion::isValidCandidate(const MachineBasicBlock *B)
364 const {
365 if (!B)
366 return true;
367 if (B->isEHPad() || B->hasAddressTaken())
368 return false;
369 if (B->succ_size() == 0)
370 return false;
371
372 for (auto &MI : *B) {
373 if (MI.isDebugValue())
374 continue;
375 if (MI.isConditionalBranch())
376 return false;
377 unsigned Opc = MI.getOpcode();
378 bool IsJMP = (Opc == Hexagon::J2_jump);
379 if (!isPredicableStore(&MI) && !IsJMP && !isSafeToSpeculate(&MI))
380 return false;
381 // Look for predicate registers defined by this instruction. It's ok
382 // to speculate such an instruction, but the predicate register cannot
383 // be used outside of this block (or else it won't be possible to
384 // update the use of it after predication). PHI uses will be updated
385 // to use a result of a MUX, and a MUX cannot be created for predicate
386 // registers.
Matthias Braunfc371552016-10-24 21:36:43 +0000387 for (const MachineOperand &MO : MI.operands()) {
388 if (!MO.isReg() || !MO.isDef())
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000389 continue;
Matthias Braunfc371552016-10-24 21:36:43 +0000390 unsigned R = MO.getReg();
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000391 if (!TargetRegisterInfo::isVirtualRegister(R))
392 continue;
Krzysztof Parzyszek056c9452017-03-02 18:10:59 +0000393 switch (MRI->getRegClass(R)->getID()) {
394 case Hexagon::PredRegsRegClassID:
395 case Hexagon::VecPredRegsRegClassID:
396 case Hexagon::VecPredRegs128BRegClassID:
397 break;
398 default:
399 continue;
400 }
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000401 for (auto U = MRI->use_begin(R); U != MRI->use_end(); ++U)
402 if (U->getParent()->isPHI())
403 return false;
404 }
405 }
406 return true;
407}
408
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000409bool HexagonEarlyIfConversion::usesUndefVReg(const MachineInstr *MI) const {
Matthias Braunfc371552016-10-24 21:36:43 +0000410 for (const MachineOperand &MO : MI->operands()) {
411 if (!MO.isReg() || !MO.isUse())
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000412 continue;
Matthias Braunfc371552016-10-24 21:36:43 +0000413 unsigned R = MO.getReg();
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000414 if (!TargetRegisterInfo::isVirtualRegister(R))
415 continue;
416 const MachineInstr *DefI = MRI->getVRegDef(R);
417 // "Undefined" virtual registers are actually defined via IMPLICIT_DEF.
418 assert(DefI && "Expecting a reaching def in MRI");
419 if (DefI->isImplicitDef())
420 return true;
421 }
422 return false;
423}
424
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000425bool HexagonEarlyIfConversion::isValid(const FlowPattern &FP) const {
426 if (hasEHLabel(FP.SplitB)) // KLUDGE: see function definition
427 return false;
428 if (FP.TrueB && !isValidCandidate(FP.TrueB))
429 return false;
430 if (FP.FalseB && !isValidCandidate(FP.FalseB))
431 return false;
432 // Check the PHIs in the join block. If any of them use a register
433 // that is defined as IMPLICIT_DEF, do not convert this. This can
434 // legitimately happen if one side of the split never executes, but
435 // the compiler is unable to prove it. That side may then seem to
436 // provide an "undef" value to the join block, however it will never
437 // execute at run-time. If we convert this case, the "undef" will
438 // be used in a MUX instruction, and that may seem like actually
439 // using an undefined value to other optimizations. This could lead
440 // to trouble further down the optimization stream, cause assertions
441 // to fail, etc.
442 if (FP.JoinB) {
443 const MachineBasicBlock &B = *FP.JoinB;
444 for (auto &MI : B) {
445 if (!MI.isPHI())
446 break;
447 if (usesUndefVReg(&MI))
448 return false;
449 unsigned DefR = MI.getOperand(0).getReg();
450 const TargetRegisterClass *RC = MRI->getRegClass(DefR);
451 if (RC == &Hexagon::PredRegsRegClass)
452 return false;
453 }
454 }
455 return true;
456}
457
Krzysztof Parzyszek8a4c6012017-03-06 17:24:04 +0000458unsigned HexagonEarlyIfConversion::computePhiCost(const MachineBasicBlock *B,
459 const FlowPattern &FP) const {
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000460 if (B->pred_size() < 2)
461 return 0;
462
463 unsigned Cost = 0;
Krzysztof Parzyszek8a4c6012017-03-06 17:24:04 +0000464 for (const MachineInstr &MI : *B) {
465 if (!MI.isPHI())
466 break;
467 // If both incoming blocks are one of the TrueB/FalseB/SplitB, then
468 // a MUX may be needed. Otherwise the PHI will need to be updated at
469 // no extra cost.
470 // Find the interesting PHI operands for further checks.
471 SmallVector<unsigned,2> Inc;
472 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
473 const MachineBasicBlock *BB = MI.getOperand(i+1).getMBB();
474 if (BB == FP.SplitB || BB == FP.TrueB || BB == FP.FalseB)
475 Inc.push_back(i);
476 }
477 assert(Inc.size() <= 2);
478 if (Inc.size() < 2)
479 continue;
480
481 const MachineOperand &RA = MI.getOperand(1);
482 const MachineOperand &RB = MI.getOperand(3);
483 assert(RA.isReg() && RB.isReg());
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000484 // Must have a MUX if the phi uses a subregister.
Krzysztof Parzyszek8a4c6012017-03-06 17:24:04 +0000485 if (RA.getSubReg() != 0 || RA.getSubReg() != 0) {
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000486 Cost++;
487 continue;
488 }
Krzysztof Parzyszek8a4c6012017-03-06 17:24:04 +0000489 const MachineInstr *Def1 = MRI->getVRegDef(RA.getReg());
490 const MachineInstr *Def3 = MRI->getVRegDef(RB.getReg());
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000491 if (!HII->isPredicable(*Def1) || !HII->isPredicable(*Def3))
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000492 Cost++;
493 }
494 return Cost;
495}
496
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000497unsigned HexagonEarlyIfConversion::countPredicateDefs(
498 const MachineBasicBlock *B) const {
499 unsigned PredDefs = 0;
500 for (auto &MI : *B) {
Matthias Braunfc371552016-10-24 21:36:43 +0000501 for (const MachineOperand &MO : MI.operands()) {
502 if (!MO.isReg() || !MO.isDef())
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000503 continue;
Matthias Braunfc371552016-10-24 21:36:43 +0000504 unsigned R = MO.getReg();
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000505 if (!TargetRegisterInfo::isVirtualRegister(R))
506 continue;
507 if (MRI->getRegClass(R) == &Hexagon::PredRegsRegClass)
508 PredDefs++;
509 }
510 }
511 return PredDefs;
512}
513
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000514bool HexagonEarlyIfConversion::isProfitable(const FlowPattern &FP) const {
515 if (FP.TrueB && FP.FalseB) {
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000516 // Do not IfCovert if the branch is one sided.
517 if (MBPI) {
518 BranchProbability Prob(9, 10);
519 if (MBPI->getEdgeProbability(FP.SplitB, FP.TrueB) > Prob)
520 return false;
521 if (MBPI->getEdgeProbability(FP.SplitB, FP.FalseB) > Prob)
522 return false;
523 }
524
525 // If both sides are predicable, convert them if they join, and the
526 // join block has no other predecessors.
527 MachineBasicBlock *TSB = *FP.TrueB->succ_begin();
528 MachineBasicBlock *FSB = *FP.FalseB->succ_begin();
529 if (TSB != FSB)
530 return false;
531 if (TSB->pred_size() != 2)
532 return false;
533 }
534
535 // Calculate the total size of the predicated blocks.
536 // Assume instruction counts without branches to be the approximation of
537 // the code size. If the predicated blocks are smaller than a packet size,
538 // approximate the spare room in the packet that could be filled with the
539 // predicated/speculated instructions.
540 unsigned TS = 0, FS = 0, Spare = 0;
541 if (FP.TrueB) {
542 TS = std::distance(FP.TrueB->begin(), FP.TrueB->getFirstTerminator());
543 if (TS < HEXAGON_PACKET_SIZE)
544 Spare += HEXAGON_PACKET_SIZE-TS;
545 }
546 if (FP.FalseB) {
547 FS = std::distance(FP.FalseB->begin(), FP.FalseB->getFirstTerminator());
548 if (FS < HEXAGON_PACKET_SIZE)
549 Spare += HEXAGON_PACKET_SIZE-TS;
550 }
551 unsigned TotalIn = TS+FS;
552 DEBUG(dbgs() << "Total number of instructions to be predicated/speculated: "
553 << TotalIn << ", spare room: " << Spare << "\n");
554 if (TotalIn >= SizeLimit+Spare)
555 return false;
556
557 // Count the number of PHI nodes that will need to be updated (converted
558 // to MUX). Those can be later converted to predicated instructions, so
559 // they aren't always adding extra cost.
560 // KLUDGE: Also, count the number of predicate register definitions in
561 // each block. The scheduler may increase the pressure of these and cause
562 // expensive spills (e.g. bitmnp01).
563 unsigned TotalPh = 0;
564 unsigned PredDefs = countPredicateDefs(FP.SplitB);
565 if (FP.JoinB) {
Krzysztof Parzyszek8a4c6012017-03-06 17:24:04 +0000566 TotalPh = computePhiCost(FP.JoinB, FP);
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000567 PredDefs += countPredicateDefs(FP.JoinB);
568 } else {
569 if (FP.TrueB && FP.TrueB->succ_size() > 0) {
570 MachineBasicBlock *SB = *FP.TrueB->succ_begin();
Krzysztof Parzyszek8a4c6012017-03-06 17:24:04 +0000571 TotalPh += computePhiCost(SB, FP);
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000572 PredDefs += countPredicateDefs(SB);
573 }
574 if (FP.FalseB && FP.FalseB->succ_size() > 0) {
575 MachineBasicBlock *SB = *FP.FalseB->succ_begin();
Krzysztof Parzyszek8a4c6012017-03-06 17:24:04 +0000576 TotalPh += computePhiCost(SB, FP);
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000577 PredDefs += countPredicateDefs(SB);
578 }
579 }
580 DEBUG(dbgs() << "Total number of extra muxes from converted phis: "
581 << TotalPh << "\n");
582 if (TotalIn+TotalPh >= SizeLimit+Spare)
583 return false;
584
585 DEBUG(dbgs() << "Total number of predicate registers: " << PredDefs << "\n");
586 if (PredDefs > 4)
587 return false;
588
589 return true;
590}
591
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000592bool HexagonEarlyIfConversion::visitBlock(MachineBasicBlock *B,
593 MachineLoop *L) {
594 bool Changed = false;
595
596 // Visit all dominated blocks from the same loop first, then process B.
597 MachineDomTreeNode *N = MDT->getNode(B);
598 typedef GraphTraits<MachineDomTreeNode*> GTN;
599 // We will change CFG/DT during this traversal, so take precautions to
600 // avoid problems related to invalidated iterators. In fact, processing
601 // a child C of B cannot cause another child to be removed, but it can
602 // cause a new child to be added (which was a child of C before C itself
603 // was removed. This new child C, however, would have been processed
604 // prior to processing B, so there is no need to process it again.
605 // Simply keep a list of children of B, and traverse that list.
606 typedef SmallVector<MachineDomTreeNode*,4> DTNodeVectType;
607 DTNodeVectType Cn(GTN::child_begin(N), GTN::child_end(N));
608 for (DTNodeVectType::iterator I = Cn.begin(), E = Cn.end(); I != E; ++I) {
609 MachineBasicBlock *SB = (*I)->getBlock();
610 if (!Deleted.count(SB))
611 Changed |= visitBlock(SB, L);
612 }
613 // When walking down the dominator tree, we want to traverse through
614 // blocks from nested (other) loops, because they can dominate blocks
615 // that are in L. Skip the non-L blocks only after the tree traversal.
616 if (MLI->getLoopFor(B) != L)
617 return Changed;
618
619 FlowPattern FP;
620 if (!matchFlowPattern(B, L, FP))
621 return Changed;
622
623 if (!isValid(FP)) {
624 DEBUG(dbgs() << "Conversion is not valid\n");
625 return Changed;
626 }
627 if (!isProfitable(FP)) {
628 DEBUG(dbgs() << "Conversion is not profitable\n");
629 return Changed;
630 }
631
632 convert(FP);
633 simplifyFlowGraph(FP);
634 return true;
635}
636
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000637bool HexagonEarlyIfConversion::visitLoop(MachineLoop *L) {
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000638 MachineBasicBlock *HB = L ? L->getHeader() : nullptr;
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000639 DEBUG((L ? dbgs() << "Visiting loop H:" << PrintMB(HB)
640 : dbgs() << "Visiting function") << "\n");
641 bool Changed = false;
642 if (L) {
643 for (MachineLoop::iterator I = L->begin(), E = L->end(); I != E; ++I)
644 Changed |= visitLoop(*I);
645 }
646
647 MachineBasicBlock *EntryB = GraphTraits<MachineFunction*>::getEntryNode(MFN);
648 Changed |= visitBlock(L ? HB : EntryB, L);
649 return Changed;
650}
651
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000652bool HexagonEarlyIfConversion::isPredicableStore(const MachineInstr *MI)
653 const {
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000654 // HexagonInstrInfo::isPredicable will consider these stores are non-
655 // -predicable if the offset would become constant-extended after
656 // predication.
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000657 unsigned Opc = MI->getOpcode();
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000658 switch (Opc) {
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000659 case Hexagon::S2_storerb_io:
660 case Hexagon::S2_storerbnew_io:
661 case Hexagon::S2_storerh_io:
662 case Hexagon::S2_storerhnew_io:
663 case Hexagon::S2_storeri_io:
664 case Hexagon::S2_storerinew_io:
665 case Hexagon::S2_storerd_io:
666 case Hexagon::S4_storeirb_io:
667 case Hexagon::S4_storeirh_io:
668 case Hexagon::S4_storeiri_io:
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000669 return true;
670 }
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000671
672 // TargetInstrInfo::isPredicable takes a non-const pointer.
673 return MI->mayStore() && HII->isPredicable(const_cast<MachineInstr&>(*MI));
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000674}
675
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000676bool HexagonEarlyIfConversion::isSafeToSpeculate(const MachineInstr *MI)
677 const {
678 if (MI->mayLoad() || MI->mayStore())
679 return false;
680 if (MI->isCall() || MI->isBarrier() || MI->isBranch())
681 return false;
682 if (MI->hasUnmodeledSideEffects())
683 return false;
684
685 return true;
686}
687
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000688unsigned HexagonEarlyIfConversion::getCondStoreOpcode(unsigned Opc,
689 bool IfTrue) const {
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000690 return HII->getCondOpcode(Opc, !IfTrue);
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000691}
692
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000693void HexagonEarlyIfConversion::predicateInstr(MachineBasicBlock *ToB,
694 MachineBasicBlock::iterator At, MachineInstr *MI,
695 unsigned PredR, bool IfTrue) {
696 DebugLoc DL;
697 if (At != ToB->end())
698 DL = At->getDebugLoc();
699 else if (!ToB->empty())
700 DL = ToB->back().getDebugLoc();
701
702 unsigned Opc = MI->getOpcode();
703
704 if (isPredicableStore(MI)) {
705 unsigned COpc = getCondStoreOpcode(Opc, IfTrue);
706 assert(COpc);
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000707 MachineInstrBuilder MIB = BuildMI(*ToB, At, DL, HII->get(COpc));
Matthias Braunfc371552016-10-24 21:36:43 +0000708 MachineInstr::mop_iterator MOI = MI->operands_begin();
Krzysztof Parzyszek8fb181c2016-08-01 17:55:48 +0000709 if (HII->isPostIncrement(*MI)) {
Diana Picus116bbab2017-01-13 09:58:52 +0000710 MIB.add(*MOI);
Matthias Braunfc371552016-10-24 21:36:43 +0000711 ++MOI;
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000712 }
713 MIB.addReg(PredR);
Matthias Braunfc371552016-10-24 21:36:43 +0000714 for (const MachineOperand &MO : make_range(MOI, MI->operands_end()))
Diana Picus116bbab2017-01-13 09:58:52 +0000715 MIB.add(MO);
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000716
717 // Set memory references.
718 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
719 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
720 MIB.setMemRefs(MMOBegin, MMOEnd);
721
722 MI->eraseFromParent();
723 return;
724 }
725
726 if (Opc == Hexagon::J2_jump) {
727 MachineBasicBlock *TB = MI->getOperand(0).getMBB();
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000728 const MCInstrDesc &D = HII->get(IfTrue ? Hexagon::J2_jumpt
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000729 : Hexagon::J2_jumpf);
730 BuildMI(*ToB, At, DL, D)
731 .addReg(PredR)
732 .addMBB(TB);
733 MI->eraseFromParent();
734 return;
735 }
736
737 // Print the offending instruction unconditionally as we are about to
738 // abort.
739 dbgs() << *MI;
740 llvm_unreachable("Unexpected instruction");
741}
742
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000743// Predicate/speculate non-branch instructions from FromB into block ToB.
744// Leave the branches alone, they will be handled later. Btw, at this point
745// FromB should have at most one branch, and it should be unconditional.
746void HexagonEarlyIfConversion::predicateBlockNB(MachineBasicBlock *ToB,
747 MachineBasicBlock::iterator At, MachineBasicBlock *FromB,
748 unsigned PredR, bool IfTrue) {
749 DEBUG(dbgs() << "Predicating block " << PrintMB(FromB) << "\n");
750 MachineBasicBlock::iterator End = FromB->getFirstTerminator();
751 MachineBasicBlock::iterator I, NextI;
752
753 for (I = FromB->begin(); I != End; I = NextI) {
754 assert(!I->isPHI());
755 NextI = std::next(I);
756 if (isSafeToSpeculate(&*I))
757 ToB->splice(At, FromB, I);
758 else
759 predicateInstr(ToB, At, &*I, PredR, IfTrue);
760 }
761}
762
Krzysztof Parzyszek8a4c6012017-03-06 17:24:04 +0000763unsigned HexagonEarlyIfConversion::buildMux(MachineBasicBlock *B,
764 MachineBasicBlock::iterator At, const TargetRegisterClass *DRC,
765 unsigned PredR, unsigned TR, unsigned TSR, unsigned FR, unsigned FSR) {
766 unsigned Opc = 0;
767 switch (DRC->getID()) {
768 case Hexagon::IntRegsRegClassID:
769 Opc = Hexagon::C2_mux;
770 break;
771 case Hexagon::DoubleRegsRegClassID:
772 Opc = Hexagon::PS_pselect;
773 break;
774 case Hexagon::VectorRegsRegClassID:
775 Opc = Hexagon::PS_vselect;
776 break;
777 case Hexagon::VecDblRegsRegClassID:
778 Opc = Hexagon::PS_wselect;
779 break;
780 case Hexagon::VectorRegs128BRegClassID:
781 Opc = Hexagon::PS_vselect_128B;
782 break;
783 case Hexagon::VecDblRegs128BRegClassID:
784 Opc = Hexagon::PS_wselect_128B;
785 break;
786 default:
787 llvm_unreachable("unexpected register type");
788 }
789 const MCInstrDesc &D = HII->get(Opc);
790
791 DebugLoc DL = B->findBranchDebugLoc();
792 unsigned MuxR = MRI->createVirtualRegister(DRC);
793 BuildMI(*B, At, DL, D, MuxR)
794 .addReg(PredR)
795 .addReg(TR, 0, TSR)
796 .addReg(FR, 0, FSR);
797 return MuxR;
798}
799
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000800void HexagonEarlyIfConversion::updatePhiNodes(MachineBasicBlock *WhereB,
801 const FlowPattern &FP) {
802 // Visit all PHI nodes in the WhereB block and generate MUX instructions
803 // in the split block. Update the PHI nodes with the values of the MUX.
804 auto NonPHI = WhereB->getFirstNonPHI();
805 for (auto I = WhereB->begin(); I != NonPHI; ++I) {
806 MachineInstr *PN = &*I;
807 // Registers and subregisters corresponding to TrueB, FalseB and SplitB.
808 unsigned TR = 0, TSR = 0, FR = 0, FSR = 0, SR = 0, SSR = 0;
809 for (int i = PN->getNumOperands()-2; i > 0; i -= 2) {
810 const MachineOperand &RO = PN->getOperand(i), &BO = PN->getOperand(i+1);
811 if (BO.getMBB() == FP.SplitB)
812 SR = RO.getReg(), SSR = RO.getSubReg();
813 else if (BO.getMBB() == FP.TrueB)
814 TR = RO.getReg(), TSR = RO.getSubReg();
815 else if (BO.getMBB() == FP.FalseB)
816 FR = RO.getReg(), FSR = RO.getSubReg();
817 else
818 continue;
819 PN->RemoveOperand(i+1);
820 PN->RemoveOperand(i);
821 }
822 if (TR == 0)
823 TR = SR, TSR = SSR;
824 else if (FR == 0)
825 FR = SR, FSR = SSR;
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000826
Krzysztof Parzyszek8a4c6012017-03-06 17:24:04 +0000827 assert(TR || FR);
828 unsigned MuxR = 0, MuxSR = 0;
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000829
Krzysztof Parzyszek8a4c6012017-03-06 17:24:04 +0000830 if (TR && FR) {
831 unsigned DR = PN->getOperand(0).getReg();
832 const TargetRegisterClass *RC = MRI->getRegClass(DR);
833 MuxR = buildMux(FP.SplitB, FP.SplitB->getFirstTerminator(), RC,
834 FP.PredR, TR, TSR, FR, FSR);
835 } else if (TR) {
836 MuxR = TR;
837 MuxSR = TSR;
838 } else {
839 MuxR = FR;
840 MuxSR = FSR;
841 }
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000842
Krzysztof Parzyszek8a4c6012017-03-06 17:24:04 +0000843 PN->addOperand(MachineOperand::CreateReg(MuxR, false, false, false, false,
844 false, false, MuxSR));
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000845 PN->addOperand(MachineOperand::CreateMBB(FP.SplitB));
846 }
847}
848
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000849void HexagonEarlyIfConversion::convert(const FlowPattern &FP) {
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000850 MachineBasicBlock *TSB = nullptr, *FSB = nullptr;
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000851 MachineBasicBlock::iterator OldTI = FP.SplitB->getFirstTerminator();
852 assert(OldTI != FP.SplitB->end());
853 DebugLoc DL = OldTI->getDebugLoc();
854
855 if (FP.TrueB) {
856 TSB = *FP.TrueB->succ_begin();
857 predicateBlockNB(FP.SplitB, OldTI, FP.TrueB, FP.PredR, true);
858 }
859 if (FP.FalseB) {
860 FSB = *FP.FalseB->succ_begin();
861 MachineBasicBlock::iterator At = FP.SplitB->getFirstTerminator();
862 predicateBlockNB(FP.SplitB, At, FP.FalseB, FP.PredR, false);
863 }
864
865 // Regenerate new terminators in the split block and update the successors.
866 // First, remember any information that may be needed later and remove the
867 // existing terminators/successors from the split block.
Eugene Zelenkof9f8c682016-12-14 22:50:46 +0000868 MachineBasicBlock *SSB = nullptr;
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000869 FP.SplitB->erase(OldTI, FP.SplitB->end());
870 while (FP.SplitB->succ_size() > 0) {
871 MachineBasicBlock *T = *FP.SplitB->succ_begin();
872 // It's possible that the split block had a successor that is not a pre-
873 // dicated block. This could only happen if there was only one block to
874 // be predicated. Example:
875 // split_b:
876 // if (p) jump true_b
877 // jump unrelated2_b
878 // unrelated1_b:
879 // ...
880 // unrelated2_b: ; can have other predecessors, so it's not "false_b"
881 // jump other_b
882 // true_b: ; only reachable from split_b, can be predicated
883 // ...
884 //
885 // Find this successor (SSB) if it exists.
886 if (T != FP.TrueB && T != FP.FalseB) {
887 assert(!SSB);
888 SSB = T;
889 }
890 FP.SplitB->removeSuccessor(FP.SplitB->succ_begin());
891 }
892
893 // Insert new branches and update the successors of the split block. This
894 // may create unconditional branches to the layout successor, etc., but
895 // that will be cleaned up later. For now, make sure that correct code is
896 // generated.
897 if (FP.JoinB) {
898 assert(!SSB || SSB == FP.JoinB);
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000899 BuildMI(*FP.SplitB, FP.SplitB->end(), DL, HII->get(Hexagon::J2_jump))
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000900 .addMBB(FP.JoinB);
901 FP.SplitB->addSuccessor(FP.JoinB);
902 } else {
903 bool HasBranch = false;
904 if (TSB) {
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000905 BuildMI(*FP.SplitB, FP.SplitB->end(), DL, HII->get(Hexagon::J2_jumpt))
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000906 .addReg(FP.PredR)
907 .addMBB(TSB);
908 FP.SplitB->addSuccessor(TSB);
909 HasBranch = true;
910 }
911 if (FSB) {
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000912 const MCInstrDesc &D = HasBranch ? HII->get(Hexagon::J2_jump)
913 : HII->get(Hexagon::J2_jumpf);
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000914 MachineInstrBuilder MIB = BuildMI(*FP.SplitB, FP.SplitB->end(), DL, D);
915 if (!HasBranch)
916 MIB.addReg(FP.PredR);
917 MIB.addMBB(FSB);
918 FP.SplitB->addSuccessor(FSB);
919 }
920 if (SSB) {
921 // This cannot happen if both TSB and FSB are set. [TF]SB are the
922 // successor blocks of the TrueB and FalseB (or null of the TrueB
923 // or FalseB block is null). SSB is the potential successor block
924 // of the SplitB that is neither TrueB nor FalseB.
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000925 BuildMI(*FP.SplitB, FP.SplitB->end(), DL, HII->get(Hexagon::J2_jump))
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000926 .addMBB(SSB);
927 FP.SplitB->addSuccessor(SSB);
928 }
929 }
930
931 // What is left to do is to update the PHI nodes that could have entries
932 // referring to predicated blocks.
933 if (FP.JoinB) {
934 updatePhiNodes(FP.JoinB, FP);
935 } else {
936 if (TSB)
937 updatePhiNodes(TSB, FP);
938 if (FSB)
939 updatePhiNodes(FSB, FP);
940 // Nothing to update in SSB, since SSB's predecessors haven't changed.
941 }
942}
943
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000944void HexagonEarlyIfConversion::removeBlock(MachineBasicBlock *B) {
945 DEBUG(dbgs() << "Removing block " << PrintMB(B) << "\n");
946
947 // Transfer the immediate dominator information from B to its descendants.
948 MachineDomTreeNode *N = MDT->getNode(B);
949 MachineDomTreeNode *IDN = N->getIDom();
950 if (IDN) {
951 MachineBasicBlock *IDB = IDN->getBlock();
952 typedef GraphTraits<MachineDomTreeNode*> GTN;
953 typedef SmallVector<MachineDomTreeNode*,4> DTNodeVectType;
954 DTNodeVectType Cn(GTN::child_begin(N), GTN::child_end(N));
955 for (DTNodeVectType::iterator I = Cn.begin(), E = Cn.end(); I != E; ++I) {
956 MachineBasicBlock *SB = (*I)->getBlock();
957 MDT->changeImmediateDominator(SB, IDB);
958 }
959 }
960
961 while (B->succ_size() > 0)
962 B->removeSuccessor(B->succ_begin());
963
964 for (auto I = B->pred_begin(), E = B->pred_end(); I != E; ++I)
Cong Houc1069892015-12-13 09:26:17 +0000965 (*I)->removeSuccessor(B, true);
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000966
967 Deleted.insert(B);
968 MDT->eraseNode(B);
Duncan P. N. Exon Smitha72c6e22015-10-20 00:46:39 +0000969 MFN->erase(B->getIterator());
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000970}
971
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000972void HexagonEarlyIfConversion::eliminatePhis(MachineBasicBlock *B) {
973 DEBUG(dbgs() << "Removing phi nodes from block " << PrintMB(B) << "\n");
974 MachineBasicBlock::iterator I, NextI, NonPHI = B->getFirstNonPHI();
975 for (I = B->begin(); I != NonPHI; I = NextI) {
976 NextI = std::next(I);
977 MachineInstr *PN = &*I;
978 assert(PN->getNumOperands() == 3 && "Invalid phi node");
979 MachineOperand &UO = PN->getOperand(1);
980 unsigned UseR = UO.getReg(), UseSR = UO.getSubReg();
981 unsigned DefR = PN->getOperand(0).getReg();
982 unsigned NewR = UseR;
983 if (UseSR) {
984 // MRI.replaceVregUsesWith does not allow to update the subregister,
985 // so instead of doing the use-iteration here, create a copy into a
986 // "non-subregistered" register.
Benjamin Kramer4ca41fd2016-06-12 17:30:47 +0000987 const DebugLoc &DL = PN->getDebugLoc();
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000988 const TargetRegisterClass *RC = MRI->getRegClass(DefR);
989 NewR = MRI->createVirtualRegister(RC);
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +0000990 NonPHI = BuildMI(*B, NonPHI, DL, HII->get(TargetOpcode::COPY), NewR)
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000991 .addReg(UseR, 0, UseSR);
992 }
993 MRI->replaceRegWith(DefR, NewR);
994 B->erase(I);
995 }
996}
997
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +0000998void HexagonEarlyIfConversion::replacePhiEdges(MachineBasicBlock *OldB,
999 MachineBasicBlock *NewB) {
1000 for (auto I = OldB->succ_begin(), E = OldB->succ_end(); I != E; ++I) {
1001 MachineBasicBlock *SB = *I;
1002 MachineBasicBlock::iterator P, N = SB->getFirstNonPHI();
1003 for (P = SB->begin(); P != N; ++P) {
Duncan P. N. Exon Smithf9ab4162016-02-27 17:05:33 +00001004 MachineInstr &PN = *P;
Matthias Braunfc371552016-10-24 21:36:43 +00001005 for (MachineOperand &MO : PN.operands())
1006 if (MO.isMBB() && MO.getMBB() == OldB)
1007 MO.setMBB(NewB);
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +00001008 }
1009 }
1010}
1011
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +00001012void HexagonEarlyIfConversion::mergeBlocks(MachineBasicBlock *PredB,
1013 MachineBasicBlock *SuccB) {
1014 DEBUG(dbgs() << "Merging blocks " << PrintMB(PredB) << " and "
1015 << PrintMB(SuccB) << "\n");
1016 bool TermOk = hasUncondBranch(SuccB);
1017 eliminatePhis(SuccB);
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001018 HII->removeBranch(*PredB);
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +00001019 PredB->removeSuccessor(SuccB);
1020 PredB->splice(PredB->end(), SuccB, SuccB->begin(), SuccB->end());
1021 MachineBasicBlock::succ_iterator I, E = SuccB->succ_end();
1022 for (I = SuccB->succ_begin(); I != E; ++I)
1023 PredB->addSuccessor(*I);
Cong Houc1069892015-12-13 09:26:17 +00001024 PredB->normalizeSuccProbs();
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +00001025 replacePhiEdges(SuccB, PredB);
1026 removeBlock(SuccB);
1027 if (!TermOk)
1028 PredB->updateTerminator();
1029}
1030
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +00001031void HexagonEarlyIfConversion::simplifyFlowGraph(const FlowPattern &FP) {
1032 if (FP.TrueB)
1033 removeBlock(FP.TrueB);
1034 if (FP.FalseB)
1035 removeBlock(FP.FalseB);
1036
1037 FP.SplitB->updateTerminator();
1038 if (FP.SplitB->succ_size() != 1)
1039 return;
1040
1041 MachineBasicBlock *SB = *FP.SplitB->succ_begin();
1042 if (SB->pred_size() != 1)
1043 return;
1044
1045 // By now, the split block has only one successor (SB), and SB has only
1046 // one predecessor. We can try to merge them. We will need to update ter-
1047 // minators in FP.Split+SB, and that requires working AnalyzeBranch, which
1048 // fails on Hexagon for blocks that have EH_LABELs. However, if SB ends
1049 // with an unconditional branch, we won't need to touch the terminators.
1050 if (!hasEHLabel(SB) || hasUncondBranch(SB))
1051 mergeBlocks(FP.SplitB, SB);
1052}
1053
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +00001054bool HexagonEarlyIfConversion::runOnMachineFunction(MachineFunction &MF) {
Andrew Kaylor5b444a22016-04-26 19:46:28 +00001055 if (skipFunction(*MF.getFunction()))
1056 return false;
1057
Krzysztof Parzyszek2a480592016-07-26 20:30:30 +00001058 auto &ST = MF.getSubtarget<HexagonSubtarget>();
1059 HII = ST.getInstrInfo();
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +00001060 TRI = ST.getRegisterInfo();
1061 MFN = &MF;
1062 MRI = &MF.getRegInfo();
1063 MDT = &getAnalysis<MachineDominatorTree>();
1064 MLI = &getAnalysis<MachineLoopInfo>();
1065 MBPI = EnableHexagonBP ? &getAnalysis<MachineBranchProbabilityInfo>() :
1066 nullptr;
1067
1068 Deleted.clear();
1069 bool Changed = false;
1070
1071 for (MachineLoopInfo::iterator I = MLI->begin(), E = MLI->end(); I != E; ++I)
1072 Changed |= visitLoop(*I);
Eugene Zelenkof9f8c682016-12-14 22:50:46 +00001073 Changed |= visitLoop(nullptr);
Krzysztof Parzyszekfb338242015-10-06 15:49:14 +00001074
1075 return Changed;
1076}
1077
1078//===----------------------------------------------------------------------===//
1079// Public Constructor Functions
1080//===----------------------------------------------------------------------===//
1081FunctionPass *llvm::createHexagonEarlyIfConversion() {
1082 return new HexagonEarlyIfConversion();
1083}