1 //===- HexagonGenInsert.cpp -----------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "BitTracker.h"
10 #include "HexagonBitTracker.h"
11 #include "HexagonInstrInfo.h"
12 #include "HexagonRegisterInfo.h"
13 #include "HexagonSubtarget.h"
14 #include "llvm/ADT/BitVector.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/GraphTraits.h"
17 #include "llvm/ADT/PostOrderIterator.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/CodeGen/MachineBasicBlock.h"
23 #include "llvm/CodeGen/MachineDominators.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineOperand.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/TargetRegisterInfo.h"
31 #include "llvm/IR/DebugLoc.h"
32 #include "llvm/InitializePasses.h"
33 #include "llvm/Pass.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Timer.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include <algorithm>
40 #include <cassert>
41 #include <cstdint>
42 #include <iterator>
43 #include <utility>
44 #include <vector>
45 
46 #define DEBUG_TYPE "hexinsert"
47 
48 using namespace llvm;
49 
50 static cl::opt<unsigned>
51     VRegIndexCutoff("insert-vreg-cutoff", cl::init(~0U), cl::Hidden,
52                     cl::desc("Vreg# cutoff for insert generation."));
53 // The distance cutoff is selected based on the precheckin-perf results:
54 // cutoffs 20, 25, 35, and 40 are worse than 30.
55 static cl::opt<unsigned>
56     VRegDistCutoff("insert-dist-cutoff", cl::init(30U), cl::Hidden,
57                    cl::desc("Vreg distance cutoff for insert "
58                             "generation."));
59 
60 // Limit the container sizes for extreme cases where we run out of memory.
61 static cl::opt<unsigned>
62     MaxORLSize("insert-max-orl", cl::init(4096), cl::Hidden,
63                cl::desc("Maximum size of OrderedRegisterList"));
64 static cl::opt<unsigned> MaxIFMSize("insert-max-ifmap", cl::init(1024),
65                                     cl::Hidden,
66                                     cl::desc("Maximum size of IFMap"));
67 
68 static cl::opt<bool> OptTiming("insert-timing", cl::Hidden, cl::ZeroOrMore,
69                                cl::desc("Enable timing of insert generation"));
70 static cl::opt<bool>
71     OptTimingDetail("insert-timing-detail", cl::Hidden,
72                     cl::desc("Enable detailed timing of insert "
73                              "generation"));
74 
75 static cl::opt<bool> OptSelectAll0("insert-all0", cl::init(false), cl::Hidden,
76   cl::ZeroOrMore);
77 static cl::opt<bool> OptSelectHas0("insert-has0", cl::init(false), cl::Hidden,
78   cl::ZeroOrMore);
79 // Whether to construct constant values via "insert". Could eliminate constant
80 // extenders, but often not practical.
81 static cl::opt<bool> OptConst("insert-const", cl::init(false), cl::Hidden,
82   cl::ZeroOrMore);
83 
84 // The preprocessor gets confused when the DEBUG macro is passed larger
85 // chunks of code. Use this function to detect debugging.
86 inline static bool isDebug() {
87 #ifndef NDEBUG
88   return DebugFlag && isCurrentDebugType(DEBUG_TYPE);
89 #else
90   return false;
91 #endif
92 }
93 
94 namespace {
95 
96   // Set of virtual registers, based on BitVector.
97   struct RegisterSet : private BitVector {
98     RegisterSet() = default;
99     explicit RegisterSet(unsigned s, bool t = false) : BitVector(s, t) {}
100     RegisterSet(const RegisterSet &RS) = default;
101     RegisterSet &operator=(const RegisterSet &RS) = default;
102 
103     using BitVector::clear;
104 
105     unsigned find_first() const {
106       int First = BitVector::find_first();
107       if (First < 0)
108         return 0;
109       return x2v(First);
110     }
111 
112     unsigned find_next(unsigned Prev) const {
113       int Next = BitVector::find_next(v2x(Prev));
114       if (Next < 0)
115         return 0;
116       return x2v(Next);
117     }
118 
119     RegisterSet &insert(unsigned R) {
120       unsigned Idx = v2x(R);
121       ensure(Idx);
122       return static_cast<RegisterSet&>(BitVector::set(Idx));
123     }
124     RegisterSet &remove(unsigned R) {
125       unsigned Idx = v2x(R);
126       if (Idx >= size())
127         return *this;
128       return static_cast<RegisterSet&>(BitVector::reset(Idx));
129     }
130 
131     RegisterSet &insert(const RegisterSet &Rs) {
132       return static_cast<RegisterSet&>(BitVector::operator|=(Rs));
133     }
134     RegisterSet &remove(const RegisterSet &Rs) {
135       return static_cast<RegisterSet&>(BitVector::reset(Rs));
136     }
137 
138     reference operator[](unsigned R) {
139       unsigned Idx = v2x(R);
140       ensure(Idx);
141       return BitVector::operator[](Idx);
142     }
143     bool operator[](unsigned R) const {
144       unsigned Idx = v2x(R);
145       assert(Idx < size());
146       return BitVector::operator[](Idx);
147     }
148     bool has(unsigned R) const {
149       unsigned Idx = v2x(R);
150       if (Idx >= size())
151         return false;
152       return BitVector::test(Idx);
153     }
154 
155     bool empty() const {
156       return !BitVector::any();
157     }
158     bool includes(const RegisterSet &Rs) const {
159       // A.BitVector::test(B)  <=>  A-B != {}
160       return !Rs.BitVector::test(*this);
161     }
162     bool intersects(const RegisterSet &Rs) const {
163       return BitVector::anyCommon(Rs);
164     }
165 
166   private:
167     void ensure(unsigned Idx) {
168       if (size() <= Idx)
169         resize(std::max(Idx+1, 32U));
170     }
171 
172     static inline unsigned v2x(unsigned v) {
173       return Register::virtReg2Index(v);
174     }
175 
176     static inline unsigned x2v(unsigned x) {
177       return Register::index2VirtReg(x);
178     }
179   };
180 
181   struct PrintRegSet {
182     PrintRegSet(const RegisterSet &S, const TargetRegisterInfo *RI)
183       : RS(S), TRI(RI) {}
184 
185     friend raw_ostream &operator<< (raw_ostream &OS,
186           const PrintRegSet &P);
187 
188   private:
189     const RegisterSet &RS;
190     const TargetRegisterInfo *TRI;
191   };
192 
193   raw_ostream &operator<< (raw_ostream &OS, const PrintRegSet &P) {
194     OS << '{';
195     for (unsigned R = P.RS.find_first(); R; R = P.RS.find_next(R))
196       OS << ' ' << printReg(R, P.TRI);
197     OS << " }";
198     return OS;
199   }
200 
201   // A convenience class to associate unsigned numbers (such as virtual
202   // registers) with unsigned numbers.
203   struct UnsignedMap : public DenseMap<unsigned,unsigned> {
204     UnsignedMap() = default;
205 
206   private:
207     using BaseType = DenseMap<unsigned, unsigned>;
208   };
209 
210   // A utility to establish an ordering between virtual registers:
211   // VRegA < VRegB  <=>  RegisterOrdering[VRegA] < RegisterOrdering[VRegB]
212   // This is meant as a cache for the ordering of virtual registers defined
213   // by a potentially expensive comparison function, or obtained by a proce-
214   // dure that should not be repeated each time two registers are compared.
215   struct RegisterOrdering : public UnsignedMap {
216     RegisterOrdering() = default;
217 
218     unsigned operator[](unsigned VR) const {
219       const_iterator F = find(VR);
220       assert(F != end());
221       return F->second;
222     }
223 
224     // Add operator(), so that objects of this class can be used as
225     // comparators in std::sort et al.
226     bool operator() (unsigned VR1, unsigned VR2) const {
227       return operator[](VR1) < operator[](VR2);
228     }
229   };
230 
231   // Ordering of bit values. This class does not have operator[], but
232   // is supplies a comparison operator() for use in std:: algorithms.
233   // The order is as follows:
234   // - 0 < 1 < ref
235   // - ref1 < ref2, if ord(ref1.Reg) < ord(ref2.Reg),
236   //   or ord(ref1.Reg) == ord(ref2.Reg), and ref1.Pos < ref2.Pos.
237   struct BitValueOrdering {
238     BitValueOrdering(const RegisterOrdering &RB) : BaseOrd(RB) {}
239 
240     bool operator() (const BitTracker::BitValue &V1,
241           const BitTracker::BitValue &V2) const;
242 
243     const RegisterOrdering &BaseOrd;
244   };
245 
246 } // end anonymous namespace
247 
248 bool BitValueOrdering::operator() (const BitTracker::BitValue &V1,
249       const BitTracker::BitValue &V2) const {
250   if (V1 == V2)
251     return false;
252   // V1==0 => true, V2==0 => false
253   if (V1.is(0) || V2.is(0))
254     return V1.is(0);
255   // Neither of V1,V2 is 0, and V1!=V2.
256   // V2==1 => false, V1==1 => true
257   if (V2.is(1) || V1.is(1))
258     return !V2.is(1);
259   // Both V1,V2 are refs.
260   unsigned Ind1 = BaseOrd[V1.RefI.Reg], Ind2 = BaseOrd[V2.RefI.Reg];
261   if (Ind1 != Ind2)
262     return Ind1 < Ind2;
263   // If V1.Pos==V2.Pos
264   assert(V1.RefI.Pos != V2.RefI.Pos && "Bit values should be different");
265   return V1.RefI.Pos < V2.RefI.Pos;
266 }
267 
268 namespace {
269 
270   // Cache for the BitTracker's cell map. Map lookup has a logarithmic
271   // complexity, this class will memoize the lookup results to reduce
272   // the access time for repeated lookups of the same cell.
273   struct CellMapShadow {
274     CellMapShadow(const BitTracker &T) : BT(T) {}
275 
276     const BitTracker::RegisterCell &lookup(unsigned VR) {
277       unsigned RInd = Register::virtReg2Index(VR);
278       // Grow the vector to at least 32 elements.
279       if (RInd >= CVect.size())
280         CVect.resize(std::max(RInd+16, 32U), nullptr);
281       const BitTracker::RegisterCell *CP = CVect[RInd];
282       if (CP == nullptr)
283         CP = CVect[RInd] = &BT.lookup(VR);
284       return *CP;
285     }
286 
287     const BitTracker &BT;
288 
289   private:
290     using CellVectType = std::vector<const BitTracker::RegisterCell *>;
291 
292     CellVectType CVect;
293   };
294 
295   // Comparator class for lexicographic ordering of virtual registers
296   // according to the corresponding BitTracker::RegisterCell objects.
297   struct RegisterCellLexCompare {
298     RegisterCellLexCompare(const BitValueOrdering &BO, CellMapShadow &M)
299       : BitOrd(BO), CM(M) {}
300 
301     bool operator() (unsigned VR1, unsigned VR2) const;
302 
303   private:
304     const BitValueOrdering &BitOrd;
305     CellMapShadow &CM;
306   };
307 
308   // Comparator class for lexicographic ordering of virtual registers
309   // according to the specified bits of the corresponding BitTracker::
310   // RegisterCell objects.
311   // Specifically, this class will be used to compare bit B of a register
312   // cell for a selected virtual register R with bit N of any register
313   // other than R.
314   struct RegisterCellBitCompareSel {
315     RegisterCellBitCompareSel(unsigned R, unsigned B, unsigned N,
316           const BitValueOrdering &BO, CellMapShadow &M)
317       : SelR(R), SelB(B), BitN(N), BitOrd(BO), CM(M) {}
318 
319     bool operator() (unsigned VR1, unsigned VR2) const;
320 
321   private:
322     const unsigned SelR, SelB;
323     const unsigned BitN;
324     const BitValueOrdering &BitOrd;
325     CellMapShadow &CM;
326   };
327 
328 } // end anonymous namespace
329 
330 bool RegisterCellLexCompare::operator() (unsigned VR1, unsigned VR2) const {
331   // Ordering of registers, made up from two given orderings:
332   // - the ordering of the register numbers, and
333   // - the ordering of register cells.
334   // Def. R1 < R2 if:
335   // - cell(R1) < cell(R2), or
336   // - cell(R1) == cell(R2), and index(R1) < index(R2).
337   //
338   // For register cells, the ordering is lexicographic, with index 0 being
339   // the most significant.
340   if (VR1 == VR2)
341     return false;
342 
343   const BitTracker::RegisterCell &RC1 = CM.lookup(VR1), &RC2 = CM.lookup(VR2);
344   uint16_t W1 = RC1.width(), W2 = RC2.width();
345   for (uint16_t i = 0, w = std::min(W1, W2); i < w; ++i) {
346     const BitTracker::BitValue &V1 = RC1[i], &V2 = RC2[i];
347     if (V1 != V2)
348       return BitOrd(V1, V2);
349   }
350   // Cells are equal up until the common length.
351   if (W1 != W2)
352     return W1 < W2;
353 
354   return BitOrd.BaseOrd[VR1] < BitOrd.BaseOrd[VR2];
355 }
356 
357 bool RegisterCellBitCompareSel::operator() (unsigned VR1, unsigned VR2) const {
358   if (VR1 == VR2)
359     return false;
360   const BitTracker::RegisterCell &RC1 = CM.lookup(VR1);
361   const BitTracker::RegisterCell &RC2 = CM.lookup(VR2);
362   uint16_t W1 = RC1.width(), W2 = RC2.width();
363   uint16_t Bit1 = (VR1 == SelR) ? SelB : BitN;
364   uint16_t Bit2 = (VR2 == SelR) ? SelB : BitN;
365   // If Bit1 exceeds the width of VR1, then:
366   // - return false, if at the same time Bit2 exceeds VR2, or
367   // - return true, otherwise.
368   // (I.e. "a bit value that does not exist is less than any bit value
369   // that does exist".)
370   if (W1 <= Bit1)
371     return Bit2 < W2;
372   // If Bit1 is within VR1, but Bit2 is not within VR2, return false.
373   if (W2 <= Bit2)
374     return false;
375 
376   const BitTracker::BitValue &V1 = RC1[Bit1], V2 = RC2[Bit2];
377   if (V1 != V2)
378     return BitOrd(V1, V2);
379   return false;
380 }
381 
382 namespace {
383 
384   class OrderedRegisterList {
385     using ListType = std::vector<unsigned>;
386     const unsigned MaxSize;
387 
388   public:
389     OrderedRegisterList(const RegisterOrdering &RO)
390       : MaxSize(MaxORLSize), Ord(RO) {}
391 
392     void insert(unsigned VR);
393     void remove(unsigned VR);
394 
395     unsigned operator[](unsigned Idx) const {
396       assert(Idx < Seq.size());
397       return Seq[Idx];
398     }
399 
400     unsigned size() const {
401       return Seq.size();
402     }
403 
404     using iterator = ListType::iterator;
405     using const_iterator = ListType::const_iterator;
406 
407     iterator begin() { return Seq.begin(); }
408     iterator end() { return Seq.end(); }
409     const_iterator begin() const { return Seq.begin(); }
410     const_iterator end() const { return Seq.end(); }
411 
412     // Convenience function to convert an iterator to the corresponding index.
413     unsigned idx(iterator It) const { return It-begin(); }
414 
415   private:
416     ListType Seq;
417     const RegisterOrdering &Ord;
418   };
419 
420   struct PrintORL {
421     PrintORL(const OrderedRegisterList &L, const TargetRegisterInfo *RI)
422       : RL(L), TRI(RI) {}
423 
424     friend raw_ostream &operator<< (raw_ostream &OS, const PrintORL &P);
425 
426   private:
427     const OrderedRegisterList &RL;
428     const TargetRegisterInfo *TRI;
429   };
430 
431   raw_ostream &operator<< (raw_ostream &OS, const PrintORL &P) {
432     OS << '(';
433     OrderedRegisterList::const_iterator B = P.RL.begin(), E = P.RL.end();
434     for (OrderedRegisterList::const_iterator I = B; I != E; ++I) {
435       if (I != B)
436         OS << ", ";
437       OS << printReg(*I, P.TRI);
438     }
439     OS << ')';
440     return OS;
441   }
442 
443 } // end anonymous namespace
444 
445 void OrderedRegisterList::insert(unsigned VR) {
446   iterator L = llvm::lower_bound(Seq, VR, Ord);
447   if (L == Seq.end())
448     Seq.push_back(VR);
449   else
450     Seq.insert(L, VR);
451 
452   unsigned S = Seq.size();
453   if (S > MaxSize)
454     Seq.resize(MaxSize);
455   assert(Seq.size() <= MaxSize);
456 }
457 
458 void OrderedRegisterList::remove(unsigned VR) {
459   iterator L = llvm::lower_bound(Seq, VR, Ord);
460   if (L != Seq.end())
461     Seq.erase(L);
462 }
463 
464 namespace {
465 
466   // A record of the insert form. The fields correspond to the operands
467   // of the "insert" instruction:
468   // ... = insert(SrcR, InsR, #Wdh, #Off)
469   struct IFRecord {
470     IFRecord(unsigned SR = 0, unsigned IR = 0, uint16_t W = 0, uint16_t O = 0)
471       : SrcR(SR), InsR(IR), Wdh(W), Off(O) {}
472 
473     unsigned SrcR, InsR;
474     uint16_t Wdh, Off;
475   };
476 
477   struct PrintIFR {
478     PrintIFR(const IFRecord &R, const TargetRegisterInfo *RI)
479       : IFR(R), TRI(RI) {}
480 
481   private:
482     friend raw_ostream &operator<< (raw_ostream &OS, const PrintIFR &P);
483 
484     const IFRecord &IFR;
485     const TargetRegisterInfo *TRI;
486   };
487 
488   raw_ostream &operator<< (raw_ostream &OS, const PrintIFR &P) {
489     unsigned SrcR = P.IFR.SrcR, InsR = P.IFR.InsR;
490     OS << '(' << printReg(SrcR, P.TRI) << ',' << printReg(InsR, P.TRI)
491        << ",#" << P.IFR.Wdh << ",#" << P.IFR.Off << ')';
492     return OS;
493   }
494 
495   using IFRecordWithRegSet = std::pair<IFRecord, RegisterSet>;
496 
497 } // end anonymous namespace
498 
499 namespace llvm {
500 
501   void initializeHexagonGenInsertPass(PassRegistry&);
502   FunctionPass *createHexagonGenInsert();
503 
504 } // end namespace llvm
505 
506 namespace {
507 
508   class HexagonGenInsert : public MachineFunctionPass {
509   public:
510     static char ID;
511 
512     HexagonGenInsert() : MachineFunctionPass(ID) {
513       initializeHexagonGenInsertPass(*PassRegistry::getPassRegistry());
514     }
515 
516     StringRef getPassName() const override {
517       return "Hexagon generate \"insert\" instructions";
518     }
519 
520     void getAnalysisUsage(AnalysisUsage &AU) const override {
521       AU.addRequired<MachineDominatorTree>();
522       AU.addPreserved<MachineDominatorTree>();
523       MachineFunctionPass::getAnalysisUsage(AU);
524     }
525 
526     bool runOnMachineFunction(MachineFunction &MF) override;
527 
528   private:
529     using PairMapType = DenseMap<std::pair<unsigned, unsigned>, unsigned>;
530 
531     void buildOrderingMF(RegisterOrdering &RO) const;
532     void buildOrderingBT(RegisterOrdering &RB, RegisterOrdering &RO) const;
533     bool isIntClass(const TargetRegisterClass *RC) const;
534     bool isConstant(unsigned VR) const;
535     bool isSmallConstant(unsigned VR) const;
536     bool isValidInsertForm(unsigned DstR, unsigned SrcR, unsigned InsR,
537           uint16_t L, uint16_t S) const;
538     bool findSelfReference(unsigned VR) const;
539     bool findNonSelfReference(unsigned VR) const;
540     void getInstrDefs(const MachineInstr *MI, RegisterSet &Defs) const;
541     void getInstrUses(const MachineInstr *MI, RegisterSet &Uses) const;
542     unsigned distance(const MachineBasicBlock *FromB,
543           const MachineBasicBlock *ToB, const UnsignedMap &RPO,
544           PairMapType &M) const;
545     unsigned distance(MachineBasicBlock::const_iterator FromI,
546           MachineBasicBlock::const_iterator ToI, const UnsignedMap &RPO,
547           PairMapType &M) const;
548     bool findRecordInsertForms(unsigned VR, OrderedRegisterList &AVs);
549     void collectInBlock(MachineBasicBlock *B, OrderedRegisterList &AVs);
550     void findRemovableRegisters(unsigned VR, IFRecord IF,
551           RegisterSet &RMs) const;
552     void computeRemovableRegisters();
553 
554     void pruneEmptyLists();
555     void pruneCoveredSets(unsigned VR);
556     void pruneUsesTooFar(unsigned VR, const UnsignedMap &RPO, PairMapType &M);
557     void pruneRegCopies(unsigned VR);
558     void pruneCandidates();
559     void selectCandidates();
560     bool generateInserts();
561 
562     bool removeDeadCode(MachineDomTreeNode *N);
563 
564     // IFRecord coupled with a set of potentially removable registers:
565     using IFListType = std::vector<IFRecordWithRegSet>;
566     using IFMapType = DenseMap<unsigned, IFListType>; // vreg -> IFListType
567 
568     void dump_map() const;
569 
570     const HexagonInstrInfo *HII = nullptr;
571     const HexagonRegisterInfo *HRI = nullptr;
572 
573     MachineFunction *MFN;
574     MachineRegisterInfo *MRI;
575     MachineDominatorTree *MDT;
576     CellMapShadow *CMS;
577 
578     RegisterOrdering BaseOrd;
579     RegisterOrdering CellOrd;
580     IFMapType IFMap;
581   };
582 
583 } // end anonymous namespace
584 
585 char HexagonGenInsert::ID = 0;
586 
587 void HexagonGenInsert::dump_map() const {
588   for (const auto &I : IFMap) {
589     dbgs() << "  " << printReg(I.first, HRI) << ":\n";
590     const IFListType &LL = I.second;
591     for (const auto &J : LL)
592       dbgs() << "    " << PrintIFR(J.first, HRI) << ", "
593              << PrintRegSet(J.second, HRI) << '\n';
594   }
595 }
596 
597 void HexagonGenInsert::buildOrderingMF(RegisterOrdering &RO) const {
598   unsigned Index = 0;
599 
600   for (const MachineBasicBlock &B : *MFN) {
601     if (!CMS->BT.reached(&B))
602       continue;
603 
604     for (const MachineInstr &MI : B) {
605       for (const MachineOperand &MO : MI.operands()) {
606         if (MO.isReg() && MO.isDef()) {
607           Register R = MO.getReg();
608           assert(MO.getSubReg() == 0 && "Unexpected subregister in definition");
609           if (R.isVirtual())
610             RO.insert(std::make_pair(R, Index++));
611         }
612       }
613     }
614   }
615   // Since some virtual registers may have had their def and uses eliminated,
616   // they are no longer referenced in the code, and so they will not appear
617   // in the map.
618 }
619 
620 void HexagonGenInsert::buildOrderingBT(RegisterOrdering &RB,
621       RegisterOrdering &RO) const {
622   // Create a vector of all virtual registers (collect them from the base
623   // ordering RB), and then sort it using the RegisterCell comparator.
624   BitValueOrdering BVO(RB);
625   RegisterCellLexCompare LexCmp(BVO, *CMS);
626 
627   using SortableVectorType = std::vector<unsigned>;
628 
629   SortableVectorType VRs;
630   for (auto &I : RB)
631     VRs.push_back(I.first);
632   llvm::sort(VRs, LexCmp);
633   // Transfer the results to the outgoing register ordering.
634   for (unsigned i = 0, n = VRs.size(); i < n; ++i)
635     RO.insert(std::make_pair(VRs[i], i));
636 }
637 
638 inline bool HexagonGenInsert::isIntClass(const TargetRegisterClass *RC) const {
639   return RC == &Hexagon::IntRegsRegClass || RC == &Hexagon::DoubleRegsRegClass;
640 }
641 
642 bool HexagonGenInsert::isConstant(unsigned VR) const {
643   const BitTracker::RegisterCell &RC = CMS->lookup(VR);
644   uint16_t W = RC.width();
645   for (uint16_t i = 0; i < W; ++i) {
646     const BitTracker::BitValue &BV = RC[i];
647     if (BV.is(0) || BV.is(1))
648       continue;
649     return false;
650   }
651   return true;
652 }
653 
654 bool HexagonGenInsert::isSmallConstant(unsigned VR) const {
655   const BitTracker::RegisterCell &RC = CMS->lookup(VR);
656   uint16_t W = RC.width();
657   if (W > 64)
658     return false;
659   uint64_t V = 0, B = 1;
660   for (uint16_t i = 0; i < W; ++i) {
661     const BitTracker::BitValue &BV = RC[i];
662     if (BV.is(1))
663       V |= B;
664     else if (!BV.is(0))
665       return false;
666     B <<= 1;
667   }
668 
669   // For 32-bit registers, consider: Rd = #s16.
670   if (W == 32)
671     return isInt<16>(V);
672 
673   // For 64-bit registers, it's Rdd = #s8 or Rdd = combine(#s8,#s8)
674   return isInt<8>(Lo_32(V)) && isInt<8>(Hi_32(V));
675 }
676 
677 bool HexagonGenInsert::isValidInsertForm(unsigned DstR, unsigned SrcR,
678       unsigned InsR, uint16_t L, uint16_t S) const {
679   const TargetRegisterClass *DstRC = MRI->getRegClass(DstR);
680   const TargetRegisterClass *SrcRC = MRI->getRegClass(SrcR);
681   const TargetRegisterClass *InsRC = MRI->getRegClass(InsR);
682   // Only integet (32-/64-bit) register classes.
683   if (!isIntClass(DstRC) || !isIntClass(SrcRC) || !isIntClass(InsRC))
684     return false;
685   // The "source" register must be of the same class as DstR.
686   if (DstRC != SrcRC)
687     return false;
688   if (DstRC == InsRC)
689     return true;
690   // A 64-bit register can only be generated from other 64-bit registers.
691   if (DstRC == &Hexagon::DoubleRegsRegClass)
692     return false;
693   // Otherwise, the L and S cannot span 32-bit word boundary.
694   if (S < 32 && S+L > 32)
695     return false;
696   return true;
697 }
698 
699 bool HexagonGenInsert::findSelfReference(unsigned VR) const {
700   const BitTracker::RegisterCell &RC = CMS->lookup(VR);
701   for (uint16_t i = 0, w = RC.width(); i < w; ++i) {
702     const BitTracker::BitValue &V = RC[i];
703     if (V.Type == BitTracker::BitValue::Ref && V.RefI.Reg == VR)
704       return true;
705   }
706   return false;
707 }
708 
709 bool HexagonGenInsert::findNonSelfReference(unsigned VR) const {
710   BitTracker::RegisterCell RC = CMS->lookup(VR);
711   for (uint16_t i = 0, w = RC.width(); i < w; ++i) {
712     const BitTracker::BitValue &V = RC[i];
713     if (V.Type == BitTracker::BitValue::Ref && V.RefI.Reg != VR)
714       return true;
715   }
716   return false;
717 }
718 
719 void HexagonGenInsert::getInstrDefs(const MachineInstr *MI,
720       RegisterSet &Defs) const {
721   for (const MachineOperand &MO : MI->operands()) {
722     if (!MO.isReg() || !MO.isDef())
723       continue;
724     Register R = MO.getReg();
725     if (!R.isVirtual())
726       continue;
727     Defs.insert(R);
728   }
729 }
730 
731 void HexagonGenInsert::getInstrUses(const MachineInstr *MI,
732       RegisterSet &Uses) const {
733   for (const MachineOperand &MO : MI->operands()) {
734     if (!MO.isReg() || !MO.isUse())
735       continue;
736     Register R = MO.getReg();
737     if (!R.isVirtual())
738       continue;
739     Uses.insert(R);
740   }
741 }
742 
743 unsigned HexagonGenInsert::distance(const MachineBasicBlock *FromB,
744       const MachineBasicBlock *ToB, const UnsignedMap &RPO,
745       PairMapType &M) const {
746   // Forward distance from the end of a block to the beginning of it does
747   // not make sense. This function should not be called with FromB == ToB.
748   assert(FromB != ToB);
749 
750   unsigned FromN = FromB->getNumber(), ToN = ToB->getNumber();
751   // If we have already computed it, return the cached result.
752   PairMapType::iterator F = M.find(std::make_pair(FromN, ToN));
753   if (F != M.end())
754     return F->second;
755   unsigned ToRPO = RPO.lookup(ToN);
756 
757   unsigned MaxD = 0;
758 
759   for (const MachineBasicBlock *PB : ToB->predecessors()) {
760     // Skip back edges. Also, if FromB is a predecessor of ToB, the distance
761     // along that path will be 0, and we don't need to do any calculations
762     // on it.
763     if (PB == FromB || RPO.lookup(PB->getNumber()) >= ToRPO)
764       continue;
765     unsigned D = PB->size() + distance(FromB, PB, RPO, M);
766     if (D > MaxD)
767       MaxD = D;
768   }
769 
770   // Memoize the result for later lookup.
771   M.insert(std::make_pair(std::make_pair(FromN, ToN), MaxD));
772   return MaxD;
773 }
774 
775 unsigned HexagonGenInsert::distance(MachineBasicBlock::const_iterator FromI,
776       MachineBasicBlock::const_iterator ToI, const UnsignedMap &RPO,
777       PairMapType &M) const {
778   const MachineBasicBlock *FB = FromI->getParent(), *TB = ToI->getParent();
779   if (FB == TB)
780     return std::distance(FromI, ToI);
781   unsigned D1 = std::distance(TB->begin(), ToI);
782   unsigned D2 = distance(FB, TB, RPO, M);
783   unsigned D3 = std::distance(FromI, FB->end());
784   return D1+D2+D3;
785 }
786 
787 bool HexagonGenInsert::findRecordInsertForms(unsigned VR,
788       OrderedRegisterList &AVs) {
789   if (isDebug()) {
790     dbgs() << __func__ << ": " << printReg(VR, HRI)
791            << "  AVs: " << PrintORL(AVs, HRI) << "\n";
792   }
793   if (AVs.size() == 0)
794     return false;
795 
796   using iterator = OrderedRegisterList::iterator;
797 
798   BitValueOrdering BVO(BaseOrd);
799   const BitTracker::RegisterCell &RC = CMS->lookup(VR);
800   uint16_t W = RC.width();
801 
802   using RSRecord = std::pair<unsigned, uint16_t>; // (reg,shift)
803   using RSListType = std::vector<RSRecord>;
804   // Have a map, with key being the matching prefix length, and the value
805   // being the list of pairs (R,S), where R's prefix matches VR at S.
806   // (DenseMap<uint16_t,RSListType> fails to instantiate.)
807   using LRSMapType = DenseMap<unsigned, RSListType>;
808   LRSMapType LM;
809 
810   // Conceptually, rotate the cell RC right (i.e. towards the LSB) by S,
811   // and find matching prefixes from AVs with the rotated RC. Such a prefix
812   // would match a string of bits (of length L) in RC starting at S.
813   for (uint16_t S = 0; S < W; ++S) {
814     iterator B = AVs.begin(), E = AVs.end();
815     // The registers in AVs are ordered according to the lexical order of
816     // the corresponding register cells. This means that the range of regis-
817     // ters in AVs that match a prefix of length L+1 will be contained in
818     // the range that matches a prefix of length L. This means that we can
819     // keep narrowing the search space as the prefix length goes up. This
820     // helps reduce the overall complexity of the search.
821     uint16_t L;
822     for (L = 0; L < W-S; ++L) {
823       // Compare against VR's bits starting at S, which emulates rotation
824       // of VR by S.
825       RegisterCellBitCompareSel RCB(VR, S+L, L, BVO, *CMS);
826       iterator NewB = std::lower_bound(B, E, VR, RCB);
827       iterator NewE = std::upper_bound(NewB, E, VR, RCB);
828       // For the registers that are eliminated from the next range, L is
829       // the longest prefix matching VR at position S (their prefixes
830       // differ from VR at S+L). If L>0, record this information for later
831       // use.
832       if (L > 0) {
833         for (iterator I = B; I != NewB; ++I)
834           LM[L].push_back(std::make_pair(*I, S));
835         for (iterator I = NewE; I != E; ++I)
836           LM[L].push_back(std::make_pair(*I, S));
837       }
838       B = NewB, E = NewE;
839       if (B == E)
840         break;
841     }
842     // Record the final register range. If this range is non-empty, then
843     // L=W-S.
844     assert(B == E || L == W-S);
845     if (B != E) {
846       for (iterator I = B; I != E; ++I)
847         LM[L].push_back(std::make_pair(*I, S));
848       // If B!=E, then we found a range of registers whose prefixes cover the
849       // rest of VR from position S. There is no need to further advance S.
850       break;
851     }
852   }
853 
854   if (isDebug()) {
855     dbgs() << "Prefixes matching register " << printReg(VR, HRI) << "\n";
856     for (const auto &I : LM) {
857       dbgs() << "  L=" << I.first << ':';
858       const RSListType &LL = I.second;
859       for (const auto &J : LL)
860         dbgs() << " (" << printReg(J.first, HRI) << ",@" << J.second << ')';
861       dbgs() << '\n';
862     }
863   }
864 
865   bool Recorded = false;
866 
867   for (unsigned SrcR : AVs) {
868     int FDi = -1, LDi = -1;   // First/last different bit.
869     const BitTracker::RegisterCell &AC = CMS->lookup(SrcR);
870     uint16_t AW = AC.width();
871     for (uint16_t i = 0, w = std::min(W, AW); i < w; ++i) {
872       if (RC[i] == AC[i])
873         continue;
874       if (FDi == -1)
875         FDi = i;
876       LDi = i;
877     }
878     if (FDi == -1)
879       continue;  // TODO (future): Record identical registers.
880     // Look for a register whose prefix could patch the range [FD..LD]
881     // where VR and SrcR differ.
882     uint16_t FD = FDi, LD = LDi;  // Switch to unsigned type.
883     uint16_t MinL = LD-FD+1;
884     for (uint16_t L = MinL; L < W; ++L) {
885       LRSMapType::iterator F = LM.find(L);
886       if (F == LM.end())
887         continue;
888       RSListType &LL = F->second;
889       for (const auto &I : LL) {
890         uint16_t S = I.second;
891         // MinL is the minimum length of the prefix. Any length above MinL
892         // allows some flexibility as to where the prefix can start:
893         // given the extra length EL=L-MinL, the prefix must start between
894         // max(0,FD-EL) and FD.
895         if (S > FD)   // Starts too late.
896           continue;
897         uint16_t EL = L-MinL;
898         uint16_t LowS = (EL < FD) ? FD-EL : 0;
899         if (S < LowS) // Starts too early.
900           continue;
901         unsigned InsR = I.first;
902         if (!isValidInsertForm(VR, SrcR, InsR, L, S))
903           continue;
904         if (isDebug()) {
905           dbgs() << printReg(VR, HRI) << " = insert(" << printReg(SrcR, HRI)
906                  << ',' << printReg(InsR, HRI) << ",#" << L << ",#"
907                  << S << ")\n";
908         }
909         IFRecordWithRegSet RR(IFRecord(SrcR, InsR, L, S), RegisterSet());
910         IFMap[VR].push_back(RR);
911         Recorded = true;
912       }
913     }
914   }
915 
916   return Recorded;
917 }
918 
919 void HexagonGenInsert::collectInBlock(MachineBasicBlock *B,
920       OrderedRegisterList &AVs) {
921   if (isDebug())
922     dbgs() << "visiting block " << printMBBReference(*B) << "\n";
923 
924   // First, check if this block is reachable at all. If not, the bit tracker
925   // will not have any information about registers in it.
926   if (!CMS->BT.reached(B))
927     return;
928 
929   bool DoConst = OptConst;
930   // Keep a separate set of registers defined in this block, so that we
931   // can remove them from the list of available registers once all DT
932   // successors have been processed.
933   RegisterSet BlockDefs, InsDefs;
934   for (MachineInstr &MI : *B) {
935     InsDefs.clear();
936     getInstrDefs(&MI, InsDefs);
937     // Leave those alone. They are more transparent than "insert".
938     bool Skip = MI.isCopy() || MI.isRegSequence();
939 
940     if (!Skip) {
941       // Visit all defined registers, and attempt to find the corresponding
942       // "insert" representations.
943       for (unsigned VR = InsDefs.find_first(); VR; VR = InsDefs.find_next(VR)) {
944         // Do not collect registers that are known to be compile-time cons-
945         // tants, unless requested.
946         if (!DoConst && isConstant(VR))
947           continue;
948         // If VR's cell contains a reference to VR, then VR cannot be defined
949         // via "insert". If VR is a constant that can be generated in a single
950         // instruction (without constant extenders), generating it via insert
951         // makes no sense.
952         if (findSelfReference(VR) || isSmallConstant(VR))
953           continue;
954 
955         findRecordInsertForms(VR, AVs);
956         // Stop if the map size is too large.
957         if (IFMap.size() > MaxIFMSize)
958           return;
959       }
960     }
961 
962     // Insert the defined registers into the list of available registers
963     // after they have been processed.
964     for (unsigned VR = InsDefs.find_first(); VR; VR = InsDefs.find_next(VR))
965       AVs.insert(VR);
966     BlockDefs.insert(InsDefs);
967   }
968 
969   for (auto *DTN : children<MachineDomTreeNode*>(MDT->getNode(B))) {
970     MachineBasicBlock *SB = DTN->getBlock();
971     collectInBlock(SB, AVs);
972   }
973 
974   for (unsigned VR = BlockDefs.find_first(); VR; VR = BlockDefs.find_next(VR))
975     AVs.remove(VR);
976 }
977 
978 void HexagonGenInsert::findRemovableRegisters(unsigned VR, IFRecord IF,
979       RegisterSet &RMs) const {
980   // For a given register VR and a insert form, find the registers that are
981   // used by the current definition of VR, and which would no longer be
982   // needed for it after the definition of VR is replaced with the insert
983   // form. These are the registers that could potentially become dead.
984   RegisterSet Regs[2];
985 
986   unsigned S = 0;  // Register set selector.
987   Regs[S].insert(VR);
988 
989   while (!Regs[S].empty()) {
990     // Breadth-first search.
991     unsigned OtherS = 1-S;
992     Regs[OtherS].clear();
993     for (unsigned R = Regs[S].find_first(); R; R = Regs[S].find_next(R)) {
994       Regs[S].remove(R);
995       if (R == IF.SrcR || R == IF.InsR)
996         continue;
997       // Check if a given register has bits that are references to any other
998       // registers. This is to detect situations where the instruction that
999       // defines register R takes register Q as an operand, but R itself does
1000       // not contain any bits from Q. Loads are examples of how this could
1001       // happen:
1002       //   R = load Q
1003       // In this case (assuming we do not have any knowledge about the loaded
1004       // value), we must not treat R as a "conveyance" of the bits from Q.
1005       // (The information in BT about R's bits would have them as constants,
1006       // in case of zero-extending loads, or refs to R.)
1007       if (!findNonSelfReference(R))
1008         continue;
1009       RMs.insert(R);
1010       const MachineInstr *DefI = MRI->getVRegDef(R);
1011       assert(DefI);
1012       // Do not iterate past PHI nodes to avoid infinite loops. This can
1013       // make the final set a bit less accurate, but the removable register
1014       // sets are an approximation anyway.
1015       if (DefI->isPHI())
1016         continue;
1017       getInstrUses(DefI, Regs[OtherS]);
1018     }
1019     S = OtherS;
1020   }
1021   // The register VR is added to the list as a side-effect of the algorithm,
1022   // but it is not "potentially removable". A potentially removable register
1023   // is one that may become unused (dead) after conversion to the insert form
1024   // IF, and obviously VR (or its replacement) will not become dead by apply-
1025   // ing IF.
1026   RMs.remove(VR);
1027 }
1028 
1029 void HexagonGenInsert::computeRemovableRegisters() {
1030   for (auto &I : IFMap) {
1031     IFListType &LL = I.second;
1032     for (auto &J : LL)
1033       findRemovableRegisters(I.first, J.first, J.second);
1034   }
1035 }
1036 
1037 void HexagonGenInsert::pruneEmptyLists() {
1038   // Remove all entries from the map, where the register has no insert forms
1039   // associated with it.
1040   using IterListType = SmallVector<IFMapType::iterator, 16>;
1041   IterListType Prune;
1042   for (IFMapType::iterator I = IFMap.begin(), E = IFMap.end(); I != E; ++I) {
1043     if (I->second.empty())
1044       Prune.push_back(I);
1045   }
1046   for (unsigned i = 0, n = Prune.size(); i < n; ++i)
1047     IFMap.erase(Prune[i]);
1048 }
1049 
1050 void HexagonGenInsert::pruneCoveredSets(unsigned VR) {
1051   IFMapType::iterator F = IFMap.find(VR);
1052   assert(F != IFMap.end());
1053   IFListType &LL = F->second;
1054 
1055   // First, examine the IF candidates for register VR whose removable-regis-
1056   // ter sets are empty. This means that a given candidate will not help eli-
1057   // minate any registers, but since "insert" is not a constant-extendable
1058   // instruction, using such a candidate may reduce code size if the defini-
1059   // tion of VR is constant-extended.
1060   // If there exists a candidate with a non-empty set, the ones with empty
1061   // sets will not be used and can be removed.
1062   MachineInstr *DefVR = MRI->getVRegDef(VR);
1063   bool DefEx = HII->isConstExtended(*DefVR);
1064   bool HasNE = false;
1065   for (const auto &I : LL) {
1066     if (I.second.empty())
1067       continue;
1068     HasNE = true;
1069     break;
1070   }
1071   if (!DefEx || HasNE) {
1072     // The definition of VR is not constant-extended, or there is a candidate
1073     // with a non-empty set. Remove all candidates with empty sets.
1074     auto IsEmpty = [] (const IFRecordWithRegSet &IR) -> bool {
1075       return IR.second.empty();
1076     };
1077     llvm::erase_if(LL, IsEmpty);
1078   } else {
1079     // The definition of VR is constant-extended, and all candidates have
1080     // empty removable-register sets. Pick the maximum candidate, and remove
1081     // all others. The "maximum" does not have any special meaning here, it
1082     // is only so that the candidate that will remain on the list is selec-
1083     // ted deterministically.
1084     IFRecord MaxIF = LL[0].first;
1085     for (unsigned i = 1, n = LL.size(); i < n; ++i) {
1086       // If LL[MaxI] < LL[i], then MaxI = i.
1087       const IFRecord &IF = LL[i].first;
1088       unsigned M0 = BaseOrd[MaxIF.SrcR], M1 = BaseOrd[MaxIF.InsR];
1089       unsigned R0 = BaseOrd[IF.SrcR], R1 = BaseOrd[IF.InsR];
1090       if (M0 > R0)
1091         continue;
1092       if (M0 == R0) {
1093         if (M1 > R1)
1094           continue;
1095         if (M1 == R1) {
1096           if (MaxIF.Wdh > IF.Wdh)
1097             continue;
1098           if (MaxIF.Wdh == IF.Wdh && MaxIF.Off >= IF.Off)
1099             continue;
1100         }
1101       }
1102       // MaxIF < IF.
1103       MaxIF = IF;
1104     }
1105     // Remove everything except the maximum candidate. All register sets
1106     // are empty, so no need to preserve anything.
1107     LL.clear();
1108     LL.push_back(std::make_pair(MaxIF, RegisterSet()));
1109   }
1110 
1111   // Now, remove those whose sets of potentially removable registers are
1112   // contained in another IF candidate for VR. For example, given these
1113   // candidates for %45,
1114   //   %45:
1115   //     (%44,%41,#9,#8), { %42 }
1116   //     (%43,%41,#9,#8), { %42 %44 }
1117   // remove the first one, since it is contained in the second one.
1118   for (unsigned i = 0, n = LL.size(); i < n; ) {
1119     const RegisterSet &RMi = LL[i].second;
1120     unsigned j = 0;
1121     while (j < n) {
1122       if (j != i && LL[j].second.includes(RMi))
1123         break;
1124       j++;
1125     }
1126     if (j == n) {   // RMi not contained in anything else.
1127       i++;
1128       continue;
1129     }
1130     LL.erase(LL.begin()+i);
1131     n = LL.size();
1132   }
1133 }
1134 
1135 void HexagonGenInsert::pruneUsesTooFar(unsigned VR, const UnsignedMap &RPO,
1136       PairMapType &M) {
1137   IFMapType::iterator F = IFMap.find(VR);
1138   assert(F != IFMap.end());
1139   IFListType &LL = F->second;
1140   unsigned Cutoff = VRegDistCutoff;
1141   const MachineInstr *DefV = MRI->getVRegDef(VR);
1142 
1143   for (unsigned i = LL.size(); i > 0; --i) {
1144     unsigned SR = LL[i-1].first.SrcR, IR = LL[i-1].first.InsR;
1145     const MachineInstr *DefS = MRI->getVRegDef(SR);
1146     const MachineInstr *DefI = MRI->getVRegDef(IR);
1147     unsigned DSV = distance(DefS, DefV, RPO, M);
1148     if (DSV < Cutoff) {
1149       unsigned DIV = distance(DefI, DefV, RPO, M);
1150       if (DIV < Cutoff)
1151         continue;
1152     }
1153     LL.erase(LL.begin()+(i-1));
1154   }
1155 }
1156 
1157 void HexagonGenInsert::pruneRegCopies(unsigned VR) {
1158   IFMapType::iterator F = IFMap.find(VR);
1159   assert(F != IFMap.end());
1160   IFListType &LL = F->second;
1161 
1162   auto IsCopy = [] (const IFRecordWithRegSet &IR) -> bool {
1163     return IR.first.Wdh == 32 && (IR.first.Off == 0 || IR.first.Off == 32);
1164   };
1165   llvm::erase_if(LL, IsCopy);
1166 }
1167 
1168 void HexagonGenInsert::pruneCandidates() {
1169   // Remove candidates that are not beneficial, regardless of the final
1170   // selection method.
1171   // First, remove candidates whose potentially removable set is a subset
1172   // of another candidate's set.
1173   for (const auto &I : IFMap)
1174     pruneCoveredSets(I.first);
1175 
1176   UnsignedMap RPO;
1177 
1178   using RPOTType = ReversePostOrderTraversal<const MachineFunction *>;
1179 
1180   RPOTType RPOT(MFN);
1181   unsigned RPON = 0;
1182   for (const auto &I : RPOT)
1183     RPO[I->getNumber()] = RPON++;
1184 
1185   PairMapType Memo; // Memoization map for distance calculation.
1186   // Remove candidates that would use registers defined too far away.
1187   for (const auto &I : IFMap)
1188     pruneUsesTooFar(I.first, RPO, Memo);
1189 
1190   pruneEmptyLists();
1191 
1192   for (const auto &I : IFMap)
1193     pruneRegCopies(I.first);
1194 }
1195 
1196 namespace {
1197 
1198   // Class for comparing IF candidates for registers that have multiple of
1199   // them. The smaller the candidate, according to this ordering, the better.
1200   // First, compare the number of zeros in the associated potentially remova-
1201   // ble register sets. "Zero" indicates that the register is very likely to
1202   // become dead after this transformation.
1203   // Second, compare "averages", i.e. use-count per size. The lower wins.
1204   // After that, it does not really matter which one is smaller. Resolve
1205   // the tie in some deterministic way.
1206   struct IFOrdering {
1207     IFOrdering(const UnsignedMap &UC, const RegisterOrdering &BO)
1208       : UseC(UC), BaseOrd(BO) {}
1209 
1210     bool operator() (const IFRecordWithRegSet &A,
1211                      const IFRecordWithRegSet &B) const;
1212 
1213   private:
1214     void stats(const RegisterSet &Rs, unsigned &Size, unsigned &Zero,
1215           unsigned &Sum) const;
1216 
1217     const UnsignedMap &UseC;
1218     const RegisterOrdering &BaseOrd;
1219   };
1220 
1221 } // end anonymous namespace
1222 
1223 bool IFOrdering::operator() (const IFRecordWithRegSet &A,
1224       const IFRecordWithRegSet &B) const {
1225   unsigned SizeA = 0, ZeroA = 0, SumA = 0;
1226   unsigned SizeB = 0, ZeroB = 0, SumB = 0;
1227   stats(A.second, SizeA, ZeroA, SumA);
1228   stats(B.second, SizeB, ZeroB, SumB);
1229 
1230   // We will pick the minimum element. The more zeros, the better.
1231   if (ZeroA != ZeroB)
1232     return ZeroA > ZeroB;
1233   // Compare SumA/SizeA with SumB/SizeB, lower is better.
1234   uint64_t AvgA = SumA*SizeB, AvgB = SumB*SizeA;
1235   if (AvgA != AvgB)
1236     return AvgA < AvgB;
1237 
1238   // The sets compare identical so far. Resort to comparing the IF records.
1239   // The actual values don't matter, this is only for determinism.
1240   unsigned OSA = BaseOrd[A.first.SrcR], OSB = BaseOrd[B.first.SrcR];
1241   if (OSA != OSB)
1242     return OSA < OSB;
1243   unsigned OIA = BaseOrd[A.first.InsR], OIB = BaseOrd[B.first.InsR];
1244   if (OIA != OIB)
1245     return OIA < OIB;
1246   if (A.first.Wdh != B.first.Wdh)
1247     return A.first.Wdh < B.first.Wdh;
1248   return A.first.Off < B.first.Off;
1249 }
1250 
1251 void IFOrdering::stats(const RegisterSet &Rs, unsigned &Size, unsigned &Zero,
1252       unsigned &Sum) const {
1253   for (unsigned R = Rs.find_first(); R; R = Rs.find_next(R)) {
1254     UnsignedMap::const_iterator F = UseC.find(R);
1255     assert(F != UseC.end());
1256     unsigned UC = F->second;
1257     if (UC == 0)
1258       Zero++;
1259     Sum += UC;
1260     Size++;
1261   }
1262 }
1263 
1264 void HexagonGenInsert::selectCandidates() {
1265   // Some registers may have multiple valid candidates. Pick the best one
1266   // (or decide not to use any).
1267 
1268   // Compute the "removability" measure of R:
1269   // For each potentially removable register R, record the number of regis-
1270   // ters with IF candidates, where R appears in at least one set.
1271   RegisterSet AllRMs;
1272   UnsignedMap UseC, RemC;
1273   IFMapType::iterator End = IFMap.end();
1274 
1275   for (IFMapType::iterator I = IFMap.begin(); I != End; ++I) {
1276     const IFListType &LL = I->second;
1277     RegisterSet TT;
1278     for (const auto &J : LL)
1279       TT.insert(J.second);
1280     for (unsigned R = TT.find_first(); R; R = TT.find_next(R))
1281       RemC[R]++;
1282     AllRMs.insert(TT);
1283   }
1284 
1285   for (unsigned R = AllRMs.find_first(); R; R = AllRMs.find_next(R)) {
1286     using use_iterator = MachineRegisterInfo::use_nodbg_iterator;
1287     using InstrSet = SmallSet<const MachineInstr *, 16>;
1288 
1289     InstrSet UIs;
1290     // Count as the number of instructions in which R is used, not the
1291     // number of operands.
1292     use_iterator E = MRI->use_nodbg_end();
1293     for (use_iterator I = MRI->use_nodbg_begin(R); I != E; ++I)
1294       UIs.insert(I->getParent());
1295     unsigned C = UIs.size();
1296     // Calculate a measure, which is the number of instructions using R,
1297     // minus the "removability" count computed earlier.
1298     unsigned D = RemC[R];
1299     UseC[R] = (C > D) ? C-D : 0;  // doz
1300   }
1301 
1302   bool SelectAll0 = OptSelectAll0, SelectHas0 = OptSelectHas0;
1303   if (!SelectAll0 && !SelectHas0)
1304     SelectAll0 = true;
1305 
1306   // The smaller the number UseC for a given register R, the "less used"
1307   // R is aside from the opportunities for removal offered by generating
1308   // "insert" instructions.
1309   // Iterate over the IF map, and for those registers that have multiple
1310   // candidates, pick the minimum one according to IFOrdering.
1311   IFOrdering IFO(UseC, BaseOrd);
1312   for (IFMapType::iterator I = IFMap.begin(); I != End; ++I) {
1313     IFListType &LL = I->second;
1314     if (LL.empty())
1315       continue;
1316     // Get the minimum element, remember it and clear the list. If the
1317     // element found is adequate, we will put it back on the list, other-
1318     // wise the list will remain empty, and the entry for this register
1319     // will be removed (i.e. this register will not be replaced by insert).
1320     IFListType::iterator MinI = std::min_element(LL.begin(), LL.end(), IFO);
1321     assert(MinI != LL.end());
1322     IFRecordWithRegSet M = *MinI;
1323     LL.clear();
1324 
1325     // We want to make sure that this replacement will have a chance to be
1326     // beneficial, and that means that we want to have indication that some
1327     // register will be removed. The most likely registers to be eliminated
1328     // are the use operands in the definition of I->first. Accept/reject a
1329     // candidate based on how many of its uses it can potentially eliminate.
1330 
1331     RegisterSet Us;
1332     const MachineInstr *DefI = MRI->getVRegDef(I->first);
1333     getInstrUses(DefI, Us);
1334     bool Accept = false;
1335 
1336     if (SelectAll0) {
1337       bool All0 = true;
1338       for (unsigned R = Us.find_first(); R; R = Us.find_next(R)) {
1339         if (UseC[R] == 0)
1340           continue;
1341         All0 = false;
1342         break;
1343       }
1344       Accept = All0;
1345     } else if (SelectHas0) {
1346       bool Has0 = false;
1347       for (unsigned R = Us.find_first(); R; R = Us.find_next(R)) {
1348         if (UseC[R] != 0)
1349           continue;
1350         Has0 = true;
1351         break;
1352       }
1353       Accept = Has0;
1354     }
1355     if (Accept)
1356       LL.push_back(M);
1357   }
1358 
1359   // Remove candidates that add uses of removable registers, unless the
1360   // removable registers are among replacement candidates.
1361   // Recompute the removable registers, since some candidates may have
1362   // been eliminated.
1363   AllRMs.clear();
1364   for (IFMapType::iterator I = IFMap.begin(); I != End; ++I) {
1365     const IFListType &LL = I->second;
1366     if (!LL.empty())
1367       AllRMs.insert(LL[0].second);
1368   }
1369   for (IFMapType::iterator I = IFMap.begin(); I != End; ++I) {
1370     IFListType &LL = I->second;
1371     if (LL.empty())
1372       continue;
1373     unsigned SR = LL[0].first.SrcR, IR = LL[0].first.InsR;
1374     if (AllRMs[SR] || AllRMs[IR])
1375       LL.clear();
1376   }
1377 
1378   pruneEmptyLists();
1379 }
1380 
1381 bool HexagonGenInsert::generateInserts() {
1382   // Create a new register for each one from IFMap, and store them in the
1383   // map.
1384   UnsignedMap RegMap;
1385   for (auto &I : IFMap) {
1386     unsigned VR = I.first;
1387     const TargetRegisterClass *RC = MRI->getRegClass(VR);
1388     Register NewVR = MRI->createVirtualRegister(RC);
1389     RegMap[VR] = NewVR;
1390   }
1391 
1392   // We can generate the "insert" instructions using potentially stale re-
1393   // gisters: SrcR and InsR for a given VR may be among other registers that
1394   // are also replaced. This is fine, we will do the mass "rauw" a bit later.
1395   for (auto &I : IFMap) {
1396     MachineInstr *MI = MRI->getVRegDef(I.first);
1397     MachineBasicBlock &B = *MI->getParent();
1398     DebugLoc DL = MI->getDebugLoc();
1399     unsigned NewR = RegMap[I.first];
1400     bool R32 = MRI->getRegClass(NewR) == &Hexagon::IntRegsRegClass;
1401     const MCInstrDesc &D = R32 ? HII->get(Hexagon::S2_insert)
1402                                : HII->get(Hexagon::S2_insertp);
1403     IFRecord IF = I.second[0].first;
1404     unsigned Wdh = IF.Wdh, Off = IF.Off;
1405     unsigned InsS = 0;
1406     if (R32 && MRI->getRegClass(IF.InsR) == &Hexagon::DoubleRegsRegClass) {
1407       InsS = Hexagon::isub_lo;
1408       if (Off >= 32) {
1409         InsS = Hexagon::isub_hi;
1410         Off -= 32;
1411       }
1412     }
1413     // Advance to the proper location for inserting instructions. This could
1414     // be B.end().
1415     MachineBasicBlock::iterator At = MI;
1416     if (MI->isPHI())
1417       At = B.getFirstNonPHI();
1418 
1419     BuildMI(B, At, DL, D, NewR)
1420       .addReg(IF.SrcR)
1421       .addReg(IF.InsR, 0, InsS)
1422       .addImm(Wdh)
1423       .addImm(Off);
1424 
1425     MRI->clearKillFlags(IF.SrcR);
1426     MRI->clearKillFlags(IF.InsR);
1427   }
1428 
1429   for (const auto &I : IFMap) {
1430     MachineInstr *DefI = MRI->getVRegDef(I.first);
1431     MRI->replaceRegWith(I.first, RegMap[I.first]);
1432     DefI->eraseFromParent();
1433   }
1434 
1435   return true;
1436 }
1437 
1438 bool HexagonGenInsert::removeDeadCode(MachineDomTreeNode *N) {
1439   bool Changed = false;
1440 
1441   for (auto *DTN : children<MachineDomTreeNode*>(N))
1442     Changed |= removeDeadCode(DTN);
1443 
1444   MachineBasicBlock *B = N->getBlock();
1445   std::vector<MachineInstr*> Instrs;
1446   for (MachineInstr &MI : llvm::reverse(*B))
1447     Instrs.push_back(&MI);
1448 
1449   for (MachineInstr *MI : Instrs) {
1450     unsigned Opc = MI->getOpcode();
1451     // Do not touch lifetime markers. This is why the target-independent DCE
1452     // cannot be used.
1453     if (Opc == TargetOpcode::LIFETIME_START ||
1454         Opc == TargetOpcode::LIFETIME_END)
1455       continue;
1456     bool Store = false;
1457     if (MI->isInlineAsm() || !MI->isSafeToMove(nullptr, Store))
1458       continue;
1459 
1460     bool AllDead = true;
1461     SmallVector<unsigned,2> Regs;
1462     for (const MachineOperand &MO : MI->operands()) {
1463       if (!MO.isReg() || !MO.isDef())
1464         continue;
1465       Register R = MO.getReg();
1466       if (!R.isVirtual() || !MRI->use_nodbg_empty(R)) {
1467         AllDead = false;
1468         break;
1469       }
1470       Regs.push_back(R);
1471     }
1472     if (!AllDead)
1473       continue;
1474 
1475     B->erase(MI);
1476     for (unsigned I = 0, N = Regs.size(); I != N; ++I)
1477       MRI->markUsesInDebugValueAsUndef(Regs[I]);
1478     Changed = true;
1479   }
1480 
1481   return Changed;
1482 }
1483 
1484 bool HexagonGenInsert::runOnMachineFunction(MachineFunction &MF) {
1485   if (skipFunction(MF.getFunction()))
1486     return false;
1487 
1488   bool Timing = OptTiming, TimingDetail = Timing && OptTimingDetail;
1489   bool Changed = false;
1490 
1491   // Verify: one, but not both.
1492   assert(!OptSelectAll0 || !OptSelectHas0);
1493 
1494   IFMap.clear();
1495   BaseOrd.clear();
1496   CellOrd.clear();
1497 
1498   const auto &ST = MF.getSubtarget<HexagonSubtarget>();
1499   HII = ST.getInstrInfo();
1500   HRI = ST.getRegisterInfo();
1501   MFN = &MF;
1502   MRI = &MF.getRegInfo();
1503   MDT = &getAnalysis<MachineDominatorTree>();
1504 
1505   // Clean up before any further processing, so that dead code does not
1506   // get used in a newly generated "insert" instruction. Have a custom
1507   // version of DCE that preserves lifetime markers. Without it, merging
1508   // of stack objects can fail to recognize and merge disjoint objects
1509   // leading to unnecessary stack growth.
1510   Changed = removeDeadCode(MDT->getRootNode());
1511 
1512   const HexagonEvaluator HE(*HRI, *MRI, *HII, MF);
1513   BitTracker BTLoc(HE, MF);
1514   BTLoc.trace(isDebug());
1515   BTLoc.run();
1516   CellMapShadow MS(BTLoc);
1517   CMS = &MS;
1518 
1519   buildOrderingMF(BaseOrd);
1520   buildOrderingBT(BaseOrd, CellOrd);
1521 
1522   if (isDebug()) {
1523     dbgs() << "Cell ordering:\n";
1524     for (const auto &I : CellOrd) {
1525       unsigned VR = I.first, Pos = I.second;
1526       dbgs() << printReg(VR, HRI) << " -> " << Pos << "\n";
1527     }
1528   }
1529 
1530   // Collect candidates for conversion into the insert forms.
1531   MachineBasicBlock *RootB = MDT->getRoot();
1532   OrderedRegisterList AvailR(CellOrd);
1533 
1534   const char *const TGName = "hexinsert";
1535   const char *const TGDesc = "Generate Insert Instructions";
1536 
1537   {
1538     NamedRegionTimer _T("collection", "collection", TGName, TGDesc,
1539                         TimingDetail);
1540     collectInBlock(RootB, AvailR);
1541     // Complete the information gathered in IFMap.
1542     computeRemovableRegisters();
1543   }
1544 
1545   if (isDebug()) {
1546     dbgs() << "Candidates after collection:\n";
1547     dump_map();
1548   }
1549 
1550   if (IFMap.empty())
1551     return Changed;
1552 
1553   {
1554     NamedRegionTimer _T("pruning", "pruning", TGName, TGDesc, TimingDetail);
1555     pruneCandidates();
1556   }
1557 
1558   if (isDebug()) {
1559     dbgs() << "Candidates after pruning:\n";
1560     dump_map();
1561   }
1562 
1563   if (IFMap.empty())
1564     return Changed;
1565 
1566   {
1567     NamedRegionTimer _T("selection", "selection", TGName, TGDesc, TimingDetail);
1568     selectCandidates();
1569   }
1570 
1571   if (isDebug()) {
1572     dbgs() << "Candidates after selection:\n";
1573     dump_map();
1574   }
1575 
1576   // Filter out vregs beyond the cutoff.
1577   if (VRegIndexCutoff.getPosition()) {
1578     unsigned Cutoff = VRegIndexCutoff;
1579 
1580     using IterListType = SmallVector<IFMapType::iterator, 16>;
1581 
1582     IterListType Out;
1583     for (IFMapType::iterator I = IFMap.begin(), E = IFMap.end(); I != E; ++I) {
1584       unsigned Idx = Register::virtReg2Index(I->first);
1585       if (Idx >= Cutoff)
1586         Out.push_back(I);
1587     }
1588     for (unsigned i = 0, n = Out.size(); i < n; ++i)
1589       IFMap.erase(Out[i]);
1590   }
1591   if (IFMap.empty())
1592     return Changed;
1593 
1594   {
1595     NamedRegionTimer _T("generation", "generation", TGName, TGDesc,
1596                         TimingDetail);
1597     generateInserts();
1598   }
1599 
1600   return true;
1601 }
1602 
1603 FunctionPass *llvm::createHexagonGenInsert() {
1604   return new HexagonGenInsert();
1605 }
1606 
1607 //===----------------------------------------------------------------------===//
1608 //                         Public Constructor Functions
1609 //===----------------------------------------------------------------------===//
1610 
1611 INITIALIZE_PASS_BEGIN(HexagonGenInsert, "hexinsert",
1612   "Hexagon generate \"insert\" instructions", false, false)
1613 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
1614 INITIALIZE_PASS_END(HexagonGenInsert, "hexinsert",
1615   "Hexagon generate \"insert\" instructions", false, false)
1616