forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHexagonGenInsert.cpp
1610 lines (1390 loc) · 51.4 KB
/
HexagonGenInsert.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===- HexagonGenInsert.cpp -----------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "BitTracker.h"
#include "HexagonBitTracker.h"
#include "HexagonInstrInfo.h"
#include "HexagonRegisterInfo.h"
#include "HexagonSubtarget.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/GraphTraits.h"
#include "llvm/ADT/PostOrderIterator.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/Timer.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <iterator>
#include <utility>
#include <vector>
#define DEBUG_TYPE "hexinsert"
using namespace llvm;
static cl::opt<unsigned> VRegIndexCutoff("insert-vreg-cutoff", cl::init(~0U),
cl::Hidden, cl::ZeroOrMore, cl::desc("Vreg# cutoff for insert generation."));
// The distance cutoff is selected based on the precheckin-perf results:
// cutoffs 20, 25, 35, and 40 are worse than 30.
static cl::opt<unsigned> VRegDistCutoff("insert-dist-cutoff", cl::init(30U),
cl::Hidden, cl::ZeroOrMore, cl::desc("Vreg distance cutoff for insert "
"generation."));
// Limit the container sizes for extreme cases where we run out of memory.
static cl::opt<unsigned> MaxORLSize("insert-max-orl", cl::init(4096),
cl::Hidden, cl::ZeroOrMore, cl::desc("Maximum size of OrderedRegisterList"));
static cl::opt<unsigned> MaxIFMSize("insert-max-ifmap", cl::init(1024),
cl::Hidden, cl::ZeroOrMore, cl::desc("Maximum size of IFMap"));
static cl::opt<bool> OptTiming("insert-timing", cl::init(false), cl::Hidden,
cl::ZeroOrMore, cl::desc("Enable timing of insert generation"));
static cl::opt<bool> OptTimingDetail("insert-timing-detail", cl::init(false),
cl::Hidden, cl::ZeroOrMore, cl::desc("Enable detailed timing of insert "
"generation"));
static cl::opt<bool> OptSelectAll0("insert-all0", cl::init(false), cl::Hidden,
cl::ZeroOrMore);
static cl::opt<bool> OptSelectHas0("insert-has0", cl::init(false), cl::Hidden,
cl::ZeroOrMore);
// Whether to construct constant values via "insert". Could eliminate constant
// extenders, but often not practical.
static cl::opt<bool> OptConst("insert-const", cl::init(false), cl::Hidden,
cl::ZeroOrMore);
// The preprocessor gets confused when the DEBUG macro is passed larger
// chunks of code. Use this function to detect debugging.
inline static bool isDebug() {
#ifndef NDEBUG
return DebugFlag && isCurrentDebugType(DEBUG_TYPE);
#else
return false;
#endif
}
namespace {
// Set of virtual registers, based on BitVector.
struct RegisterSet : private BitVector {
RegisterSet() = default;
explicit RegisterSet(unsigned s, bool t = false) : BitVector(s, t) {}
RegisterSet(const RegisterSet &RS) = default;
RegisterSet &operator=(const RegisterSet &RS) = default;
using BitVector::clear;
unsigned find_first() const {
int First = BitVector::find_first();
if (First < 0)
return 0;
return x2v(First);
}
unsigned find_next(unsigned Prev) const {
int Next = BitVector::find_next(v2x(Prev));
if (Next < 0)
return 0;
return x2v(Next);
}
RegisterSet &insert(unsigned R) {
unsigned Idx = v2x(R);
ensure(Idx);
return static_cast<RegisterSet&>(BitVector::set(Idx));
}
RegisterSet &remove(unsigned R) {
unsigned Idx = v2x(R);
if (Idx >= size())
return *this;
return static_cast<RegisterSet&>(BitVector::reset(Idx));
}
RegisterSet &insert(const RegisterSet &Rs) {
return static_cast<RegisterSet&>(BitVector::operator|=(Rs));
}
RegisterSet &remove(const RegisterSet &Rs) {
return static_cast<RegisterSet&>(BitVector::reset(Rs));
}
reference operator[](unsigned R) {
unsigned Idx = v2x(R);
ensure(Idx);
return BitVector::operator[](Idx);
}
bool operator[](unsigned R) const {
unsigned Idx = v2x(R);
assert(Idx < size());
return BitVector::operator[](Idx);
}
bool has(unsigned R) const {
unsigned Idx = v2x(R);
if (Idx >= size())
return false;
return BitVector::test(Idx);
}
bool empty() const {
return !BitVector::any();
}
bool includes(const RegisterSet &Rs) const {
// A.BitVector::test(B) <=> A-B != {}
return !Rs.BitVector::test(*this);
}
bool intersects(const RegisterSet &Rs) const {
return BitVector::anyCommon(Rs);
}
private:
void ensure(unsigned Idx) {
if (size() <= Idx)
resize(std::max(Idx+1, 32U));
}
static inline unsigned v2x(unsigned v) {
return Register::virtReg2Index(v);
}
static inline unsigned x2v(unsigned x) {
return Register::index2VirtReg(x);
}
};
struct PrintRegSet {
PrintRegSet(const RegisterSet &S, const TargetRegisterInfo *RI)
: RS(S), TRI(RI) {}
friend raw_ostream &operator<< (raw_ostream &OS,
const PrintRegSet &P);
private:
const RegisterSet &RS;
const TargetRegisterInfo *TRI;
};
raw_ostream &operator<< (raw_ostream &OS, const PrintRegSet &P) {
OS << '{';
for (unsigned R = P.RS.find_first(); R; R = P.RS.find_next(R))
OS << ' ' << printReg(R, P.TRI);
OS << " }";
return OS;
}
// A convenience class to associate unsigned numbers (such as virtual
// registers) with unsigned numbers.
struct UnsignedMap : public DenseMap<unsigned,unsigned> {
UnsignedMap() = default;
private:
using BaseType = DenseMap<unsigned, unsigned>;
};
// A utility to establish an ordering between virtual registers:
// VRegA < VRegB <=> RegisterOrdering[VRegA] < RegisterOrdering[VRegB]
// This is meant as a cache for the ordering of virtual registers defined
// by a potentially expensive comparison function, or obtained by a proce-
// dure that should not be repeated each time two registers are compared.
struct RegisterOrdering : public UnsignedMap {
RegisterOrdering() = default;
unsigned operator[](unsigned VR) const {
const_iterator F = find(VR);
assert(F != end());
return F->second;
}
// Add operator(), so that objects of this class can be used as
// comparators in std::sort et al.
bool operator() (unsigned VR1, unsigned VR2) const {
return operator[](VR1) < operator[](VR2);
}
};
// Ordering of bit values. This class does not have operator[], but
// is supplies a comparison operator() for use in std:: algorithms.
// The order is as follows:
// - 0 < 1 < ref
// - ref1 < ref2, if ord(ref1.Reg) < ord(ref2.Reg),
// or ord(ref1.Reg) == ord(ref2.Reg), and ref1.Pos < ref2.Pos.
struct BitValueOrdering {
BitValueOrdering(const RegisterOrdering &RB) : BaseOrd(RB) {}
bool operator() (const BitTracker::BitValue &V1,
const BitTracker::BitValue &V2) const;
const RegisterOrdering &BaseOrd;
};
} // end anonymous namespace
bool BitValueOrdering::operator() (const BitTracker::BitValue &V1,
const BitTracker::BitValue &V2) const {
if (V1 == V2)
return false;
// V1==0 => true, V2==0 => false
if (V1.is(0) || V2.is(0))
return V1.is(0);
// Neither of V1,V2 is 0, and V1!=V2.
// V2==1 => false, V1==1 => true
if (V2.is(1) || V1.is(1))
return !V2.is(1);
// Both V1,V2 are refs.
unsigned Ind1 = BaseOrd[V1.RefI.Reg], Ind2 = BaseOrd[V2.RefI.Reg];
if (Ind1 != Ind2)
return Ind1 < Ind2;
// If V1.Pos==V2.Pos
assert(V1.RefI.Pos != V2.RefI.Pos && "Bit values should be different");
return V1.RefI.Pos < V2.RefI.Pos;
}
namespace {
// Cache for the BitTracker's cell map. Map lookup has a logarithmic
// complexity, this class will memoize the lookup results to reduce
// the access time for repeated lookups of the same cell.
struct CellMapShadow {
CellMapShadow(const BitTracker &T) : BT(T) {}
const BitTracker::RegisterCell &lookup(unsigned VR) {
unsigned RInd = Register::virtReg2Index(VR);
// Grow the vector to at least 32 elements.
if (RInd >= CVect.size())
CVect.resize(std::max(RInd+16, 32U), nullptr);
const BitTracker::RegisterCell *CP = CVect[RInd];
if (CP == nullptr)
CP = CVect[RInd] = &BT.lookup(VR);
return *CP;
}
const BitTracker &BT;
private:
using CellVectType = std::vector<const BitTracker::RegisterCell *>;
CellVectType CVect;
};
// Comparator class for lexicographic ordering of virtual registers
// according to the corresponding BitTracker::RegisterCell objects.
struct RegisterCellLexCompare {
RegisterCellLexCompare(const BitValueOrdering &BO, CellMapShadow &M)
: BitOrd(BO), CM(M) {}
bool operator() (unsigned VR1, unsigned VR2) const;
private:
const BitValueOrdering &BitOrd;
CellMapShadow &CM;
};
// Comparator class for lexicographic ordering of virtual registers
// according to the specified bits of the corresponding BitTracker::
// RegisterCell objects.
// Specifically, this class will be used to compare bit B of a register
// cell for a selected virtual register R with bit N of any register
// other than R.
struct RegisterCellBitCompareSel {
RegisterCellBitCompareSel(unsigned R, unsigned B, unsigned N,
const BitValueOrdering &BO, CellMapShadow &M)
: SelR(R), SelB(B), BitN(N), BitOrd(BO), CM(M) {}
bool operator() (unsigned VR1, unsigned VR2) const;
private:
const unsigned SelR, SelB;
const unsigned BitN;
const BitValueOrdering &BitOrd;
CellMapShadow &CM;
};
} // end anonymous namespace
bool RegisterCellLexCompare::operator() (unsigned VR1, unsigned VR2) const {
// Ordering of registers, made up from two given orderings:
// - the ordering of the register numbers, and
// - the ordering of register cells.
// Def. R1 < R2 if:
// - cell(R1) < cell(R2), or
// - cell(R1) == cell(R2), and index(R1) < index(R2).
//
// For register cells, the ordering is lexicographic, with index 0 being
// the most significant.
if (VR1 == VR2)
return false;
const BitTracker::RegisterCell &RC1 = CM.lookup(VR1), &RC2 = CM.lookup(VR2);
uint16_t W1 = RC1.width(), W2 = RC2.width();
for (uint16_t i = 0, w = std::min(W1, W2); i < w; ++i) {
const BitTracker::BitValue &V1 = RC1[i], &V2 = RC2[i];
if (V1 != V2)
return BitOrd(V1, V2);
}
// Cells are equal up until the common length.
if (W1 != W2)
return W1 < W2;
return BitOrd.BaseOrd[VR1] < BitOrd.BaseOrd[VR2];
}
bool RegisterCellBitCompareSel::operator() (unsigned VR1, unsigned VR2) const {
if (VR1 == VR2)
return false;
const BitTracker::RegisterCell &RC1 = CM.lookup(VR1);
const BitTracker::RegisterCell &RC2 = CM.lookup(VR2);
uint16_t W1 = RC1.width(), W2 = RC2.width();
uint16_t Bit1 = (VR1 == SelR) ? SelB : BitN;
uint16_t Bit2 = (VR2 == SelR) ? SelB : BitN;
// If Bit1 exceeds the width of VR1, then:
// - return false, if at the same time Bit2 exceeds VR2, or
// - return true, otherwise.
// (I.e. "a bit value that does not exist is less than any bit value
// that does exist".)
if (W1 <= Bit1)
return Bit2 < W2;
// If Bit1 is within VR1, but Bit2 is not within VR2, return false.
if (W2 <= Bit2)
return false;
const BitTracker::BitValue &V1 = RC1[Bit1], V2 = RC2[Bit2];
if (V1 != V2)
return BitOrd(V1, V2);
return false;
}
namespace {
class OrderedRegisterList {
using ListType = std::vector<unsigned>;
const unsigned MaxSize;
public:
OrderedRegisterList(const RegisterOrdering &RO)
: MaxSize(MaxORLSize), Ord(RO) {}
void insert(unsigned VR);
void remove(unsigned VR);
unsigned operator[](unsigned Idx) const {
assert(Idx < Seq.size());
return Seq[Idx];
}
unsigned size() const {
return Seq.size();
}
using iterator = ListType::iterator;
using const_iterator = ListType::const_iterator;
iterator begin() { return Seq.begin(); }
iterator end() { return Seq.end(); }
const_iterator begin() const { return Seq.begin(); }
const_iterator end() const { return Seq.end(); }
// Convenience function to convert an iterator to the corresponding index.
unsigned idx(iterator It) const { return It-begin(); }
private:
ListType Seq;
const RegisterOrdering &Ord;
};
struct PrintORL {
PrintORL(const OrderedRegisterList &L, const TargetRegisterInfo *RI)
: RL(L), TRI(RI) {}
friend raw_ostream &operator<< (raw_ostream &OS, const PrintORL &P);
private:
const OrderedRegisterList &RL;
const TargetRegisterInfo *TRI;
};
raw_ostream &operator<< (raw_ostream &OS, const PrintORL &P) {
OS << '(';
OrderedRegisterList::const_iterator B = P.RL.begin(), E = P.RL.end();
for (OrderedRegisterList::const_iterator I = B; I != E; ++I) {
if (I != B)
OS << ", ";
OS << printReg(*I, P.TRI);
}
OS << ')';
return OS;
}
} // end anonymous namespace
void OrderedRegisterList::insert(unsigned VR) {
iterator L = llvm::lower_bound(Seq, VR, Ord);
if (L == Seq.end())
Seq.push_back(VR);
else
Seq.insert(L, VR);
unsigned S = Seq.size();
if (S > MaxSize)
Seq.resize(MaxSize);
assert(Seq.size() <= MaxSize);
}
void OrderedRegisterList::remove(unsigned VR) {
iterator L = llvm::lower_bound(Seq, VR, Ord);
if (L != Seq.end())
Seq.erase(L);
}
namespace {
// A record of the insert form. The fields correspond to the operands
// of the "insert" instruction:
// ... = insert(SrcR, InsR, #Wdh, #Off)
struct IFRecord {
IFRecord(unsigned SR = 0, unsigned IR = 0, uint16_t W = 0, uint16_t O = 0)
: SrcR(SR), InsR(IR), Wdh(W), Off(O) {}
unsigned SrcR, InsR;
uint16_t Wdh, Off;
};
struct PrintIFR {
PrintIFR(const IFRecord &R, const TargetRegisterInfo *RI)
: IFR(R), TRI(RI) {}
private:
friend raw_ostream &operator<< (raw_ostream &OS, const PrintIFR &P);
const IFRecord &IFR;
const TargetRegisterInfo *TRI;
};
raw_ostream &operator<< (raw_ostream &OS, const PrintIFR &P) {
unsigned SrcR = P.IFR.SrcR, InsR = P.IFR.InsR;
OS << '(' << printReg(SrcR, P.TRI) << ',' << printReg(InsR, P.TRI)
<< ",#" << P.IFR.Wdh << ",#" << P.IFR.Off << ')';
return OS;
}
using IFRecordWithRegSet = std::pair<IFRecord, RegisterSet>;
} // end anonymous namespace
namespace llvm {
void initializeHexagonGenInsertPass(PassRegistry&);
FunctionPass *createHexagonGenInsert();
} // end namespace llvm
namespace {
class HexagonGenInsert : public MachineFunctionPass {
public:
static char ID;
HexagonGenInsert() : MachineFunctionPass(ID) {
initializeHexagonGenInsertPass(*PassRegistry::getPassRegistry());
}
StringRef getPassName() const override {
return "Hexagon generate \"insert\" instructions";
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<MachineDominatorTree>();
AU.addPreserved<MachineDominatorTree>();
MachineFunctionPass::getAnalysisUsage(AU);
}
bool runOnMachineFunction(MachineFunction &MF) override;
private:
using PairMapType = DenseMap<std::pair<unsigned, unsigned>, unsigned>;
void buildOrderingMF(RegisterOrdering &RO) const;
void buildOrderingBT(RegisterOrdering &RB, RegisterOrdering &RO) const;
bool isIntClass(const TargetRegisterClass *RC) const;
bool isConstant(unsigned VR) const;
bool isSmallConstant(unsigned VR) const;
bool isValidInsertForm(unsigned DstR, unsigned SrcR, unsigned InsR,
uint16_t L, uint16_t S) const;
bool findSelfReference(unsigned VR) const;
bool findNonSelfReference(unsigned VR) const;
void getInstrDefs(const MachineInstr *MI, RegisterSet &Defs) const;
void getInstrUses(const MachineInstr *MI, RegisterSet &Uses) const;
unsigned distance(const MachineBasicBlock *FromB,
const MachineBasicBlock *ToB, const UnsignedMap &RPO,
PairMapType &M) const;
unsigned distance(MachineBasicBlock::const_iterator FromI,
MachineBasicBlock::const_iterator ToI, const UnsignedMap &RPO,
PairMapType &M) const;
bool findRecordInsertForms(unsigned VR, OrderedRegisterList &AVs);
void collectInBlock(MachineBasicBlock *B, OrderedRegisterList &AVs);
void findRemovableRegisters(unsigned VR, IFRecord IF,
RegisterSet &RMs) const;
void computeRemovableRegisters();
void pruneEmptyLists();
void pruneCoveredSets(unsigned VR);
void pruneUsesTooFar(unsigned VR, const UnsignedMap &RPO, PairMapType &M);
void pruneRegCopies(unsigned VR);
void pruneCandidates();
void selectCandidates();
bool generateInserts();
bool removeDeadCode(MachineDomTreeNode *N);
// IFRecord coupled with a set of potentially removable registers:
using IFListType = std::vector<IFRecordWithRegSet>;
using IFMapType = DenseMap<unsigned, IFListType>; // vreg -> IFListType
void dump_map() const;
const HexagonInstrInfo *HII = nullptr;
const HexagonRegisterInfo *HRI = nullptr;
MachineFunction *MFN;
MachineRegisterInfo *MRI;
MachineDominatorTree *MDT;
CellMapShadow *CMS;
RegisterOrdering BaseOrd;
RegisterOrdering CellOrd;
IFMapType IFMap;
};
} // end anonymous namespace
char HexagonGenInsert::ID = 0;
void HexagonGenInsert::dump_map() const {
for (const auto &I : IFMap) {
dbgs() << " " << printReg(I.first, HRI) << ":\n";
const IFListType &LL = I.second;
for (const auto &J : LL)
dbgs() << " " << PrintIFR(J.first, HRI) << ", "
<< PrintRegSet(J.second, HRI) << '\n';
}
}
void HexagonGenInsert::buildOrderingMF(RegisterOrdering &RO) const {
unsigned Index = 0;
for (const MachineBasicBlock &B : *MFN) {
if (!CMS->BT.reached(&B))
continue;
for (const MachineInstr &MI : B) {
for (const MachineOperand &MO : MI.operands()) {
if (MO.isReg() && MO.isDef()) {
Register R = MO.getReg();
assert(MO.getSubReg() == 0 && "Unexpected subregister in definition");
if (R.isVirtual())
RO.insert(std::make_pair(R, Index++));
}
}
}
}
// Since some virtual registers may have had their def and uses eliminated,
// they are no longer referenced in the code, and so they will not appear
// in the map.
}
void HexagonGenInsert::buildOrderingBT(RegisterOrdering &RB,
RegisterOrdering &RO) const {
// Create a vector of all virtual registers (collect them from the base
// ordering RB), and then sort it using the RegisterCell comparator.
BitValueOrdering BVO(RB);
RegisterCellLexCompare LexCmp(BVO, *CMS);
using SortableVectorType = std::vector<unsigned>;
SortableVectorType VRs;
for (auto &I : RB)
VRs.push_back(I.first);
llvm::sort(VRs, LexCmp);
// Transfer the results to the outgoing register ordering.
for (unsigned i = 0, n = VRs.size(); i < n; ++i)
RO.insert(std::make_pair(VRs[i], i));
}
inline bool HexagonGenInsert::isIntClass(const TargetRegisterClass *RC) const {
return RC == &Hexagon::IntRegsRegClass || RC == &Hexagon::DoubleRegsRegClass;
}
bool HexagonGenInsert::isConstant(unsigned VR) const {
const BitTracker::RegisterCell &RC = CMS->lookup(VR);
uint16_t W = RC.width();
for (uint16_t i = 0; i < W; ++i) {
const BitTracker::BitValue &BV = RC[i];
if (BV.is(0) || BV.is(1))
continue;
return false;
}
return true;
}
bool HexagonGenInsert::isSmallConstant(unsigned VR) const {
const BitTracker::RegisterCell &RC = CMS->lookup(VR);
uint16_t W = RC.width();
if (W > 64)
return false;
uint64_t V = 0, B = 1;
for (uint16_t i = 0; i < W; ++i) {
const BitTracker::BitValue &BV = RC[i];
if (BV.is(1))
V |= B;
else if (!BV.is(0))
return false;
B <<= 1;
}
// For 32-bit registers, consider: Rd = #s16.
if (W == 32)
return isInt<16>(V);
// For 64-bit registers, it's Rdd = #s8 or Rdd = combine(#s8,#s8)
return isInt<8>(Lo_32(V)) && isInt<8>(Hi_32(V));
}
bool HexagonGenInsert::isValidInsertForm(unsigned DstR, unsigned SrcR,
unsigned InsR, uint16_t L, uint16_t S) const {
const TargetRegisterClass *DstRC = MRI->getRegClass(DstR);
const TargetRegisterClass *SrcRC = MRI->getRegClass(SrcR);
const TargetRegisterClass *InsRC = MRI->getRegClass(InsR);
// Only integet (32-/64-bit) register classes.
if (!isIntClass(DstRC) || !isIntClass(SrcRC) || !isIntClass(InsRC))
return false;
// The "source" register must be of the same class as DstR.
if (DstRC != SrcRC)
return false;
if (DstRC == InsRC)
return true;
// A 64-bit register can only be generated from other 64-bit registers.
if (DstRC == &Hexagon::DoubleRegsRegClass)
return false;
// Otherwise, the L and S cannot span 32-bit word boundary.
if (S < 32 && S+L > 32)
return false;
return true;
}
bool HexagonGenInsert::findSelfReference(unsigned VR) const {
const BitTracker::RegisterCell &RC = CMS->lookup(VR);
for (uint16_t i = 0, w = RC.width(); i < w; ++i) {
const BitTracker::BitValue &V = RC[i];
if (V.Type == BitTracker::BitValue::Ref && V.RefI.Reg == VR)
return true;
}
return false;
}
bool HexagonGenInsert::findNonSelfReference(unsigned VR) const {
BitTracker::RegisterCell RC = CMS->lookup(VR);
for (uint16_t i = 0, w = RC.width(); i < w; ++i) {
const BitTracker::BitValue &V = RC[i];
if (V.Type == BitTracker::BitValue::Ref && V.RefI.Reg != VR)
return true;
}
return false;
}
void HexagonGenInsert::getInstrDefs(const MachineInstr *MI,
RegisterSet &Defs) const {
for (const MachineOperand &MO : MI->operands()) {
if (!MO.isReg() || !MO.isDef())
continue;
Register R = MO.getReg();
if (!R.isVirtual())
continue;
Defs.insert(R);
}
}
void HexagonGenInsert::getInstrUses(const MachineInstr *MI,
RegisterSet &Uses) const {
for (const MachineOperand &MO : MI->operands()) {
if (!MO.isReg() || !MO.isUse())
continue;
Register R = MO.getReg();
if (!R.isVirtual())
continue;
Uses.insert(R);
}
}
unsigned HexagonGenInsert::distance(const MachineBasicBlock *FromB,
const MachineBasicBlock *ToB, const UnsignedMap &RPO,
PairMapType &M) const {
// Forward distance from the end of a block to the beginning of it does
// not make sense. This function should not be called with FromB == ToB.
assert(FromB != ToB);
unsigned FromN = FromB->getNumber(), ToN = ToB->getNumber();
// If we have already computed it, return the cached result.
PairMapType::iterator F = M.find(std::make_pair(FromN, ToN));
if (F != M.end())
return F->second;
unsigned ToRPO = RPO.lookup(ToN);
unsigned MaxD = 0;
for (const MachineBasicBlock *PB : ToB->predecessors()) {
// Skip back edges. Also, if FromB is a predecessor of ToB, the distance
// along that path will be 0, and we don't need to do any calculations
// on it.
if (PB == FromB || RPO.lookup(PB->getNumber()) >= ToRPO)
continue;
unsigned D = PB->size() + distance(FromB, PB, RPO, M);
if (D > MaxD)
MaxD = D;
}
// Memoize the result for later lookup.
M.insert(std::make_pair(std::make_pair(FromN, ToN), MaxD));
return MaxD;
}
unsigned HexagonGenInsert::distance(MachineBasicBlock::const_iterator FromI,
MachineBasicBlock::const_iterator ToI, const UnsignedMap &RPO,
PairMapType &M) const {
const MachineBasicBlock *FB = FromI->getParent(), *TB = ToI->getParent();
if (FB == TB)
return std::distance(FromI, ToI);
unsigned D1 = std::distance(TB->begin(), ToI);
unsigned D2 = distance(FB, TB, RPO, M);
unsigned D3 = std::distance(FromI, FB->end());
return D1+D2+D3;
}
bool HexagonGenInsert::findRecordInsertForms(unsigned VR,
OrderedRegisterList &AVs) {
if (isDebug()) {
dbgs() << __func__ << ": " << printReg(VR, HRI)
<< " AVs: " << PrintORL(AVs, HRI) << "\n";
}
if (AVs.size() == 0)
return false;
using iterator = OrderedRegisterList::iterator;
BitValueOrdering BVO(BaseOrd);
const BitTracker::RegisterCell &RC = CMS->lookup(VR);
uint16_t W = RC.width();
using RSRecord = std::pair<unsigned, uint16_t>; // (reg,shift)
using RSListType = std::vector<RSRecord>;
// Have a map, with key being the matching prefix length, and the value
// being the list of pairs (R,S), where R's prefix matches VR at S.
// (DenseMap<uint16_t,RSListType> fails to instantiate.)
using LRSMapType = DenseMap<unsigned, RSListType>;
LRSMapType LM;
// Conceptually, rotate the cell RC right (i.e. towards the LSB) by S,
// and find matching prefixes from AVs with the rotated RC. Such a prefix
// would match a string of bits (of length L) in RC starting at S.
for (uint16_t S = 0; S < W; ++S) {
iterator B = AVs.begin(), E = AVs.end();
// The registers in AVs are ordered according to the lexical order of
// the corresponding register cells. This means that the range of regis-
// ters in AVs that match a prefix of length L+1 will be contained in
// the range that matches a prefix of length L. This means that we can
// keep narrowing the search space as the prefix length goes up. This
// helps reduce the overall complexity of the search.
uint16_t L;
for (L = 0; L < W-S; ++L) {
// Compare against VR's bits starting at S, which emulates rotation
// of VR by S.
RegisterCellBitCompareSel RCB(VR, S+L, L, BVO, *CMS);
iterator NewB = std::lower_bound(B, E, VR, RCB);
iterator NewE = std::upper_bound(NewB, E, VR, RCB);
// For the registers that are eliminated from the next range, L is
// the longest prefix matching VR at position S (their prefixes
// differ from VR at S+L). If L>0, record this information for later
// use.
if (L > 0) {
for (iterator I = B; I != NewB; ++I)
LM[L].push_back(std::make_pair(*I, S));
for (iterator I = NewE; I != E; ++I)
LM[L].push_back(std::make_pair(*I, S));
}
B = NewB, E = NewE;
if (B == E)
break;
}
// Record the final register range. If this range is non-empty, then
// L=W-S.
assert(B == E || L == W-S);
if (B != E) {
for (iterator I = B; I != E; ++I)
LM[L].push_back(std::make_pair(*I, S));
// If B!=E, then we found a range of registers whose prefixes cover the
// rest of VR from position S. There is no need to further advance S.
break;
}
}
if (isDebug()) {
dbgs() << "Prefixes matching register " << printReg(VR, HRI) << "\n";
for (const auto &I : LM) {
dbgs() << " L=" << I.first << ':';
const RSListType &LL = I.second;
for (const auto &J : LL)
dbgs() << " (" << printReg(J.first, HRI) << ",@" << J.second << ')';
dbgs() << '\n';
}
}
bool Recorded = false;
for (unsigned SrcR : AVs) {
int FDi = -1, LDi = -1; // First/last different bit.
const BitTracker::RegisterCell &AC = CMS->lookup(SrcR);
uint16_t AW = AC.width();
for (uint16_t i = 0, w = std::min(W, AW); i < w; ++i) {
if (RC[i] == AC[i])
continue;
if (FDi == -1)
FDi = i;
LDi = i;
}
if (FDi == -1)
continue; // TODO (future): Record identical registers.
// Look for a register whose prefix could patch the range [FD..LD]
// where VR and SrcR differ.
uint16_t FD = FDi, LD = LDi; // Switch to unsigned type.
uint16_t MinL = LD-FD+1;
for (uint16_t L = MinL; L < W; ++L) {
LRSMapType::iterator F = LM.find(L);
if (F == LM.end())
continue;
RSListType &LL = F->second;
for (const auto &I : LL) {
uint16_t S = I.second;
// MinL is the minimum length of the prefix. Any length above MinL
// allows some flexibility as to where the prefix can start:
// given the extra length EL=L-MinL, the prefix must start between
// max(0,FD-EL) and FD.
if (S > FD) // Starts too late.
continue;
uint16_t EL = L-MinL;
uint16_t LowS = (EL < FD) ? FD-EL : 0;
if (S < LowS) // Starts too early.
continue;
unsigned InsR = I.first;
if (!isValidInsertForm(VR, SrcR, InsR, L, S))
continue;
if (isDebug()) {
dbgs() << printReg(VR, HRI) << " = insert(" << printReg(SrcR, HRI)
<< ',' << printReg(InsR, HRI) << ",#" << L << ",#"
<< S << ")\n";
}
IFRecordWithRegSet RR(IFRecord(SrcR, InsR, L, S), RegisterSet());
IFMap[VR].push_back(RR);
Recorded = true;
}
}
}
return Recorded;
}
void HexagonGenInsert::collectInBlock(MachineBasicBlock *B,
OrderedRegisterList &AVs) {
if (isDebug())
dbgs() << "visiting block " << printMBBReference(*B) << "\n";
// First, check if this block is reachable at all. If not, the bit tracker
// will not have any information about registers in it.
if (!CMS->BT.reached(B))
return;
bool DoConst = OptConst;
// Keep a separate set of registers defined in this block, so that we
// can remove them from the list of available registers once all DT
// successors have been processed.
RegisterSet BlockDefs, InsDefs;
for (MachineInstr &MI : *B) {
InsDefs.clear();
getInstrDefs(&MI, InsDefs);
// Leave those alone. They are more transparent than "insert".
bool Skip = MI.isCopy() || MI.isRegSequence();
if (!Skip) {
// Visit all defined registers, and attempt to find the corresponding
// "insert" representations.
for (unsigned VR = InsDefs.find_first(); VR; VR = InsDefs.find_next(VR)) {
// Do not collect registers that are known to be compile-time cons-
// tants, unless requested.
if (!DoConst && isConstant(VR))
continue;
// If VR's cell contains a reference to VR, then VR cannot be defined
// via "insert". If VR is a constant that can be generated in a single
// instruction (without constant extenders), generating it via insert
// makes no sense.
if (findSelfReference(VR) || isSmallConstant(VR))
continue;
findRecordInsertForms(VR, AVs);
// Stop if the map size is too large.
if (IFMap.size() > MaxIFMSize)
return;
}
}
// Insert the defined registers into the list of available registers
// after they have been processed.
for (unsigned VR = InsDefs.find_first(); VR; VR = InsDefs.find_next(VR))
AVs.insert(VR);
BlockDefs.insert(InsDefs);
}
for (auto *DTN : children<MachineDomTreeNode*>(MDT->getNode(B))) {
MachineBasicBlock *SB = DTN->getBlock();
collectInBlock(SB, AVs);
}
for (unsigned VR = BlockDefs.find_first(); VR; VR = BlockDefs.find_next(VR))
AVs.remove(VR);
}
void HexagonGenInsert::findRemovableRegisters(unsigned VR, IFRecord IF,
RegisterSet &RMs) const {
// For a given register VR and a insert form, find the registers that are
// used by the current definition of VR, and which would no longer be
// needed for it after the definition of VR is replaced with the insert
// form. These are the registers that could potentially become dead.
RegisterSet Regs[2];
unsigned S = 0; // Register set selector.
Regs[S].insert(VR);
while (!Regs[S].empty()) {
// Breadth-first search.
unsigned OtherS = 1-S;
Regs[OtherS].clear();
for (unsigned R = Regs[S].find_first(); R; R = Regs[S].find_next(R)) {
Regs[S].remove(R);
if (R == IF.SrcR || R == IF.InsR)
continue;
// Check if a given register has bits that are references to any other
// registers. This is to detect situations where the instruction that
// defines register R takes register Q as an operand, but R itself does
// not contain any bits from Q. Loads are examples of how this could
// happen:
// R = load Q
// In this case (assuming we do not have any knowledge about the loaded
// value), we must not treat R as a "conveyance" of the bits from Q.
// (The information in BT about R's bits would have them as constants,