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