Path: blob/main/contrib/llvm-project/llvm/lib/Target/Hexagon/HexagonExpandCondsets.cpp
35269 views
//===- HexagonExpandCondsets.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//===----------------------------------------------------------------------===//78// Replace mux instructions with the corresponding legal instructions.9// It is meant to work post-SSA, but still on virtual registers. It was10// originally placed between register coalescing and machine instruction11// scheduler.12// In this place in the optimization sequence, live interval analysis had13// been performed, and the live intervals should be preserved. A large part14// of the code deals with preserving the liveness information.15//16// Liveness tracking aside, the main functionality of this pass is divided17// into two steps. The first step is to replace an instruction18// %0 = C2_mux %1, %2, %319// with a pair of conditional transfers20// %0 = A2_tfrt %1, %221// %0 = A2_tfrf %1, %322// It is the intention that the execution of this pass could be terminated23// after this step, and the code generated would be functionally correct.24//25// If the uses of the source values %1 and %2 are kills, and their26// definitions are predicable, then in the second step, the conditional27// transfers will then be rewritten as predicated instructions. E.g.28// %0 = A2_or %1, %229// %3 = A2_tfrt %99, killed %030// will be rewritten as31// %3 = A2_port %99, %1, %232//33// This replacement has two variants: "up" and "down". Consider this case:34// %0 = A2_or %1, %235// ... [intervening instructions] ...36// %3 = A2_tfrt %99, killed %037// variant "up":38// %3 = A2_port %99, %1, %239// ... [intervening instructions, %0->vreg3] ...40// [deleted]41// variant "down":42// [deleted]43// ... [intervening instructions] ...44// %3 = A2_port %99, %1, %245//46// Both, one or none of these variants may be valid, and checks are made47// to rule out inapplicable variants.48//49// As an additional optimization, before either of the two steps above is50// executed, the pass attempts to coalesce the target register with one of51// the source registers, e.g. given an instruction52// %3 = C2_mux %0, %1, %253// %3 will be coalesced with either %1 or %2. If this succeeds,54// the instruction would then be (for example)55// %3 = C2_mux %0, %3, %256// and, under certain circumstances, this could result in only one predicated57// instruction:58// %3 = A2_tfrf %0, %259//6061// Splitting a definition of a register into two predicated transfers62// creates a complication in liveness tracking. Live interval computation63// will see both instructions as actual definitions, and will mark the64// first one as dead. The definition is not actually dead, and this65// situation will need to be fixed. For example:66// dead %1 = A2_tfrt ... ; marked as dead67// %1 = A2_tfrf ...68//69// Since any of the individual predicated transfers may end up getting70// removed (in case it is an identity copy), some pre-existing def may71// be marked as dead after live interval recomputation:72// dead %1 = ... ; marked as dead73// ...74// %1 = A2_tfrf ... ; if A2_tfrt is removed75// This case happens if %1 was used as a source in A2_tfrt, which means76// that is it actually live at the A2_tfrf, and so the now dead definition77// of %1 will need to be updated to non-dead at some point.78//79// This issue could be remedied by adding implicit uses to the predicated80// transfers, but this will create a problem with subsequent predication,81// since the transfers will no longer be possible to reorder. To avoid82// that, the initial splitting will not add any implicit uses. These83// implicit uses will be added later, after predication. The extra price,84// however, is that finding the locations where the implicit uses need85// to be added, and updating the live ranges will be more involved.8687#include "HexagonInstrInfo.h"88#include "HexagonRegisterInfo.h"89#include "llvm/ADT/DenseMap.h"90#include "llvm/ADT/SetVector.h"91#include "llvm/ADT/SmallVector.h"92#include "llvm/ADT/StringRef.h"93#include "llvm/CodeGen/LiveInterval.h"94#include "llvm/CodeGen/LiveIntervals.h"95#include "llvm/CodeGen/MachineBasicBlock.h"96#include "llvm/CodeGen/MachineDominators.h"97#include "llvm/CodeGen/MachineFunction.h"98#include "llvm/CodeGen/MachineFunctionPass.h"99#include "llvm/CodeGen/MachineInstr.h"100#include "llvm/CodeGen/MachineInstrBuilder.h"101#include "llvm/CodeGen/MachineOperand.h"102#include "llvm/CodeGen/MachineRegisterInfo.h"103#include "llvm/CodeGen/SlotIndexes.h"104#include "llvm/CodeGen/TargetRegisterInfo.h"105#include "llvm/CodeGen/TargetSubtargetInfo.h"106#include "llvm/IR/DebugLoc.h"107#include "llvm/IR/Function.h"108#include "llvm/InitializePasses.h"109#include "llvm/MC/LaneBitmask.h"110#include "llvm/Pass.h"111#include "llvm/Support/CommandLine.h"112#include "llvm/Support/Debug.h"113#include "llvm/Support/ErrorHandling.h"114#include "llvm/Support/raw_ostream.h"115#include <cassert>116#include <iterator>117#include <map>118#include <set>119#include <utility>120121#define DEBUG_TYPE "expand-condsets"122123using namespace llvm;124125static cl::opt<unsigned> OptTfrLimit("expand-condsets-tfr-limit",126cl::init(~0U), cl::Hidden, cl::desc("Max number of mux expansions"));127static cl::opt<unsigned> OptCoaLimit("expand-condsets-coa-limit",128cl::init(~0U), cl::Hidden, cl::desc("Max number of segment coalescings"));129130namespace llvm {131132void initializeHexagonExpandCondsetsPass(PassRegistry&);133FunctionPass *createHexagonExpandCondsets();134135} // end namespace llvm136137namespace {138139class HexagonExpandCondsets : public MachineFunctionPass {140public:141static char ID;142143HexagonExpandCondsets() : MachineFunctionPass(ID) {144if (OptCoaLimit.getPosition())145CoaLimitActive = true, CoaLimit = OptCoaLimit;146if (OptTfrLimit.getPosition())147TfrLimitActive = true, TfrLimit = OptTfrLimit;148initializeHexagonExpandCondsetsPass(*PassRegistry::getPassRegistry());149}150151StringRef getPassName() const override { return "Hexagon Expand Condsets"; }152153void getAnalysisUsage(AnalysisUsage &AU) const override {154AU.addRequired<LiveIntervalsWrapperPass>();155AU.addPreserved<LiveIntervalsWrapperPass>();156AU.addPreserved<SlotIndexesWrapperPass>();157AU.addRequired<MachineDominatorTreeWrapperPass>();158AU.addPreserved<MachineDominatorTreeWrapperPass>();159MachineFunctionPass::getAnalysisUsage(AU);160}161162bool runOnMachineFunction(MachineFunction &MF) override;163164private:165const HexagonInstrInfo *HII = nullptr;166const TargetRegisterInfo *TRI = nullptr;167MachineDominatorTree *MDT;168MachineRegisterInfo *MRI = nullptr;169LiveIntervals *LIS = nullptr;170bool CoaLimitActive = false;171bool TfrLimitActive = false;172unsigned CoaLimit;173unsigned TfrLimit;174unsigned CoaCounter = 0;175unsigned TfrCounter = 0;176177// FIXME: Consolidate duplicate definitions of RegisterRef178struct RegisterRef {179RegisterRef(const MachineOperand &Op) : Reg(Op.getReg()),180Sub(Op.getSubReg()) {}181RegisterRef(unsigned R = 0, unsigned S = 0) : Reg(R), Sub(S) {}182183bool operator== (RegisterRef RR) const {184return Reg == RR.Reg && Sub == RR.Sub;185}186bool operator!= (RegisterRef RR) const { return !operator==(RR); }187bool operator< (RegisterRef RR) const {188return Reg < RR.Reg || (Reg == RR.Reg && Sub < RR.Sub);189}190191Register Reg;192unsigned Sub;193};194195using ReferenceMap = DenseMap<unsigned, unsigned>;196enum { Sub_Low = 0x1, Sub_High = 0x2, Sub_None = (Sub_Low | Sub_High) };197enum { Exec_Then = 0x10, Exec_Else = 0x20 };198199unsigned getMaskForSub(unsigned Sub);200bool isCondset(const MachineInstr &MI);201LaneBitmask getLaneMask(Register Reg, unsigned Sub);202203void addRefToMap(RegisterRef RR, ReferenceMap &Map, unsigned Exec);204bool isRefInMap(RegisterRef, ReferenceMap &Map, unsigned Exec);205206void updateDeadsInRange(Register Reg, LaneBitmask LM, LiveRange &Range);207void updateKillFlags(Register Reg);208void updateDeadFlags(Register Reg);209void recalculateLiveInterval(Register Reg);210void removeInstr(MachineInstr &MI);211void updateLiveness(const std::set<Register> &RegSet, bool Recalc,212bool UpdateKills, bool UpdateDeads);213void distributeLiveIntervals(const std::set<Register> &Regs);214215unsigned getCondTfrOpcode(const MachineOperand &SO, bool Cond);216MachineInstr *genCondTfrFor(MachineOperand &SrcOp,217MachineBasicBlock::iterator At, unsigned DstR,218unsigned DstSR, const MachineOperand &PredOp, bool PredSense,219bool ReadUndef, bool ImpUse);220bool split(MachineInstr &MI, std::set<Register> &UpdRegs);221222bool isPredicable(MachineInstr *MI);223MachineInstr *getReachingDefForPred(RegisterRef RD,224MachineBasicBlock::iterator UseIt, unsigned PredR, bool Cond);225bool canMoveOver(MachineInstr &MI, ReferenceMap &Defs, ReferenceMap &Uses);226bool canMoveMemTo(MachineInstr &MI, MachineInstr &ToI, bool IsDown);227void predicateAt(const MachineOperand &DefOp, MachineInstr &MI,228MachineBasicBlock::iterator Where,229const MachineOperand &PredOp, bool Cond,230std::set<Register> &UpdRegs);231void renameInRange(RegisterRef RO, RegisterRef RN, unsigned PredR,232bool Cond, MachineBasicBlock::iterator First,233MachineBasicBlock::iterator Last);234bool predicate(MachineInstr &TfrI, bool Cond, std::set<Register> &UpdRegs);235bool predicateInBlock(MachineBasicBlock &B, std::set<Register> &UpdRegs);236237bool isIntReg(RegisterRef RR, unsigned &BW);238bool isIntraBlocks(LiveInterval &LI);239bool coalesceRegisters(RegisterRef R1, RegisterRef R2);240bool coalesceSegments(const SmallVectorImpl<MachineInstr *> &Condsets,241std::set<Register> &UpdRegs);242};243244} // end anonymous namespace245246char HexagonExpandCondsets::ID = 0;247248namespace llvm {249250char &HexagonExpandCondsetsID = HexagonExpandCondsets::ID;251252} // end namespace llvm253254INITIALIZE_PASS_BEGIN(HexagonExpandCondsets, "expand-condsets",255"Hexagon Expand Condsets", false, false)256INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass)257INITIALIZE_PASS_DEPENDENCY(SlotIndexesWrapperPass)258INITIALIZE_PASS_DEPENDENCY(LiveIntervalsWrapperPass)259INITIALIZE_PASS_END(HexagonExpandCondsets, "expand-condsets",260"Hexagon Expand Condsets", false, false)261262unsigned HexagonExpandCondsets::getMaskForSub(unsigned Sub) {263switch (Sub) {264case Hexagon::isub_lo:265case Hexagon::vsub_lo:266return Sub_Low;267case Hexagon::isub_hi:268case Hexagon::vsub_hi:269return Sub_High;270case Hexagon::NoSubRegister:271return Sub_None;272}273llvm_unreachable("Invalid subregister");274}275276bool HexagonExpandCondsets::isCondset(const MachineInstr &MI) {277unsigned Opc = MI.getOpcode();278switch (Opc) {279case Hexagon::C2_mux:280case Hexagon::C2_muxii:281case Hexagon::C2_muxir:282case Hexagon::C2_muxri:283case Hexagon::PS_pselect:284return true;285break;286}287return false;288}289290LaneBitmask HexagonExpandCondsets::getLaneMask(Register Reg, unsigned Sub) {291assert(Reg.isVirtual());292return Sub != 0 ? TRI->getSubRegIndexLaneMask(Sub)293: MRI->getMaxLaneMaskForVReg(Reg);294}295296void HexagonExpandCondsets::addRefToMap(RegisterRef RR, ReferenceMap &Map,297unsigned Exec) {298unsigned Mask = getMaskForSub(RR.Sub) | Exec;299ReferenceMap::iterator F = Map.find(RR.Reg);300if (F == Map.end())301Map.insert(std::make_pair(RR.Reg, Mask));302else303F->second |= Mask;304}305306bool HexagonExpandCondsets::isRefInMap(RegisterRef RR, ReferenceMap &Map,307unsigned Exec) {308ReferenceMap::iterator F = Map.find(RR.Reg);309if (F == Map.end())310return false;311unsigned Mask = getMaskForSub(RR.Sub) | Exec;312if (Mask & F->second)313return true;314return false;315}316317void HexagonExpandCondsets::updateKillFlags(Register Reg) {318auto KillAt = [this,Reg] (SlotIndex K, LaneBitmask LM) -> void {319// Set the <kill> flag on a use of Reg whose lane mask is contained in LM.320MachineInstr *MI = LIS->getInstructionFromIndex(K);321for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {322MachineOperand &Op = MI->getOperand(i);323if (!Op.isReg() || !Op.isUse() || Op.getReg() != Reg ||324MI->isRegTiedToDefOperand(i))325continue;326LaneBitmask SLM = getLaneMask(Reg, Op.getSubReg());327if ((SLM & LM) == SLM) {328// Only set the kill flag on the first encountered use of Reg in this329// instruction.330Op.setIsKill(true);331break;332}333}334};335336LiveInterval &LI = LIS->getInterval(Reg);337for (auto I = LI.begin(), E = LI.end(); I != E; ++I) {338if (!I->end.isRegister())339continue;340// Do not mark the end of the segment as <kill>, if the next segment341// starts with a predicated instruction.342auto NextI = std::next(I);343if (NextI != E && NextI->start.isRegister()) {344MachineInstr *DefI = LIS->getInstructionFromIndex(NextI->start);345if (HII->isPredicated(*DefI))346continue;347}348bool WholeReg = true;349if (LI.hasSubRanges()) {350auto EndsAtI = [I] (LiveInterval::SubRange &S) -> bool {351LiveRange::iterator F = S.find(I->end);352return F != S.end() && I->end == F->end;353};354// Check if all subranges end at I->end. If so, make sure to kill355// the whole register.356for (LiveInterval::SubRange &S : LI.subranges()) {357if (EndsAtI(S))358KillAt(I->end, S.LaneMask);359else360WholeReg = false;361}362}363if (WholeReg)364KillAt(I->end, MRI->getMaxLaneMaskForVReg(Reg));365}366}367368void HexagonExpandCondsets::updateDeadsInRange(Register Reg, LaneBitmask LM,369LiveRange &Range) {370assert(Reg.isVirtual());371if (Range.empty())372return;373374// Return two booleans: { def-modifes-reg, def-covers-reg }.375auto IsRegDef = [this,Reg,LM] (MachineOperand &Op) -> std::pair<bool,bool> {376if (!Op.isReg() || !Op.isDef())377return { false, false };378Register DR = Op.getReg(), DSR = Op.getSubReg();379if (!DR.isVirtual() || DR != Reg)380return { false, false };381LaneBitmask SLM = getLaneMask(DR, DSR);382LaneBitmask A = SLM & LM;383return { A.any(), A == SLM };384};385386// The splitting step will create pairs of predicated definitions without387// any implicit uses (since implicit uses would interfere with predication).388// This can cause the reaching defs to become dead after live range389// recomputation, even though they are not really dead.390// We need to identify predicated defs that need implicit uses, and391// dead defs that are not really dead, and correct both problems.392393auto Dominate = [this] (SetVector<MachineBasicBlock*> &Defs,394MachineBasicBlock *Dest) -> bool {395for (MachineBasicBlock *D : Defs) {396if (D != Dest && MDT->dominates(D, Dest))397return true;398}399MachineBasicBlock *Entry = &Dest->getParent()->front();400SetVector<MachineBasicBlock*> Work(Dest->pred_begin(), Dest->pred_end());401for (unsigned i = 0; i < Work.size(); ++i) {402MachineBasicBlock *B = Work[i];403if (Defs.count(B))404continue;405if (B == Entry)406return false;407for (auto *P : B->predecessors())408Work.insert(P);409}410return true;411};412413// First, try to extend live range within individual basic blocks. This414// will leave us only with dead defs that do not reach any predicated415// defs in the same block.416SetVector<MachineBasicBlock*> Defs;417SmallVector<SlotIndex,4> PredDefs;418for (auto &Seg : Range) {419if (!Seg.start.isRegister())420continue;421MachineInstr *DefI = LIS->getInstructionFromIndex(Seg.start);422Defs.insert(DefI->getParent());423if (HII->isPredicated(*DefI))424PredDefs.push_back(Seg.start);425}426427SmallVector<SlotIndex,8> Undefs;428LiveInterval &LI = LIS->getInterval(Reg);429LI.computeSubRangeUndefs(Undefs, LM, *MRI, *LIS->getSlotIndexes());430431for (auto &SI : PredDefs) {432MachineBasicBlock *BB = LIS->getMBBFromIndex(SI);433auto P = Range.extendInBlock(Undefs, LIS->getMBBStartIdx(BB), SI);434if (P.first != nullptr || P.second)435SI = SlotIndex();436}437438// Calculate reachability for those predicated defs that were not handled439// by the in-block extension.440SmallVector<SlotIndex,4> ExtTo;441for (auto &SI : PredDefs) {442if (!SI.isValid())443continue;444MachineBasicBlock *BB = LIS->getMBBFromIndex(SI);445if (BB->pred_empty())446continue;447// If the defs from this range reach SI via all predecessors, it is live.448// It can happen that SI is reached by the defs through some paths, but449// not all. In the IR coming into this optimization, SI would not be450// considered live, since the defs would then not jointly dominate SI.451// That means that SI is an overwriting def, and no implicit use is452// needed at this point. Do not add SI to the extension points, since453// extendToIndices will abort if there is no joint dominance.454// If the abort was avoided by adding extra undefs added to Undefs,455// extendToIndices could actually indicate that SI is live, contrary456// to the original IR.457if (Dominate(Defs, BB))458ExtTo.push_back(SI);459}460461if (!ExtTo.empty())462LIS->extendToIndices(Range, ExtTo, Undefs);463464// Remove <dead> flags from all defs that are not dead after live range465// extension, and collect all def operands. They will be used to generate466// the necessary implicit uses.467// At the same time, add <dead> flag to all defs that are actually dead.468// This can happen, for example, when a mux with identical inputs is469// replaced with a COPY: the use of the predicate register disappears and470// the dead can become dead.471std::set<RegisterRef> DefRegs;472for (auto &Seg : Range) {473if (!Seg.start.isRegister())474continue;475MachineInstr *DefI = LIS->getInstructionFromIndex(Seg.start);476for (auto &Op : DefI->operands()) {477auto P = IsRegDef(Op);478if (P.second && Seg.end.isDead()) {479Op.setIsDead(true);480} else if (P.first) {481DefRegs.insert(Op);482Op.setIsDead(false);483}484}485}486487// Now, add implicit uses to each predicated def that is reached488// by other defs.489for (auto &Seg : Range) {490if (!Seg.start.isRegister() || !Range.liveAt(Seg.start.getPrevSlot()))491continue;492MachineInstr *DefI = LIS->getInstructionFromIndex(Seg.start);493if (!HII->isPredicated(*DefI))494continue;495// Construct the set of all necessary implicit uses, based on the def496// operands in the instruction. We need to tie the implicit uses to497// the corresponding defs.498std::map<RegisterRef,unsigned> ImpUses;499for (unsigned i = 0, e = DefI->getNumOperands(); i != e; ++i) {500MachineOperand &Op = DefI->getOperand(i);501if (!Op.isReg() || !DefRegs.count(Op))502continue;503if (Op.isDef()) {504// Tied defs will always have corresponding uses, so no extra505// implicit uses are needed.506if (!Op.isTied())507ImpUses.insert({Op, i});508} else {509// This function can be called for the same register with different510// lane masks. If the def in this instruction was for the whole511// register, we can get here more than once. Avoid adding multiple512// implicit uses (or adding an implicit use when an explicit one is513// present).514if (Op.isTied())515ImpUses.erase(Op);516}517}518if (ImpUses.empty())519continue;520MachineFunction &MF = *DefI->getParent()->getParent();521for (auto [R, DefIdx] : ImpUses) {522MachineInstrBuilder(MF, DefI).addReg(R.Reg, RegState::Implicit, R.Sub);523DefI->tieOperands(DefIdx, DefI->getNumOperands()-1);524}525}526}527528void HexagonExpandCondsets::updateDeadFlags(Register Reg) {529LiveInterval &LI = LIS->getInterval(Reg);530if (LI.hasSubRanges()) {531for (LiveInterval::SubRange &S : LI.subranges()) {532updateDeadsInRange(Reg, S.LaneMask, S);533LIS->shrinkToUses(S, Reg);534}535LI.clear();536LIS->constructMainRangeFromSubranges(LI);537} else {538updateDeadsInRange(Reg, MRI->getMaxLaneMaskForVReg(Reg), LI);539}540}541542void HexagonExpandCondsets::recalculateLiveInterval(Register Reg) {543LIS->removeInterval(Reg);544LIS->createAndComputeVirtRegInterval(Reg);545}546547void HexagonExpandCondsets::removeInstr(MachineInstr &MI) {548LIS->RemoveMachineInstrFromMaps(MI);549MI.eraseFromParent();550}551552void HexagonExpandCondsets::updateLiveness(const std::set<Register> &RegSet,553bool Recalc, bool UpdateKills,554bool UpdateDeads) {555UpdateKills |= UpdateDeads;556for (Register R : RegSet) {557if (!R.isVirtual()) {558assert(R.isPhysical());559// There shouldn't be any physical registers as operands, except560// possibly reserved registers.561assert(MRI->isReserved(R));562continue;563}564if (Recalc)565recalculateLiveInterval(R);566if (UpdateKills)567MRI->clearKillFlags(R);568if (UpdateDeads)569updateDeadFlags(R);570// Fixing <dead> flags may extend live ranges, so reset <kill> flags571// after that.572if (UpdateKills)573updateKillFlags(R);574LIS->getInterval(R).verify();575}576}577578void HexagonExpandCondsets::distributeLiveIntervals(579const std::set<Register> &Regs) {580ConnectedVNInfoEqClasses EQC(*LIS);581for (Register R : Regs) {582if (!R.isVirtual())583continue;584LiveInterval &LI = LIS->getInterval(R);585unsigned NumComp = EQC.Classify(LI);586if (NumComp == 1)587continue;588589SmallVector<LiveInterval*> NewLIs;590const TargetRegisterClass *RC = MRI->getRegClass(LI.reg());591for (unsigned I = 1; I < NumComp; ++I) {592Register NewR = MRI->createVirtualRegister(RC);593NewLIs.push_back(&LIS->createEmptyInterval(NewR));594}595EQC.Distribute(LI, NewLIs.begin(), *MRI);596}597}598599/// Get the opcode for a conditional transfer of the value in SO (source600/// operand). The condition (true/false) is given in Cond.601unsigned HexagonExpandCondsets::getCondTfrOpcode(const MachineOperand &SO,602bool IfTrue) {603if (SO.isReg()) {604MCRegister PhysR;605RegisterRef RS = SO;606if (RS.Reg.isVirtual()) {607const TargetRegisterClass *VC = MRI->getRegClass(RS.Reg);608assert(VC->begin() != VC->end() && "Empty register class");609PhysR = *VC->begin();610} else {611PhysR = RS.Reg;612}613MCRegister PhysS = (RS.Sub == 0) ? PhysR : TRI->getSubReg(PhysR, RS.Sub);614const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(PhysS);615switch (TRI->getRegSizeInBits(*RC)) {616case 32:617return IfTrue ? Hexagon::A2_tfrt : Hexagon::A2_tfrf;618case 64:619return IfTrue ? Hexagon::A2_tfrpt : Hexagon::A2_tfrpf;620}621llvm_unreachable("Invalid register operand");622}623switch (SO.getType()) {624case MachineOperand::MO_Immediate:625case MachineOperand::MO_FPImmediate:626case MachineOperand::MO_ConstantPoolIndex:627case MachineOperand::MO_TargetIndex:628case MachineOperand::MO_JumpTableIndex:629case MachineOperand::MO_ExternalSymbol:630case MachineOperand::MO_GlobalAddress:631case MachineOperand::MO_BlockAddress:632return IfTrue ? Hexagon::C2_cmoveit : Hexagon::C2_cmoveif;633default:634break;635}636llvm_unreachable("Unexpected source operand");637}638639/// Generate a conditional transfer, copying the value SrcOp to the640/// destination register DstR:DstSR, and using the predicate register from641/// PredOp. The Cond argument specifies whether the predicate is to be642/// if(PredOp), or if(!PredOp).643MachineInstr *HexagonExpandCondsets::genCondTfrFor(MachineOperand &SrcOp,644MachineBasicBlock::iterator At,645unsigned DstR, unsigned DstSR, const MachineOperand &PredOp,646bool PredSense, bool ReadUndef, bool ImpUse) {647MachineInstr *MI = SrcOp.getParent();648MachineBasicBlock &B = *At->getParent();649const DebugLoc &DL = MI->getDebugLoc();650651// Don't avoid identity copies here (i.e. if the source and the destination652// are the same registers). It is actually better to generate them here,653// since this would cause the copy to potentially be predicated in the next654// step. The predication will remove such a copy if it is unable to655/// predicate.656657unsigned Opc = getCondTfrOpcode(SrcOp, PredSense);658unsigned DstState = RegState::Define | (ReadUndef ? RegState::Undef : 0);659unsigned PredState = getRegState(PredOp) & ~RegState::Kill;660MachineInstrBuilder MIB;661662if (SrcOp.isReg()) {663unsigned SrcState = getRegState(SrcOp);664if (RegisterRef(SrcOp) == RegisterRef(DstR, DstSR))665SrcState &= ~RegState::Kill;666MIB = BuildMI(B, At, DL, HII->get(Opc))667.addReg(DstR, DstState, DstSR)668.addReg(PredOp.getReg(), PredState, PredOp.getSubReg())669.addReg(SrcOp.getReg(), SrcState, SrcOp.getSubReg());670} else {671MIB = BuildMI(B, At, DL, HII->get(Opc))672.addReg(DstR, DstState, DstSR)673.addReg(PredOp.getReg(), PredState, PredOp.getSubReg())674.add(SrcOp);675}676677LLVM_DEBUG(dbgs() << "created an initial copy: " << *MIB);678return &*MIB;679}680681/// Replace a MUX instruction MI with a pair A2_tfrt/A2_tfrf. This function682/// performs all necessary changes to complete the replacement.683bool HexagonExpandCondsets::split(MachineInstr &MI,684std::set<Register> &UpdRegs) {685if (TfrLimitActive) {686if (TfrCounter >= TfrLimit)687return false;688TfrCounter++;689}690LLVM_DEBUG(dbgs() << "\nsplitting " << printMBBReference(*MI.getParent())691<< ": " << MI);692MachineOperand &MD = MI.getOperand(0); // Definition693MachineOperand &MP = MI.getOperand(1); // Predicate register694assert(MD.isDef());695Register DR = MD.getReg(), DSR = MD.getSubReg();696bool ReadUndef = MD.isUndef();697MachineBasicBlock::iterator At = MI;698699auto updateRegs = [&UpdRegs] (const MachineInstr &MI) -> void {700for (auto &Op : MI.operands()) {701if (Op.isReg())702UpdRegs.insert(Op.getReg());703}704};705706// If this is a mux of the same register, just replace it with COPY.707// Ideally, this would happen earlier, so that register coalescing would708// see it.709MachineOperand &ST = MI.getOperand(2);710MachineOperand &SF = MI.getOperand(3);711if (ST.isReg() && SF.isReg()) {712RegisterRef RT(ST);713if (RT == RegisterRef(SF)) {714// Copy regs to update first.715updateRegs(MI);716MI.setDesc(HII->get(TargetOpcode::COPY));717unsigned S = getRegState(ST);718while (MI.getNumOperands() > 1)719MI.removeOperand(MI.getNumOperands()-1);720MachineFunction &MF = *MI.getParent()->getParent();721MachineInstrBuilder(MF, MI).addReg(RT.Reg, S, RT.Sub);722return true;723}724}725726// First, create the two invididual conditional transfers, and add each727// of them to the live intervals information. Do that first and then remove728// the old instruction from live intervals.729MachineInstr *TfrT =730genCondTfrFor(ST, At, DR, DSR, MP, true, ReadUndef, false);731MachineInstr *TfrF =732genCondTfrFor(SF, At, DR, DSR, MP, false, ReadUndef, true);733LIS->InsertMachineInstrInMaps(*TfrT);734LIS->InsertMachineInstrInMaps(*TfrF);735736// Will need to recalculate live intervals for all registers in MI.737updateRegs(MI);738739removeInstr(MI);740return true;741}742743bool HexagonExpandCondsets::isPredicable(MachineInstr *MI) {744if (HII->isPredicated(*MI) || !HII->isPredicable(*MI))745return false;746if (MI->hasUnmodeledSideEffects() || MI->mayStore())747return false;748// Reject instructions with multiple defs (e.g. post-increment loads).749bool HasDef = false;750for (auto &Op : MI->operands()) {751if (!Op.isReg() || !Op.isDef())752continue;753if (HasDef)754return false;755HasDef = true;756}757for (auto &Mo : MI->memoperands()) {758if (Mo->isVolatile() || Mo->isAtomic())759return false;760}761return true;762}763764/// Find the reaching definition for a predicated use of RD. The RD is used765/// under the conditions given by PredR and Cond, and this function will ignore766/// definitions that set RD under the opposite conditions.767MachineInstr *HexagonExpandCondsets::getReachingDefForPred(RegisterRef RD,768MachineBasicBlock::iterator UseIt, unsigned PredR, bool Cond) {769MachineBasicBlock &B = *UseIt->getParent();770MachineBasicBlock::iterator I = UseIt, S = B.begin();771if (I == S)772return nullptr;773774bool PredValid = true;775do {776--I;777MachineInstr *MI = &*I;778// Check if this instruction can be ignored, i.e. if it is predicated779// on the complementary condition.780if (PredValid && HII->isPredicated(*MI)) {781if (MI->readsRegister(PredR, /*TRI=*/nullptr) &&782(Cond != HII->isPredicatedTrue(*MI)))783continue;784}785786// Check the defs. If the PredR is defined, invalidate it. If RD is787// defined, return the instruction or 0, depending on the circumstances.788for (auto &Op : MI->operands()) {789if (!Op.isReg() || !Op.isDef())790continue;791RegisterRef RR = Op;792if (RR.Reg == PredR) {793PredValid = false;794continue;795}796if (RR.Reg != RD.Reg)797continue;798// If the "Reg" part agrees, there is still the subregister to check.799// If we are looking for %1:loreg, we can skip %1:hireg, but800// not %1 (w/o subregisters).801if (RR.Sub == RD.Sub)802return MI;803if (RR.Sub == 0 || RD.Sub == 0)804return nullptr;805// We have different subregisters, so we can continue looking.806}807} while (I != S);808809return nullptr;810}811812/// Check if the instruction MI can be safely moved over a set of instructions813/// whose side-effects (in terms of register defs and uses) are expressed in814/// the maps Defs and Uses. These maps reflect the conditional defs and uses815/// that depend on the same predicate register to allow moving instructions816/// over instructions predicated on the opposite condition.817bool HexagonExpandCondsets::canMoveOver(MachineInstr &MI, ReferenceMap &Defs,818ReferenceMap &Uses) {819// In order to be able to safely move MI over instructions that define820// "Defs" and use "Uses", no def operand from MI can be defined or used821// and no use operand can be defined.822for (auto &Op : MI.operands()) {823if (!Op.isReg())824continue;825RegisterRef RR = Op;826// For physical register we would need to check register aliases, etc.827// and we don't want to bother with that. It would be of little value828// before the actual register rewriting (from virtual to physical).829if (!RR.Reg.isVirtual())830return false;831// No redefs for any operand.832if (isRefInMap(RR, Defs, Exec_Then))833return false;834// For defs, there cannot be uses.835if (Op.isDef() && isRefInMap(RR, Uses, Exec_Then))836return false;837}838return true;839}840841/// Check if the instruction accessing memory (TheI) can be moved to the842/// location ToI.843bool HexagonExpandCondsets::canMoveMemTo(MachineInstr &TheI, MachineInstr &ToI,844bool IsDown) {845bool IsLoad = TheI.mayLoad(), IsStore = TheI.mayStore();846if (!IsLoad && !IsStore)847return true;848if (HII->areMemAccessesTriviallyDisjoint(TheI, ToI))849return true;850if (TheI.hasUnmodeledSideEffects())851return false;852853MachineBasicBlock::iterator StartI = IsDown ? TheI : ToI;854MachineBasicBlock::iterator EndI = IsDown ? ToI : TheI;855bool Ordered = TheI.hasOrderedMemoryRef();856857// Search for aliased memory reference in (StartI, EndI).858for (MachineInstr &MI : llvm::make_range(std::next(StartI), EndI)) {859if (MI.hasUnmodeledSideEffects())860return false;861bool L = MI.mayLoad(), S = MI.mayStore();862if (!L && !S)863continue;864if (Ordered && MI.hasOrderedMemoryRef())865return false;866867bool Conflict = (L && IsStore) || S;868if (Conflict)869return false;870}871return true;872}873874/// Generate a predicated version of MI (where the condition is given via875/// PredR and Cond) at the point indicated by Where.876void HexagonExpandCondsets::predicateAt(const MachineOperand &DefOp,877MachineInstr &MI,878MachineBasicBlock::iterator Where,879const MachineOperand &PredOp, bool Cond,880std::set<Register> &UpdRegs) {881// The problem with updating live intervals is that we can move one def882// past another def. In particular, this can happen when moving an A2_tfrt883// over an A2_tfrf defining the same register. From the point of view of884// live intervals, these two instructions are two separate definitions,885// and each one starts another live segment. LiveIntervals's "handleMove"886// does not allow such moves, so we need to handle it ourselves. To avoid887// invalidating liveness data while we are using it, the move will be888// implemented in 4 steps: (1) add a clone of the instruction MI at the889// target location, (2) update liveness, (3) delete the old instruction,890// and (4) update liveness again.891892MachineBasicBlock &B = *MI.getParent();893DebugLoc DL = Where->getDebugLoc(); // "Where" points to an instruction.894unsigned Opc = MI.getOpcode();895unsigned PredOpc = HII->getCondOpcode(Opc, !Cond);896MachineInstrBuilder MB = BuildMI(B, Where, DL, HII->get(PredOpc));897unsigned Ox = 0, NP = MI.getNumOperands();898// Skip all defs from MI first.899while (Ox < NP) {900MachineOperand &MO = MI.getOperand(Ox);901if (!MO.isReg() || !MO.isDef())902break;903Ox++;904}905// Add the new def, then the predicate register, then the rest of the906// operands.907MB.addReg(DefOp.getReg(), getRegState(DefOp), DefOp.getSubReg());908MB.addReg(PredOp.getReg(), PredOp.isUndef() ? RegState::Undef : 0,909PredOp.getSubReg());910while (Ox < NP) {911MachineOperand &MO = MI.getOperand(Ox);912if (!MO.isReg() || !MO.isImplicit())913MB.add(MO);914Ox++;915}916MB.cloneMemRefs(MI);917918MachineInstr *NewI = MB;919NewI->clearKillInfo();920LIS->InsertMachineInstrInMaps(*NewI);921922for (auto &Op : NewI->operands()) {923if (Op.isReg())924UpdRegs.insert(Op.getReg());925}926}927928/// In the range [First, Last], rename all references to the "old" register RO929/// to the "new" register RN, but only in instructions predicated on the given930/// condition.931void HexagonExpandCondsets::renameInRange(RegisterRef RO, RegisterRef RN,932unsigned PredR, bool Cond, MachineBasicBlock::iterator First,933MachineBasicBlock::iterator Last) {934MachineBasicBlock::iterator End = std::next(Last);935for (MachineInstr &MI : llvm::make_range(First, End)) {936// Do not touch instructions that are not predicated, or are predicated937// on the opposite condition.938if (!HII->isPredicated(MI))939continue;940if (!MI.readsRegister(PredR, /*TRI=*/nullptr) ||941(Cond != HII->isPredicatedTrue(MI)))942continue;943944for (auto &Op : MI.operands()) {945if (!Op.isReg() || RO != RegisterRef(Op))946continue;947Op.setReg(RN.Reg);948Op.setSubReg(RN.Sub);949// In practice, this isn't supposed to see any defs.950assert(!Op.isDef() && "Not expecting a def");951}952}953}954955/// For a given conditional copy, predicate the definition of the source of956/// the copy under the given condition (using the same predicate register as957/// the copy).958bool HexagonExpandCondsets::predicate(MachineInstr &TfrI, bool Cond,959std::set<Register> &UpdRegs) {960// TfrI - A2_tfr[tf] Instruction (not A2_tfrsi).961unsigned Opc = TfrI.getOpcode();962(void)Opc;963assert(Opc == Hexagon::A2_tfrt || Opc == Hexagon::A2_tfrf);964LLVM_DEBUG(dbgs() << "\nattempt to predicate if-" << (Cond ? "true" : "false")965<< ": " << TfrI);966967MachineOperand &MD = TfrI.getOperand(0);968MachineOperand &MP = TfrI.getOperand(1);969MachineOperand &MS = TfrI.getOperand(2);970// The source operand should be a <kill>. This is not strictly necessary,971// but it makes things a lot simpler. Otherwise, we would need to rename972// some registers, which would complicate the transformation considerably.973if (!MS.isKill())974return false;975// Avoid predicating instructions that define a subregister if subregister976// liveness tracking is not enabled.977if (MD.getSubReg() && !MRI->shouldTrackSubRegLiveness(MD.getReg()))978return false;979980RegisterRef RT(MS);981Register PredR = MP.getReg();982MachineInstr *DefI = getReachingDefForPred(RT, TfrI, PredR, Cond);983if (!DefI || !isPredicable(DefI))984return false;985986LLVM_DEBUG(dbgs() << "Source def: " << *DefI);987988// Collect the information about registers defined and used between the989// DefI and the TfrI.990// Map: reg -> bitmask of subregs991ReferenceMap Uses, Defs;992MachineBasicBlock::iterator DefIt = DefI, TfrIt = TfrI;993994// Check if the predicate register is valid between DefI and TfrI.995// If it is, we can then ignore instructions predicated on the negated996// conditions when collecting def and use information.997bool PredValid = true;998for (MachineInstr &MI : llvm::make_range(std::next(DefIt), TfrIt)) {999if (!MI.modifiesRegister(PredR, nullptr))1000continue;1001PredValid = false;1002break;1003}10041005for (MachineInstr &MI : llvm::make_range(std::next(DefIt), TfrIt)) {1006// If this instruction is predicated on the same register, it could1007// potentially be ignored.1008// By default assume that the instruction executes on the same condition1009// as TfrI (Exec_Then), and also on the opposite one (Exec_Else).1010unsigned Exec = Exec_Then | Exec_Else;1011if (PredValid && HII->isPredicated(MI) &&1012MI.readsRegister(PredR, /*TRI=*/nullptr))1013Exec = (Cond == HII->isPredicatedTrue(MI)) ? Exec_Then : Exec_Else;10141015for (auto &Op : MI.operands()) {1016if (!Op.isReg())1017continue;1018// We don't want to deal with physical registers. The reason is that1019// they can be aliased with other physical registers. Aliased virtual1020// registers must share the same register number, and can only differ1021// in the subregisters, which we are keeping track of. Physical1022// registers ters no longer have subregisters---their super- and1023// subregisters are other physical registers, and we are not checking1024// that.1025RegisterRef RR = Op;1026if (!RR.Reg.isVirtual())1027return false;10281029ReferenceMap &Map = Op.isDef() ? Defs : Uses;1030if (Op.isDef() && Op.isUndef()) {1031assert(RR.Sub && "Expecting a subregister on <def,read-undef>");1032// If this is a <def,read-undef>, then it invalidates the non-written1033// part of the register. For the purpose of checking the validity of1034// the move, assume that it modifies the whole register.1035RR.Sub = 0;1036}1037addRefToMap(RR, Map, Exec);1038}1039}10401041// The situation:1042// RT = DefI1043// ...1044// RD = TfrI ..., RT10451046// If the register-in-the-middle (RT) is used or redefined between1047// DefI and TfrI, we may not be able proceed with this transformation.1048// We can ignore a def that will not execute together with TfrI, and a1049// use that will. If there is such a use (that does execute together with1050// TfrI), we will not be able to move DefI down. If there is a use that1051// executed if TfrI's condition is false, then RT must be available1052// unconditionally (cannot be predicated).1053// Essentially, we need to be able to rename RT to RD in this segment.1054if (isRefInMap(RT, Defs, Exec_Then) || isRefInMap(RT, Uses, Exec_Else))1055return false;1056RegisterRef RD = MD;1057// If the predicate register is defined between DefI and TfrI, the only1058// potential thing to do would be to move the DefI down to TfrI, and then1059// predicate. The reaching def (DefI) must be movable down to the location1060// of the TfrI.1061// If the target register of the TfrI (RD) is not used or defined between1062// DefI and TfrI, consider moving TfrI up to DefI.1063bool CanUp = canMoveOver(TfrI, Defs, Uses);1064bool CanDown = canMoveOver(*DefI, Defs, Uses);1065// The TfrI does not access memory, but DefI could. Check if it's safe1066// to move DefI down to TfrI.1067if (DefI->mayLoadOrStore()) {1068if (!canMoveMemTo(*DefI, TfrI, true))1069CanDown = false;1070}10711072LLVM_DEBUG(dbgs() << "Can move up: " << (CanUp ? "yes" : "no")1073<< ", can move down: " << (CanDown ? "yes\n" : "no\n"));1074MachineBasicBlock::iterator PastDefIt = std::next(DefIt);1075if (CanUp)1076predicateAt(MD, *DefI, PastDefIt, MP, Cond, UpdRegs);1077else if (CanDown)1078predicateAt(MD, *DefI, TfrIt, MP, Cond, UpdRegs);1079else1080return false;10811082if (RT != RD) {1083renameInRange(RT, RD, PredR, Cond, PastDefIt, TfrIt);1084UpdRegs.insert(RT.Reg);1085}10861087removeInstr(TfrI);1088removeInstr(*DefI);1089return true;1090}10911092/// Predicate all cases of conditional copies in the specified block.1093bool HexagonExpandCondsets::predicateInBlock(MachineBasicBlock &B,1094std::set<Register> &UpdRegs) {1095bool Changed = false;1096for (MachineInstr &MI : llvm::make_early_inc_range(B)) {1097unsigned Opc = MI.getOpcode();1098if (Opc == Hexagon::A2_tfrt || Opc == Hexagon::A2_tfrf) {1099bool Done = predicate(MI, (Opc == Hexagon::A2_tfrt), UpdRegs);1100if (!Done) {1101// If we didn't predicate I, we may need to remove it in case it is1102// an "identity" copy, e.g. %1 = A2_tfrt %2, %1.1103if (RegisterRef(MI.getOperand(0)) == RegisterRef(MI.getOperand(2))) {1104for (auto &Op : MI.operands()) {1105if (Op.isReg())1106UpdRegs.insert(Op.getReg());1107}1108removeInstr(MI);1109}1110}1111Changed |= Done;1112}1113}1114return Changed;1115}11161117bool HexagonExpandCondsets::isIntReg(RegisterRef RR, unsigned &BW) {1118if (!RR.Reg.isVirtual())1119return false;1120const TargetRegisterClass *RC = MRI->getRegClass(RR.Reg);1121if (RC == &Hexagon::IntRegsRegClass) {1122BW = 32;1123return true;1124}1125if (RC == &Hexagon::DoubleRegsRegClass) {1126BW = (RR.Sub != 0) ? 32 : 64;1127return true;1128}1129return false;1130}11311132bool HexagonExpandCondsets::isIntraBlocks(LiveInterval &LI) {1133for (LiveRange::Segment &LR : LI) {1134// Range must start at a register...1135if (!LR.start.isRegister())1136return false;1137// ...and end in a register or in a dead slot.1138if (!LR.end.isRegister() && !LR.end.isDead())1139return false;1140}1141return true;1142}11431144bool HexagonExpandCondsets::coalesceRegisters(RegisterRef R1, RegisterRef R2) {1145if (CoaLimitActive) {1146if (CoaCounter >= CoaLimit)1147return false;1148CoaCounter++;1149}1150unsigned BW1, BW2;1151if (!isIntReg(R1, BW1) || !isIntReg(R2, BW2) || BW1 != BW2)1152return false;1153if (MRI->isLiveIn(R1.Reg))1154return false;1155if (MRI->isLiveIn(R2.Reg))1156return false;11571158LiveInterval &L1 = LIS->getInterval(R1.Reg);1159LiveInterval &L2 = LIS->getInterval(R2.Reg);1160if (L2.empty())1161return false;1162if (L1.hasSubRanges() || L2.hasSubRanges())1163return false;1164bool Overlap = L1.overlaps(L2);11651166LLVM_DEBUG(dbgs() << "compatible registers: ("1167<< (Overlap ? "overlap" : "disjoint") << ")\n "1168<< printReg(R1.Reg, TRI, R1.Sub) << " " << L1 << "\n "1169<< printReg(R2.Reg, TRI, R2.Sub) << " " << L2 << "\n");1170if (R1.Sub || R2.Sub)1171return false;1172if (Overlap)1173return false;11741175// Coalescing could have a negative impact on scheduling, so try to limit1176// to some reasonable extent. Only consider coalescing segments, when one1177// of them does not cross basic block boundaries.1178if (!isIntraBlocks(L1) && !isIntraBlocks(L2))1179return false;11801181MRI->replaceRegWith(R2.Reg, R1.Reg);11821183// Move all live segments from L2 to L1.1184using ValueInfoMap = DenseMap<VNInfo *, VNInfo *>;1185ValueInfoMap VM;1186for (LiveRange::Segment &I : L2) {1187VNInfo *NewVN, *OldVN = I.valno;1188ValueInfoMap::iterator F = VM.find(OldVN);1189if (F == VM.end()) {1190NewVN = L1.getNextValue(I.valno->def, LIS->getVNInfoAllocator());1191VM.insert(std::make_pair(OldVN, NewVN));1192} else {1193NewVN = F->second;1194}1195L1.addSegment(LiveRange::Segment(I.start, I.end, NewVN));1196}1197while (!L2.empty())1198L2.removeSegment(*L2.begin());1199LIS->removeInterval(R2.Reg);12001201updateKillFlags(R1.Reg);1202LLVM_DEBUG(dbgs() << "coalesced: " << L1 << "\n");1203L1.verify();12041205return true;1206}12071208/// Attempt to coalesce one of the source registers to a MUX instruction with1209/// the destination register. This could lead to having only one predicated1210/// instruction in the end instead of two.1211bool HexagonExpandCondsets::coalesceSegments(1212const SmallVectorImpl<MachineInstr *> &Condsets,1213std::set<Register> &UpdRegs) {1214SmallVector<MachineInstr*,16> TwoRegs;1215for (MachineInstr *MI : Condsets) {1216MachineOperand &S1 = MI->getOperand(2), &S2 = MI->getOperand(3);1217if (!S1.isReg() && !S2.isReg())1218continue;1219TwoRegs.push_back(MI);1220}12211222bool Changed = false;1223for (MachineInstr *CI : TwoRegs) {1224RegisterRef RD = CI->getOperand(0);1225RegisterRef RP = CI->getOperand(1);1226MachineOperand &S1 = CI->getOperand(2), &S2 = CI->getOperand(3);1227bool Done = false;1228// Consider this case:1229// %1 = instr1 ...1230// %2 = instr2 ...1231// %0 = C2_mux ..., %1, %21232// If %0 was coalesced with %1, we could end up with the following1233// code:1234// %0 = instr1 ...1235// %2 = instr2 ...1236// %0 = A2_tfrf ..., %21237// which will later become:1238// %0 = instr1 ...1239// %0 = instr2_cNotPt ...1240// i.e. there will be an unconditional definition (instr1) of %01241// followed by a conditional one. The output dependency was there before1242// and it unavoidable, but if instr1 is predicable, we will no longer be1243// able to predicate it here.1244// To avoid this scenario, don't coalesce the destination register with1245// a source register that is defined by a predicable instruction.1246if (S1.isReg()) {1247RegisterRef RS = S1;1248MachineInstr *RDef = getReachingDefForPred(RS, CI, RP.Reg, true);1249if (!RDef || !HII->isPredicable(*RDef)) {1250Done = coalesceRegisters(RD, RegisterRef(S1));1251if (Done) {1252UpdRegs.insert(RD.Reg);1253UpdRegs.insert(S1.getReg());1254}1255}1256}1257if (!Done && S2.isReg()) {1258RegisterRef RS = S2;1259MachineInstr *RDef = getReachingDefForPred(RS, CI, RP.Reg, false);1260if (!RDef || !HII->isPredicable(*RDef)) {1261Done = coalesceRegisters(RD, RegisterRef(S2));1262if (Done) {1263UpdRegs.insert(RD.Reg);1264UpdRegs.insert(S2.getReg());1265}1266}1267}1268Changed |= Done;1269}1270return Changed;1271}12721273bool HexagonExpandCondsets::runOnMachineFunction(MachineFunction &MF) {1274if (skipFunction(MF.getFunction()))1275return false;12761277HII = static_cast<const HexagonInstrInfo*>(MF.getSubtarget().getInstrInfo());1278TRI = MF.getSubtarget().getRegisterInfo();1279MDT = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();1280LIS = &getAnalysis<LiveIntervalsWrapperPass>().getLIS();1281MRI = &MF.getRegInfo();12821283LLVM_DEBUG(LIS->print(dbgs() << "Before expand-condsets\n"));12841285bool Changed = false;1286std::set<Register> CoalUpd, PredUpd;12871288SmallVector<MachineInstr*,16> Condsets;1289for (auto &B : MF) {1290for (auto &I : B) {1291if (isCondset(I))1292Condsets.push_back(&I);1293}1294}12951296// Try to coalesce the target of a mux with one of its sources.1297// This could eliminate a register copy in some circumstances.1298Changed |= coalesceSegments(Condsets, CoalUpd);12991300// Update kill flags on all source operands. This is done here because1301// at this moment (when expand-condsets runs), there are no kill flags1302// in the IR (they have been removed by live range analysis).1303// Updating them right before we split is the easiest, because splitting1304// adds definitions which would interfere with updating kills afterwards.1305std::set<Register> KillUpd;1306for (MachineInstr *MI : Condsets) {1307for (MachineOperand &Op : MI->operands()) {1308if (Op.isReg() && Op.isUse()) {1309if (!CoalUpd.count(Op.getReg()))1310KillUpd.insert(Op.getReg());1311}1312}1313}1314updateLiveness(KillUpd, false, true, false);1315LLVM_DEBUG(LIS->print(dbgs() << "After coalescing\n"));13161317// First, simply split all muxes into a pair of conditional transfers1318// and update the live intervals to reflect the new arrangement. The1319// goal is to update the kill flags, since predication will rely on1320// them.1321for (MachineInstr *MI : Condsets)1322Changed |= split(*MI, PredUpd);1323Condsets.clear(); // The contents of Condsets are invalid here anyway.13241325// Do not update live ranges after splitting. Recalculation of live1326// intervals removes kill flags, which were preserved by splitting on1327// the source operands of condsets. These kill flags are needed by1328// predication, and after splitting they are difficult to recalculate1329// (because of predicated defs), so make sure they are left untouched.1330// Predication does not use live intervals.1331LLVM_DEBUG(LIS->print(dbgs() << "After splitting\n"));13321333// Traverse all blocks and collapse predicable instructions feeding1334// conditional transfers into predicated instructions.1335// Walk over all the instructions again, so we may catch pre-existing1336// cases that were not created in the previous step.1337for (auto &B : MF)1338Changed |= predicateInBlock(B, PredUpd);1339LLVM_DEBUG(LIS->print(dbgs() << "After predicating\n"));13401341PredUpd.insert(CoalUpd.begin(), CoalUpd.end());1342updateLiveness(PredUpd, true, true, true);13431344if (Changed)1345distributeLiveIntervals(PredUpd);13461347LLVM_DEBUG({1348if (Changed)1349LIS->print(dbgs() << "After expand-condsets\n");1350});13511352return Changed;1353}13541355//===----------------------------------------------------------------------===//1356// Public Constructor Functions1357//===----------------------------------------------------------------------===//1358FunctionPass *llvm::createHexagonExpandCondsets() {1359return new HexagonExpandCondsets();1360}136113621363