#include "HexagonInstrInfo.h"
#include "HexagonSubtarget.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineLoopInfo.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
#include <cassert>
#include <cstdint>
#include <cstdlib>
#include <iterator>
#include <map>
#include <set>
#include <string>
#include <utility>
#include <vector>
using namespace llvm;
#define DEBUG_TYPE "hwloops"
#ifndef NDEBUG
static cl::opt<int> HWLoopLimit("hexagon-max-hwloop", cl::Hidden, cl::init(-1));
static cl::opt<std::string> PHFn("hexagon-hwloop-phfn", cl::Hidden,
cl::init(""));
#endif
static cl::opt<bool> HWCreatePreheader("hexagon-hwloop-preheader",
cl::Hidden, cl::init(true),
cl::desc("Add a preheader to a hardware loop if one doesn't exist"));
static cl::opt<bool> SpecPreheader("hwloop-spec-preheader", cl::Hidden,
cl::desc("Allow speculation of preheader "
"instructions"));
STATISTIC(NumHWLoops, "Number of loops converted to hardware loops");
namespace llvm {
FunctionPass *createHexagonHardwareLoops();
void initializeHexagonHardwareLoopsPass(PassRegistry&);
}
namespace {
class CountValue;
struct HexagonHardwareLoops : public MachineFunctionPass {
MachineLoopInfo *MLI;
MachineRegisterInfo *MRI;
MachineDominatorTree *MDT;
const HexagonInstrInfo *TII;
const HexagonRegisterInfo *TRI;
#ifndef NDEBUG
static int Counter;
#endif
public:
static char ID;
HexagonHardwareLoops() : MachineFunctionPass(ID) {}
bool runOnMachineFunction(MachineFunction &MF) override;
StringRef getPassName() const override { return "Hexagon Hardware Loops"; }
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<MachineDominatorTree>();
AU.addRequired<MachineLoopInfo>();
MachineFunctionPass::getAnalysisUsage(AU);
}
private:
using LoopFeederMap = std::map<unsigned, MachineInstr *>;
struct Comparison {
enum Kind {
EQ = 0x01,
NE = 0x02,
L = 0x04,
G = 0x08,
U = 0x40,
LTs = L,
LEs = L | EQ,
GTs = G,
GEs = G | EQ,
LTu = L | U,
LEu = L | EQ | U,
GTu = G | U,
GEu = G | EQ | U
};
static Kind getSwappedComparison(Kind Cmp) {
assert ((!((Cmp & L) && (Cmp & G))) && "Malformed comparison operator");
if ((Cmp & L) || (Cmp & G))
return (Kind)(Cmp ^ (L|G));
return Cmp;
}
static Kind getNegatedComparison(Kind Cmp) {
if ((Cmp & L) || (Cmp & G))
return (Kind)((Cmp ^ (L | G)) ^ EQ);
if ((Cmp & NE) || (Cmp & EQ))
return (Kind)(Cmp ^ (EQ | NE));
return (Kind)0;
}
static bool isSigned(Kind Cmp) {
return (Cmp & (L | G) && !(Cmp & U));
}
static bool isUnsigned(Kind Cmp) {
return (Cmp & U);
}
};
bool findInductionRegister(MachineLoop *L, unsigned &Reg,
int64_t &IVBump, MachineInstr *&IVOp) const;
Comparison::Kind getComparisonKind(unsigned CondOpc,
MachineOperand *InitialValue,
const MachineOperand *Endvalue,
int64_t IVBump) const;
CountValue *getLoopTripCount(MachineLoop *L,
SmallVectorImpl<MachineInstr *> &OldInsts);
CountValue *computeCount(MachineLoop *Loop, const MachineOperand *Start,
const MachineOperand *End, unsigned IVReg,
int64_t IVBump, Comparison::Kind Cmp) const;
bool isInvalidLoopOperation(const MachineInstr *MI,
bool IsInnerHWLoop) const;
bool containsInvalidInstruction(MachineLoop *L, bool IsInnerHWLoop) const;
bool convertToHardwareLoop(MachineLoop *L, bool &L0used, bool &L1used);
bool isDead(const MachineInstr *MI,
SmallVectorImpl<MachineInstr *> &DeadPhis) const;
void removeIfDead(MachineInstr *MI);
bool orderBumpCompare(MachineInstr *BumpI, MachineInstr *CmpI);
bool isLoopFeeder(MachineLoop *L, MachineBasicBlock *A, MachineInstr *MI,
const MachineOperand *MO,
LoopFeederMap &LoopFeederPhi) const;
bool phiMayWrapOrUnderflow(MachineInstr *Phi, const MachineOperand *EndVal,
MachineBasicBlock *MBB, MachineLoop *L,
LoopFeederMap &LoopFeederPhi) const;
bool loopCountMayWrapOrUnderFlow(const MachineOperand *InitVal,
const MachineOperand *EndVal,
MachineBasicBlock *MBB, MachineLoop *L,
LoopFeederMap &LoopFeederPhi) const;
bool checkForImmediate(const MachineOperand &MO, int64_t &Val) const;
bool isImmediate(const MachineOperand &MO) const {
int64_t V;
return checkForImmediate(MO, V);
}
int64_t getImmediate(const MachineOperand &MO) const {
int64_t V;
if (!checkForImmediate(MO, V))
llvm_unreachable("Invalid operand");
return V;
}
void setImmediate(MachineOperand &MO, int64_t Val);
bool fixupInductionVariable(MachineLoop *L);
MachineBasicBlock *createPreheaderForLoop(MachineLoop *L);
};
char HexagonHardwareLoops::ID = 0;
#ifndef NDEBUG
int HexagonHardwareLoops::Counter = 0;
#endif
class CountValue {
public:
enum CountValueType {
CV_Register,
CV_Immediate
};
private:
CountValueType Kind;
union Values {
struct {
unsigned Reg;
unsigned Sub;
} R;
unsigned ImmVal;
} Contents;
public:
explicit CountValue(CountValueType t, unsigned v, unsigned u = 0) {
Kind = t;
if (Kind == CV_Register) {
Contents.R.Reg = v;
Contents.R.Sub = u;
} else {
Contents.ImmVal = v;
}
}
bool isReg() const { return Kind == CV_Register; }
bool isImm() const { return Kind == CV_Immediate; }
unsigned getReg() const {
assert(isReg() && "Wrong CountValue accessor");
return Contents.R.Reg;
}
unsigned getSubReg() const {
assert(isReg() && "Wrong CountValue accessor");
return Contents.R.Sub;
}
unsigned getImm() const {
assert(isImm() && "Wrong CountValue accessor");
return Contents.ImmVal;
}
void print(raw_ostream &OS, const TargetRegisterInfo *TRI = nullptr) const {
if (isReg()) { OS << printReg(Contents.R.Reg, TRI, Contents.R.Sub); }
if (isImm()) { OS << Contents.ImmVal; }
}
};
}
INITIALIZE_PASS_BEGIN(HexagonHardwareLoops, "hwloops",
"Hexagon Hardware Loops", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
INITIALIZE_PASS_END(HexagonHardwareLoops, "hwloops",
"Hexagon Hardware Loops", false, false)
FunctionPass *llvm::createHexagonHardwareLoops() {
return new HexagonHardwareLoops();
}
bool HexagonHardwareLoops::runOnMachineFunction(MachineFunction &MF) {
LLVM_DEBUG(dbgs() << "********* Hexagon Hardware Loops *********\n");
if (skipFunction(MF.getFunction()))
return false;
bool Changed = false;
MLI = &getAnalysis<MachineLoopInfo>();
MRI = &MF.getRegInfo();
MDT = &getAnalysis<MachineDominatorTree>();
const HexagonSubtarget &HST = MF.getSubtarget<HexagonSubtarget>();
TII = HST.getInstrInfo();
TRI = HST.getRegisterInfo();
for (auto &L : *MLI)
if (L->isOutermost()) {
bool L0Used = false;
bool L1Used = false;
Changed |= convertToHardwareLoop(L, L0Used, L1Used);
}
return Changed;
}
bool HexagonHardwareLoops::findInductionRegister(MachineLoop *L,
unsigned &Reg,
int64_t &IVBump,
MachineInstr *&IVOp
) const {
MachineBasicBlock *Header = L->getHeader();
MachineBasicBlock *Preheader = MLI->findLoopPreheader(L, SpecPreheader);
MachineBasicBlock *Latch = L->getLoopLatch();
MachineBasicBlock *ExitingBlock = L->findLoopControlBlock();
if (!Header || !Preheader || !Latch || !ExitingBlock)
return false;
using RegisterBump = std::pair<unsigned, int64_t>;
using InductionMap = std::map<unsigned, RegisterBump>;
InductionMap IndMap;
using instr_iterator = MachineBasicBlock::instr_iterator;
for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
I != E && I->isPHI(); ++I) {
MachineInstr *Phi = &*I;
for (unsigned i = 1, n = Phi->getNumOperands(); i < n; i += 2) {
if (Phi->getOperand(i+1).getMBB() != Latch)
continue;
Register PhiOpReg = Phi->getOperand(i).getReg();
MachineInstr *DI = MRI->getVRegDef(PhiOpReg);
if (DI->getDesc().isAdd()) {
Register IndReg = DI->getOperand(1).getReg();
MachineOperand &Opnd2 = DI->getOperand(2);
int64_t V;
if (MRI->getVRegDef(IndReg) == Phi && checkForImmediate(Opnd2, V)) {
Register UpdReg = DI->getOperand(0).getReg();
IndMap.insert(std::make_pair(UpdReg, std::make_pair(IndReg, V)));
}
}
} }
SmallVector<MachineOperand,2> Cond;
MachineBasicBlock *TB = nullptr, *FB = nullptr;
bool NotAnalyzed = TII->analyzeBranch(*ExitingBlock, TB, FB, Cond, false);
if (NotAnalyzed)
return false;
unsigned PredR, PredPos, PredRegFlags;
if (!TII->getPredReg(Cond, PredR, PredPos, PredRegFlags))
return false;
MachineInstr *PredI = MRI->getVRegDef(PredR);
if (!PredI->isCompare())
return false;
Register CmpReg1, CmpReg2;
int64_t CmpImm = 0, CmpMask = 0;
bool CmpAnalyzed =
TII->analyzeCompare(*PredI, CmpReg1, CmpReg2, CmpMask, CmpImm);
if (!CmpAnalyzed)
return false;
InductionMap::iterator IndMapEnd = IndMap.end();
InductionMap::iterator F = IndMapEnd;
if (CmpReg1 != 0) {
InductionMap::iterator F1 = IndMap.find(CmpReg1);
if (F1 != IndMapEnd)
F = F1;
}
if (CmpReg2 != 0) {
InductionMap::iterator F2 = IndMap.find(CmpReg2);
if (F2 != IndMapEnd) {
if (F != IndMapEnd)
return false;
F = F2;
}
}
if (F == IndMapEnd)
return false;
Reg = F->second.first;
IVBump = F->second.second;
IVOp = MRI->getVRegDef(F->first);
return true;
}
HexagonHardwareLoops::Comparison::Kind
HexagonHardwareLoops::getComparisonKind(unsigned CondOpc,
MachineOperand *InitialValue,
const MachineOperand *EndValue,
int64_t IVBump) const {
Comparison::Kind Cmp = (Comparison::Kind)0;
switch (CondOpc) {
case Hexagon::C2_cmpeq:
case Hexagon::C2_cmpeqi:
case Hexagon::C2_cmpeqp:
Cmp = Comparison::EQ;
break;
case Hexagon::C4_cmpneq:
case Hexagon::C4_cmpneqi:
Cmp = Comparison::NE;
break;
case Hexagon::C2_cmplt:
Cmp = Comparison::LTs;
break;
case Hexagon::C2_cmpltu:
Cmp = Comparison::LTu;
break;
case Hexagon::C4_cmplte:
case Hexagon::C4_cmpltei:
Cmp = Comparison::LEs;
break;
case Hexagon::C4_cmplteu:
case Hexagon::C4_cmplteui:
Cmp = Comparison::LEu;
break;
case Hexagon::C2_cmpgt:
case Hexagon::C2_cmpgti:
case Hexagon::C2_cmpgtp:
Cmp = Comparison::GTs;
break;
case Hexagon::C2_cmpgtu:
case Hexagon::C2_cmpgtui:
case Hexagon::C2_cmpgtup:
Cmp = Comparison::GTu;
break;
case Hexagon::C2_cmpgei:
Cmp = Comparison::GEs;
break;
case Hexagon::C2_cmpgeui:
Cmp = Comparison::GEs;
break;
default:
return (Comparison::Kind)0;
}
return Cmp;
}
CountValue *HexagonHardwareLoops::getLoopTripCount(MachineLoop *L,
SmallVectorImpl<MachineInstr *> &OldInsts) {
MachineBasicBlock *TopMBB = L->getTopBlock();
MachineBasicBlock::pred_iterator PI = TopMBB->pred_begin();
assert(PI != TopMBB->pred_end() &&
"Loop must have more than one incoming edge!");
MachineBasicBlock *Backedge = *PI++;
if (PI == TopMBB->pred_end()) return nullptr;
MachineBasicBlock *Incoming = *PI++;
if (PI != TopMBB->pred_end()) return nullptr;
if (L->contains(Incoming)) {
if (L->contains(Backedge))
return nullptr;
std::swap(Incoming, Backedge);
} else if (!L->contains(Backedge))
return nullptr;
MachineBasicBlock *ExitingBlock = L->findLoopControlBlock();
if (!ExitingBlock)
return nullptr;
unsigned IVReg = 0;
int64_t IVBump = 0;
MachineInstr *IVOp;
bool FoundIV = findInductionRegister(L, IVReg, IVBump, IVOp);
if (!FoundIV)
return nullptr;
MachineBasicBlock *Preheader = MLI->findLoopPreheader(L, SpecPreheader);
MachineOperand *InitialValue = nullptr;
MachineInstr *IV_Phi = MRI->getVRegDef(IVReg);
MachineBasicBlock *Latch = L->getLoopLatch();
for (unsigned i = 1, n = IV_Phi->getNumOperands(); i < n; i += 2) {
MachineBasicBlock *MBB = IV_Phi->getOperand(i+1).getMBB();
if (MBB == Preheader)
InitialValue = &IV_Phi->getOperand(i);
else if (MBB == Latch)
IVReg = IV_Phi->getOperand(i).getReg(); }
if (!InitialValue)
return nullptr;
SmallVector<MachineOperand,2> Cond;
MachineBasicBlock *TB = nullptr, *FB = nullptr;
bool NotAnalyzed = TII->analyzeBranch(*ExitingBlock, TB, FB, Cond, false);
if (NotAnalyzed)
return nullptr;
MachineBasicBlock *Header = L->getHeader();
assert (TB && "Exit block without a branch?");
if (ExitingBlock != Latch && (TB == Latch || FB == Latch)) {
MachineBasicBlock *LTB = nullptr, *LFB = nullptr;
SmallVector<MachineOperand,2> LCond;
bool NotAnalyzed = TII->analyzeBranch(*Latch, LTB, LFB, LCond, false);
if (NotAnalyzed)
return nullptr;
if (TB == Latch)
TB = (LTB == Header) ? LTB : LFB;
else
FB = (LTB == Header) ? LTB: LFB;
}
assert ((!FB || TB == Header || FB == Header) && "Branches not to header?");
if (!TB || (FB && TB != Header && FB != Header))
return nullptr;
bool Negated = TII->predOpcodeHasNot(Cond) ^ (TB != Header);
unsigned PredReg, PredPos, PredRegFlags;
if (!TII->getPredReg(Cond, PredReg, PredPos, PredRegFlags))
return nullptr;
MachineInstr *CondI = MRI->getVRegDef(PredReg);
unsigned CondOpc = CondI->getOpcode();
Register CmpReg1, CmpReg2;
int64_t Mask = 0, ImmValue = 0;
bool AnalyzedCmp =
TII->analyzeCompare(*CondI, CmpReg1, CmpReg2, Mask, ImmValue);
if (!AnalyzedCmp)
return nullptr;
OldInsts.push_back(CondI);
OldInsts.push_back(IVOp);
Comparison::Kind Cmp;
bool isSwapped = false;
const MachineOperand &Op1 = CondI->getOperand(1);
const MachineOperand &Op2 = CondI->getOperand(2);
const MachineOperand *EndValue = nullptr;
if (Op1.isReg()) {
if (Op2.isImm() || Op1.getReg() == IVReg)
EndValue = &Op2;
else {
EndValue = &Op1;
isSwapped = true;
}
}
if (!EndValue)
return nullptr;
Cmp = getComparisonKind(CondOpc, InitialValue, EndValue, IVBump);
if (!Cmp)
return nullptr;
if (Negated)
Cmp = Comparison::getNegatedComparison(Cmp);
if (isSwapped)
Cmp = Comparison::getSwappedComparison(Cmp);
if (InitialValue->isReg()) {
Register R = InitialValue->getReg();
MachineBasicBlock *DefBB = MRI->getVRegDef(R)->getParent();
if (!MDT->properlyDominates(DefBB, Header)) {
int64_t V;
if (!checkForImmediate(*InitialValue, V))
return nullptr;
}
OldInsts.push_back(MRI->getVRegDef(R));
}
if (EndValue->isReg()) {
Register R = EndValue->getReg();
MachineBasicBlock *DefBB = MRI->getVRegDef(R)->getParent();
if (!MDT->properlyDominates(DefBB, Header)) {
int64_t V;
if (!checkForImmediate(*EndValue, V))
return nullptr;
}
OldInsts.push_back(MRI->getVRegDef(R));
}
return computeCount(L, InitialValue, EndValue, IVReg, IVBump, Cmp);
}
CountValue *HexagonHardwareLoops::computeCount(MachineLoop *Loop,
const MachineOperand *Start,
const MachineOperand *End,
unsigned IVReg,
int64_t IVBump,
Comparison::Kind Cmp) const {
if (Cmp == Comparison::EQ)
return nullptr;
if (Start->isReg()) {
const MachineInstr *StartValInstr = MRI->getVRegDef(Start->getReg());
if (StartValInstr && (StartValInstr->getOpcode() == Hexagon::A2_tfrsi ||
StartValInstr->getOpcode() == Hexagon::A2_tfrpi))
Start = &StartValInstr->getOperand(1);
}
if (End->isReg()) {
const MachineInstr *EndValInstr = MRI->getVRegDef(End->getReg());
if (EndValInstr && (EndValInstr->getOpcode() == Hexagon::A2_tfrsi ||
EndValInstr->getOpcode() == Hexagon::A2_tfrpi))
End = &EndValInstr->getOperand(1);
}
if (!Start->isReg() && !Start->isImm())
return nullptr;
if (!End->isReg() && !End->isImm())
return nullptr;
bool CmpLess = Cmp & Comparison::L;
bool CmpGreater = Cmp & Comparison::G;
bool CmpHasEqual = Cmp & Comparison::EQ;
if (CmpLess && IVBump < 0)
return nullptr;
if (CmpGreater && IVBump > 0)
return nullptr;
LoopFeederMap LoopFeederPhi;
if (loopCountMayWrapOrUnderFlow(Start, End, Loop->getLoopPreheader(), Loop,
LoopFeederPhi))
return nullptr;
if (Start->isImm() && End->isImm()) {
int64_t StartV = Start->getImm();
int64_t EndV = End->getImm();
int64_t Dist = EndV - StartV;
if (Dist == 0)
return nullptr;
bool Exact = (Dist % IVBump) == 0;
if (Cmp == Comparison::NE) {
if (!Exact)
return nullptr;
if ((Dist < 0) ^ (IVBump < 0))
return nullptr;
}
if (CmpHasEqual)
Dist = Dist > 0 ? Dist+1 : Dist-1;
if ((CmpLess && Dist < 0) || (CmpGreater && Dist > 0))
return nullptr;
int64_t Dist1 = (IVBump > 0) ? (Dist + (IVBump - 1)) / IVBump
: (-Dist + (-IVBump - 1)) / (-IVBump);
assert (Dist1 > 0 && "Fishy thing. Both operands have the same sign.");
uint64_t Count = Dist1;
if (Count > 0xFFFFFFFFULL)
return nullptr;
return new CountValue(CountValue::CV_Immediate, Count);
}
if (!isPowerOf2_64(std::abs(IVBump)))
return nullptr;
MachineBasicBlock *PH = MLI->findLoopPreheader(Loop, SpecPreheader);
assert (PH && "Should have a preheader by now");
MachineBasicBlock::iterator InsertPos = PH->getFirstTerminator();
DebugLoc DL;
if (InsertPos != PH->end())
DL = InsertPos->getDebugLoc();
if (IVBump < 0) {
std::swap(Start, End);
IVBump = -IVBump;
}
bool RegToImm = Start->isReg() && End->isImm(); bool RegToReg = Start->isReg() && End->isReg();
int64_t StartV = 0, EndV = 0;
if (Start->isImm())
StartV = Start->getImm();
if (End->isImm())
EndV = End->getImm();
int64_t AdjV = 0;
if (CmpHasEqual) {
if (Start->isImm())
StartV--;
else if (End->isImm())
EndV++;
else
AdjV += 1;
}
if (Cmp != Comparison::NE) {
if (Start->isImm())
StartV -= (IVBump-1);
else if (End->isImm())
EndV += (IVBump-1);
else
AdjV += (IVBump-1);
}
unsigned R = 0, SR = 0;
if (Start->isReg()) {
R = Start->getReg();
SR = Start->getSubReg();
} else {
R = End->getReg();
SR = End->getSubReg();
}
const TargetRegisterClass *RC = MRI->getRegClass(R);
if (!SR && RC == &Hexagon::DoubleRegsRegClass)
return nullptr;
const TargetRegisterClass *IntRC = &Hexagon::IntRegsRegClass;
unsigned DistR, DistSR;
if (Start->isImm() && StartV == 0) {
DistR = End->getReg();
DistSR = End->getSubReg();
} else {
const MCInstrDesc &SubD = RegToReg ? TII->get(Hexagon::A2_sub) :
(RegToImm ? TII->get(Hexagon::A2_subri) :
TII->get(Hexagon::A2_addi));
if (RegToReg || RegToImm) {
Register SubR = MRI->createVirtualRegister(IntRC);
MachineInstrBuilder SubIB =
BuildMI(*PH, InsertPos, DL, SubD, SubR);
if (RegToReg)
SubIB.addReg(End->getReg(), 0, End->getSubReg())
.addReg(Start->getReg(), 0, Start->getSubReg());
else
SubIB.addImm(EndV)
.addReg(Start->getReg(), 0, Start->getSubReg());
DistR = SubR;
} else {
const MachineInstr *EndValInstr = MRI->getVRegDef(End->getReg());
if (EndValInstr->getOpcode() == Hexagon::A2_addi &&
EndValInstr->getOperand(1).getSubReg() == 0 &&
EndValInstr->getOperand(2).getImm() == StartV) {
DistR = EndValInstr->getOperand(1).getReg();
} else {
Register SubR = MRI->createVirtualRegister(IntRC);
MachineInstrBuilder SubIB =
BuildMI(*PH, InsertPos, DL, SubD, SubR);
SubIB.addReg(End->getReg(), 0, End->getSubReg())
.addImm(-StartV);
DistR = SubR;
}
}
DistSR = 0;
}
unsigned AdjR, AdjSR;
if (AdjV == 0) {
AdjR = DistR;
AdjSR = DistSR;
} else {
Register AddR = MRI->createVirtualRegister(IntRC);
MCInstrDesc const &AddD = TII->get(Hexagon::A2_addi);
BuildMI(*PH, InsertPos, DL, AddD, AddR)
.addReg(DistR, 0, DistSR)
.addImm(AdjV);
AdjR = AddR;
AdjSR = 0;
}
unsigned CountR, CountSR;
if (IVBump == 1) {
CountR = AdjR;
CountSR = AdjSR;
} else {
unsigned Shift = Log2_32(IVBump);
Register LsrR = MRI->createVirtualRegister(IntRC);
const MCInstrDesc &LsrD = TII->get(Hexagon::S2_lsr_i_r);
BuildMI(*PH, InsertPos, DL, LsrD, LsrR)
.addReg(AdjR, 0, AdjSR)
.addImm(Shift);
CountR = LsrR;
CountSR = 0;
}
return new CountValue(CountValue::CV_Register, CountR, CountSR);
}
bool HexagonHardwareLoops::isInvalidLoopOperation(const MachineInstr *MI,
bool IsInnerHWLoop) const {
if (MI->getDesc().isCall())
return !TII->doesNotReturn(*MI);
using namespace Hexagon;
static const unsigned Regs01[] = { LC0, SA0, LC1, SA1 };
static const unsigned Regs1[] = { LC1, SA1 };
auto CheckRegs = IsInnerHWLoop ? makeArrayRef(Regs01, array_lengthof(Regs01))
: makeArrayRef(Regs1, array_lengthof(Regs1));
for (unsigned R : CheckRegs)
if (MI->modifiesRegister(R, TRI))
return true;
return false;
}
bool HexagonHardwareLoops::containsInvalidInstruction(MachineLoop *L,
bool IsInnerHWLoop) const {
LLVM_DEBUG(dbgs() << "\nhw_loop head, "
<< printMBBReference(**L->block_begin()));
for (MachineBasicBlock *MBB : L->getBlocks()) {
for (const MachineInstr &MI : *MBB) {
if (isInvalidLoopOperation(&MI, IsInnerHWLoop)) {
LLVM_DEBUG(dbgs() << "\nCannot convert to hw_loop due to:";
MI.dump(););
return true;
}
}
}
return false;
}
bool HexagonHardwareLoops::isDead(const MachineInstr *MI,
SmallVectorImpl<MachineInstr *> &DeadPhis) const {
for (const MachineOperand &MO : MI->operands()) {
if (!MO.isReg() || !MO.isDef())
continue;
Register Reg = MO.getReg();
if (MRI->use_nodbg_empty(Reg))
continue;
using use_nodbg_iterator = MachineRegisterInfo::use_nodbg_iterator;
use_nodbg_iterator I = MRI->use_nodbg_begin(Reg);
use_nodbg_iterator End = MRI->use_nodbg_end();
if (std::next(I) != End || !I->getParent()->isPHI())
return false;
MachineInstr *OnePhi = I->getParent();
for (unsigned j = 0, f = OnePhi->getNumOperands(); j != f; ++j) {
const MachineOperand &OPO = OnePhi->getOperand(j);
if (!OPO.isReg() || !OPO.isDef())
continue;
Register OPReg = OPO.getReg();
use_nodbg_iterator nextJ;
for (use_nodbg_iterator J = MRI->use_nodbg_begin(OPReg);
J != End; J = nextJ) {
nextJ = std::next(J);
MachineOperand &Use = *J;
MachineInstr *UseMI = Use.getParent();
if (MI != UseMI)
return false;
}
}
DeadPhis.push_back(OnePhi);
}
return true;
}
void HexagonHardwareLoops::removeIfDead(MachineInstr *MI) {
SmallVector<MachineInstr*, 1> DeadPhis;
if (isDead(MI, DeadPhis)) {
LLVM_DEBUG(dbgs() << "HW looping will remove: " << *MI);
for (const MachineOperand &MO : MI->operands()) {
if (!MO.isReg() || !MO.isDef())
continue;
Register Reg = MO.getReg();
for (MachineOperand &MO :
llvm::make_early_inc_range(MRI->use_operands(Reg))) {
MachineInstr *UseMI = MO.getParent();
if (UseMI == MI)
continue;
if (MO.isDebug())
MO.setReg(0U);
}
}
MI->eraseFromParent();
for (unsigned i = 0; i < DeadPhis.size(); ++i)
DeadPhis[i]->eraseFromParent();
}
}
bool HexagonHardwareLoops::convertToHardwareLoop(MachineLoop *L,
bool &RecL0used,
bool &RecL1used) {
assert(L->getHeader() && "Loop without a header?");
bool Changed = false;
bool L0Used = false;
bool L1Used = false;
for (MachineLoop *I : *L) {
Changed |= convertToHardwareLoop(I, RecL0used, RecL1used);
L0Used |= RecL0used;
L1Used |= RecL1used;
}
if (Changed && L0Used && L1Used)
return Changed;
unsigned LOOP_i;
unsigned LOOP_r;
unsigned ENDLOOP;
unsigned IsInnerHWLoop = 1;
if (L0Used) {
LOOP_i = Hexagon::J2_loop1i;
LOOP_r = Hexagon::J2_loop1r;
ENDLOOP = Hexagon::ENDLOOP1;
IsInnerHWLoop = 0;
} else {
LOOP_i = Hexagon::J2_loop0i;
LOOP_r = Hexagon::J2_loop0r;
ENDLOOP = Hexagon::ENDLOOP0;
}
#ifndef NDEBUG
int Limit = HWLoopLimit;
if (Limit >= 0) {
if (Counter >= HWLoopLimit)
return false;
Counter++;
}
#endif
if (containsInvalidInstruction(L, IsInnerHWLoop))
return false;
MachineBasicBlock *LastMBB = L->findLoopControlBlock();
if (!LastMBB)
return false;
MachineBasicBlock::iterator LastI = LastMBB->getFirstTerminator();
if (LastI == LastMBB->end())
return false;
if (!fixupInductionVariable(L))
return false;
MachineBasicBlock *Preheader = MLI->findLoopPreheader(L, SpecPreheader);
if (!Preheader) {
Preheader = createPreheaderForLoop(L);
if (!Preheader)
return false;
}
MachineBasicBlock::iterator InsertPos = Preheader->getFirstTerminator();
SmallVector<MachineInstr*, 2> OldInsts;
CountValue *TripCount = getLoopTripCount(L, OldInsts);
if (!TripCount)
return false;
if (TripCount->isReg()) {
MachineInstr *TCDef = MRI->getVRegDef(TripCount->getReg());
MachineBasicBlock *BBDef = TCDef->getParent();
if (!MDT->dominates(BBDef, Preheader))
return false;
}
MachineBasicBlock *TopBlock = L->getTopBlock();
MachineBasicBlock *ExitingBlock = L->findLoopControlBlock();
MachineBasicBlock *LoopStart = nullptr;
if (ExitingBlock != L->getLoopLatch()) {
MachineBasicBlock *TB = nullptr, *FB = nullptr;
SmallVector<MachineOperand, 2> Cond;
if (TII->analyzeBranch(*ExitingBlock, TB, FB, Cond, false))
return false;
if (L->contains(TB))
LoopStart = TB;
else if (L->contains(FB))
LoopStart = FB;
else
return false;
}
else
LoopStart = TopBlock;
LLVM_DEBUG(dbgs() << "Change to hardware loop at "; L->dump());
DebugLoc DL;
if (InsertPos != Preheader->end())
DL = InsertPos->getDebugLoc();
if (TripCount->isReg()) {
Register CountReg = MRI->createVirtualRegister(&Hexagon::IntRegsRegClass);
BuildMI(*Preheader, InsertPos, DL, TII->get(TargetOpcode::COPY), CountReg)
.addReg(TripCount->getReg(), 0, TripCount->getSubReg());
BuildMI(*Preheader, InsertPos, DL, TII->get(LOOP_r)).addMBB(LoopStart)
.addReg(CountReg);
} else {
assert(TripCount->isImm() && "Expecting immediate value for trip count");
int64_t CountImm = TripCount->getImm();
if (!TII->isValidOffset(LOOP_i, CountImm, TRI)) {
Register CountReg = MRI->createVirtualRegister(&Hexagon::IntRegsRegClass);
BuildMI(*Preheader, InsertPos, DL, TII->get(Hexagon::A2_tfrsi), CountReg)
.addImm(CountImm);
BuildMI(*Preheader, InsertPos, DL, TII->get(LOOP_r))
.addMBB(LoopStart).addReg(CountReg);
} else
BuildMI(*Preheader, InsertPos, DL, TII->get(LOOP_i))
.addMBB(LoopStart).addImm(CountImm);
}
LoopStart->setHasAddressTaken();
BlockAddress::get(const_cast<BasicBlock *>(LoopStart->getBasicBlock()));
DebugLoc LastIDL = LastI->getDebugLoc();
BuildMI(*LastMBB, LastI, LastIDL, TII->get(ENDLOOP)).addMBB(LoopStart);
if (LastI->getOpcode() == Hexagon::J2_jumpt ||
LastI->getOpcode() == Hexagon::J2_jumpf) {
MachineBasicBlock *BranchTarget = LastI->getOperand(1).getMBB();
LastI = LastMBB->erase(LastI);
if (!L->contains(BranchTarget)) {
if (LastI != LastMBB->end())
LastI = LastMBB->erase(LastI);
SmallVector<MachineOperand, 0> Cond;
TII->insertBranch(*LastMBB, BranchTarget, nullptr, Cond, LastIDL);
}
} else {
LastMBB->erase(LastI);
}
delete TripCount;
for (unsigned i = 0; i < OldInsts.size(); ++i)
removeIfDead(OldInsts[i]);
++NumHWLoops;
if (L0Used) RecL1used = true;
else
RecL0used = true;
return true;
}
bool HexagonHardwareLoops::orderBumpCompare(MachineInstr *BumpI,
MachineInstr *CmpI) {
assert (BumpI != CmpI && "Bump and compare in the same instruction?");
MachineBasicBlock *BB = BumpI->getParent();
if (CmpI->getParent() != BB)
return false;
using instr_iterator = MachineBasicBlock::instr_iterator;
for (instr_iterator I(BumpI), E = BB->instr_end(); I != E; ++I)
if (&*I == CmpI)
return true;
Register PredR = CmpI->getOperand(0).getReg();
bool FoundBump = false;
instr_iterator CmpIt = CmpI->getIterator(), NextIt = std::next(CmpIt);
for (instr_iterator I = NextIt, E = BB->instr_end(); I != E; ++I) {
MachineInstr *In = &*I;
for (unsigned i = 0, n = In->getNumOperands(); i < n; ++i) {
MachineOperand &MO = In->getOperand(i);
if (MO.isReg() && MO.isUse()) {
if (MO.getReg() == PredR) return false;
}
}
if (In == BumpI) {
BB->splice(++BumpI->getIterator(), BB, CmpI->getIterator());
FoundBump = true;
break;
}
}
assert (FoundBump && "Cannot determine instruction order");
return FoundBump;
}
bool HexagonHardwareLoops::isLoopFeeder(MachineLoop *L, MachineBasicBlock *A,
MachineInstr *MI,
const MachineOperand *MO,
LoopFeederMap &LoopFeederPhi) const {
if (LoopFeederPhi.find(MO->getReg()) == LoopFeederPhi.end()) {
LLVM_DEBUG(dbgs() << "\nhw_loop head, "
<< printMBBReference(**L->block_begin()));
if (llvm::is_contained(L->getBlocks(), A))
return false;
MachineInstr *Def = MRI->getVRegDef(MO->getReg());
LoopFeederPhi.insert(std::make_pair(MO->getReg(), Def));
return true;
} else
return false;
}
bool HexagonHardwareLoops::phiMayWrapOrUnderflow(
MachineInstr *Phi, const MachineOperand *EndVal, MachineBasicBlock *MBB,
MachineLoop *L, LoopFeederMap &LoopFeederPhi) const {
assert(Phi->isPHI() && "Expecting a Phi.");
for (int i = 1, n = Phi->getNumOperands(); i < n; i += 2)
if (isLoopFeeder(L, MBB, Phi, &(Phi->getOperand(i)), LoopFeederPhi))
if (loopCountMayWrapOrUnderFlow(&(Phi->getOperand(i)), EndVal,
Phi->getParent(), L, LoopFeederPhi))
return true;
return false;
}
bool HexagonHardwareLoops::loopCountMayWrapOrUnderFlow(
const MachineOperand *InitVal, const MachineOperand *EndVal,
MachineBasicBlock *MBB, MachineLoop *L,
LoopFeederMap &LoopFeederPhi) const {
if (!InitVal->isReg())
return false;
if (!EndVal->isImm())
return false;
int64_t Imm;
if (checkForImmediate(*InitVal, Imm))
return (EndVal->getImm() == Imm);
Register Reg = InitVal->getReg();
if (!Reg.isVirtual())
return true;
MachineInstr *Def = MRI->getVRegDef(Reg);
if (!Def)
return true;
if (Def->isPHI() && !phiMayWrapOrUnderflow(Def, EndVal, Def->getParent(),
L, LoopFeederPhi))
return false;
if (Def->isCopy() && !loopCountMayWrapOrUnderFlow(&(Def->getOperand(1)),
EndVal, Def->getParent(),
L, LoopFeederPhi))
return false;
for (MachineRegisterInfo::use_instr_nodbg_iterator I = MRI->use_instr_nodbg_begin(Reg),
E = MRI->use_instr_nodbg_end(); I != E; ++I) {
MachineInstr *MI = &*I;
Register CmpReg1, CmpReg2;
int64_t CmpMask = 0, CmpValue = 0;
if (!TII->analyzeCompare(*MI, CmpReg1, CmpReg2, CmpMask, CmpValue))
continue;
MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
SmallVector<MachineOperand, 2> Cond;
if (TII->analyzeBranch(*MI->getParent(), TBB, FBB, Cond, false))
continue;
Comparison::Kind Cmp =
getComparisonKind(MI->getOpcode(), nullptr, nullptr, 0);
if (Cmp == 0)
continue;
if (TII->predOpcodeHasNot(Cond) ^ (TBB != MBB))
Cmp = Comparison::getNegatedComparison(Cmp);
if (CmpReg2 != 0 && CmpReg2 == Reg)
Cmp = Comparison::getSwappedComparison(Cmp);
if (Comparison::isSigned(Cmp))
return false;
if ((Cmp & Comparison::G) || Cmp == Comparison::NE)
return false;
}
if (!Def->isCopy() && !Def->isPHI())
return false;
return true;
}
bool HexagonHardwareLoops::checkForImmediate(const MachineOperand &MO,
int64_t &Val) const {
if (MO.isImm()) {
Val = MO.getImm();
return true;
}
if (!MO.isReg())
return false;
int64_t TV;
Register R = MO.getReg();
if (!R.isVirtual())
return false;
MachineInstr *DI = MRI->getVRegDef(R);
unsigned DOpc = DI->getOpcode();
switch (DOpc) {
case TargetOpcode::COPY:
case Hexagon::A2_tfrsi:
case Hexagon::A2_tfrpi:
case Hexagon::CONST32:
case Hexagon::CONST64:
if (!checkForImmediate(DI->getOperand(1), TV))
return false;
break;
case Hexagon::A2_combineii:
case Hexagon::A4_combineir:
case Hexagon::A4_combineii:
case Hexagon::A4_combineri:
case Hexagon::A2_combinew: {
const MachineOperand &S1 = DI->getOperand(1);
const MachineOperand &S2 = DI->getOperand(2);
int64_t V1, V2;
if (!checkForImmediate(S1, V1) || !checkForImmediate(S2, V2))
return false;
TV = V2 | (static_cast<uint64_t>(V1) << 32);
break;
}
case TargetOpcode::REG_SEQUENCE: {
const MachineOperand &S1 = DI->getOperand(1);
const MachineOperand &S3 = DI->getOperand(3);
int64_t V1, V3;
if (!checkForImmediate(S1, V1) || !checkForImmediate(S3, V3))
return false;
unsigned Sub2 = DI->getOperand(2).getImm();
unsigned Sub4 = DI->getOperand(4).getImm();
if (Sub2 == Hexagon::isub_lo && Sub4 == Hexagon::isub_hi)
TV = V1 | (V3 << 32);
else if (Sub2 == Hexagon::isub_hi && Sub4 == Hexagon::isub_lo)
TV = V3 | (V1 << 32);
else
llvm_unreachable("Unexpected form of REG_SEQUENCE");
break;
}
default:
return false;
}
switch (MO.getSubReg()) {
case Hexagon::isub_lo:
Val = TV & 0xFFFFFFFFULL;
break;
case Hexagon::isub_hi:
Val = (TV >> 32) & 0xFFFFFFFFULL;
break;
default:
Val = TV;
break;
}
return true;
}
void HexagonHardwareLoops::setImmediate(MachineOperand &MO, int64_t Val) {
if (MO.isImm()) {
MO.setImm(Val);
return;
}
assert(MO.isReg());
Register R = MO.getReg();
MachineInstr *DI = MRI->getVRegDef(R);
const TargetRegisterClass *RC = MRI->getRegClass(R);
Register NewR = MRI->createVirtualRegister(RC);
MachineBasicBlock &B = *DI->getParent();
DebugLoc DL = DI->getDebugLoc();
BuildMI(B, DI, DL, TII->get(DI->getOpcode()), NewR).addImm(Val);
MO.setReg(NewR);
}
bool HexagonHardwareLoops::fixupInductionVariable(MachineLoop *L) {
MachineBasicBlock *Header = L->getHeader();
MachineBasicBlock *Latch = L->getLoopLatch();
MachineBasicBlock *ExitingBlock = L->findLoopControlBlock();
if (!(Header && Latch && ExitingBlock))
return false;
using RegisterBump = std::pair<unsigned, int64_t>;
using RegisterInduction = std::pair<unsigned, RegisterBump>;
using RegisterInductionSet = std::set<RegisterInduction>;
RegisterInductionSet IndRegs;
using instr_iterator = MachineBasicBlock::instr_iterator;
for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
I != E && I->isPHI(); ++I) {
MachineInstr *Phi = &*I;
for (unsigned i = 1, n = Phi->getNumOperands(); i < n; i += 2) {
if (Phi->getOperand(i+1).getMBB() != Latch)
continue;
Register PhiReg = Phi->getOperand(i).getReg();
MachineInstr *DI = MRI->getVRegDef(PhiReg);
if (DI->getDesc().isAdd()) {
Register IndReg = DI->getOperand(1).getReg();
MachineOperand &Opnd2 = DI->getOperand(2);
int64_t V;
if (MRI->getVRegDef(IndReg) == Phi && checkForImmediate(Opnd2, V)) {
Register UpdReg = DI->getOperand(0).getReg();
IndRegs.insert(std::make_pair(UpdReg, std::make_pair(IndReg, V)));
}
}
} }
if (IndRegs.empty())
return false;
MachineBasicBlock *TB = nullptr, *FB = nullptr;
SmallVector<MachineOperand,2> Cond;
bool NotAnalyzed = TII->analyzeBranch(*ExitingBlock, TB, FB, Cond, false);
if (NotAnalyzed || Cond.empty())
return false;
if (ExitingBlock != Latch && (TB == Latch || FB == Latch)) {
MachineBasicBlock *LTB = nullptr, *LFB = nullptr;
SmallVector<MachineOperand,2> LCond;
bool NotAnalyzed = TII->analyzeBranch(*Latch, LTB, LFB, LCond, false);
if (NotAnalyzed)
return false;
if (TB == Latch)
TB = (LTB == Header) ? LTB : LFB;
else
FB = (LTB == Header) ? LTB : LFB;
}
if (TB != Header) {
if (FB != Header) {
return false;
}
if (MDT->dominates(TB, FB))
return false;
}
unsigned CSz = Cond.size();
if (CSz != 1 && CSz != 2)
return false;
if (!Cond[CSz-1].isReg())
return false;
Register P = Cond[CSz - 1].getReg();
MachineInstr *PredDef = MRI->getVRegDef(P);
if (!PredDef->isCompare())
return false;
SmallSet<unsigned,2> CmpRegs;
MachineOperand *CmpImmOp = nullptr;
for (unsigned i = 0, n = PredDef->getNumOperands(); i < n; ++i) {
MachineOperand &MO = PredDef->getOperand(i);
if (MO.isReg()) {
if (MO.isImplicit())
continue;
if (MO.isUse()) {
if (!isImmediate(MO)) {
CmpRegs.insert(MO.getReg());
continue;
}
if (CmpImmOp)
return false;
CmpImmOp = &MO;
}
} else if (MO.isImm()) {
if (CmpImmOp) return false;
CmpImmOp = &MO;
}
}
if (CmpRegs.empty())
return false;
for (RegisterInductionSet::iterator I = IndRegs.begin(), E = IndRegs.end();
I != E; ++I) {
if (CmpRegs.count(I->first))
return true;
const RegisterBump &RB = I->second;
if (CmpRegs.count(RB.first)) {
if (!CmpImmOp) {
MachineInstr *IndI = nullptr;
MachineInstr *nonIndI = nullptr;
MachineOperand *IndMO = nullptr;
MachineOperand *nonIndMO = nullptr;
for (unsigned i = 1, n = PredDef->getNumOperands(); i < n; ++i) {
MachineOperand &MO = PredDef->getOperand(i);
if (MO.isReg() && MO.getReg() == RB.first) {
LLVM_DEBUG(dbgs() << "\n DefMI(" << i
<< ") = " << *(MRI->getVRegDef(I->first)));
if (IndI)
return false;
IndI = MRI->getVRegDef(I->first);
IndMO = &MO;
} else if (MO.isReg()) {
LLVM_DEBUG(dbgs() << "\n DefMI(" << i
<< ") = " << *(MRI->getVRegDef(MO.getReg())));
if (nonIndI)
return false;
nonIndI = MRI->getVRegDef(MO.getReg());
nonIndMO = &MO;
}
}
if (IndI && nonIndI &&
nonIndI->getOpcode() == Hexagon::A2_addi &&
nonIndI->getOperand(2).isImm() &&
nonIndI->getOperand(2).getImm() == - RB.second) {
bool Order = orderBumpCompare(IndI, PredDef);
if (Order) {
IndMO->setReg(I->first);
nonIndMO->setReg(nonIndI->getOperand(1).getReg());
return true;
}
}
return false;
}
Comparison::Kind Cmp =
getComparisonKind(PredDef->getOpcode(), nullptr, nullptr, 0);
if (!Cmp || Comparison::isUnsigned(Cmp))
return false;
int64_t CmpImm = getImmediate(*CmpImmOp);
int64_t V = RB.second;
if (((V > 0) && (CmpImm > INT64_MAX - V)) ||
((V < 0) && (CmpImm < INT64_MIN - V)))
return false;
CmpImm += V;
if (CmpImmOp->isImm() && !TII->isExtendable(*PredDef) &&
!TII->isValidOffset(PredDef->getOpcode(), CmpImm, TRI, false))
return false;
MachineInstr *BumpI = MRI->getVRegDef(I->first);
bool Order = orderBumpCompare(BumpI, PredDef);
if (!Order)
return false;
setImmediate(*CmpImmOp, CmpImm);
for (unsigned i = 0, n = PredDef->getNumOperands(); i < n; ++i) {
MachineOperand &MO = PredDef->getOperand(i);
if (MO.isReg() && MO.getReg() == RB.first) {
MO.setReg(I->first);
return true;
}
}
}
}
return false;
}
MachineBasicBlock *HexagonHardwareLoops::createPreheaderForLoop(
MachineLoop *L) {
if (MachineBasicBlock *TmpPH = MLI->findLoopPreheader(L, SpecPreheader))
return TmpPH;
if (!HWCreatePreheader)
return nullptr;
MachineBasicBlock *Header = L->getHeader();
MachineBasicBlock *Latch = L->getLoopLatch();
MachineBasicBlock *ExitingBlock = L->findLoopControlBlock();
MachineFunction *MF = Header->getParent();
DebugLoc DL;
#ifndef NDEBUG
if ((!PHFn.empty()) && (PHFn != MF->getName()))
return nullptr;
#endif
if (!Latch || !ExitingBlock || Header->hasAddressTaken())
return nullptr;
using instr_iterator = MachineBasicBlock::instr_iterator;
using MBBVector = std::vector<MachineBasicBlock *>;
MBBVector Preds(Header->pred_begin(), Header->pred_end());
SmallVector<MachineOperand,2> Tmp1;
MachineBasicBlock *TB = nullptr, *FB = nullptr;
if (TII->analyzeBranch(*ExitingBlock, TB, FB, Tmp1, false))
return nullptr;
for (MachineBasicBlock *PB : Preds) {
bool NotAnalyzed = TII->analyzeBranch(*PB, TB, FB, Tmp1, false);
if (NotAnalyzed)
return nullptr;
}
MachineBasicBlock *NewPH = MF->CreateMachineBasicBlock();
MF->insert(Header->getIterator(), NewPH);
if (Header->pred_size() > 2) {
for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
I != E && I->isPHI(); ++I) {
MachineInstr *PN = &*I;
const MCInstrDesc &PD = TII->get(TargetOpcode::PHI);
MachineInstr *NewPN = MF->CreateMachineInstr(PD, DL);
NewPH->insert(NewPH->end(), NewPN);
Register PR = PN->getOperand(0).getReg();
const TargetRegisterClass *RC = MRI->getRegClass(PR);
Register NewPR = MRI->createVirtualRegister(RC);
NewPN->addOperand(MachineOperand::CreateReg(NewPR, true));
for (unsigned i = 1, n = PN->getNumOperands(); i < n; i += 2) {
Register PredR = PN->getOperand(i).getReg();
unsigned PredRSub = PN->getOperand(i).getSubReg();
MachineBasicBlock *PredB = PN->getOperand(i+1).getMBB();
if (PredB == Latch)
continue;
MachineOperand MO = MachineOperand::CreateReg(PredR, false);
MO.setSubReg(PredRSub);
NewPN->addOperand(MO);
NewPN->addOperand(MachineOperand::CreateMBB(PredB));
}
for (int i = PN->getNumOperands()-2; i > 0; i -= 2) {
MachineBasicBlock *PredB = PN->getOperand(i+1).getMBB();
if (PredB != Latch) {
PN->removeOperand(i+1);
PN->removeOperand(i);
}
}
PN->addOperand(MachineOperand::CreateReg(NewPR, false));
PN->addOperand(MachineOperand::CreateMBB(NewPH));
}
} else {
assert(Header->pred_size() == 2);
for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
I != E && I->isPHI(); ++I) {
MachineInstr *PN = &*I;
for (unsigned i = 1, n = PN->getNumOperands(); i < n; i += 2) {
MachineOperand &MO = PN->getOperand(i+1);
if (MO.getMBB() != Latch)
MO.setMBB(NewPH);
}
}
}
SmallVector<MachineOperand,1> Tmp2;
SmallVector<MachineOperand,1> EmptyCond;
TB = FB = nullptr;
for (MachineBasicBlock *PB : Preds) {
if (PB != Latch) {
Tmp2.clear();
bool NotAnalyzed = TII->analyzeBranch(*PB, TB, FB, Tmp2, false);
(void)NotAnalyzed; assert (!NotAnalyzed && "Should be analyzable!");
if (TB != Header && (Tmp2.empty() || FB != Header))
TII->insertBranch(*PB, NewPH, nullptr, EmptyCond, DL);
PB->ReplaceUsesOfBlockWith(Header, NewPH);
}
}
TB = FB = nullptr;
bool LatchNotAnalyzed = TII->analyzeBranch(*Latch, TB, FB, Tmp2, false);
(void)LatchNotAnalyzed; assert (!LatchNotAnalyzed && "Should be analyzable!");
if (!TB && !FB)
TII->insertBranch(*Latch, Header, nullptr, EmptyCond, DL);
TII->insertBranch(*NewPH, Header, nullptr, EmptyCond, DL);
NewPH->addSuccessor(Header);
MachineLoop *ParentLoop = L->getParentLoop();
if (ParentLoop)
ParentLoop->addBasicBlockToLoop(NewPH, MLI->getBase());
if (MDT) {
if (MachineDomTreeNode *HN = MDT->getNode(Header)) {
if (MachineDomTreeNode *DHN = HN->getIDom()) {
MDT->addNewBlock(NewPH, DHN->getBlock());
MDT->changeImmediateDominator(Header, NewPH);
}
}
}
return NewPH;
}