1 //===--- HexagonExpandCondsets.cpp ----------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 // Replace mux instructions with the corresponding legal instructions.
11 // It is meant to work post-SSA, but still on virtual registers. It was
12 // originally placed between register coalescing and machine instruction
13 // scheduler.
14 // In this place in the optimization sequence, live interval analysis had
15 // been performed, and the live intervals should be preserved. A large part
16 // of the code deals with preserving the liveness information.
17 //
18 // Liveness tracking aside, the main functionality of this pass is divided
19 // into two steps. The first step is to replace an instruction
20 //   vreg0 = C2_mux vreg1, vreg2, vreg3
21 // with a pair of conditional transfers
22 //   vreg0 = A2_tfrt vreg1, vreg2
23 //   vreg0 = A2_tfrf vreg1, vreg3
24 // It is the intention that the execution of this pass could be terminated
25 // after this step, and the code generated would be functionally correct.
26 //
27 // If the uses of the source values vreg1 and vreg2 are kills, and their
28 // definitions are predicable, then in the second step, the conditional
29 // transfers will then be rewritten as predicated instructions. E.g.
30 //   vreg0 = A2_or vreg1, vreg2
31 //   vreg3 = A2_tfrt vreg99, vreg0<kill>
32 // will be rewritten as
33 //   vreg3 = A2_port vreg99, vreg1, vreg2
34 //
35 // This replacement has two variants: "up" and "down". Consider this case:
36 //   vreg0 = A2_or vreg1, vreg2
37 //   ... [intervening instructions] ...
38 //   vreg3 = A2_tfrt vreg99, vreg0<kill>
39 // variant "up":
40 //   vreg3 = A2_port vreg99, vreg1, vreg2
41 //   ... [intervening instructions, vreg0->vreg3] ...
42 //   [deleted]
43 // variant "down":
44 //   [deleted]
45 //   ... [intervening instructions] ...
46 //   vreg3 = A2_port vreg99, vreg1, vreg2
47 //
48 // Both, one or none of these variants may be valid, and checks are made
49 // to rule out inapplicable variants.
50 //
51 // As an additional optimization, before either of the two steps above is
52 // executed, the pass attempts to coalesce the target register with one of
53 // the source registers, e.g. given an instruction
54 //   vreg3 = C2_mux vreg0, vreg1, vreg2
55 // vreg3 will be coalesced with either vreg1 or vreg2. If this succeeds,
56 // the instruction would then be (for example)
57 //   vreg3 = C2_mux vreg0, vreg3, vreg2
58 // and, under certain circumstances, this could result in only one predicated
59 // instruction:
60 //   vreg3 = A2_tfrf vreg0, vreg2
61 //
62 
63 // Splitting a definition of a register into two predicated transfers
64 // creates a complication in liveness tracking. Live interval computation
65 // will see both instructions as actual definitions, and will mark the
66 // first one as dead. The definition is not actually dead, and this
67 // situation will need to be fixed. For example:
68 //   vreg1<def,dead> = A2_tfrt ...  ; marked as dead
69 //   vreg1<def> = A2_tfrf ...
70 //
71 // Since any of the individual predicated transfers may end up getting
72 // removed (in case it is an identity copy), some pre-existing def may
73 // be marked as dead after live interval recomputation:
74 //   vreg1<def,dead> = ...          ; marked as dead
75 //   ...
76 //   vreg1<def> = A2_tfrf ...       ; if A2_tfrt is removed
77 // This case happens if vreg1 was used as a source in A2_tfrt, which means
78 // that is it actually live at the A2_tfrf, and so the now dead definition
79 // of vreg1 will need to be updated to non-dead at some point.
80 //
81 // This issue could be remedied by adding implicit uses to the predicated
82 // transfers, but this will create a problem with subsequent predication,
83 // since the transfers will no longer be possible to reorder. To avoid
84 // that, the initial splitting will not add any implicit uses. These
85 // implicit uses will be added later, after predication. The extra price,
86 // however, is that finding the locations where the implicit uses need
87 // to be added, and updating the live ranges will be more involved.
88 
89 #define DEBUG_TYPE "expand-condsets"
90 
91 #include "HexagonTargetMachine.h"
92 #include "llvm/ADT/SetVector.h"
93 #include "llvm/CodeGen/Passes.h"
94 #include "llvm/CodeGen/LiveInterval.h"
95 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
96 #include "llvm/CodeGen/MachineDominators.h"
97 #include "llvm/CodeGen/MachineFunction.h"
98 #include "llvm/CodeGen/MachineInstrBuilder.h"
99 #include "llvm/CodeGen/MachineRegisterInfo.h"
100 #include "llvm/Target/TargetInstrInfo.h"
101 #include "llvm/Target/TargetMachine.h"
102 #include "llvm/Target/TargetRegisterInfo.h"
103 #include "llvm/Support/CommandLine.h"
104 #include "llvm/Support/Debug.h"
105 #include "llvm/Support/raw_ostream.h"
106 
107 #include <algorithm>
108 #include <iterator>
109 #include <set>
110 #include <utility>
111 
112 using namespace llvm;
113 
114 static cl::opt<unsigned> OptTfrLimit("expand-condsets-tfr-limit",
115   cl::init(~0U), cl::Hidden, cl::desc("Max number of mux expansions"));
116 static cl::opt<unsigned> OptCoaLimit("expand-condsets-coa-limit",
117   cl::init(~0U), cl::Hidden, cl::desc("Max number of segment coalescings"));
118 
119 namespace llvm {
120   void initializeHexagonExpandCondsetsPass(PassRegistry&);
121   FunctionPass *createHexagonExpandCondsets();
122 }
123 
124 namespace {
125   class HexagonExpandCondsets : public MachineFunctionPass {
126   public:
127     static char ID;
128     HexagonExpandCondsets() :
129         MachineFunctionPass(ID), HII(0), TRI(0), MRI(0),
130         LIS(0), CoaLimitActive(false),
131         TfrLimitActive(false), CoaCounter(0), TfrCounter(0) {
132       if (OptCoaLimit.getPosition())
133         CoaLimitActive = true, CoaLimit = OptCoaLimit;
134       if (OptTfrLimit.getPosition())
135         TfrLimitActive = true, TfrLimit = OptTfrLimit;
136       initializeHexagonExpandCondsetsPass(*PassRegistry::getPassRegistry());
137     }
138 
139     StringRef getPassName() const override { return "Hexagon Expand Condsets"; }
140     void getAnalysisUsage(AnalysisUsage &AU) const override {
141       AU.addRequired<LiveIntervals>();
142       AU.addPreserved<LiveIntervals>();
143       AU.addPreserved<SlotIndexes>();
144       AU.addRequired<MachineDominatorTree>();
145       AU.addPreserved<MachineDominatorTree>();
146       MachineFunctionPass::getAnalysisUsage(AU);
147     }
148     bool runOnMachineFunction(MachineFunction &MF) override;
149 
150   private:
151     const HexagonInstrInfo *HII;
152     const TargetRegisterInfo *TRI;
153     MachineDominatorTree *MDT;
154     MachineRegisterInfo *MRI;
155     LiveIntervals *LIS;
156 
157     bool CoaLimitActive, TfrLimitActive;
158     unsigned CoaLimit, TfrLimit, CoaCounter, TfrCounter;
159 
160     struct RegisterRef {
161       RegisterRef(const MachineOperand &Op) : Reg(Op.getReg()),
162           Sub(Op.getSubReg()) {}
163       RegisterRef(unsigned R = 0, unsigned S = 0) : Reg(R), Sub(S) {}
164       bool operator== (RegisterRef RR) const {
165         return Reg == RR.Reg && Sub == RR.Sub;
166       }
167       bool operator!= (RegisterRef RR) const { return !operator==(RR); }
168       bool operator< (RegisterRef RR) const {
169         return Reg < RR.Reg || (Reg == RR.Reg && Sub < RR.Sub);
170       }
171       unsigned Reg, Sub;
172     };
173 
174     typedef DenseMap<unsigned,unsigned> ReferenceMap;
175     enum { Sub_Low = 0x1, Sub_High = 0x2, Sub_None = (Sub_Low | Sub_High) };
176     enum { Exec_Then = 0x10, Exec_Else = 0x20 };
177     unsigned getMaskForSub(unsigned Sub);
178     bool isCondset(const MachineInstr &MI);
179     LaneBitmask getLaneMask(unsigned Reg, unsigned Sub);
180 
181     void addRefToMap(RegisterRef RR, ReferenceMap &Map, unsigned Exec);
182     bool isRefInMap(RegisterRef, ReferenceMap &Map, unsigned Exec);
183 
184     void updateDeadsInRange(unsigned Reg, LaneBitmask LM, LiveRange &Range);
185     void updateKillFlags(unsigned Reg);
186     void updateDeadFlags(unsigned Reg);
187     void recalculateLiveInterval(unsigned Reg);
188     void removeInstr(MachineInstr &MI);
189     void updateLiveness(std::set<unsigned> &RegSet, bool Recalc,
190         bool UpdateKills, bool UpdateDeads);
191 
192     unsigned getCondTfrOpcode(const MachineOperand &SO, bool Cond);
193     MachineInstr *genCondTfrFor(MachineOperand &SrcOp,
194         MachineBasicBlock::iterator At, unsigned DstR,
195         unsigned DstSR, const MachineOperand &PredOp, bool PredSense,
196         bool ReadUndef, bool ImpUse);
197     bool split(MachineInstr &MI, std::set<unsigned> &UpdRegs);
198 
199     bool isPredicable(MachineInstr *MI);
200     MachineInstr *getReachingDefForPred(RegisterRef RD,
201         MachineBasicBlock::iterator UseIt, unsigned PredR, bool Cond);
202     bool canMoveOver(MachineInstr &MI, ReferenceMap &Defs, ReferenceMap &Uses);
203     bool canMoveMemTo(MachineInstr &MI, MachineInstr &ToI, bool IsDown);
204     void predicateAt(const MachineOperand &DefOp, MachineInstr &MI,
205                      MachineBasicBlock::iterator Where,
206                      const MachineOperand &PredOp, bool Cond,
207                      std::set<unsigned> &UpdRegs);
208     void renameInRange(RegisterRef RO, RegisterRef RN, unsigned PredR,
209         bool Cond, MachineBasicBlock::iterator First,
210         MachineBasicBlock::iterator Last);
211     bool predicate(MachineInstr &TfrI, bool Cond, std::set<unsigned> &UpdRegs);
212     bool predicateInBlock(MachineBasicBlock &B,
213         std::set<unsigned> &UpdRegs);
214 
215     bool isIntReg(RegisterRef RR, unsigned &BW);
216     bool isIntraBlocks(LiveInterval &LI);
217     bool coalesceRegisters(RegisterRef R1, RegisterRef R2);
218     bool coalesceSegments(const SmallVectorImpl<MachineInstr*> &Condsets,
219                           std::set<unsigned> &UpdRegs);
220   };
221 }
222 
223 char HexagonExpandCondsets::ID = 0;
224 
225 namespace llvm {
226   char &HexagonExpandCondsetsID = HexagonExpandCondsets::ID;
227 }
228 
229 INITIALIZE_PASS_BEGIN(HexagonExpandCondsets, "expand-condsets",
230   "Hexagon Expand Condsets", false, false)
231 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
232 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
233 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
234 INITIALIZE_PASS_END(HexagonExpandCondsets, "expand-condsets",
235   "Hexagon Expand Condsets", false, false)
236 
237 unsigned HexagonExpandCondsets::getMaskForSub(unsigned Sub) {
238   switch (Sub) {
239     case Hexagon::isub_lo:
240     case Hexagon::vsub_lo:
241       return Sub_Low;
242     case Hexagon::isub_hi:
243     case Hexagon::vsub_hi:
244       return Sub_High;
245     case Hexagon::NoSubRegister:
246       return Sub_None;
247   }
248   llvm_unreachable("Invalid subregister");
249 }
250 
251 bool HexagonExpandCondsets::isCondset(const MachineInstr &MI) {
252   unsigned Opc = MI.getOpcode();
253   switch (Opc) {
254     case Hexagon::C2_mux:
255     case Hexagon::C2_muxii:
256     case Hexagon::C2_muxir:
257     case Hexagon::C2_muxri:
258     case Hexagon::PS_pselect:
259         return true;
260       break;
261   }
262   return false;
263 }
264 
265 
266 LaneBitmask HexagonExpandCondsets::getLaneMask(unsigned Reg, unsigned Sub) {
267   assert(TargetRegisterInfo::isVirtualRegister(Reg));
268   return Sub != 0 ? TRI->getSubRegIndexLaneMask(Sub)
269                   : MRI->getMaxLaneMaskForVReg(Reg);
270 }
271 
272 
273 void HexagonExpandCondsets::addRefToMap(RegisterRef RR, ReferenceMap &Map,
274       unsigned Exec) {
275   unsigned Mask = getMaskForSub(RR.Sub) | Exec;
276   ReferenceMap::iterator F = Map.find(RR.Reg);
277   if (F == Map.end())
278     Map.insert(std::make_pair(RR.Reg, Mask));
279   else
280     F->second |= Mask;
281 }
282 
283 
284 bool HexagonExpandCondsets::isRefInMap(RegisterRef RR, ReferenceMap &Map,
285       unsigned Exec) {
286   ReferenceMap::iterator F = Map.find(RR.Reg);
287   if (F == Map.end())
288     return false;
289   unsigned Mask = getMaskForSub(RR.Sub) | Exec;
290   if (Mask & F->second)
291     return true;
292   return false;
293 }
294 
295 
296 void HexagonExpandCondsets::updateKillFlags(unsigned Reg) {
297   auto KillAt = [this,Reg] (SlotIndex K, LaneBitmask LM) -> void {
298     // Set the <kill> flag on a use of Reg whose lane mask is contained in LM.
299     MachineInstr *MI = LIS->getInstructionFromIndex(K);
300     for (auto &Op : MI->operands()) {
301       if (!Op.isReg() || !Op.isUse() || Op.getReg() != Reg)
302         continue;
303       LaneBitmask SLM = getLaneMask(Reg, Op.getSubReg());
304       if ((SLM & LM) == SLM) {
305         // Only set the kill flag on the first encountered use of Reg in this
306         // instruction.
307         Op.setIsKill(true);
308         break;
309       }
310     }
311   };
312 
313   LiveInterval &LI = LIS->getInterval(Reg);
314   for (auto I = LI.begin(), E = LI.end(); I != E; ++I) {
315     if (!I->end.isRegister())
316       continue;
317     // Do not mark the end of the segment as <kill>, if the next segment
318     // starts with a predicated instruction.
319     auto NextI = std::next(I);
320     if (NextI != E && NextI->start.isRegister()) {
321       MachineInstr *DefI = LIS->getInstructionFromIndex(NextI->start);
322       if (HII->isPredicated(*DefI))
323         continue;
324     }
325     bool WholeReg = true;
326     if (LI.hasSubRanges()) {
327       auto EndsAtI = [I] (LiveInterval::SubRange &S) -> bool {
328         LiveRange::iterator F = S.find(I->end);
329         return F != S.end() && I->end == F->end;
330       };
331       // Check if all subranges end at I->end. If so, make sure to kill
332       // the whole register.
333       for (LiveInterval::SubRange &S : LI.subranges()) {
334         if (EndsAtI(S))
335           KillAt(I->end, S.LaneMask);
336         else
337           WholeReg = false;
338       }
339     }
340     if (WholeReg)
341       KillAt(I->end, MRI->getMaxLaneMaskForVReg(Reg));
342   }
343 }
344 
345 
346 void HexagonExpandCondsets::updateDeadsInRange(unsigned Reg, LaneBitmask LM,
347       LiveRange &Range) {
348   assert(TargetRegisterInfo::isVirtualRegister(Reg));
349   if (Range.empty())
350     return;
351 
352   auto IsRegDef = [this,Reg,LM] (MachineOperand &Op) -> bool {
353     if (!Op.isReg() || !Op.isDef())
354       return false;
355     unsigned DR = Op.getReg(), DSR = Op.getSubReg();
356     if (!TargetRegisterInfo::isVirtualRegister(DR) || DR != Reg)
357       return false;
358     LaneBitmask SLM = getLaneMask(DR, DSR);
359     return (SLM & LM) != 0;
360   };
361 
362   // The splitting step will create pairs of predicated definitions without
363   // any implicit uses (since implicit uses would interfere with predication).
364   // This can cause the reaching defs to become dead after live range
365   // recomputation, even though they are not really dead.
366   // We need to identify predicated defs that need implicit uses, and
367   // dead defs that are not really dead, and correct both problems.
368 
369   auto Dominate = [this] (SetVector<MachineBasicBlock*> &Defs,
370                           MachineBasicBlock *Dest) -> bool {
371     for (MachineBasicBlock *D : Defs)
372       if (D != Dest && MDT->dominates(D, Dest))
373         return true;
374 
375     MachineBasicBlock *Entry = &Dest->getParent()->front();
376     SetVector<MachineBasicBlock*> Work(Dest->pred_begin(), Dest->pred_end());
377     for (unsigned i = 0; i < Work.size(); ++i) {
378       MachineBasicBlock *B = Work[i];
379       if (Defs.count(B))
380         continue;
381       if (B == Entry)
382         return false;
383       for (auto *P : B->predecessors())
384         Work.insert(P);
385     }
386     return true;
387   };
388 
389   // First, try to extend live range within individual basic blocks. This
390   // will leave us only with dead defs that do not reach any predicated
391   // defs in the same block.
392   SetVector<MachineBasicBlock*> Defs;
393   SmallVector<SlotIndex,4> PredDefs;
394   for (auto &Seg : Range) {
395     if (!Seg.start.isRegister())
396       continue;
397     MachineInstr *DefI = LIS->getInstructionFromIndex(Seg.start);
398     Defs.insert(DefI->getParent());
399     if (HII->isPredicated(*DefI))
400       PredDefs.push_back(Seg.start);
401   }
402 
403   SmallVector<SlotIndex,8> Undefs;
404   LiveInterval &LI = LIS->getInterval(Reg);
405   LI.computeSubRangeUndefs(Undefs, LM, *MRI, *LIS->getSlotIndexes());
406 
407   for (auto &SI : PredDefs) {
408     MachineBasicBlock *BB = LIS->getMBBFromIndex(SI);
409     auto P = Range.extendInBlock(Undefs, LIS->getMBBStartIdx(BB), SI);
410     if (P.first != nullptr || P.second)
411       SI = SlotIndex();
412   }
413 
414   // Calculate reachability for those predicated defs that were not handled
415   // by the in-block extension.
416   SmallVector<SlotIndex,4> ExtTo;
417   for (auto &SI : PredDefs) {
418     if (!SI.isValid())
419       continue;
420     MachineBasicBlock *BB = LIS->getMBBFromIndex(SI);
421     if (BB->pred_empty())
422       continue;
423     // If the defs from this range reach SI via all predecessors, it is live.
424     // It can happen that SI is reached by the defs through some paths, but
425     // not all. In the IR coming into this optimization, SI would not be
426     // considered live, since the defs would then not jointly dominate SI.
427     // That means that SI is an overwriting def, and no implicit use is
428     // needed at this point. Do not add SI to the extension points, since
429     // extendToIndices will abort if there is no joint dominance.
430     // If the abort was avoided by adding extra undefs added to Undefs,
431     // extendToIndices could actually indicate that SI is live, contrary
432     // to the original IR.
433     if (Dominate(Defs, BB))
434       ExtTo.push_back(SI);
435   }
436 
437   if (!ExtTo.empty())
438     LIS->extendToIndices(Range, ExtTo, Undefs);
439 
440   // Remove <dead> flags from all defs that are not dead after live range
441   // extension, and collect all def operands. They will be used to generate
442   // the necessary implicit uses.
443   std::set<RegisterRef> DefRegs;
444   for (auto &Seg : Range) {
445     if (!Seg.start.isRegister())
446       continue;
447     MachineInstr *DefI = LIS->getInstructionFromIndex(Seg.start);
448     for (auto &Op : DefI->operands()) {
449       if (Seg.start.isDead() || !IsRegDef(Op))
450         continue;
451       DefRegs.insert(Op);
452       Op.setIsDead(false);
453     }
454   }
455 
456   // Finally, add implicit uses to each predicated def that is reached
457   // by other defs.
458   for (auto &Seg : Range) {
459     if (!Seg.start.isRegister() || !Range.liveAt(Seg.start.getPrevSlot()))
460       continue;
461     MachineInstr *DefI = LIS->getInstructionFromIndex(Seg.start);
462     if (!HII->isPredicated(*DefI))
463       continue;
464     // Construct the set of all necessary implicit uses, based on the def
465     // operands in the instruction.
466     std::set<RegisterRef> ImpUses;
467     for (auto &Op : DefI->operands())
468       if (Op.isReg() && Op.isDef() && DefRegs.count(Op))
469         ImpUses.insert(Op);
470     if (ImpUses.empty())
471       continue;
472     MachineFunction &MF = *DefI->getParent()->getParent();
473     for (RegisterRef R : ImpUses)
474       MachineInstrBuilder(MF, DefI).addReg(R.Reg, RegState::Implicit, R.Sub);
475   }
476 }
477 
478 
479 void HexagonExpandCondsets::updateDeadFlags(unsigned Reg) {
480   LiveInterval &LI = LIS->getInterval(Reg);
481   if (LI.hasSubRanges()) {
482     for (LiveInterval::SubRange &S : LI.subranges()) {
483       updateDeadsInRange(Reg, S.LaneMask, S);
484       LIS->shrinkToUses(S, Reg);
485     }
486     LI.clear();
487     LIS->constructMainRangeFromSubranges(LI);
488   } else {
489     updateDeadsInRange(Reg, MRI->getMaxLaneMaskForVReg(Reg), LI);
490   }
491 }
492 
493 
494 void HexagonExpandCondsets::recalculateLiveInterval(unsigned Reg) {
495   LIS->removeInterval(Reg);
496   LIS->createAndComputeVirtRegInterval(Reg);
497 }
498 
499 
500 void HexagonExpandCondsets::removeInstr(MachineInstr &MI) {
501   LIS->RemoveMachineInstrFromMaps(MI);
502   MI.eraseFromParent();
503 }
504 
505 
506 void HexagonExpandCondsets::updateLiveness(std::set<unsigned> &RegSet,
507       bool Recalc, bool UpdateKills, bool UpdateDeads) {
508   UpdateKills |= UpdateDeads;
509   for (auto R : RegSet) {
510     if (Recalc)
511       recalculateLiveInterval(R);
512     if (UpdateKills)
513       MRI->clearKillFlags(R);
514     if (UpdateDeads)
515       updateDeadFlags(R);
516     // Fixing <dead> flags may extend live ranges, so reset <kill> flags
517     // after that.
518     if (UpdateKills)
519       updateKillFlags(R);
520     LIS->getInterval(R).verify();
521   }
522 }
523 
524 
525 /// Get the opcode for a conditional transfer of the value in SO (source
526 /// operand). The condition (true/false) is given in Cond.
527 unsigned HexagonExpandCondsets::getCondTfrOpcode(const MachineOperand &SO,
528       bool IfTrue) {
529   using namespace Hexagon;
530   if (SO.isReg()) {
531     unsigned PhysR;
532     RegisterRef RS = SO;
533     if (TargetRegisterInfo::isVirtualRegister(RS.Reg)) {
534       const TargetRegisterClass *VC = MRI->getRegClass(RS.Reg);
535       assert(VC->begin() != VC->end() && "Empty register class");
536       PhysR = *VC->begin();
537     } else {
538       assert(TargetRegisterInfo::isPhysicalRegister(RS.Reg));
539       PhysR = RS.Reg;
540     }
541     unsigned PhysS = (RS.Sub == 0) ? PhysR : TRI->getSubReg(PhysR, RS.Sub);
542     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(PhysS);
543     switch (RC->getSize()) {
544       case 4:
545         return IfTrue ? A2_tfrt : A2_tfrf;
546       case 8:
547         return IfTrue ? A2_tfrpt : A2_tfrpf;
548     }
549     llvm_unreachable("Invalid register operand");
550   }
551   if (SO.isImm() || SO.isFPImm())
552     return IfTrue ? C2_cmoveit : C2_cmoveif;
553   llvm_unreachable("Unexpected source operand");
554 }
555 
556 
557 /// Generate a conditional transfer, copying the value SrcOp to the
558 /// destination register DstR:DstSR, and using the predicate register from
559 /// PredOp. The Cond argument specifies whether the predicate is to be
560 /// if(PredOp), or if(!PredOp).
561 MachineInstr *HexagonExpandCondsets::genCondTfrFor(MachineOperand &SrcOp,
562       MachineBasicBlock::iterator At,
563       unsigned DstR, unsigned DstSR, const MachineOperand &PredOp,
564       bool PredSense, bool ReadUndef, bool ImpUse) {
565   MachineInstr *MI = SrcOp.getParent();
566   MachineBasicBlock &B = *At->getParent();
567   const DebugLoc &DL = MI->getDebugLoc();
568 
569   // Don't avoid identity copies here (i.e. if the source and the destination
570   // are the same registers). It is actually better to generate them here,
571   // since this would cause the copy to potentially be predicated in the next
572   // step. The predication will remove such a copy if it is unable to
573   /// predicate.
574 
575   unsigned Opc = getCondTfrOpcode(SrcOp, PredSense);
576   unsigned DstState = RegState::Define | (ReadUndef ? RegState::Undef : 0);
577   unsigned PredState = getRegState(PredOp) & ~RegState::Kill;
578   MachineInstrBuilder MIB;
579 
580   if (SrcOp.isReg()) {
581     unsigned SrcState = getRegState(SrcOp);
582     if (RegisterRef(SrcOp) == RegisterRef(DstR, DstSR))
583       SrcState &= ~RegState::Kill;
584     MIB = BuildMI(B, At, DL, HII->get(Opc))
585           .addReg(DstR, DstState, DstSR)
586           .addReg(PredOp.getReg(), PredState, PredOp.getSubReg())
587           .addReg(SrcOp.getReg(), SrcState, SrcOp.getSubReg());
588   } else {
589     MIB = BuildMI(B, At, DL, HII->get(Opc))
590           .addReg(DstR, DstState, DstSR)
591           .addReg(PredOp.getReg(), PredState, PredOp.getSubReg())
592           .addOperand(SrcOp);
593   }
594 
595   DEBUG(dbgs() << "created an initial copy: " << *MIB);
596   return &*MIB;
597 }
598 
599 
600 /// Replace a MUX instruction MI with a pair A2_tfrt/A2_tfrf. This function
601 /// performs all necessary changes to complete the replacement.
602 bool HexagonExpandCondsets::split(MachineInstr &MI,
603                                   std::set<unsigned> &UpdRegs) {
604   if (TfrLimitActive) {
605     if (TfrCounter >= TfrLimit)
606       return false;
607     TfrCounter++;
608   }
609   DEBUG(dbgs() << "\nsplitting BB#" << MI.getParent()->getNumber() << ": "
610                << MI);
611   MachineOperand &MD = MI.getOperand(0);  // Definition
612   MachineOperand &MP = MI.getOperand(1);  // Predicate register
613   assert(MD.isDef());
614   unsigned DR = MD.getReg(), DSR = MD.getSubReg();
615   bool ReadUndef = MD.isUndef();
616   MachineBasicBlock::iterator At = MI;
617 
618   // If this is a mux of the same register, just replace it with COPY.
619   // Ideally, this would happen earlier, so that register coalescing would
620   // see it.
621   MachineOperand &ST = MI.getOperand(2);
622   MachineOperand &SF = MI.getOperand(3);
623   if (ST.isReg() && SF.isReg()) {
624     RegisterRef RT(ST);
625     if (RT == RegisterRef(SF)) {
626       MI.setDesc(HII->get(TargetOpcode::COPY));
627       unsigned S = getRegState(ST);
628       while (MI.getNumOperands() > 1)
629         MI.RemoveOperand(MI.getNumOperands()-1);
630       MachineFunction &MF = *MI.getParent()->getParent();
631       MachineInstrBuilder(MF, MI).addReg(RT.Reg, S, RT.Sub);
632       return true;
633     }
634   }
635 
636   // First, create the two invididual conditional transfers, and add each
637   // of them to the live intervals information. Do that first and then remove
638   // the old instruction from live intervals.
639   MachineInstr *TfrT =
640       genCondTfrFor(ST, At, DR, DSR, MP, true, ReadUndef, false);
641   MachineInstr *TfrF =
642       genCondTfrFor(SF, At, DR, DSR, MP, false, ReadUndef, true);
643   LIS->InsertMachineInstrInMaps(*TfrT);
644   LIS->InsertMachineInstrInMaps(*TfrF);
645 
646   // Will need to recalculate live intervals for all registers in MI.
647   for (auto &Op : MI.operands())
648     if (Op.isReg())
649       UpdRegs.insert(Op.getReg());
650 
651   removeInstr(MI);
652   return true;
653 }
654 
655 bool HexagonExpandCondsets::isPredicable(MachineInstr *MI) {
656   if (HII->isPredicated(*MI) || !HII->isPredicable(*MI))
657     return false;
658   if (MI->hasUnmodeledSideEffects() || MI->mayStore())
659     return false;
660   // Reject instructions with multiple defs (e.g. post-increment loads).
661   bool HasDef = false;
662   for (auto &Op : MI->operands()) {
663     if (!Op.isReg() || !Op.isDef())
664       continue;
665     if (HasDef)
666       return false;
667     HasDef = true;
668   }
669   for (auto &Mo : MI->memoperands())
670     if (Mo->isVolatile())
671       return false;
672   return true;
673 }
674 
675 
676 /// Find the reaching definition for a predicated use of RD. The RD is used
677 /// under the conditions given by PredR and Cond, and this function will ignore
678 /// definitions that set RD under the opposite conditions.
679 MachineInstr *HexagonExpandCondsets::getReachingDefForPred(RegisterRef RD,
680       MachineBasicBlock::iterator UseIt, unsigned PredR, bool Cond) {
681   MachineBasicBlock &B = *UseIt->getParent();
682   MachineBasicBlock::iterator I = UseIt, S = B.begin();
683   if (I == S)
684     return 0;
685 
686   bool PredValid = true;
687   do {
688     --I;
689     MachineInstr *MI = &*I;
690     // Check if this instruction can be ignored, i.e. if it is predicated
691     // on the complementary condition.
692     if (PredValid && HII->isPredicated(*MI)) {
693       if (MI->readsRegister(PredR) && (Cond != HII->isPredicatedTrue(*MI)))
694         continue;
695     }
696 
697     // Check the defs. If the PredR is defined, invalidate it. If RD is
698     // defined, return the instruction or 0, depending on the circumstances.
699     for (auto &Op : MI->operands()) {
700       if (!Op.isReg() || !Op.isDef())
701         continue;
702       RegisterRef RR = Op;
703       if (RR.Reg == PredR) {
704         PredValid = false;
705         continue;
706       }
707       if (RR.Reg != RD.Reg)
708         continue;
709       // If the "Reg" part agrees, there is still the subregister to check.
710       // If we are looking for vreg1:loreg, we can skip vreg1:hireg, but
711       // not vreg1 (w/o subregisters).
712       if (RR.Sub == RD.Sub)
713         return MI;
714       if (RR.Sub == 0 || RD.Sub == 0)
715         return 0;
716       // We have different subregisters, so we can continue looking.
717     }
718   } while (I != S);
719 
720   return 0;
721 }
722 
723 
724 /// Check if the instruction MI can be safely moved over a set of instructions
725 /// whose side-effects (in terms of register defs and uses) are expressed in
726 /// the maps Defs and Uses. These maps reflect the conditional defs and uses
727 /// that depend on the same predicate register to allow moving instructions
728 /// over instructions predicated on the opposite condition.
729 bool HexagonExpandCondsets::canMoveOver(MachineInstr &MI, ReferenceMap &Defs,
730                                         ReferenceMap &Uses) {
731   // In order to be able to safely move MI over instructions that define
732   // "Defs" and use "Uses", no def operand from MI can be defined or used
733   // and no use operand can be defined.
734   for (auto &Op : MI.operands()) {
735     if (!Op.isReg())
736       continue;
737     RegisterRef RR = Op;
738     // For physical register we would need to check register aliases, etc.
739     // and we don't want to bother with that. It would be of little value
740     // before the actual register rewriting (from virtual to physical).
741     if (!TargetRegisterInfo::isVirtualRegister(RR.Reg))
742       return false;
743     // No redefs for any operand.
744     if (isRefInMap(RR, Defs, Exec_Then))
745       return false;
746     // For defs, there cannot be uses.
747     if (Op.isDef() && isRefInMap(RR, Uses, Exec_Then))
748       return false;
749   }
750   return true;
751 }
752 
753 
754 /// Check if the instruction accessing memory (TheI) can be moved to the
755 /// location ToI.
756 bool HexagonExpandCondsets::canMoveMemTo(MachineInstr &TheI, MachineInstr &ToI,
757                                          bool IsDown) {
758   bool IsLoad = TheI.mayLoad(), IsStore = TheI.mayStore();
759   if (!IsLoad && !IsStore)
760     return true;
761   if (HII->areMemAccessesTriviallyDisjoint(TheI, ToI))
762     return true;
763   if (TheI.hasUnmodeledSideEffects())
764     return false;
765 
766   MachineBasicBlock::iterator StartI = IsDown ? TheI : ToI;
767   MachineBasicBlock::iterator EndI = IsDown ? ToI : TheI;
768   bool Ordered = TheI.hasOrderedMemoryRef();
769 
770   // Search for aliased memory reference in (StartI, EndI).
771   for (MachineBasicBlock::iterator I = std::next(StartI); I != EndI; ++I) {
772     MachineInstr *MI = &*I;
773     if (MI->hasUnmodeledSideEffects())
774       return false;
775     bool L = MI->mayLoad(), S = MI->mayStore();
776     if (!L && !S)
777       continue;
778     if (Ordered && MI->hasOrderedMemoryRef())
779       return false;
780 
781     bool Conflict = (L && IsStore) || S;
782     if (Conflict)
783       return false;
784   }
785   return true;
786 }
787 
788 
789 /// Generate a predicated version of MI (where the condition is given via
790 /// PredR and Cond) at the point indicated by Where.
791 void HexagonExpandCondsets::predicateAt(const MachineOperand &DefOp,
792                                         MachineInstr &MI,
793                                         MachineBasicBlock::iterator Where,
794                                         const MachineOperand &PredOp, bool Cond,
795                                         std::set<unsigned> &UpdRegs) {
796   // The problem with updating live intervals is that we can move one def
797   // past another def. In particular, this can happen when moving an A2_tfrt
798   // over an A2_tfrf defining the same register. From the point of view of
799   // live intervals, these two instructions are two separate definitions,
800   // and each one starts another live segment. LiveIntervals's "handleMove"
801   // does not allow such moves, so we need to handle it ourselves. To avoid
802   // invalidating liveness data while we are using it, the move will be
803   // implemented in 4 steps: (1) add a clone of the instruction MI at the
804   // target location, (2) update liveness, (3) delete the old instruction,
805   // and (4) update liveness again.
806 
807   MachineBasicBlock &B = *MI.getParent();
808   DebugLoc DL = Where->getDebugLoc();  // "Where" points to an instruction.
809   unsigned Opc = MI.getOpcode();
810   unsigned PredOpc = HII->getCondOpcode(Opc, !Cond);
811   MachineInstrBuilder MB = BuildMI(B, Where, DL, HII->get(PredOpc));
812   unsigned Ox = 0, NP = MI.getNumOperands();
813   // Skip all defs from MI first.
814   while (Ox < NP) {
815     MachineOperand &MO = MI.getOperand(Ox);
816     if (!MO.isReg() || !MO.isDef())
817       break;
818     Ox++;
819   }
820   // Add the new def, then the predicate register, then the rest of the
821   // operands.
822   MB.addReg(DefOp.getReg(), getRegState(DefOp), DefOp.getSubReg());
823   MB.addReg(PredOp.getReg(), PredOp.isUndef() ? RegState::Undef : 0,
824             PredOp.getSubReg());
825   while (Ox < NP) {
826     MachineOperand &MO = MI.getOperand(Ox);
827     if (!MO.isReg() || !MO.isImplicit())
828       MB.addOperand(MO);
829     Ox++;
830   }
831 
832   MachineFunction &MF = *B.getParent();
833   MachineInstr::mmo_iterator I = MI.memoperands_begin();
834   unsigned NR = std::distance(I, MI.memoperands_end());
835   MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(NR);
836   for (unsigned i = 0; i < NR; ++i)
837     MemRefs[i] = *I++;
838   MB.setMemRefs(MemRefs, MemRefs+NR);
839 
840   MachineInstr *NewI = MB;
841   NewI->clearKillInfo();
842   LIS->InsertMachineInstrInMaps(*NewI);
843 
844   for (auto &Op : NewI->operands())
845     if (Op.isReg())
846       UpdRegs.insert(Op.getReg());
847 }
848 
849 
850 /// In the range [First, Last], rename all references to the "old" register RO
851 /// to the "new" register RN, but only in instructions predicated on the given
852 /// condition.
853 void HexagonExpandCondsets::renameInRange(RegisterRef RO, RegisterRef RN,
854       unsigned PredR, bool Cond, MachineBasicBlock::iterator First,
855       MachineBasicBlock::iterator Last) {
856   MachineBasicBlock::iterator End = std::next(Last);
857   for (MachineBasicBlock::iterator I = First; I != End; ++I) {
858     MachineInstr *MI = &*I;
859     // Do not touch instructions that are not predicated, or are predicated
860     // on the opposite condition.
861     if (!HII->isPredicated(*MI))
862       continue;
863     if (!MI->readsRegister(PredR) || (Cond != HII->isPredicatedTrue(*MI)))
864       continue;
865 
866     for (auto &Op : MI->operands()) {
867       if (!Op.isReg() || RO != RegisterRef(Op))
868         continue;
869       Op.setReg(RN.Reg);
870       Op.setSubReg(RN.Sub);
871       // In practice, this isn't supposed to see any defs.
872       assert(!Op.isDef() && "Not expecting a def");
873     }
874   }
875 }
876 
877 
878 /// For a given conditional copy, predicate the definition of the source of
879 /// the copy under the given condition (using the same predicate register as
880 /// the copy).
881 bool HexagonExpandCondsets::predicate(MachineInstr &TfrI, bool Cond,
882                                       std::set<unsigned> &UpdRegs) {
883   // TfrI - A2_tfr[tf] Instruction (not A2_tfrsi).
884   unsigned Opc = TfrI.getOpcode();
885   (void)Opc;
886   assert(Opc == Hexagon::A2_tfrt || Opc == Hexagon::A2_tfrf);
887   DEBUG(dbgs() << "\nattempt to predicate if-" << (Cond ? "true" : "false")
888                << ": " << TfrI);
889 
890   MachineOperand &MD = TfrI.getOperand(0);
891   MachineOperand &MP = TfrI.getOperand(1);
892   MachineOperand &MS = TfrI.getOperand(2);
893   // The source operand should be a <kill>. This is not strictly necessary,
894   // but it makes things a lot simpler. Otherwise, we would need to rename
895   // some registers, which would complicate the transformation considerably.
896   if (!MS.isKill())
897     return false;
898   // Avoid predicating instructions that define a subregister if subregister
899   // liveness tracking is not enabled.
900   if (MD.getSubReg() && !MRI->shouldTrackSubRegLiveness(MD.getReg()))
901     return false;
902 
903   RegisterRef RT(MS);
904   unsigned PredR = MP.getReg();
905   MachineInstr *DefI = getReachingDefForPred(RT, TfrI, PredR, Cond);
906   if (!DefI || !isPredicable(DefI))
907     return false;
908 
909   DEBUG(dbgs() << "Source def: " << *DefI);
910 
911   // Collect the information about registers defined and used between the
912   // DefI and the TfrI.
913   // Map: reg -> bitmask of subregs
914   ReferenceMap Uses, Defs;
915   MachineBasicBlock::iterator DefIt = DefI, TfrIt = TfrI;
916 
917   // Check if the predicate register is valid between DefI and TfrI.
918   // If it is, we can then ignore instructions predicated on the negated
919   // conditions when collecting def and use information.
920   bool PredValid = true;
921   for (MachineBasicBlock::iterator I = std::next(DefIt); I != TfrIt; ++I) {
922     if (!I->modifiesRegister(PredR, 0))
923       continue;
924     PredValid = false;
925     break;
926   }
927 
928   for (MachineBasicBlock::iterator I = std::next(DefIt); I != TfrIt; ++I) {
929     MachineInstr *MI = &*I;
930     // If this instruction is predicated on the same register, it could
931     // potentially be ignored.
932     // By default assume that the instruction executes on the same condition
933     // as TfrI (Exec_Then), and also on the opposite one (Exec_Else).
934     unsigned Exec = Exec_Then | Exec_Else;
935     if (PredValid && HII->isPredicated(*MI) && MI->readsRegister(PredR))
936       Exec = (Cond == HII->isPredicatedTrue(*MI)) ? Exec_Then : Exec_Else;
937 
938     for (auto &Op : MI->operands()) {
939       if (!Op.isReg())
940         continue;
941       // We don't want to deal with physical registers. The reason is that
942       // they can be aliased with other physical registers. Aliased virtual
943       // registers must share the same register number, and can only differ
944       // in the subregisters, which we are keeping track of. Physical
945       // registers ters no longer have subregisters---their super- and
946       // subregisters are other physical registers, and we are not checking
947       // that.
948       RegisterRef RR = Op;
949       if (!TargetRegisterInfo::isVirtualRegister(RR.Reg))
950         return false;
951 
952       ReferenceMap &Map = Op.isDef() ? Defs : Uses;
953       if (Op.isDef() && Op.isUndef()) {
954         assert(RR.Sub && "Expecting a subregister on <def,read-undef>");
955         // If this is a <def,read-undef>, then it invalidates the non-written
956         // part of the register. For the purpose of checking the validity of
957         // the move, assume that it modifies the whole register.
958         RR.Sub = 0;
959       }
960       addRefToMap(RR, Map, Exec);
961     }
962   }
963 
964   // The situation:
965   //   RT = DefI
966   //   ...
967   //   RD = TfrI ..., RT
968 
969   // If the register-in-the-middle (RT) is used or redefined between
970   // DefI and TfrI, we may not be able proceed with this transformation.
971   // We can ignore a def that will not execute together with TfrI, and a
972   // use that will. If there is such a use (that does execute together with
973   // TfrI), we will not be able to move DefI down. If there is a use that
974   // executed if TfrI's condition is false, then RT must be available
975   // unconditionally (cannot be predicated).
976   // Essentially, we need to be able to rename RT to RD in this segment.
977   if (isRefInMap(RT, Defs, Exec_Then) || isRefInMap(RT, Uses, Exec_Else))
978     return false;
979   RegisterRef RD = MD;
980   // If the predicate register is defined between DefI and TfrI, the only
981   // potential thing to do would be to move the DefI down to TfrI, and then
982   // predicate. The reaching def (DefI) must be movable down to the location
983   // of the TfrI.
984   // If the target register of the TfrI (RD) is not used or defined between
985   // DefI and TfrI, consider moving TfrI up to DefI.
986   bool CanUp =   canMoveOver(TfrI, Defs, Uses);
987   bool CanDown = canMoveOver(*DefI, Defs, Uses);
988   // The TfrI does not access memory, but DefI could. Check if it's safe
989   // to move DefI down to TfrI.
990   if (DefI->mayLoad() || DefI->mayStore())
991     if (!canMoveMemTo(*DefI, TfrI, true))
992       CanDown = false;
993 
994   DEBUG(dbgs() << "Can move up: " << (CanUp ? "yes" : "no")
995                << ", can move down: " << (CanDown ? "yes\n" : "no\n"));
996   MachineBasicBlock::iterator PastDefIt = std::next(DefIt);
997   if (CanUp)
998     predicateAt(MD, *DefI, PastDefIt, MP, Cond, UpdRegs);
999   else if (CanDown)
1000     predicateAt(MD, *DefI, TfrIt, MP, Cond, UpdRegs);
1001   else
1002     return false;
1003 
1004   if (RT != RD) {
1005     renameInRange(RT, RD, PredR, Cond, PastDefIt, TfrIt);
1006     UpdRegs.insert(RT.Reg);
1007   }
1008 
1009   removeInstr(TfrI);
1010   removeInstr(*DefI);
1011   return true;
1012 }
1013 
1014 
1015 /// Predicate all cases of conditional copies in the specified block.
1016 bool HexagonExpandCondsets::predicateInBlock(MachineBasicBlock &B,
1017       std::set<unsigned> &UpdRegs) {
1018   bool Changed = false;
1019   MachineBasicBlock::iterator I, E, NextI;
1020   for (I = B.begin(), E = B.end(); I != E; I = NextI) {
1021     NextI = std::next(I);
1022     unsigned Opc = I->getOpcode();
1023     if (Opc == Hexagon::A2_tfrt || Opc == Hexagon::A2_tfrf) {
1024       bool Done = predicate(*I, (Opc == Hexagon::A2_tfrt), UpdRegs);
1025       if (!Done) {
1026         // If we didn't predicate I, we may need to remove it in case it is
1027         // an "identity" copy, e.g.  vreg1 = A2_tfrt vreg2, vreg1.
1028         if (RegisterRef(I->getOperand(0)) == RegisterRef(I->getOperand(2))) {
1029           for (auto &Op : I->operands())
1030             if (Op.isReg())
1031               UpdRegs.insert(Op.getReg());
1032           removeInstr(*I);
1033         }
1034       }
1035       Changed |= Done;
1036     }
1037   }
1038   return Changed;
1039 }
1040 
1041 
1042 bool HexagonExpandCondsets::isIntReg(RegisterRef RR, unsigned &BW) {
1043   if (!TargetRegisterInfo::isVirtualRegister(RR.Reg))
1044     return false;
1045   const TargetRegisterClass *RC = MRI->getRegClass(RR.Reg);
1046   if (RC == &Hexagon::IntRegsRegClass) {
1047     BW = 32;
1048     return true;
1049   }
1050   if (RC == &Hexagon::DoubleRegsRegClass) {
1051     BW = (RR.Sub != 0) ? 32 : 64;
1052     return true;
1053   }
1054   return false;
1055 }
1056 
1057 
1058 bool HexagonExpandCondsets::isIntraBlocks(LiveInterval &LI) {
1059   for (LiveInterval::iterator I = LI.begin(), E = LI.end(); I != E; ++I) {
1060     LiveRange::Segment &LR = *I;
1061     // Range must start at a register...
1062     if (!LR.start.isRegister())
1063       return false;
1064     // ...and end in a register or in a dead slot.
1065     if (!LR.end.isRegister() && !LR.end.isDead())
1066       return false;
1067   }
1068   return true;
1069 }
1070 
1071 
1072 bool HexagonExpandCondsets::coalesceRegisters(RegisterRef R1, RegisterRef R2) {
1073   if (CoaLimitActive) {
1074     if (CoaCounter >= CoaLimit)
1075       return false;
1076     CoaCounter++;
1077   }
1078   unsigned BW1, BW2;
1079   if (!isIntReg(R1, BW1) || !isIntReg(R2, BW2) || BW1 != BW2)
1080     return false;
1081   if (MRI->isLiveIn(R1.Reg))
1082     return false;
1083   if (MRI->isLiveIn(R2.Reg))
1084     return false;
1085 
1086   LiveInterval &L1 = LIS->getInterval(R1.Reg);
1087   LiveInterval &L2 = LIS->getInterval(R2.Reg);
1088   if (L2.empty())
1089     return false;
1090   if (L1.hasSubRanges() || L2.hasSubRanges())
1091     return false;
1092   bool Overlap = L1.overlaps(L2);
1093 
1094   DEBUG(dbgs() << "compatible registers: ("
1095                << (Overlap ? "overlap" : "disjoint") << ")\n  "
1096                << PrintReg(R1.Reg, TRI, R1.Sub) << "  " << L1 << "\n  "
1097                << PrintReg(R2.Reg, TRI, R2.Sub) << "  " << L2 << "\n");
1098   if (R1.Sub || R2.Sub)
1099     return false;
1100   if (Overlap)
1101     return false;
1102 
1103   // Coalescing could have a negative impact on scheduling, so try to limit
1104   // to some reasonable extent. Only consider coalescing segments, when one
1105   // of them does not cross basic block boundaries.
1106   if (!isIntraBlocks(L1) && !isIntraBlocks(L2))
1107     return false;
1108 
1109   MRI->replaceRegWith(R2.Reg, R1.Reg);
1110 
1111   // Move all live segments from L2 to L1.
1112   typedef DenseMap<VNInfo*,VNInfo*> ValueInfoMap;
1113   ValueInfoMap VM;
1114   for (LiveInterval::iterator I = L2.begin(), E = L2.end(); I != E; ++I) {
1115     VNInfo *NewVN, *OldVN = I->valno;
1116     ValueInfoMap::iterator F = VM.find(OldVN);
1117     if (F == VM.end()) {
1118       NewVN = L1.getNextValue(I->valno->def, LIS->getVNInfoAllocator());
1119       VM.insert(std::make_pair(OldVN, NewVN));
1120     } else {
1121       NewVN = F->second;
1122     }
1123     L1.addSegment(LiveRange::Segment(I->start, I->end, NewVN));
1124   }
1125   while (L2.begin() != L2.end())
1126     L2.removeSegment(*L2.begin());
1127   LIS->removeInterval(R2.Reg);
1128 
1129   updateKillFlags(R1.Reg);
1130   DEBUG(dbgs() << "coalesced: " << L1 << "\n");
1131   L1.verify();
1132 
1133   return true;
1134 }
1135 
1136 
1137 /// Attempt to coalesce one of the source registers to a MUX instruction with
1138 /// the destination register. This could lead to having only one predicated
1139 /// instruction in the end instead of two.
1140 bool HexagonExpandCondsets::coalesceSegments(
1141       const SmallVectorImpl<MachineInstr*> &Condsets,
1142       std::set<unsigned> &UpdRegs) {
1143   SmallVector<MachineInstr*,16> TwoRegs;
1144   for (MachineInstr *MI : Condsets) {
1145     MachineOperand &S1 = MI->getOperand(2), &S2 = MI->getOperand(3);
1146     if (!S1.isReg() && !S2.isReg())
1147       continue;
1148     TwoRegs.push_back(MI);
1149   }
1150 
1151   bool Changed = false;
1152   for (MachineInstr *CI : TwoRegs) {
1153     RegisterRef RD = CI->getOperand(0);
1154     RegisterRef RP = CI->getOperand(1);
1155     MachineOperand &S1 = CI->getOperand(2), &S2 = CI->getOperand(3);
1156     bool Done = false;
1157     // Consider this case:
1158     //   vreg1 = instr1 ...
1159     //   vreg2 = instr2 ...
1160     //   vreg0 = C2_mux ..., vreg1, vreg2
1161     // If vreg0 was coalesced with vreg1, we could end up with the following
1162     // code:
1163     //   vreg0 = instr1 ...
1164     //   vreg2 = instr2 ...
1165     //   vreg0 = A2_tfrf ..., vreg2
1166     // which will later become:
1167     //   vreg0 = instr1 ...
1168     //   vreg0 = instr2_cNotPt ...
1169     // i.e. there will be an unconditional definition (instr1) of vreg0
1170     // followed by a conditional one. The output dependency was there before
1171     // and it unavoidable, but if instr1 is predicable, we will no longer be
1172     // able to predicate it here.
1173     // To avoid this scenario, don't coalesce the destination register with
1174     // a source register that is defined by a predicable instruction.
1175     if (S1.isReg()) {
1176       RegisterRef RS = S1;
1177       MachineInstr *RDef = getReachingDefForPred(RS, CI, RP.Reg, true);
1178       if (!RDef || !HII->isPredicable(*RDef)) {
1179         Done = coalesceRegisters(RD, RegisterRef(S1));
1180         if (Done) {
1181           UpdRegs.insert(RD.Reg);
1182           UpdRegs.insert(S1.getReg());
1183         }
1184       }
1185     }
1186     if (!Done && S2.isReg()) {
1187       RegisterRef RS = S2;
1188       MachineInstr *RDef = getReachingDefForPred(RS, CI, RP.Reg, false);
1189       if (!RDef || !HII->isPredicable(*RDef)) {
1190         Done = coalesceRegisters(RD, RegisterRef(S2));
1191         if (Done) {
1192           UpdRegs.insert(RD.Reg);
1193           UpdRegs.insert(S2.getReg());
1194         }
1195       }
1196     }
1197     Changed |= Done;
1198   }
1199   return Changed;
1200 }
1201 
1202 
1203 bool HexagonExpandCondsets::runOnMachineFunction(MachineFunction &MF) {
1204   if (skipFunction(*MF.getFunction()))
1205     return false;
1206 
1207   HII = static_cast<const HexagonInstrInfo*>(MF.getSubtarget().getInstrInfo());
1208   TRI = MF.getSubtarget().getRegisterInfo();
1209   MDT = &getAnalysis<MachineDominatorTree>();
1210   LIS = &getAnalysis<LiveIntervals>();
1211   MRI = &MF.getRegInfo();
1212 
1213   DEBUG(LIS->print(dbgs() << "Before expand-condsets\n",
1214                    MF.getFunction()->getParent()));
1215 
1216   bool Changed = false;
1217   std::set<unsigned> CoalUpd, PredUpd;
1218 
1219   SmallVector<MachineInstr*,16> Condsets;
1220   for (auto &B : MF)
1221     for (auto &I : B)
1222       if (isCondset(I))
1223         Condsets.push_back(&I);
1224 
1225   // Try to coalesce the target of a mux with one of its sources.
1226   // This could eliminate a register copy in some circumstances.
1227   Changed |= coalesceSegments(Condsets, CoalUpd);
1228 
1229   // Update kill flags on all source operands. This is done here because
1230   // at this moment (when expand-condsets runs), there are no kill flags
1231   // in the IR (they have been removed by live range analysis).
1232   // Updating them right before we split is the easiest, because splitting
1233   // adds definitions which would interfere with updating kills afterwards.
1234   std::set<unsigned> KillUpd;
1235   for (MachineInstr *MI : Condsets)
1236     for (MachineOperand &Op : MI->operands())
1237       if (Op.isReg() && Op.isUse())
1238         if (!CoalUpd.count(Op.getReg()))
1239           KillUpd.insert(Op.getReg());
1240   updateLiveness(KillUpd, false, true, false);
1241   DEBUG(LIS->print(dbgs() << "After coalescing\n",
1242                    MF.getFunction()->getParent()));
1243 
1244   // First, simply split all muxes into a pair of conditional transfers
1245   // and update the live intervals to reflect the new arrangement. The
1246   // goal is to update the kill flags, since predication will rely on
1247   // them.
1248   for (MachineInstr *MI : Condsets)
1249     Changed |= split(*MI, PredUpd);
1250   Condsets.clear(); // The contents of Condsets are invalid here anyway.
1251 
1252   // Do not update live ranges after splitting. Recalculation of live
1253   // intervals removes kill flags, which were preserved by splitting on
1254   // the source operands of condsets. These kill flags are needed by
1255   // predication, and after splitting they are difficult to recalculate
1256   // (because of predicated defs), so make sure they are left untouched.
1257   // Predication does not use live intervals.
1258   DEBUG(LIS->print(dbgs() << "After splitting\n",
1259                    MF.getFunction()->getParent()));
1260 
1261   // Traverse all blocks and collapse predicable instructions feeding
1262   // conditional transfers into predicated instructions.
1263   // Walk over all the instructions again, so we may catch pre-existing
1264   // cases that were not created in the previous step.
1265   for (auto &B : MF)
1266     Changed |= predicateInBlock(B, PredUpd);
1267   DEBUG(LIS->print(dbgs() << "After predicating\n",
1268                    MF.getFunction()->getParent()));
1269 
1270   PredUpd.insert(CoalUpd.begin(), CoalUpd.end());
1271   updateLiveness(PredUpd, true, true, true);
1272 
1273   DEBUG({
1274     if (Changed)
1275       LIS->print(dbgs() << "After expand-condsets\n",
1276                  MF.getFunction()->getParent());
1277   });
1278 
1279   return Changed;
1280 }
1281 
1282 
1283 //===----------------------------------------------------------------------===//
1284 //                         Public Constructor Functions
1285 //===----------------------------------------------------------------------===//
1286 
1287 FunctionPass *llvm::createHexagonExpandCondsets() {
1288   return new HexagonExpandCondsets();
1289 }
1290