Path: blob/main/contrib/llvm-project/llvm/lib/Target/Hexagon/HexagonEarlyIfConv.cpp
35267 views
//===- HexagonEarlyIfConv.cpp ---------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This implements a Hexagon-specific if-conversion pass that runs on the9// SSA form.10// In SSA it is not straightforward to represent instructions that condi-11// tionally define registers, since a conditionally-defined register may12// only be used under the same condition on which the definition was based.13// To avoid complications of this nature, this patch will only generate14// predicated stores, and speculate other instructions from the "if-conver-15// ted" block.16// The code will recognize CFG patterns where a block with a conditional17// branch "splits" into a "true block" and a "false block". Either of these18// could be omitted (in case of a triangle, for example).19// If after conversion of the side block(s) the CFG allows it, the resul-20// ting blocks may be merged. If the "join" block contained PHI nodes, they21// will be replaced with MUX (or MUX-like) instructions to maintain the22// semantics of the PHI.23//24// Example:25//26// %40 = L2_loadrub_io killed %39, 127// %41 = S2_tstbit_i killed %40, 028// J2_jumpt killed %41, <%bb.5>, implicit dead %pc29// J2_jump <%bb.4>, implicit dead %pc30// Successors according to CFG: %bb.4(62) %bb.5(62)31//32// %bb.4: derived from LLVM BB %if.then33// Predecessors according to CFG: %bb.334// %11 = A2_addp %6, %1035// S2_storerd_io %32, 16, %1136// Successors according to CFG: %bb.537//38// %bb.5: derived from LLVM BB %if.end39// Predecessors according to CFG: %bb.3 %bb.440// %12 = PHI %6, <%bb.3>, %11, <%bb.4>41// %13 = A2_addp %7, %1242// %42 = C2_cmpeqi %9, 1043// J2_jumpf killed %42, <%bb.3>, implicit dead %pc44// J2_jump <%bb.6>, implicit dead %pc45// Successors according to CFG: %bb.6(4) %bb.3(124)46//47// would become:48//49// %40 = L2_loadrub_io killed %39, 150// %41 = S2_tstbit_i killed %40, 051// spec-> %11 = A2_addp %6, %1052// pred-> S2_pstorerdf_io %41, %32, 16, %1153// %46 = PS_pselect %41, %6, %1154// %13 = A2_addp %7, %4655// %42 = C2_cmpeqi %9, 1056// J2_jumpf killed %42, <%bb.3>, implicit dead %pc57// J2_jump <%bb.6>, implicit dead %pc58// Successors according to CFG: %bb.6 %bb.35960#include "Hexagon.h"61#include "HexagonInstrInfo.h"62#include "HexagonSubtarget.h"63#include "llvm/ADT/DenseSet.h"64#include "llvm/ADT/SmallVector.h"65#include "llvm/ADT/StringRef.h"66#include "llvm/ADT/iterator_range.h"67#include "llvm/CodeGen/MachineBasicBlock.h"68#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"69#include "llvm/CodeGen/MachineDominators.h"70#include "llvm/CodeGen/MachineFunction.h"71#include "llvm/CodeGen/MachineFunctionPass.h"72#include "llvm/CodeGen/MachineInstr.h"73#include "llvm/CodeGen/MachineInstrBuilder.h"74#include "llvm/CodeGen/MachineLoopInfo.h"75#include "llvm/CodeGen/MachineOperand.h"76#include "llvm/CodeGen/MachineRegisterInfo.h"77#include "llvm/CodeGen/TargetRegisterInfo.h"78#include "llvm/IR/DebugLoc.h"79#include "llvm/Pass.h"80#include "llvm/Support/BranchProbability.h"81#include "llvm/Support/CommandLine.h"82#include "llvm/Support/Compiler.h"83#include "llvm/Support/Debug.h"84#include "llvm/Support/ErrorHandling.h"85#include "llvm/Support/raw_ostream.h"86#include <cassert>87#include <iterator>8889#define DEBUG_TYPE "hexagon-eif"9091using namespace llvm;9293namespace llvm {9495FunctionPass *createHexagonEarlyIfConversion();96void initializeHexagonEarlyIfConversionPass(PassRegistry& Registry);9798} // end namespace llvm99100static cl::opt<bool> EnableHexagonBP("enable-hexagon-br-prob", cl::Hidden,101cl::init(true), cl::desc("Enable branch probability info"));102static cl::opt<unsigned> SizeLimit("eif-limit", cl::init(6), cl::Hidden,103cl::desc("Size limit in Hexagon early if-conversion"));104static cl::opt<bool> SkipExitBranches("eif-no-loop-exit", cl::init(false),105cl::Hidden, cl::desc("Do not convert branches that may exit the loop"));106107namespace {108109struct PrintMB {110PrintMB(const MachineBasicBlock *B) : MB(B) {}111112const MachineBasicBlock *MB;113};114raw_ostream &operator<< (raw_ostream &OS, const PrintMB &P) {115if (!P.MB)116return OS << "<none>";117return OS << '#' << P.MB->getNumber();118}119120struct FlowPattern {121FlowPattern() = default;122FlowPattern(MachineBasicBlock *B, unsigned PR, MachineBasicBlock *TB,123MachineBasicBlock *FB, MachineBasicBlock *JB)124: SplitB(B), TrueB(TB), FalseB(FB), JoinB(JB), PredR(PR) {}125126MachineBasicBlock *SplitB = nullptr;127MachineBasicBlock *TrueB = nullptr;128MachineBasicBlock *FalseB = nullptr;129MachineBasicBlock *JoinB = nullptr;130unsigned PredR = 0;131};132133struct PrintFP {134PrintFP(const FlowPattern &P, const TargetRegisterInfo &T)135: FP(P), TRI(T) {}136137const FlowPattern &FP;138const TargetRegisterInfo &TRI;139friend raw_ostream &operator<< (raw_ostream &OS, const PrintFP &P);140};141raw_ostream &operator<<(raw_ostream &OS,142const PrintFP &P) LLVM_ATTRIBUTE_UNUSED;143raw_ostream &operator<<(raw_ostream &OS, const PrintFP &P) {144OS << "{ SplitB:" << PrintMB(P.FP.SplitB)145<< ", PredR:" << printReg(P.FP.PredR, &P.TRI)146<< ", TrueB:" << PrintMB(P.FP.TrueB)147<< ", FalseB:" << PrintMB(P.FP.FalseB)148<< ", JoinB:" << PrintMB(P.FP.JoinB) << " }";149return OS;150}151152class HexagonEarlyIfConversion : public MachineFunctionPass {153public:154static char ID;155156HexagonEarlyIfConversion() : MachineFunctionPass(ID) {}157158StringRef getPassName() const override {159return "Hexagon early if conversion";160}161162void getAnalysisUsage(AnalysisUsage &AU) const override {163AU.addRequired<MachineBranchProbabilityInfoWrapperPass>();164AU.addRequired<MachineDominatorTreeWrapperPass>();165AU.addPreserved<MachineDominatorTreeWrapperPass>();166AU.addRequired<MachineLoopInfoWrapperPass>();167MachineFunctionPass::getAnalysisUsage(AU);168}169170bool runOnMachineFunction(MachineFunction &MF) override;171172private:173using BlockSetType = DenseSet<MachineBasicBlock *>;174175bool isPreheader(const MachineBasicBlock *B) const;176bool matchFlowPattern(MachineBasicBlock *B, MachineLoop *L,177FlowPattern &FP);178bool visitBlock(MachineBasicBlock *B, MachineLoop *L);179bool visitLoop(MachineLoop *L);180181bool hasEHLabel(const MachineBasicBlock *B) const;182bool hasUncondBranch(const MachineBasicBlock *B) const;183bool isValidCandidate(const MachineBasicBlock *B) const;184bool usesUndefVReg(const MachineInstr *MI) const;185bool isValid(const FlowPattern &FP) const;186unsigned countPredicateDefs(const MachineBasicBlock *B) const;187unsigned computePhiCost(const MachineBasicBlock *B,188const FlowPattern &FP) const;189bool isProfitable(const FlowPattern &FP) const;190bool isPredicableStore(const MachineInstr *MI) const;191bool isSafeToSpeculate(const MachineInstr *MI) const;192bool isPredicate(unsigned R) const;193194unsigned getCondStoreOpcode(unsigned Opc, bool IfTrue) const;195void predicateInstr(MachineBasicBlock *ToB, MachineBasicBlock::iterator At,196MachineInstr *MI, unsigned PredR, bool IfTrue);197void predicateBlockNB(MachineBasicBlock *ToB,198MachineBasicBlock::iterator At, MachineBasicBlock *FromB,199unsigned PredR, bool IfTrue);200201unsigned buildMux(MachineBasicBlock *B, MachineBasicBlock::iterator At,202const TargetRegisterClass *DRC, unsigned PredR, unsigned TR,203unsigned TSR, unsigned FR, unsigned FSR);204void updatePhiNodes(MachineBasicBlock *WhereB, const FlowPattern &FP);205void convert(const FlowPattern &FP);206207void removeBlock(MachineBasicBlock *B);208void eliminatePhis(MachineBasicBlock *B);209void mergeBlocks(MachineBasicBlock *PredB, MachineBasicBlock *SuccB);210void simplifyFlowGraph(const FlowPattern &FP);211212const HexagonInstrInfo *HII = nullptr;213const TargetRegisterInfo *TRI = nullptr;214MachineFunction *MFN = nullptr;215MachineRegisterInfo *MRI = nullptr;216MachineDominatorTree *MDT = nullptr;217MachineLoopInfo *MLI = nullptr;218BlockSetType Deleted;219const MachineBranchProbabilityInfo *MBPI = nullptr;220};221222} // end anonymous namespace223224char HexagonEarlyIfConversion::ID = 0;225226INITIALIZE_PASS(HexagonEarlyIfConversion, "hexagon-early-if",227"Hexagon early if conversion", false, false)228229bool HexagonEarlyIfConversion::isPreheader(const MachineBasicBlock *B) const {230if (B->succ_size() != 1)231return false;232MachineBasicBlock *SB = *B->succ_begin();233MachineLoop *L = MLI->getLoopFor(SB);234return L && SB == L->getHeader() && MDT->dominates(B, SB);235}236237bool HexagonEarlyIfConversion::matchFlowPattern(MachineBasicBlock *B,238MachineLoop *L, FlowPattern &FP) {239LLVM_DEBUG(dbgs() << "Checking flow pattern at " << printMBBReference(*B)240<< "\n");241242// Interested only in conditional branches, no .new, no new-value, etc.243// Check the terminators directly, it's easier than handling all responses244// from analyzeBranch.245MachineBasicBlock *TB = nullptr, *FB = nullptr;246MachineBasicBlock::const_iterator T1I = B->getFirstTerminator();247if (T1I == B->end())248return false;249unsigned Opc = T1I->getOpcode();250if (Opc != Hexagon::J2_jumpt && Opc != Hexagon::J2_jumpf)251return false;252Register PredR = T1I->getOperand(0).getReg();253254// Get the layout successor, or 0 if B does not have one.255MachineFunction::iterator NextBI = std::next(MachineFunction::iterator(B));256MachineBasicBlock *NextB = (NextBI != MFN->end()) ? &*NextBI : nullptr;257258MachineBasicBlock *T1B = T1I->getOperand(1).getMBB();259MachineBasicBlock::const_iterator T2I = std::next(T1I);260// The second terminator should be an unconditional branch.261assert(T2I == B->end() || T2I->getOpcode() == Hexagon::J2_jump);262MachineBasicBlock *T2B = (T2I == B->end()) ? NextB263: T2I->getOperand(0).getMBB();264if (T1B == T2B) {265// XXX merge if T1B == NextB, or convert branch to unconditional.266// mark as diamond with both sides equal?267return false;268}269270// Record the true/false blocks in such a way that "true" means "if (PredR)",271// and "false" means "if (!PredR)".272if (Opc == Hexagon::J2_jumpt)273TB = T1B, FB = T2B;274else275TB = T2B, FB = T1B;276277if (!MDT->properlyDominates(B, TB) || !MDT->properlyDominates(B, FB))278return false;279280// Detect triangle first. In case of a triangle, one of the blocks TB/FB281// can fall through into the other, in other words, it will be executed282// in both cases. We only want to predicate the block that is executed283// conditionally.284assert(TB && FB && "Failed to find triangle control flow blocks");285unsigned TNP = TB->pred_size(), FNP = FB->pred_size();286unsigned TNS = TB->succ_size(), FNS = FB->succ_size();287288// A block is predicable if it has one predecessor (it must be B), and289// it has a single successor. In fact, the block has to end either with290// an unconditional branch (which can be predicated), or with a fall-291// through.292// Also, skip blocks that do not belong to the same loop.293bool TOk = (TNP == 1 && TNS == 1 && MLI->getLoopFor(TB) == L);294bool FOk = (FNP == 1 && FNS == 1 && MLI->getLoopFor(FB) == L);295296// If requested (via an option), do not consider branches where the297// true and false targets do not belong to the same loop.298if (SkipExitBranches && MLI->getLoopFor(TB) != MLI->getLoopFor(FB))299return false;300301// If neither is predicable, there is nothing interesting.302if (!TOk && !FOk)303return false;304305MachineBasicBlock *TSB = (TNS > 0) ? *TB->succ_begin() : nullptr;306MachineBasicBlock *FSB = (FNS > 0) ? *FB->succ_begin() : nullptr;307MachineBasicBlock *JB = nullptr;308309if (TOk) {310if (FOk) {311if (TSB == FSB)312JB = TSB;313// Diamond: "if (P) then TB; else FB;".314} else {315// TOk && !FOk316if (TSB == FB)317JB = FB;318FB = nullptr;319}320} else {321// !TOk && FOk (at least one must be true by now).322if (FSB == TB)323JB = TB;324TB = nullptr;325}326// Don't try to predicate loop preheaders.327if ((TB && isPreheader(TB)) || (FB && isPreheader(FB))) {328LLVM_DEBUG(dbgs() << "One of blocks " << PrintMB(TB) << ", " << PrintMB(FB)329<< " is a loop preheader. Skipping.\n");330return false;331}332333FP = FlowPattern(B, PredR, TB, FB, JB);334LLVM_DEBUG(dbgs() << "Detected " << PrintFP(FP, *TRI) << "\n");335return true;336}337338// KLUDGE: HexagonInstrInfo::analyzeBranch won't work on a block that339// contains EH_LABEL.340bool HexagonEarlyIfConversion::hasEHLabel(const MachineBasicBlock *B) const {341for (auto &I : *B)342if (I.isEHLabel())343return true;344return false;345}346347// KLUDGE: HexagonInstrInfo::analyzeBranch may be unable to recognize348// that a block can never fall-through.349bool HexagonEarlyIfConversion::hasUncondBranch(const MachineBasicBlock *B)350const {351MachineBasicBlock::const_iterator I = B->getFirstTerminator(), E = B->end();352while (I != E) {353if (I->isBarrier())354return true;355++I;356}357return false;358}359360bool HexagonEarlyIfConversion::isValidCandidate(const MachineBasicBlock *B)361const {362if (!B)363return true;364if (B->isEHPad() || B->hasAddressTaken())365return false;366if (B->succ_empty())367return false;368369for (auto &MI : *B) {370if (MI.isDebugInstr())371continue;372if (MI.isConditionalBranch())373return false;374unsigned Opc = MI.getOpcode();375bool IsJMP = (Opc == Hexagon::J2_jump);376if (!isPredicableStore(&MI) && !IsJMP && !isSafeToSpeculate(&MI))377return false;378// Look for predicate registers defined by this instruction. It's ok379// to speculate such an instruction, but the predicate register cannot380// be used outside of this block (or else it won't be possible to381// update the use of it after predication). PHI uses will be updated382// to use a result of a MUX, and a MUX cannot be created for predicate383// registers.384for (const MachineOperand &MO : MI.operands()) {385if (!MO.isReg() || !MO.isDef())386continue;387Register R = MO.getReg();388if (!R.isVirtual())389continue;390if (!isPredicate(R))391continue;392for (const MachineOperand &U : MRI->use_operands(R))393if (U.getParent()->isPHI())394return false;395}396}397return true;398}399400bool HexagonEarlyIfConversion::usesUndefVReg(const MachineInstr *MI) const {401for (const MachineOperand &MO : MI->operands()) {402if (!MO.isReg() || !MO.isUse())403continue;404Register R = MO.getReg();405if (!R.isVirtual())406continue;407const MachineInstr *DefI = MRI->getVRegDef(R);408// "Undefined" virtual registers are actually defined via IMPLICIT_DEF.409assert(DefI && "Expecting a reaching def in MRI");410if (DefI->isImplicitDef())411return true;412}413return false;414}415416bool HexagonEarlyIfConversion::isValid(const FlowPattern &FP) const {417if (hasEHLabel(FP.SplitB)) // KLUDGE: see function definition418return false;419if (FP.TrueB && !isValidCandidate(FP.TrueB))420return false;421if (FP.FalseB && !isValidCandidate(FP.FalseB))422return false;423// Check the PHIs in the join block. If any of them use a register424// that is defined as IMPLICIT_DEF, do not convert this. This can425// legitimately happen if one side of the split never executes, but426// the compiler is unable to prove it. That side may then seem to427// provide an "undef" value to the join block, however it will never428// execute at run-time. If we convert this case, the "undef" will429// be used in a MUX instruction, and that may seem like actually430// using an undefined value to other optimizations. This could lead431// to trouble further down the optimization stream, cause assertions432// to fail, etc.433if (FP.JoinB) {434const MachineBasicBlock &B = *FP.JoinB;435for (auto &MI : B) {436if (!MI.isPHI())437break;438if (usesUndefVReg(&MI))439return false;440Register DefR = MI.getOperand(0).getReg();441if (isPredicate(DefR))442return false;443}444}445return true;446}447448unsigned HexagonEarlyIfConversion::computePhiCost(const MachineBasicBlock *B,449const FlowPattern &FP) const {450if (B->pred_size() < 2)451return 0;452453unsigned Cost = 0;454for (const MachineInstr &MI : *B) {455if (!MI.isPHI())456break;457// If both incoming blocks are one of the TrueB/FalseB/SplitB, then458// a MUX may be needed. Otherwise the PHI will need to be updated at459// no extra cost.460// Find the interesting PHI operands for further checks.461SmallVector<unsigned,2> Inc;462for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {463const MachineBasicBlock *BB = MI.getOperand(i+1).getMBB();464if (BB == FP.SplitB || BB == FP.TrueB || BB == FP.FalseB)465Inc.push_back(i);466}467assert(Inc.size() <= 2);468if (Inc.size() < 2)469continue;470471const MachineOperand &RA = MI.getOperand(1);472const MachineOperand &RB = MI.getOperand(3);473assert(RA.isReg() && RB.isReg());474// Must have a MUX if the phi uses a subregister.475if (RA.getSubReg() != 0 || RB.getSubReg() != 0) {476Cost++;477continue;478}479const MachineInstr *Def1 = MRI->getVRegDef(RA.getReg());480const MachineInstr *Def3 = MRI->getVRegDef(RB.getReg());481if (!HII->isPredicable(*Def1) || !HII->isPredicable(*Def3))482Cost++;483}484return Cost;485}486487unsigned HexagonEarlyIfConversion::countPredicateDefs(488const MachineBasicBlock *B) const {489unsigned PredDefs = 0;490for (auto &MI : *B) {491for (const MachineOperand &MO : MI.operands()) {492if (!MO.isReg() || !MO.isDef())493continue;494Register R = MO.getReg();495if (!R.isVirtual())496continue;497if (isPredicate(R))498PredDefs++;499}500}501return PredDefs;502}503504bool HexagonEarlyIfConversion::isProfitable(const FlowPattern &FP) const {505BranchProbability JumpProb(1, 10);506BranchProbability Prob(9, 10);507if (MBPI && FP.TrueB && !FP.FalseB &&508(MBPI->getEdgeProbability(FP.SplitB, FP.TrueB) < JumpProb ||509MBPI->getEdgeProbability(FP.SplitB, FP.TrueB) > Prob))510return false;511512if (MBPI && !FP.TrueB && FP.FalseB &&513(MBPI->getEdgeProbability(FP.SplitB, FP.FalseB) < JumpProb ||514MBPI->getEdgeProbability(FP.SplitB, FP.FalseB) > Prob))515return false;516517if (FP.TrueB && FP.FalseB) {518// Do not IfCovert if the branch is one sided.519if (MBPI) {520if (MBPI->getEdgeProbability(FP.SplitB, FP.TrueB) > Prob)521return false;522if (MBPI->getEdgeProbability(FP.SplitB, FP.FalseB) > Prob)523return false;524}525526// If both sides are predicable, convert them if they join, and the527// join block has no other predecessors.528MachineBasicBlock *TSB = *FP.TrueB->succ_begin();529MachineBasicBlock *FSB = *FP.FalseB->succ_begin();530if (TSB != FSB)531return false;532if (TSB->pred_size() != 2)533return false;534}535536// Calculate the total size of the predicated blocks.537// Assume instruction counts without branches to be the approximation of538// the code size. If the predicated blocks are smaller than a packet size,539// approximate the spare room in the packet that could be filled with the540// predicated/speculated instructions.541auto TotalCount = [] (const MachineBasicBlock *B, unsigned &Spare) {542if (!B)543return 0u;544unsigned T = std::count_if(B->begin(), B->getFirstTerminator(),545[](const MachineInstr &MI) {546return !MI.isMetaInstruction();547});548if (T < HEXAGON_PACKET_SIZE)549Spare += HEXAGON_PACKET_SIZE-T;550return T;551};552unsigned Spare = 0;553unsigned TotalIn = TotalCount(FP.TrueB, Spare) + TotalCount(FP.FalseB, Spare);554LLVM_DEBUG(555dbgs() << "Total number of instructions to be predicated/speculated: "556<< TotalIn << ", spare room: " << Spare << "\n");557if (TotalIn >= SizeLimit+Spare)558return false;559560// Count the number of PHI nodes that will need to be updated (converted561// to MUX). Those can be later converted to predicated instructions, so562// they aren't always adding extra cost.563// KLUDGE: Also, count the number of predicate register definitions in564// each block. The scheduler may increase the pressure of these and cause565// expensive spills (e.g. bitmnp01).566unsigned TotalPh = 0;567unsigned PredDefs = countPredicateDefs(FP.SplitB);568if (FP.JoinB) {569TotalPh = computePhiCost(FP.JoinB, FP);570PredDefs += countPredicateDefs(FP.JoinB);571} else {572if (FP.TrueB && !FP.TrueB->succ_empty()) {573MachineBasicBlock *SB = *FP.TrueB->succ_begin();574TotalPh += computePhiCost(SB, FP);575PredDefs += countPredicateDefs(SB);576}577if (FP.FalseB && !FP.FalseB->succ_empty()) {578MachineBasicBlock *SB = *FP.FalseB->succ_begin();579TotalPh += computePhiCost(SB, FP);580PredDefs += countPredicateDefs(SB);581}582}583LLVM_DEBUG(dbgs() << "Total number of extra muxes from converted phis: "584<< TotalPh << "\n");585if (TotalIn+TotalPh >= SizeLimit+Spare)586return false;587588LLVM_DEBUG(dbgs() << "Total number of predicate registers: " << PredDefs589<< "\n");590if (PredDefs > 4)591return false;592593return true;594}595596bool HexagonEarlyIfConversion::visitBlock(MachineBasicBlock *B,597MachineLoop *L) {598bool Changed = false;599600// Visit all dominated blocks from the same loop first, then process B.601MachineDomTreeNode *N = MDT->getNode(B);602603// We will change CFG/DT during this traversal, so take precautions to604// avoid problems related to invalidated iterators. In fact, processing605// a child C of B cannot cause another child to be removed, but it can606// cause a new child to be added (which was a child of C before C itself607// was removed. This new child C, however, would have been processed608// prior to processing B, so there is no need to process it again.609// Simply keep a list of children of B, and traverse that list.610using DTNodeVectType = SmallVector<MachineDomTreeNode *, 4>;611DTNodeVectType Cn(llvm::children<MachineDomTreeNode *>(N));612for (auto &I : Cn) {613MachineBasicBlock *SB = I->getBlock();614if (!Deleted.count(SB))615Changed |= visitBlock(SB, L);616}617// When walking down the dominator tree, we want to traverse through618// blocks from nested (other) loops, because they can dominate blocks619// that are in L. Skip the non-L blocks only after the tree traversal.620if (MLI->getLoopFor(B) != L)621return Changed;622623FlowPattern FP;624if (!matchFlowPattern(B, L, FP))625return Changed;626627if (!isValid(FP)) {628LLVM_DEBUG(dbgs() << "Conversion is not valid\n");629return Changed;630}631if (!isProfitable(FP)) {632LLVM_DEBUG(dbgs() << "Conversion is not profitable\n");633return Changed;634}635636convert(FP);637simplifyFlowGraph(FP);638return true;639}640641bool HexagonEarlyIfConversion::visitLoop(MachineLoop *L) {642MachineBasicBlock *HB = L ? L->getHeader() : nullptr;643LLVM_DEBUG((L ? dbgs() << "Visiting loop H:" << PrintMB(HB)644: dbgs() << "Visiting function")645<< "\n");646bool Changed = false;647if (L) {648for (MachineLoop *I : *L)649Changed |= visitLoop(I);650}651652MachineBasicBlock *EntryB = GraphTraits<MachineFunction*>::getEntryNode(MFN);653Changed |= visitBlock(L ? HB : EntryB, L);654return Changed;655}656657bool HexagonEarlyIfConversion::isPredicableStore(const MachineInstr *MI)658const {659// HexagonInstrInfo::isPredicable will consider these stores are non-660// -predicable if the offset would become constant-extended after661// predication.662unsigned Opc = MI->getOpcode();663switch (Opc) {664case Hexagon::S2_storerb_io:665case Hexagon::S2_storerbnew_io:666case Hexagon::S2_storerh_io:667case Hexagon::S2_storerhnew_io:668case Hexagon::S2_storeri_io:669case Hexagon::S2_storerinew_io:670case Hexagon::S2_storerd_io:671case Hexagon::S4_storeirb_io:672case Hexagon::S4_storeirh_io:673case Hexagon::S4_storeiri_io:674return true;675}676677// TargetInstrInfo::isPredicable takes a non-const pointer.678return MI->mayStore() && HII->isPredicable(const_cast<MachineInstr&>(*MI));679}680681bool HexagonEarlyIfConversion::isSafeToSpeculate(const MachineInstr *MI)682const {683if (MI->mayLoadOrStore())684return false;685if (MI->isCall() || MI->isBarrier() || MI->isBranch())686return false;687if (MI->hasUnmodeledSideEffects())688return false;689if (MI->getOpcode() == TargetOpcode::LIFETIME_END)690return false;691692return true;693}694695bool HexagonEarlyIfConversion::isPredicate(unsigned R) const {696const TargetRegisterClass *RC = MRI->getRegClass(R);697return RC == &Hexagon::PredRegsRegClass ||698RC == &Hexagon::HvxQRRegClass;699}700701unsigned HexagonEarlyIfConversion::getCondStoreOpcode(unsigned Opc,702bool IfTrue) const {703return HII->getCondOpcode(Opc, !IfTrue);704}705706void HexagonEarlyIfConversion::predicateInstr(MachineBasicBlock *ToB,707MachineBasicBlock::iterator At, MachineInstr *MI,708unsigned PredR, bool IfTrue) {709DebugLoc DL;710if (At != ToB->end())711DL = At->getDebugLoc();712else if (!ToB->empty())713DL = ToB->back().getDebugLoc();714715unsigned Opc = MI->getOpcode();716717if (isPredicableStore(MI)) {718unsigned COpc = getCondStoreOpcode(Opc, IfTrue);719assert(COpc);720MachineInstrBuilder MIB = BuildMI(*ToB, At, DL, HII->get(COpc));721MachineInstr::mop_iterator MOI = MI->operands_begin();722if (HII->isPostIncrement(*MI)) {723MIB.add(*MOI);724++MOI;725}726MIB.addReg(PredR);727for (const MachineOperand &MO : make_range(MOI, MI->operands_end()))728MIB.add(MO);729730// Set memory references.731MIB.cloneMemRefs(*MI);732733MI->eraseFromParent();734return;735}736737if (Opc == Hexagon::J2_jump) {738MachineBasicBlock *TB = MI->getOperand(0).getMBB();739const MCInstrDesc &D = HII->get(IfTrue ? Hexagon::J2_jumpt740: Hexagon::J2_jumpf);741BuildMI(*ToB, At, DL, D)742.addReg(PredR)743.addMBB(TB);744MI->eraseFromParent();745return;746}747748// Print the offending instruction unconditionally as we are about to749// abort.750dbgs() << *MI;751llvm_unreachable("Unexpected instruction");752}753754// Predicate/speculate non-branch instructions from FromB into block ToB.755// Leave the branches alone, they will be handled later. Btw, at this point756// FromB should have at most one branch, and it should be unconditional.757void HexagonEarlyIfConversion::predicateBlockNB(MachineBasicBlock *ToB,758MachineBasicBlock::iterator At, MachineBasicBlock *FromB,759unsigned PredR, bool IfTrue) {760LLVM_DEBUG(dbgs() << "Predicating block " << PrintMB(FromB) << "\n");761MachineBasicBlock::iterator End = FromB->getFirstTerminator();762MachineBasicBlock::iterator I, NextI;763764for (I = FromB->begin(); I != End; I = NextI) {765assert(!I->isPHI());766NextI = std::next(I);767if (isSafeToSpeculate(&*I))768ToB->splice(At, FromB, I);769else770predicateInstr(ToB, At, &*I, PredR, IfTrue);771}772}773774unsigned HexagonEarlyIfConversion::buildMux(MachineBasicBlock *B,775MachineBasicBlock::iterator At, const TargetRegisterClass *DRC,776unsigned PredR, unsigned TR, unsigned TSR, unsigned FR, unsigned FSR) {777unsigned Opc = 0;778switch (DRC->getID()) {779case Hexagon::IntRegsRegClassID:780case Hexagon::IntRegsLow8RegClassID:781Opc = Hexagon::C2_mux;782break;783case Hexagon::DoubleRegsRegClassID:784case Hexagon::GeneralDoubleLow8RegsRegClassID:785Opc = Hexagon::PS_pselect;786break;787case Hexagon::HvxVRRegClassID:788Opc = Hexagon::PS_vselect;789break;790case Hexagon::HvxWRRegClassID:791Opc = Hexagon::PS_wselect;792break;793default:794llvm_unreachable("unexpected register type");795}796const MCInstrDesc &D = HII->get(Opc);797798DebugLoc DL = B->findBranchDebugLoc();799Register MuxR = MRI->createVirtualRegister(DRC);800BuildMI(*B, At, DL, D, MuxR)801.addReg(PredR)802.addReg(TR, 0, TSR)803.addReg(FR, 0, FSR);804return MuxR;805}806807void HexagonEarlyIfConversion::updatePhiNodes(MachineBasicBlock *WhereB,808const FlowPattern &FP) {809// Visit all PHI nodes in the WhereB block and generate MUX instructions810// in the split block. Update the PHI nodes with the values of the MUX.811auto NonPHI = WhereB->getFirstNonPHI();812for (auto I = WhereB->begin(); I != NonPHI; ++I) {813MachineInstr *PN = &*I;814// Registers and subregisters corresponding to TrueB, FalseB and SplitB.815unsigned TR = 0, TSR = 0, FR = 0, FSR = 0, SR = 0, SSR = 0;816for (int i = PN->getNumOperands()-2; i > 0; i -= 2) {817const MachineOperand &RO = PN->getOperand(i), &BO = PN->getOperand(i+1);818if (BO.getMBB() == FP.SplitB)819SR = RO.getReg(), SSR = RO.getSubReg();820else if (BO.getMBB() == FP.TrueB)821TR = RO.getReg(), TSR = RO.getSubReg();822else if (BO.getMBB() == FP.FalseB)823FR = RO.getReg(), FSR = RO.getSubReg();824else825continue;826PN->removeOperand(i+1);827PN->removeOperand(i);828}829if (TR == 0)830TR = SR, TSR = SSR;831else if (FR == 0)832FR = SR, FSR = SSR;833834assert(TR || FR);835unsigned MuxR = 0, MuxSR = 0;836837if (TR && FR) {838Register DR = PN->getOperand(0).getReg();839const TargetRegisterClass *RC = MRI->getRegClass(DR);840MuxR = buildMux(FP.SplitB, FP.SplitB->getFirstTerminator(), RC,841FP.PredR, TR, TSR, FR, FSR);842} else if (TR) {843MuxR = TR;844MuxSR = TSR;845} else {846MuxR = FR;847MuxSR = FSR;848}849850PN->addOperand(MachineOperand::CreateReg(MuxR, false, false, false, false,851false, false, MuxSR));852PN->addOperand(MachineOperand::CreateMBB(FP.SplitB));853}854}855856void HexagonEarlyIfConversion::convert(const FlowPattern &FP) {857MachineBasicBlock *TSB = nullptr, *FSB = nullptr;858MachineBasicBlock::iterator OldTI = FP.SplitB->getFirstTerminator();859assert(OldTI != FP.SplitB->end());860DebugLoc DL = OldTI->getDebugLoc();861862if (FP.TrueB) {863TSB = *FP.TrueB->succ_begin();864predicateBlockNB(FP.SplitB, OldTI, FP.TrueB, FP.PredR, true);865}866if (FP.FalseB) {867FSB = *FP.FalseB->succ_begin();868MachineBasicBlock::iterator At = FP.SplitB->getFirstTerminator();869predicateBlockNB(FP.SplitB, At, FP.FalseB, FP.PredR, false);870}871872// Regenerate new terminators in the split block and update the successors.873// First, remember any information that may be needed later and remove the874// existing terminators/successors from the split block.875MachineBasicBlock *SSB = nullptr;876FP.SplitB->erase(OldTI, FP.SplitB->end());877while (!FP.SplitB->succ_empty()) {878MachineBasicBlock *T = *FP.SplitB->succ_begin();879// It's possible that the split block had a successor that is not a pre-880// dicated block. This could only happen if there was only one block to881// be predicated. Example:882// split_b:883// if (p) jump true_b884// jump unrelated2_b885// unrelated1_b:886// ...887// unrelated2_b: ; can have other predecessors, so it's not "false_b"888// jump other_b889// true_b: ; only reachable from split_b, can be predicated890// ...891//892// Find this successor (SSB) if it exists.893if (T != FP.TrueB && T != FP.FalseB) {894assert(!SSB);895SSB = T;896}897FP.SplitB->removeSuccessor(FP.SplitB->succ_begin());898}899900// Insert new branches and update the successors of the split block. This901// may create unconditional branches to the layout successor, etc., but902// that will be cleaned up later. For now, make sure that correct code is903// generated.904if (FP.JoinB) {905assert(!SSB || SSB == FP.JoinB);906BuildMI(*FP.SplitB, FP.SplitB->end(), DL, HII->get(Hexagon::J2_jump))907.addMBB(FP.JoinB);908FP.SplitB->addSuccessor(FP.JoinB);909} else {910bool HasBranch = false;911if (TSB) {912BuildMI(*FP.SplitB, FP.SplitB->end(), DL, HII->get(Hexagon::J2_jumpt))913.addReg(FP.PredR)914.addMBB(TSB);915FP.SplitB->addSuccessor(TSB);916HasBranch = true;917}918if (FSB) {919const MCInstrDesc &D = HasBranch ? HII->get(Hexagon::J2_jump)920: HII->get(Hexagon::J2_jumpf);921MachineInstrBuilder MIB = BuildMI(*FP.SplitB, FP.SplitB->end(), DL, D);922if (!HasBranch)923MIB.addReg(FP.PredR);924MIB.addMBB(FSB);925FP.SplitB->addSuccessor(FSB);926}927if (SSB) {928// This cannot happen if both TSB and FSB are set. [TF]SB are the929// successor blocks of the TrueB and FalseB (or null of the TrueB930// or FalseB block is null). SSB is the potential successor block931// of the SplitB that is neither TrueB nor FalseB.932BuildMI(*FP.SplitB, FP.SplitB->end(), DL, HII->get(Hexagon::J2_jump))933.addMBB(SSB);934FP.SplitB->addSuccessor(SSB);935}936}937938// What is left to do is to update the PHI nodes that could have entries939// referring to predicated blocks.940if (FP.JoinB) {941updatePhiNodes(FP.JoinB, FP);942} else {943if (TSB)944updatePhiNodes(TSB, FP);945if (FSB)946updatePhiNodes(FSB, FP);947// Nothing to update in SSB, since SSB's predecessors haven't changed.948}949}950951void HexagonEarlyIfConversion::removeBlock(MachineBasicBlock *B) {952LLVM_DEBUG(dbgs() << "Removing block " << PrintMB(B) << "\n");953954// Transfer the immediate dominator information from B to its descendants.955MachineDomTreeNode *N = MDT->getNode(B);956MachineDomTreeNode *IDN = N->getIDom();957if (IDN) {958MachineBasicBlock *IDB = IDN->getBlock();959960using GTN = GraphTraits<MachineDomTreeNode *>;961using DTNodeVectType = SmallVector<MachineDomTreeNode *, 4>;962963DTNodeVectType Cn(GTN::child_begin(N), GTN::child_end(N));964for (auto &I : Cn) {965MachineBasicBlock *SB = I->getBlock();966MDT->changeImmediateDominator(SB, IDB);967}968}969970while (!B->succ_empty())971B->removeSuccessor(B->succ_begin());972973for (MachineBasicBlock *Pred : B->predecessors())974Pred->removeSuccessor(B, true);975976Deleted.insert(B);977MDT->eraseNode(B);978MFN->erase(B->getIterator());979}980981void HexagonEarlyIfConversion::eliminatePhis(MachineBasicBlock *B) {982LLVM_DEBUG(dbgs() << "Removing phi nodes from block " << PrintMB(B) << "\n");983MachineBasicBlock::iterator I, NextI, NonPHI = B->getFirstNonPHI();984for (I = B->begin(); I != NonPHI; I = NextI) {985NextI = std::next(I);986MachineInstr *PN = &*I;987assert(PN->getNumOperands() == 3 && "Invalid phi node");988MachineOperand &UO = PN->getOperand(1);989Register UseR = UO.getReg(), UseSR = UO.getSubReg();990Register DefR = PN->getOperand(0).getReg();991unsigned NewR = UseR;992if (UseSR) {993// MRI.replaceVregUsesWith does not allow to update the subregister,994// so instead of doing the use-iteration here, create a copy into a995// "non-subregistered" register.996const DebugLoc &DL = PN->getDebugLoc();997const TargetRegisterClass *RC = MRI->getRegClass(DefR);998NewR = MRI->createVirtualRegister(RC);999NonPHI = BuildMI(*B, NonPHI, DL, HII->get(TargetOpcode::COPY), NewR)1000.addReg(UseR, 0, UseSR);1001}1002MRI->replaceRegWith(DefR, NewR);1003B->erase(I);1004}1005}10061007void HexagonEarlyIfConversion::mergeBlocks(MachineBasicBlock *PredB,1008MachineBasicBlock *SuccB) {1009LLVM_DEBUG(dbgs() << "Merging blocks " << PrintMB(PredB) << " and "1010<< PrintMB(SuccB) << "\n");1011bool TermOk = hasUncondBranch(SuccB);1012eliminatePhis(SuccB);1013HII->removeBranch(*PredB);1014PredB->removeSuccessor(SuccB);1015PredB->splice(PredB->end(), SuccB, SuccB->begin(), SuccB->end());1016PredB->transferSuccessorsAndUpdatePHIs(SuccB);1017MachineBasicBlock *OldLayoutSuccessor = SuccB->getNextNode();1018removeBlock(SuccB);1019if (!TermOk)1020PredB->updateTerminator(OldLayoutSuccessor);1021}10221023void HexagonEarlyIfConversion::simplifyFlowGraph(const FlowPattern &FP) {1024MachineBasicBlock *OldLayoutSuccessor = FP.SplitB->getNextNode();1025if (FP.TrueB)1026removeBlock(FP.TrueB);1027if (FP.FalseB)1028removeBlock(FP.FalseB);10291030FP.SplitB->updateTerminator(OldLayoutSuccessor);1031if (FP.SplitB->succ_size() != 1)1032return;10331034MachineBasicBlock *SB = *FP.SplitB->succ_begin();1035if (SB->pred_size() != 1)1036return;10371038// By now, the split block has only one successor (SB), and SB has only1039// one predecessor. We can try to merge them. We will need to update ter-1040// minators in FP.Split+SB, and that requires working analyzeBranch, which1041// fails on Hexagon for blocks that have EH_LABELs. However, if SB ends1042// with an unconditional branch, we won't need to touch the terminators.1043if (!hasEHLabel(SB) || hasUncondBranch(SB))1044mergeBlocks(FP.SplitB, SB);1045}10461047bool HexagonEarlyIfConversion::runOnMachineFunction(MachineFunction &MF) {1048if (skipFunction(MF.getFunction()))1049return false;10501051auto &ST = MF.getSubtarget<HexagonSubtarget>();1052HII = ST.getInstrInfo();1053TRI = ST.getRegisterInfo();1054MFN = &MF;1055MRI = &MF.getRegInfo();1056MDT = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();1057MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();1058MBPI = EnableHexagonBP1059? &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI()1060: nullptr;10611062Deleted.clear();1063bool Changed = false;10641065for (MachineLoop *L : *MLI)1066Changed |= visitLoop(L);1067Changed |= visitLoop(nullptr);10681069return Changed;1070}10711072//===----------------------------------------------------------------------===//1073// Public Constructor Functions1074//===----------------------------------------------------------------------===//1075FunctionPass *llvm::createHexagonEarlyIfConversion() {1076return new HexagonEarlyIfConversion();1077}107810791080