1 //===- HexagonConstExtenders.cpp ------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "HexagonInstrInfo.h"
11 #include "HexagonRegisterInfo.h"
12 #include "HexagonSubtarget.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/CodeGen/MachineDominators.h"
15 #include "llvm/CodeGen/MachineFunctionPass.h"
16 #include "llvm/CodeGen/MachineInstrBuilder.h"
17 #include "llvm/CodeGen/MachineRegisterInfo.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/raw_ostream.h"
20 #include "llvm/Pass.h"
21 #include <map>
22 #include <set>
23 #include <utility>
24 #include <vector>
25 
26 #define DEBUG_TYPE "hexagon-cext-opt"
27 
28 using namespace llvm;
29 
30 static cl::opt<unsigned> CountThreshold("hexagon-cext-threshold",
31   cl::init(3), cl::Hidden, cl::ZeroOrMore,
32   cl::desc("Minimum number of extenders to trigger replacement"));
33 
34 static cl::opt<unsigned> ReplaceLimit("hexagon-cext-limit", cl::init(0),
35   cl::Hidden, cl::ZeroOrMore, cl::desc("Maximum number of replacements"));
36 
37 namespace llvm {
38   void initializeHexagonConstExtendersPass(PassRegistry&);
39   FunctionPass *createHexagonConstExtenders();
40 }
41 
42 namespace {
43   struct OffsetRange {
44     int32_t Min = INT_MIN, Max = INT_MAX;
45     uint8_t Align = 1;
46 
47     OffsetRange() = default;
48     OffsetRange(int32_t L, int32_t H, uint8_t A)
49       : Min(L), Max(H), Align(A) {}
50     OffsetRange &intersect(OffsetRange A) {
51       Align = std::max(Align, A.Align);
52       Min = std::max(Min, A.Min);
53       Max = std::min(Max, A.Max);
54       // Canonicalize empty ranges.
55       if (Min > Max)
56         std::tie(Min, Max, Align) = std::make_tuple(0, -1, 1);
57       return *this;
58     }
59     OffsetRange &shift(int32_t S) {
60       assert(alignTo(std::abs(S), Align) == uint64_t(std::abs(S)));
61       Min += S;
62       Max += S;
63       return *this;
64     }
65     OffsetRange &extendBy(int32_t D) {
66       // If D < 0, extend Min, otherwise extend Max.
67       if (D < 0)
68         Min = (INT_MIN-D < Min) ? Min+D : INT_MIN;
69       else
70         Max = (INT_MAX-D > Max) ? Max+D : INT_MAX;
71       return *this;
72     }
73     bool empty() const {
74       return Min > Max;
75     }
76     bool contains(int32_t V) const {
77       return Min <= V && V <= Max && (V % Align) == 0;
78     }
79     bool operator==(const OffsetRange &R) const {
80       return Min == R.Min && Max == R.Max && Align == R.Align;
81     }
82     bool operator!=(const OffsetRange &R) const {
83       return !operator==(R);
84     }
85     bool operator<(const OffsetRange &R) const {
86       if (Min != R.Min)
87         return Min < R.Min;
88       if (Max != R.Max)
89         return Max < R.Max;
90       return Align < R.Align;
91     }
92     static OffsetRange zero() { return {0, 0, 1}; }
93   };
94 
95   struct RangeTree {
96     struct Node {
97       Node(const OffsetRange &R) : MaxEnd(R.Max), Range(R) {}
98       unsigned Height = 1;
99       unsigned Count = 1;
100       int32_t MaxEnd;
101       const OffsetRange &Range;
102       Node *Left = nullptr, *Right = nullptr;
103     };
104 
105     Node *Root = nullptr;
106 
107     void add(const OffsetRange &R) {
108       Root = add(Root, R);
109     }
110     void erase(const Node *N) {
111       Root = remove(Root, N);
112       delete N;
113     }
114     void order(SmallVectorImpl<Node*> &Seq) const {
115       order(Root, Seq);
116     }
117     SmallVector<Node*,8> nodesWith(int32_t P, bool CheckAlign = true) {
118       SmallVector<Node*,8> Nodes;
119       nodesWith(Root, P, CheckAlign, Nodes);
120       return Nodes;
121     }
122     void dump() const;
123     ~RangeTree() {
124       SmallVector<Node*,8> Nodes;
125       order(Nodes);
126       for (Node *N : Nodes)
127         delete N;
128     }
129 
130   private:
131     void dump(const Node *N) const;
132     void order(Node *N, SmallVectorImpl<Node*> &Seq) const;
133     void nodesWith(Node *N, int32_t P, bool CheckA,
134                    SmallVectorImpl<Node*> &Seq) const;
135 
136     Node *add(Node *N, const OffsetRange &R);
137     Node *remove(Node *N, const Node *D);
138     Node *rotateLeft(Node *Lower, Node *Higher);
139     Node *rotateRight(Node *Lower, Node *Higher);
140     unsigned height(Node *N) {
141       return N != nullptr ? N->Height : 0;
142     }
143     Node *update(Node *N) {
144       assert(N != nullptr);
145       N->Height = 1 + std::max(height(N->Left), height(N->Right));
146       if (N->Left)
147         N->MaxEnd = std::max(N->MaxEnd, N->Left->MaxEnd);
148       if (N->Right)
149         N->MaxEnd = std::max(N->MaxEnd, N->Right->MaxEnd);
150       return N;
151     }
152     Node *rebalance(Node *N) {
153       assert(N != nullptr);
154       int32_t Balance = height(N->Right) - height(N->Left);
155       if (Balance < -1)
156         return rotateRight(N->Left, N);
157       if (Balance > 1)
158         return rotateLeft(N->Right, N);
159       return N;
160     }
161   };
162 
163   struct Loc {
164     MachineBasicBlock *Block = nullptr;
165     MachineBasicBlock::iterator At;
166 
167     Loc(MachineBasicBlock *B, MachineBasicBlock::iterator It)
168       : Block(B), At(It) {
169       if (B->end() == It) {
170         Pos = -1;
171       } else {
172         assert(It->getParent() == B);
173         Pos = std::distance(B->begin(), It);
174       }
175     }
176     bool operator<(Loc A) const {
177       if (Block != A.Block)
178         return Block->getNumber() < A.Block->getNumber();
179       if (A.Pos == -1)
180         return Pos != A.Pos;
181       return Pos != -1 && Pos < A.Pos;
182     }
183   private:
184     int Pos = 0;
185   };
186 
187   struct HexagonConstExtenders : public MachineFunctionPass {
188     static char ID;
189     HexagonConstExtenders() : MachineFunctionPass(ID) {}
190 
191     void getAnalysisUsage(AnalysisUsage &AU) const override {
192       AU.addRequired<MachineDominatorTree>();
193       AU.addPreserved<MachineDominatorTree>();
194       MachineFunctionPass::getAnalysisUsage(AU);
195     }
196 
197     StringRef getPassName() const override {
198       return "Hexagon constant-extender optimization";
199     }
200     bool runOnMachineFunction(MachineFunction &MF) override;
201 
202   private:
203     struct Register {
204       Register() = default;
205       Register(unsigned R, unsigned S) : Reg(R), Sub(S) {}
206       Register(const MachineOperand &Op)
207         : Reg(Op.getReg()), Sub(Op.getSubReg()) {}
208       Register &operator=(const MachineOperand &Op) {
209         if (Op.isReg()) {
210           Reg = Op.getReg();
211           Sub = Op.getSubReg();
212         } else if (Op.isFI()) {
213           Reg = TargetRegisterInfo::index2StackSlot(Op.getIndex());
214         }
215         return *this;
216       }
217       bool isVReg() const {
218         return Reg != 0 && !TargetRegisterInfo::isStackSlot(Reg) &&
219                TargetRegisterInfo::isVirtualRegister(Reg);
220       }
221       bool isSlot() const {
222         return Reg != 0 && TargetRegisterInfo::isStackSlot(Reg);
223       }
224       operator MachineOperand() const {
225         if (isVReg())
226           return MachineOperand::CreateReg(Reg, /*Def*/false, /*Imp*/false,
227                           /*Kill*/false, /*Dead*/false, /*Undef*/false,
228                           /*EarlyClobber*/false, Sub);
229         if (TargetRegisterInfo::isStackSlot(Reg)) {
230           int FI = TargetRegisterInfo::stackSlot2Index(Reg);
231           return MachineOperand::CreateFI(FI);
232         }
233         llvm_unreachable("Cannot create MachineOperand");
234       }
235       bool operator==(Register R) const { return Reg == R.Reg && Sub == R.Sub; }
236       bool operator!=(Register R) const { return !operator==(R); }
237       bool operator<(Register R) const {
238         // For std::map.
239         return Reg < R.Reg || (Reg == R.Reg && Sub < R.Sub);
240       }
241       unsigned Reg = 0, Sub = 0;
242     };
243 
244     struct ExtExpr {
245       // A subexpression in which the extender is used. In general, this
246       // represents an expression where adding D to the extender will be
247       // equivalent to adding D to the expression as a whole. In other
248       // words, expr(add(##V,D) = add(expr(##V),D).
249 
250       // The original motivation for this are the io/ur addressing modes,
251       // where the offset is extended. Consider the io example:
252       // In memw(Rs+##V), the ##V could be replaced by a register Rt to
253       // form the rr mode: memw(Rt+Rs<<0). In such case, however, the
254       // register Rt must have exactly the value of ##V. If there was
255       // another instruction memw(Rs+##V+4), it would need a different Rt.
256       // Now, if Rt was initialized as "##V+Rs<<0", both of these
257       // instructions could use the same Rt, just with different offsets.
258       // Here it's clear that "initializer+4" should be the same as if
259       // the offset 4 was added to the ##V in the initializer.
260 
261       // The only kinds of expressions that support the requirement of
262       // commuting with addition are addition and subtraction from ##V.
263       // Include shifting the Rs to account for the ur addressing mode:
264       //   ##Val + Rs << S
265       //   ##Val - Rs
266       Register Rs;
267       unsigned S = 0;
268       bool Neg = false;
269 
270       ExtExpr() = default;
271       ExtExpr(Register RS, bool NG, unsigned SH) : Rs(RS), S(SH), Neg(NG) {}
272       // Expression is trivial if it does not modify the extender.
273       bool trivial() const {
274         return Rs.Reg == 0;
275       }
276       bool operator==(const ExtExpr &Ex) const {
277         return Rs == Ex.Rs && S == Ex.S && Neg == Ex.Neg;
278       }
279       bool operator!=(const ExtExpr &Ex) const {
280         return !operator==(Ex);
281       }
282       bool operator<(const ExtExpr &Ex) const {
283         if (Rs != Ex.Rs)
284           return Rs < Ex.Rs;
285         if (S != Ex.S)
286           return S < Ex.S;
287         return !Neg && Ex.Neg;
288       }
289     };
290 
291     struct ExtDesc {
292       MachineInstr *UseMI = nullptr;
293       unsigned OpNum = -1u;
294       // The subexpression in which the extender is used (e.g. address
295       // computation).
296       ExtExpr Expr;
297       // Optional register that is assigned the value of Expr.
298       Register Rd;
299       // Def means that the output of the instruction may differ from the
300       // original by a constant c, and that the difference can be corrected
301       // by adding/subtracting c in all users of the defined register.
302       bool IsDef = false;
303 
304       MachineOperand &getOp() {
305         return UseMI->getOperand(OpNum);
306       }
307       const MachineOperand &getOp() const {
308         return UseMI->getOperand(OpNum);
309       }
310     };
311 
312     struct ExtRoot {
313       union {
314         const ConstantFP *CFP;  // MO_FPImmediate
315         const char *SymbolName; // MO_ExternalSymbol
316         const GlobalValue *GV;  // MO_GlobalAddress
317         const BlockAddress *BA; // MO_BlockAddress
318         int64_t ImmVal;         // MO_Immediate, MO_TargetIndex,
319                                 // and MO_ConstantPoolIndex
320       } V;
321       unsigned Kind;            // Same as in MachineOperand.
322       unsigned char TF;         // TargetFlags.
323 
324       ExtRoot(const MachineOperand &Op);
325       bool operator==(const ExtRoot &ER) const {
326         return Kind == ER.Kind && V.ImmVal == ER.V.ImmVal;
327       }
328       bool operator!=(const ExtRoot &ER) const {
329         return !operator==(ER);
330       }
331       bool operator<(const ExtRoot &ER) const;
332     };
333 
334     struct ExtValue : public ExtRoot {
335       int32_t Offset;
336 
337       ExtValue(const MachineOperand &Op);
338       ExtValue(const ExtDesc &ED) : ExtValue(ED.getOp()) {}
339       ExtValue(const ExtRoot &ER, int32_t Off) : ExtRoot(ER), Offset(Off) {}
340       bool operator<(const ExtValue &EV) const;
341       bool operator==(const ExtValue &EV) const {
342         return ExtRoot(*this) == ExtRoot(EV) && Offset == EV.Offset;
343       }
344       bool operator!=(const ExtValue &EV) const {
345         return !operator==(EV);
346       }
347       explicit operator MachineOperand() const;
348     };
349 
350     using IndexList = SetVector<unsigned>;
351     using ExtenderInit = std::pair<ExtValue, ExtExpr>;
352     using AssignmentMap = std::map<ExtenderInit, IndexList>;
353     using LocDefMap = std::map<Loc, IndexList>;
354 
355     const HexagonInstrInfo *HII = nullptr;
356     const HexagonRegisterInfo *HRI = nullptr;
357     MachineDominatorTree *MDT = nullptr;
358     MachineRegisterInfo *MRI = nullptr;
359     std::vector<ExtDesc> Extenders;
360     std::vector<unsigned> NewRegs;
361 
362     bool isStoreImmediate(unsigned Opc) const;
363     bool isRegOffOpcode(unsigned ExtOpc) const ;
364     unsigned getRegOffOpcode(unsigned ExtOpc) const;
365     unsigned getDirectRegReplacement(unsigned ExtOpc) const;
366     OffsetRange getOffsetRange(Register R, const MachineInstr &MI) const;
367     OffsetRange getOffsetRange(const ExtDesc &ED) const;
368     OffsetRange getOffsetRange(Register Rd) const;
369 
370     void recordExtender(MachineInstr &MI, unsigned OpNum);
371     void collectInstr(MachineInstr &MI);
372     void collect(MachineFunction &MF);
373     void assignInits(const ExtRoot &ER, unsigned Begin, unsigned End,
374                      AssignmentMap &IMap);
375     void calculatePlacement(const ExtenderInit &ExtI, const IndexList &Refs,
376                             LocDefMap &Defs);
377     Register insertInitializer(Loc DefL, const ExtenderInit &ExtI);
378     bool replaceInstrExact(const ExtDesc &ED, Register ExtR);
379     bool replaceInstrExpr(const ExtDesc &ED, const ExtenderInit &ExtI,
380                           Register ExtR, int32_t &Diff);
381     bool replaceInstr(unsigned Idx, Register ExtR, const ExtenderInit &ExtI);
382     bool replaceExtenders(const AssignmentMap &IMap);
383 
384     unsigned getOperandIndex(const MachineInstr &MI,
385                              const MachineOperand &Op) const;
386     const MachineOperand &getPredicateOp(const MachineInstr &MI) const;
387     const MachineOperand &getLoadResultOp(const MachineInstr &MI) const;
388     const MachineOperand &getStoredValueOp(const MachineInstr &MI) const;
389 
390     friend struct PrintRegister;
391     friend struct PrintExpr;
392     friend struct PrintInit;
393     friend struct PrintIMap;
394     friend raw_ostream &operator<< (raw_ostream &OS,
395                                     const struct PrintRegister &P);
396     friend raw_ostream &operator<< (raw_ostream &OS, const struct PrintExpr &P);
397     friend raw_ostream &operator<< (raw_ostream &OS, const struct PrintInit &P);
398     friend raw_ostream &operator<< (raw_ostream &OS, const ExtDesc &ED);
399     friend raw_ostream &operator<< (raw_ostream &OS, const ExtRoot &ER);
400     friend raw_ostream &operator<< (raw_ostream &OS, const ExtValue &EV);
401     friend raw_ostream &operator<< (raw_ostream &OS, const OffsetRange &OR);
402     friend raw_ostream &operator<< (raw_ostream &OS, const struct PrintIMap &P);
403   };
404 
405   using HCE = HexagonConstExtenders;
406 
407   LLVM_ATTRIBUTE_UNUSED
408   raw_ostream &operator<< (raw_ostream &OS, const OffsetRange &OR) {
409     if (OR.Min > OR.Max)
410       OS << '!';
411     OS << '[' << OR.Min << ',' << OR.Max << "]a" << unsigned(OR.Align);
412     return OS;
413   }
414 
415   struct PrintRegister {
416     PrintRegister(HCE::Register R, const HexagonRegisterInfo &I)
417       : Rs(R), HRI(I) {}
418     HCE::Register Rs;
419     const HexagonRegisterInfo &HRI;
420   };
421 
422   LLVM_ATTRIBUTE_UNUSED
423   raw_ostream &operator<< (raw_ostream &OS, const PrintRegister &P) {
424     if (P.Rs.Reg != 0)
425       OS << printReg(P.Rs.Reg, &P.HRI, P.Rs.Sub);
426     else
427       OS << "noreg";
428     return OS;
429   }
430 
431   struct PrintExpr {
432     PrintExpr(const HCE::ExtExpr &E, const HexagonRegisterInfo &I)
433       : Ex(E), HRI(I) {}
434     const HCE::ExtExpr &Ex;
435     const HexagonRegisterInfo &HRI;
436   };
437 
438   LLVM_ATTRIBUTE_UNUSED
439   raw_ostream &operator<< (raw_ostream &OS, const PrintExpr &P) {
440     OS << "## " << (P.Ex.Neg ? "- " : "+ ");
441     if (P.Ex.Rs.Reg != 0)
442       OS << printReg(P.Ex.Rs.Reg, &P.HRI, P.Ex.Rs.Sub);
443     else
444       OS << "__";
445     OS << " << " << P.Ex.S;
446     return OS;
447   }
448 
449   struct PrintInit {
450     PrintInit(const HCE::ExtenderInit &EI, const HexagonRegisterInfo &I)
451       : ExtI(EI), HRI(I) {}
452     const HCE::ExtenderInit &ExtI;
453     const HexagonRegisterInfo &HRI;
454   };
455 
456   LLVM_ATTRIBUTE_UNUSED
457   raw_ostream &operator<< (raw_ostream &OS, const PrintInit &P) {
458     OS << '[' << P.ExtI.first << ", "
459        << PrintExpr(P.ExtI.second, P.HRI) << ']';
460     return OS;
461   }
462 
463   LLVM_ATTRIBUTE_UNUSED
464   raw_ostream &operator<< (raw_ostream &OS, const HCE::ExtDesc &ED) {
465     assert(ED.OpNum != -1u);
466     const MachineBasicBlock &MBB = *ED.getOp().getParent()->getParent();
467     const MachineFunction &MF = *MBB.getParent();
468     const auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
469     OS << "bb#" << MBB.getNumber() << ": ";
470     if (ED.Rd.Reg != 0)
471       OS << printReg(ED.Rd.Reg, &HRI, ED.Rd.Sub);
472     else
473       OS << "__";
474     OS << " = " << PrintExpr(ED.Expr, HRI);
475     if (ED.IsDef)
476       OS << ", def";
477     return OS;
478   }
479 
480   LLVM_ATTRIBUTE_UNUSED
481   raw_ostream &operator<< (raw_ostream &OS, const HCE::ExtRoot &ER) {
482     switch (ER.Kind) {
483       case MachineOperand::MO_Immediate:
484         OS << "imm:" << ER.V.ImmVal;
485         break;
486       case MachineOperand::MO_FPImmediate:
487         OS << "fpi:" << *ER.V.CFP;
488         break;
489       case MachineOperand::MO_ExternalSymbol:
490         OS << "sym:" << *ER.V.SymbolName;
491         break;
492       case MachineOperand::MO_GlobalAddress:
493         OS << "gad:" << ER.V.GV->getName();
494         break;
495       case MachineOperand::MO_BlockAddress:
496         OS << "blk:" << *ER.V.BA;
497         break;
498       case MachineOperand::MO_TargetIndex:
499         OS << "tgi:" << ER.V.ImmVal;
500         break;
501       case MachineOperand::MO_ConstantPoolIndex:
502         OS << "cpi:" << ER.V.ImmVal;
503         break;
504       case MachineOperand::MO_JumpTableIndex:
505         OS << "jti:" << ER.V.ImmVal;
506         break;
507       default:
508         OS << "???:" << ER.V.ImmVal;
509         break;
510     }
511     return OS;
512   }
513 
514   LLVM_ATTRIBUTE_UNUSED
515   raw_ostream &operator<< (raw_ostream &OS, const HCE::ExtValue &EV) {
516     OS << HCE::ExtRoot(EV) << "  off:" << EV.Offset;
517     return OS;
518   }
519 
520   struct PrintIMap {
521     PrintIMap(const HCE::AssignmentMap &M, const HexagonRegisterInfo &I)
522       : IMap(M), HRI(I) {}
523     const HCE::AssignmentMap &IMap;
524     const HexagonRegisterInfo &HRI;
525   };
526 
527   LLVM_ATTRIBUTE_UNUSED
528   raw_ostream &operator<< (raw_ostream &OS, const PrintIMap &P) {
529     OS << "{\n";
530     for (const std::pair<HCE::ExtenderInit,HCE::IndexList> &Q : P.IMap) {
531       OS << "  " << PrintInit(Q.first, P.HRI) << " -> {";
532       for (unsigned I : Q.second)
533         OS << ' ' << I;
534       OS << " }\n";
535     }
536     OS << "}\n";
537     return OS;
538   }
539 }
540 
541 INITIALIZE_PASS_BEGIN(HexagonConstExtenders, "hexagon-cext-opt",
542       "Hexagon constant-extender optimization", false, false)
543 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
544 INITIALIZE_PASS_END(HexagonConstExtenders, "hexagon-cext-opt",
545       "Hexagon constant-extender optimization", false, false)
546 
547 static unsigned ReplaceCounter = 0;
548 
549 char HCE::ID = 0;
550 
551 #ifndef NDEBUG
552 LLVM_DUMP_METHOD void RangeTree::dump() const {
553   dbgs() << "Root: " << Root << '\n';
554   if (Root)
555     dump(Root);
556 }
557 
558 LLVM_DUMP_METHOD void RangeTree::dump(const Node *N) const {
559   dbgs() << "Node: " << N << '\n';
560   dbgs() << "  Height: " << N->Height << '\n';
561   dbgs() << "  Count: " << N->Count << '\n';
562   dbgs() << "  MaxEnd: " << N->MaxEnd << '\n';
563   dbgs() << "  Range: " << N->Range << '\n';
564   dbgs() << "  Left: " << N->Left << '\n';
565   dbgs() << "  Right: " << N->Right << "\n\n";
566 
567   if (N->Left)
568     dump(N->Left);
569   if (N->Right)
570     dump(N->Right);
571 }
572 #endif
573 
574 void RangeTree::order(Node *N, SmallVectorImpl<Node*> &Seq) const {
575   if (N == nullptr)
576     return;
577   order(N->Left, Seq);
578   Seq.push_back(N);
579   order(N->Right, Seq);
580 }
581 
582 void RangeTree::nodesWith(Node *N, int32_t P, bool CheckA,
583       SmallVectorImpl<Node*> &Seq) const {
584   if (N == nullptr || N->MaxEnd < P)
585     return;
586   nodesWith(N->Left, P, CheckA, Seq);
587   if (N->Range.Min <= P) {
588     if ((CheckA && N->Range.contains(P)) || (!CheckA && P <= N->Range.Max))
589       Seq.push_back(N);
590     nodesWith(N->Right, P, CheckA, Seq);
591   }
592 }
593 
594 RangeTree::Node *RangeTree::add(Node *N, const OffsetRange &R) {
595   if (N == nullptr)
596     return new Node(R);
597 
598   if (N->Range == R) {
599     N->Count++;
600     return N;
601   }
602 
603   if (R < N->Range)
604     N->Left = add(N->Left, R);
605   else
606     N->Right = add(N->Right, R);
607   return rebalance(update(N));
608 }
609 
610 RangeTree::Node *RangeTree::remove(Node *N, const Node *D) {
611   assert(N != nullptr);
612 
613   if (N != D) {
614     assert(N->Range != D->Range && "N and D should not be equal");
615     if (D->Range < N->Range)
616       N->Left = remove(N->Left, D);
617     else
618       N->Right = remove(N->Right, D);
619     return rebalance(update(N));
620   }
621 
622   // We got to the node we need to remove. If any of its children are
623   // missing, simply replace it with the other child.
624   if (N->Left == nullptr || N->Right == nullptr)
625     return (N->Left == nullptr) ? N->Right : N->Left;
626 
627   // Find the rightmost child of N->Left, remove it and plug it in place
628   // of N.
629   Node *M = N->Left;
630   while (M->Right)
631     M = M->Right;
632   M->Left = remove(N->Left, M);
633   M->Right = N->Right;
634   return rebalance(update(M));
635 }
636 
637 RangeTree::Node *RangeTree::rotateLeft(Node *Lower, Node *Higher) {
638   assert(Higher->Right == Lower);
639   // The Lower node is on the right from Higher. Make sure that Lower's
640   // balance is greater to the right. Otherwise the rotation will create
641   // an unbalanced tree again.
642   if (height(Lower->Left) > height(Lower->Right))
643     Lower = rotateRight(Lower->Left, Lower);
644   assert(height(Lower->Left) <= height(Lower->Right));
645   Higher->Right = Lower->Left;
646   update(Higher);
647   Lower->Left = Higher;
648   update(Lower);
649   return Lower;
650 }
651 
652 RangeTree::Node *RangeTree::rotateRight(Node *Lower, Node *Higher) {
653   assert(Higher->Left == Lower);
654   // The Lower node is on the left from Higher. Make sure that Lower's
655   // balance is greater to the left. Otherwise the rotation will create
656   // an unbalanced tree again.
657   if (height(Lower->Left) < height(Lower->Right))
658     Lower = rotateLeft(Lower->Right, Lower);
659   assert(height(Lower->Left) >= height(Lower->Right));
660   Higher->Left = Lower->Right;
661   update(Higher);
662   Lower->Right = Higher;
663   update(Lower);
664   return Lower;
665 }
666 
667 
668 HCE::ExtRoot::ExtRoot(const MachineOperand &Op) {
669   // Always store ImmVal, since it's the field used for comparisons.
670   V.ImmVal = 0;
671   if (Op.isImm())
672     ; // Keep 0. Do not use Op.getImm() for value here (treat 0 as the root).
673   else if (Op.isFPImm())
674     V.CFP = Op.getFPImm();
675   else if (Op.isSymbol())
676     V.SymbolName = Op.getSymbolName();
677   else if (Op.isGlobal())
678     V.GV = Op.getGlobal();
679   else if (Op.isBlockAddress())
680     V.BA = Op.getBlockAddress();
681   else if (Op.isCPI() || Op.isTargetIndex() || Op.isJTI())
682     V.ImmVal = Op.getIndex();
683   else
684     llvm_unreachable("Unexpected operand type");
685 
686   Kind = Op.getType();
687   TF = Op.getTargetFlags();
688 }
689 
690 bool HCE::ExtRoot::operator< (const HCE::ExtRoot &ER) const {
691   if (Kind != ER.Kind)
692     return Kind < ER.Kind;
693   switch (Kind) {
694     case MachineOperand::MO_Immediate:
695     case MachineOperand::MO_TargetIndex:
696     case MachineOperand::MO_ConstantPoolIndex:
697     case MachineOperand::MO_JumpTableIndex:
698       return V.ImmVal < ER.V.ImmVal;
699     case MachineOperand::MO_FPImmediate: {
700       const APFloat &ThisF = V.CFP->getValueAPF();
701       const APFloat &OtherF = ER.V.CFP->getValueAPF();
702       return ThisF.bitcastToAPInt().ult(OtherF.bitcastToAPInt());
703     }
704     case MachineOperand::MO_ExternalSymbol:
705       return StringRef(V.SymbolName) < StringRef(ER.V.SymbolName);
706     case MachineOperand::MO_GlobalAddress:
707       assert(V.GV->hasName() && ER.V.GV->hasName());
708       return V.GV->getName() < ER.V.GV->getName();
709     case MachineOperand::MO_BlockAddress: {
710       const BasicBlock *ThisB = V.BA->getBasicBlock();
711       const BasicBlock *OtherB = ER.V.BA->getBasicBlock();
712       assert(ThisB->getParent() == OtherB->getParent());
713       const Function &F = *ThisB->getParent();
714       return std::distance(F.begin(), ThisB->getIterator()) <
715              std::distance(F.begin(), OtherB->getIterator());
716     }
717   }
718   return V.ImmVal < ER.V.ImmVal;
719 }
720 
721 HCE::ExtValue::ExtValue(const MachineOperand &Op) : ExtRoot(Op) {
722   if (Op.isImm())
723     Offset = Op.getImm();
724   else if (Op.isFPImm() || Op.isJTI())
725     Offset = 0;
726   else if (Op.isSymbol() || Op.isGlobal() || Op.isBlockAddress() ||
727            Op.isCPI() || Op.isTargetIndex())
728     Offset = Op.getOffset();
729   else
730     llvm_unreachable("Unexpected operand type");
731 }
732 
733 bool HCE::ExtValue::operator< (const HCE::ExtValue &EV) const {
734   const ExtRoot &ER = *this;
735   if (!(ER == ExtRoot(EV)))
736     return ER < EV;
737   return Offset < EV.Offset;
738 }
739 
740 HCE::ExtValue::operator MachineOperand() const {
741   switch (Kind) {
742     case MachineOperand::MO_Immediate:
743       return MachineOperand::CreateImm(V.ImmVal + Offset);
744     case MachineOperand::MO_FPImmediate:
745       assert(Offset == 0);
746       return MachineOperand::CreateFPImm(V.CFP);
747     case MachineOperand::MO_ExternalSymbol:
748       assert(Offset == 0);
749       return MachineOperand::CreateES(V.SymbolName, TF);
750     case MachineOperand::MO_GlobalAddress:
751       return MachineOperand::CreateGA(V.GV, Offset, TF);
752     case MachineOperand::MO_BlockAddress:
753       return MachineOperand::CreateBA(V.BA, Offset, TF);
754     case MachineOperand::MO_TargetIndex:
755       return MachineOperand::CreateTargetIndex(V.ImmVal, Offset, TF);
756     case MachineOperand::MO_ConstantPoolIndex:
757       return MachineOperand::CreateCPI(V.ImmVal, Offset, TF);
758     case MachineOperand::MO_JumpTableIndex:
759       assert(Offset == 0);
760     default:
761       llvm_unreachable("Unhandled kind");
762  }
763 }
764 
765 bool HCE::isStoreImmediate(unsigned Opc) const {
766   switch (Opc) {
767     case Hexagon::S4_storeirbt_io:
768     case Hexagon::S4_storeirbf_io:
769     case Hexagon::S4_storeirht_io:
770     case Hexagon::S4_storeirhf_io:
771     case Hexagon::S4_storeirit_io:
772     case Hexagon::S4_storeirif_io:
773     case Hexagon::S4_storeirb_io:
774     case Hexagon::S4_storeirh_io:
775     case Hexagon::S4_storeiri_io:
776       return true;
777     default:
778       break;
779   }
780   return false;
781 }
782 
783 bool HCE::isRegOffOpcode(unsigned Opc) const {
784   switch (Opc) {
785     case Hexagon::L2_loadrub_io:
786     case Hexagon::L2_loadrb_io:
787     case Hexagon::L2_loadruh_io:
788     case Hexagon::L2_loadrh_io:
789     case Hexagon::L2_loadri_io:
790     case Hexagon::L2_loadrd_io:
791     case Hexagon::L2_loadbzw2_io:
792     case Hexagon::L2_loadbzw4_io:
793     case Hexagon::L2_loadbsw2_io:
794     case Hexagon::L2_loadbsw4_io:
795     case Hexagon::L2_loadalignh_io:
796     case Hexagon::L2_loadalignb_io:
797     case Hexagon::L2_ploadrubt_io:
798     case Hexagon::L2_ploadrubf_io:
799     case Hexagon::L2_ploadrbt_io:
800     case Hexagon::L2_ploadrbf_io:
801     case Hexagon::L2_ploadruht_io:
802     case Hexagon::L2_ploadruhf_io:
803     case Hexagon::L2_ploadrht_io:
804     case Hexagon::L2_ploadrhf_io:
805     case Hexagon::L2_ploadrit_io:
806     case Hexagon::L2_ploadrif_io:
807     case Hexagon::L2_ploadrdt_io:
808     case Hexagon::L2_ploadrdf_io:
809     case Hexagon::S2_storerb_io:
810     case Hexagon::S2_storerh_io:
811     case Hexagon::S2_storerf_io:
812     case Hexagon::S2_storeri_io:
813     case Hexagon::S2_storerd_io:
814     case Hexagon::S2_pstorerbt_io:
815     case Hexagon::S2_pstorerbf_io:
816     case Hexagon::S2_pstorerht_io:
817     case Hexagon::S2_pstorerhf_io:
818     case Hexagon::S2_pstorerft_io:
819     case Hexagon::S2_pstorerff_io:
820     case Hexagon::S2_pstorerit_io:
821     case Hexagon::S2_pstorerif_io:
822     case Hexagon::S2_pstorerdt_io:
823     case Hexagon::S2_pstorerdf_io:
824     case Hexagon::A2_addi:
825       return true;
826     default:
827       break;
828   }
829   return false;
830 }
831 
832 unsigned HCE::getRegOffOpcode(unsigned ExtOpc) const {
833   // If there exists an instruction that takes a register and offset,
834   // that corresponds to the ExtOpc, return it, otherwise return 0.
835   using namespace Hexagon;
836   switch (ExtOpc) {
837     case A2_tfrsi:    return A2_addi;
838     default:
839       break;
840   }
841   const MCInstrDesc &D = HII->get(ExtOpc);
842   if (D.mayLoad() || D.mayStore()) {
843     uint64_t F = D.TSFlags;
844     unsigned AM = (F >> HexagonII::AddrModePos) & HexagonII::AddrModeMask;
845     switch (AM) {
846       case HexagonII::Absolute:
847       case HexagonII::AbsoluteSet:
848       case HexagonII::BaseLongOffset:
849         switch (ExtOpc) {
850           case PS_loadrubabs:
851           case L4_loadrub_ap:
852           case L4_loadrub_ur:     return L2_loadrub_io;
853           case PS_loadrbabs:
854           case L4_loadrb_ap:
855           case L4_loadrb_ur:      return L2_loadrb_io;
856           case PS_loadruhabs:
857           case L4_loadruh_ap:
858           case L4_loadruh_ur:     return L2_loadruh_io;
859           case PS_loadrhabs:
860           case L4_loadrh_ap:
861           case L4_loadrh_ur:      return L2_loadrh_io;
862           case PS_loadriabs:
863           case L4_loadri_ap:
864           case L4_loadri_ur:      return L2_loadri_io;
865           case PS_loadrdabs:
866           case L4_loadrd_ap:
867           case L4_loadrd_ur:      return L2_loadrd_io;
868           case L4_loadbzw2_ap:
869           case L4_loadbzw2_ur:    return L2_loadbzw2_io;
870           case L4_loadbzw4_ap:
871           case L4_loadbzw4_ur:    return L2_loadbzw4_io;
872           case L4_loadbsw2_ap:
873           case L4_loadbsw2_ur:    return L2_loadbsw2_io;
874           case L4_loadbsw4_ap:
875           case L4_loadbsw4_ur:    return L2_loadbsw4_io;
876           case L4_loadalignh_ap:
877           case L4_loadalignh_ur:  return L2_loadalignh_io;
878           case L4_loadalignb_ap:
879           case L4_loadalignb_ur:  return L2_loadalignb_io;
880           case L4_ploadrubt_abs:  return L2_ploadrubt_io;
881           case L4_ploadrubf_abs:  return L2_ploadrubf_io;
882           case L4_ploadrbt_abs:   return L2_ploadrbt_io;
883           case L4_ploadrbf_abs:   return L2_ploadrbf_io;
884           case L4_ploadruht_abs:  return L2_ploadruht_io;
885           case L4_ploadruhf_abs:  return L2_ploadruhf_io;
886           case L4_ploadrht_abs:   return L2_ploadrht_io;
887           case L4_ploadrhf_abs:   return L2_ploadrhf_io;
888           case L4_ploadrit_abs:   return L2_ploadrit_io;
889           case L4_ploadrif_abs:   return L2_ploadrif_io;
890           case L4_ploadrdt_abs:   return L2_ploadrdt_io;
891           case L4_ploadrdf_abs:   return L2_ploadrdf_io;
892           case PS_storerbabs:
893           case S4_storerb_ap:
894           case S4_storerb_ur:     return S2_storerb_io;
895           case PS_storerhabs:
896           case S4_storerh_ap:
897           case S4_storerh_ur:     return S2_storerh_io;
898           case PS_storerfabs:
899           case S4_storerf_ap:
900           case S4_storerf_ur:     return S2_storerf_io;
901           case PS_storeriabs:
902           case S4_storeri_ap:
903           case S4_storeri_ur:     return S2_storeri_io;
904           case PS_storerdabs:
905           case S4_storerd_ap:
906           case S4_storerd_ur:     return S2_storerd_io;
907           case S4_pstorerbt_abs:  return S2_pstorerbt_io;
908           case S4_pstorerbf_abs:  return S2_pstorerbf_io;
909           case S4_pstorerht_abs:  return S2_pstorerht_io;
910           case S4_pstorerhf_abs:  return S2_pstorerhf_io;
911           case S4_pstorerft_abs:  return S2_pstorerft_io;
912           case S4_pstorerff_abs:  return S2_pstorerff_io;
913           case S4_pstorerit_abs:  return S2_pstorerit_io;
914           case S4_pstorerif_abs:  return S2_pstorerif_io;
915           case S4_pstorerdt_abs:  return S2_pstorerdt_io;
916           case S4_pstorerdf_abs:  return S2_pstorerdf_io;
917           default:
918             break;
919         }
920         break;
921       case HexagonII::BaseImmOffset:
922         if (!isStoreImmediate(ExtOpc))
923           return ExtOpc;
924         break;
925       default:
926         break;
927     }
928   }
929   return 0;
930 }
931 
932 unsigned HCE::getDirectRegReplacement(unsigned ExtOpc) const {
933   switch (ExtOpc) {
934     case Hexagon::A2_addi:          return Hexagon::A2_add;
935     case Hexagon::A2_andir:         return Hexagon::A2_and;
936     case Hexagon::A2_combineii:     return Hexagon::A4_combineri;
937     case Hexagon::A2_orir:          return Hexagon::A2_or;
938     case Hexagon::A2_paddif:        return Hexagon::A2_paddf;
939     case Hexagon::A2_paddit:        return Hexagon::A2_paddt;
940     case Hexagon::A2_subri:         return Hexagon::A2_sub;
941     case Hexagon::A2_tfrsi:         return TargetOpcode::COPY;
942     case Hexagon::A4_cmpbeqi:       return Hexagon::A4_cmpbeq;
943     case Hexagon::A4_cmpbgti:       return Hexagon::A4_cmpbgt;
944     case Hexagon::A4_cmpbgtui:      return Hexagon::A4_cmpbgtu;
945     case Hexagon::A4_cmpheqi:       return Hexagon::A4_cmpheq;
946     case Hexagon::A4_cmphgti:       return Hexagon::A4_cmphgt;
947     case Hexagon::A4_cmphgtui:      return Hexagon::A4_cmphgtu;
948     case Hexagon::A4_combineii:     return Hexagon::A4_combineir;
949     case Hexagon::A4_combineir:     return TargetOpcode::REG_SEQUENCE;
950     case Hexagon::A4_combineri:     return TargetOpcode::REG_SEQUENCE;
951     case Hexagon::A4_rcmpeqi:       return Hexagon::A4_rcmpeq;
952     case Hexagon::A4_rcmpneqi:      return Hexagon::A4_rcmpneq;
953     case Hexagon::C2_cmoveif:       return Hexagon::A2_tfrpf;
954     case Hexagon::C2_cmoveit:       return Hexagon::A2_tfrpt;
955     case Hexagon::C2_cmpeqi:        return Hexagon::C2_cmpeq;
956     case Hexagon::C2_cmpgti:        return Hexagon::C2_cmpgt;
957     case Hexagon::C2_cmpgtui:       return Hexagon::C2_cmpgtu;
958     case Hexagon::C2_muxii:         return Hexagon::C2_muxir;
959     case Hexagon::C2_muxir:         return Hexagon::C2_mux;
960     case Hexagon::C2_muxri:         return Hexagon::C2_mux;
961     case Hexagon::C4_cmpltei:       return Hexagon::C4_cmplte;
962     case Hexagon::C4_cmplteui:      return Hexagon::C4_cmplteu;
963     case Hexagon::C4_cmpneqi:       return Hexagon::C4_cmpneq;
964     case Hexagon::M2_accii:         return Hexagon::M2_acci;        // T -> T
965     /* No M2_macsin */
966     case Hexagon::M2_macsip:        return Hexagon::M2_maci;        // T -> T
967     case Hexagon::M2_mpysin:        return Hexagon::M2_mpyi;
968     case Hexagon::M2_mpysip:        return Hexagon::M2_mpyi;
969     case Hexagon::M2_mpysmi:        return Hexagon::M2_mpyi;
970     case Hexagon::M2_naccii:        return Hexagon::M2_nacci;       // T -> T
971     case Hexagon::M4_mpyri_addi:    return Hexagon::M4_mpyri_addr;
972     case Hexagon::M4_mpyri_addr:    return Hexagon::M4_mpyrr_addr;  // _ -> T
973     case Hexagon::M4_mpyrr_addi:    return Hexagon::M4_mpyrr_addr;  // _ -> T
974     case Hexagon::S4_addaddi:       return Hexagon::M2_acci;        // _ -> T
975     case Hexagon::S4_addi_asl_ri:   return Hexagon::S2_asl_i_r_acc; // T -> T
976     case Hexagon::S4_addi_lsr_ri:   return Hexagon::S2_lsr_i_r_acc; // T -> T
977     case Hexagon::S4_andi_asl_ri:   return Hexagon::S2_asl_i_r_and; // T -> T
978     case Hexagon::S4_andi_lsr_ri:   return Hexagon::S2_lsr_i_r_and; // T -> T
979     case Hexagon::S4_ori_asl_ri:    return Hexagon::S2_asl_i_r_or;  // T -> T
980     case Hexagon::S4_ori_lsr_ri:    return Hexagon::S2_lsr_i_r_or;  // T -> T
981     case Hexagon::S4_subaddi:       return Hexagon::M2_subacc;      // _ -> T
982     case Hexagon::S4_subi_asl_ri:   return Hexagon::S2_asl_i_r_nac; // T -> T
983     case Hexagon::S4_subi_lsr_ri:   return Hexagon::S2_lsr_i_r_nac; // T -> T
984 
985     // Store-immediates:
986     case Hexagon::S4_storeirbf_io:  return Hexagon::S2_pstorerbf_io;
987     case Hexagon::S4_storeirb_io:   return Hexagon::S2_storerb_io;
988     case Hexagon::S4_storeirbt_io:  return Hexagon::S2_pstorerbt_io;
989     case Hexagon::S4_storeirhf_io:  return Hexagon::S2_pstorerhf_io;
990     case Hexagon::S4_storeirh_io:   return Hexagon::S2_storerh_io;
991     case Hexagon::S4_storeirht_io:  return Hexagon::S2_pstorerht_io;
992     case Hexagon::S4_storeirif_io:  return Hexagon::S2_pstorerif_io;
993     case Hexagon::S4_storeiri_io:   return Hexagon::S2_storeri_io;
994     case Hexagon::S4_storeirit_io:  return Hexagon::S2_pstorerit_io;
995 
996     default:
997       break;
998   }
999   return 0;
1000 }
1001 
1002 // Return the allowable deviation from the current value of Rb which the
1003 // instruction MI can accommodate.
1004 // The instruction MI is a user of register Rb, which is defined via an
1005 // extender. It may be possible for MI to be tweaked to work for a register
1006 // defined with a slightly different value. For example
1007 //   ... = L2_loadrub_io Rb, 0
1008 // can be modifed to be
1009 //   ... = L2_loadrub_io Rb', 1
1010 // if Rb' = Rb-1.
1011 OffsetRange HCE::getOffsetRange(Register Rb, const MachineInstr &MI) const {
1012   unsigned Opc = MI.getOpcode();
1013   // Instructions that are constant-extended may be replaced with something
1014   // else that no longer offers the same range as the original.
1015   if (!isRegOffOpcode(Opc) || HII->isConstExtended(MI))
1016     return OffsetRange::zero();
1017 
1018   if (Opc == Hexagon::A2_addi) {
1019     const MachineOperand &Op1 = MI.getOperand(1), &Op2 = MI.getOperand(2);
1020     if (Rb != Register(Op1) || !Op2.isImm())
1021       return OffsetRange::zero();
1022     OffsetRange R = { -(1<<15)+1, (1<<15)-1, 1 };
1023     return R.shift(Op2.getImm());
1024   }
1025 
1026   // HII::getBaseAndOffsetPosition returns the increment position as "offset".
1027   if (HII->isPostIncrement(MI))
1028     return OffsetRange::zero();
1029 
1030   const MCInstrDesc &D = HII->get(Opc);
1031   assert(D.mayLoad() || D.mayStore());
1032 
1033   unsigned BaseP, OffP;
1034   if (!HII->getBaseAndOffsetPosition(MI, BaseP, OffP) ||
1035       Rb != Register(MI.getOperand(BaseP)) ||
1036       !MI.getOperand(OffP).isImm())
1037     return OffsetRange::zero();
1038 
1039   uint64_t F = (D.TSFlags >> HexagonII::MemAccessSizePos) &
1040                   HexagonII::MemAccesSizeMask;
1041   uint8_t A = HexagonII::getMemAccessSizeInBytes(HexagonII::MemAccessSize(F));
1042   unsigned L = Log2_32(A);
1043   unsigned S = 10+L;  // sint11_L
1044   int32_t Min = -alignDown((1<<S)-1, A);
1045 
1046   // The range will be shifted by Off. To prefer non-negative offsets,
1047   // adjust Max accordingly.
1048   int32_t Off = MI.getOperand(OffP).getImm();
1049   int32_t Max = Off >= 0 ? 0 : -Off;
1050 
1051   OffsetRange R = { Min, Max, A };
1052   return R.shift(Off);
1053 }
1054 
1055 // Return the allowable deviation from the current value of the extender ED,
1056 // for which the instruction corresponding to ED can be modified without
1057 // using an extender.
1058 // The instruction uses the extender directly. It will be replaced with
1059 // another instruction, say MJ, where the extender will be replaced with a
1060 // register. MJ can allow some variability with respect to the value of
1061 // that register, as is the case with indexed memory instructions.
1062 OffsetRange HCE::getOffsetRange(const ExtDesc &ED) const {
1063   // The only way that there can be a non-zero range available is if
1064   // the instruction using ED will be converted to an indexed memory
1065   // instruction.
1066   unsigned IdxOpc = getRegOffOpcode(ED.UseMI->getOpcode());
1067   switch (IdxOpc) {
1068     case 0:
1069       return OffsetRange::zero();
1070     case Hexagon::A2_addi:    // s16
1071       return { -32767, 32767, 1 };
1072     case Hexagon::A2_subri:   // s10
1073       return { -511, 511, 1 };
1074   }
1075 
1076   if (!ED.UseMI->mayLoad() && !ED.UseMI->mayStore())
1077     return OffsetRange::zero();
1078   const MCInstrDesc &D = HII->get(IdxOpc);
1079   uint64_t F = (D.TSFlags >> HexagonII::MemAccessSizePos) &
1080                   HexagonII::MemAccesSizeMask;
1081   uint8_t A = HexagonII::getMemAccessSizeInBytes(HexagonII::MemAccessSize(F));
1082   unsigned L = Log2_32(A);
1083   unsigned S = 10+L;  // sint11_L
1084   int32_t Min = -alignDown((1<<S)-1, A);
1085   int32_t Max = 0;  // Force non-negative offsets.
1086   return { Min, Max, A };
1087 }
1088 
1089 // Get the allowable deviation from the current value of Rd by checking
1090 // all uses of Rd.
1091 OffsetRange HCE::getOffsetRange(Register Rd) const {
1092   OffsetRange Range;
1093   for (const MachineOperand &Op : MRI->use_operands(Rd.Reg)) {
1094     // Make sure that the register being used by this operand is identical
1095     // to the register that was defined: using a different subregister
1096     // precludes any non-trivial range.
1097     if (Rd != Register(Op))
1098       return OffsetRange::zero();
1099     Range.intersect(getOffsetRange(Rd, *Op.getParent()));
1100   }
1101   return Range;
1102 }
1103 
1104 void HCE::recordExtender(MachineInstr &MI, unsigned OpNum) {
1105   unsigned Opc = MI.getOpcode();
1106   ExtDesc ED;
1107   ED.OpNum = OpNum;
1108 
1109   bool IsLoad = MI.mayLoad();
1110   bool IsStore = MI.mayStore();
1111 
1112   if (IsLoad || IsStore) {
1113     unsigned AM = HII->getAddrMode(MI);
1114     switch (AM) {
1115       // (Re: ##Off + Rb<<S) = Rd: ##Val
1116       case HexagonII::Absolute:       // (__: ## + __<<_)
1117         break;
1118       case HexagonII::AbsoluteSet:    // (Rd: ## + __<<_)
1119         ED.Rd = MI.getOperand(OpNum-1);
1120         ED.IsDef = true;
1121         break;
1122       case HexagonII::BaseImmOffset:  // (__: ## + Rs<<0)
1123         // Store-immediates are treated as non-memory operations, since
1124         // it's the value being stored that is extended (as opposed to
1125         // a part of the address).
1126         if (!isStoreImmediate(Opc))
1127           ED.Expr.Rs = MI.getOperand(OpNum-1);
1128         break;
1129       case HexagonII::BaseLongOffset: // (__: ## + Rs<<S)
1130         ED.Expr.Rs = MI.getOperand(OpNum-2);
1131         ED.Expr.S = MI.getOperand(OpNum-1).getImm();
1132         break;
1133       default:
1134         llvm_unreachable("Unhandled memory instruction");
1135     }
1136   } else {
1137     switch (Opc) {
1138       case Hexagon::A2_tfrsi:         // (Rd: ## + __<<_)
1139         ED.Rd = MI.getOperand(0);
1140         ED.IsDef = true;
1141         break;
1142       case Hexagon::A2_combineii:     // (Rd: ## + __<<_)
1143       case Hexagon::A4_combineir:
1144         ED.Rd = { MI.getOperand(0).getReg(), Hexagon::isub_hi };
1145         ED.IsDef = true;
1146         break;
1147       case Hexagon::A4_combineri:     // (Rd: ## + __<<_)
1148         ED.Rd = { MI.getOperand(0).getReg(), Hexagon::isub_lo };
1149         ED.IsDef = true;
1150         break;
1151       case Hexagon::A2_addi:          // (Rd: ## + Rs<<0)
1152         ED.Rd = MI.getOperand(0);
1153         ED.Expr.Rs = MI.getOperand(OpNum-1);
1154         break;
1155       case Hexagon::M2_accii:         // (__: ## + Rs<<0)
1156       case Hexagon::M2_naccii:
1157       case Hexagon::S4_addaddi:
1158         ED.Expr.Rs = MI.getOperand(OpNum-1);
1159         break;
1160       case Hexagon::A2_subri:         // (Rd: ## - Rs<<0)
1161         ED.Rd = MI.getOperand(0);
1162         ED.Expr.Rs = MI.getOperand(OpNum+1);
1163         ED.Expr.Neg = true;
1164         break;
1165       case Hexagon::S4_subaddi:       // (__: ## - Rs<<0)
1166         ED.Expr.Rs = MI.getOperand(OpNum+1);
1167         ED.Expr.Neg = true;
1168       default:                        // (__: ## + __<<_)
1169         break;
1170     }
1171   }
1172 
1173   ED.UseMI = &MI;
1174   Extenders.push_back(ED);
1175 }
1176 
1177 void HCE::collectInstr(MachineInstr &MI) {
1178   if (!HII->isConstExtended(MI))
1179     return;
1180 
1181   // Skip some non-convertible instructions.
1182   unsigned Opc = MI.getOpcode();
1183   switch (Opc) {
1184     case Hexagon::M2_macsin:  // There is no Rx -= mpyi(Rs,Rt).
1185     case Hexagon::C4_addipc:
1186     case Hexagon::S4_or_andi:
1187     case Hexagon::S4_or_andix:
1188     case Hexagon::S4_or_ori:
1189       return;
1190   }
1191   recordExtender(MI, HII->getCExtOpNum(MI));
1192 }
1193 
1194 void HCE::collect(MachineFunction &MF) {
1195   Extenders.clear();
1196   for (MachineBasicBlock &MBB : MF)
1197     for (MachineInstr &MI : MBB)
1198       collectInstr(MI);
1199 }
1200 
1201 void HCE::assignInits(const ExtRoot &ER, unsigned Begin, unsigned End,
1202       AssignmentMap &IMap) {
1203   // Sanity check: make sure that all extenders in the range [Begin..End)
1204   // share the same root ER.
1205   for (unsigned I = Begin; I != End; ++I)
1206     assert(ER == ExtRoot(Extenders[I].getOp()));
1207 
1208   // Construct the list of ranges, such that for each P in Ranges[I],
1209   // a register Reg = ER+P can be used in place of Extender[I]. If the
1210   // instruction allows, uses in the form of Reg+Off are considered
1211   // (here, Off = required_value - P).
1212   std::vector<OffsetRange> Ranges(End-Begin);
1213 
1214   // For each extender that is a def, visit all uses of the defined register,
1215   // and produce an offset range that works for all uses. The def doesn't
1216   // have to be checked, because it can become dead if all uses can be updated
1217   // to use a different reg/offset.
1218   for (unsigned I = Begin; I != End; ++I) {
1219     const ExtDesc &ED = Extenders[I];
1220     if (!ED.IsDef)
1221       continue;
1222     ExtValue EV(ED);
1223     DEBUG(dbgs() << " =" << I << ". " << EV << "  " << ED << '\n');
1224     assert(ED.Rd.Reg != 0);
1225     Ranges[I-Begin] = getOffsetRange(ED.Rd).shift(EV.Offset);
1226     // A2_tfrsi is a special case: it will be replaced with A2_addi, which
1227     // has a 16-bit signed offset. This means that A2_tfrsi not only has a
1228     // range coming from its uses, but also from the fact that its replacement
1229     // has a range as well.
1230     if (ED.UseMI->getOpcode() == Hexagon::A2_tfrsi) {
1231       int32_t D = alignDown(32767, Ranges[I-Begin].Align); // XXX hardcoded
1232       Ranges[I-Begin].extendBy(-D).extendBy(D);
1233     }
1234   }
1235 
1236   // Visit all non-def extenders. For each one, determine the offset range
1237   // available for it.
1238   for (unsigned I = Begin; I != End; ++I) {
1239     const ExtDesc &ED = Extenders[I];
1240     if (ED.IsDef)
1241       continue;
1242     ExtValue EV(ED);
1243     DEBUG(dbgs() << "  " << I << ". " << EV << "  " << ED << '\n');
1244     OffsetRange Dev = getOffsetRange(ED);
1245     Ranges[I-Begin].intersect(Dev.shift(EV.Offset));
1246   }
1247 
1248   // Here for each I there is a corresponding Range[I]. Construct the
1249   // inverse map, that to each range will assign the set of indexes in
1250   // [Begin..End) that this range corresponds to.
1251   std::map<OffsetRange, IndexList> RangeMap;
1252   for (unsigned I = Begin; I != End; ++I)
1253     RangeMap[Ranges[I-Begin]].insert(I);
1254 
1255   DEBUG({
1256     dbgs() << "Ranges\n";
1257     for (unsigned I = Begin; I != End; ++I)
1258       dbgs() << "  " << I << ". " << Ranges[I-Begin] << '\n';
1259     dbgs() << "RangeMap\n";
1260     for (auto &P : RangeMap) {
1261       dbgs() << "  " << P.first << " ->";
1262       for (unsigned I : P.second)
1263         dbgs() << ' ' << I;
1264       dbgs() << '\n';
1265     }
1266   });
1267 
1268   // Select the definition points, and generate the assignment between
1269   // these points and the uses.
1270 
1271   // For each candidate offset, keep a pair CandData consisting of
1272   // the total number of ranges containing that candidate, and the
1273   // vector of corresponding RangeTree nodes.
1274   using CandData = std::pair<unsigned, SmallVector<RangeTree::Node*,8>>;
1275   std::map<int32_t, CandData> CandMap;
1276 
1277   RangeTree Tree;
1278   for (const OffsetRange &R : Ranges)
1279     Tree.add(R);
1280   SmallVector<RangeTree::Node*,8> Nodes;
1281   Tree.order(Nodes);
1282 
1283   auto MaxAlign = [](const SmallVectorImpl<RangeTree::Node*> &Nodes) {
1284     uint8_t Align = 1;
1285     for (RangeTree::Node *N : Nodes)
1286       Align = std::max(Align, N->Range.Align);
1287     return Align;
1288   };
1289 
1290   // Construct the set of all potential definition points from the endpoints
1291   // of the ranges. If a given endpoint also belongs to a different range,
1292   // but with a higher alignment, also consider the more-highly-aligned
1293   // value of this endpoint.
1294   std::set<int32_t> CandSet;
1295   for (RangeTree::Node *N : Nodes) {
1296     const OffsetRange &R = N->Range;
1297     uint8_t A0 = MaxAlign(Tree.nodesWith(R.Min, false));
1298     CandSet.insert(R.Min);
1299     if (R.Align < A0)
1300       CandSet.insert(R.Min < 0 ? -alignDown(-R.Min, A0) : alignTo(R.Min, A0));
1301     uint8_t A1 = MaxAlign(Tree.nodesWith(R.Max, false));
1302     CandSet.insert(R.Max);
1303     if (R.Align < A1)
1304       CandSet.insert(R.Max < 0 ? -alignTo(-R.Max, A1) : alignDown(R.Max, A1));
1305   }
1306 
1307   // Build the assignment map: candidate C -> { list of extender indexes }.
1308   // This has to be done iteratively:
1309   // - pick the candidate that covers the maximum number of extenders,
1310   // - add the candidate to the map,
1311   // - remove the extenders from the pool.
1312   while (true) {
1313     using CMap = std::map<int32_t,unsigned>;
1314     CMap Counts;
1315     for (auto It = CandSet.begin(), Et = CandSet.end(); It != Et; ) {
1316       auto &&V = Tree.nodesWith(*It);
1317       unsigned N = std::accumulate(V.begin(), V.end(), 0u,
1318                     [](unsigned Acc, const RangeTree::Node *N) {
1319                       return Acc + N->Count;
1320                     });
1321       if (N != 0)
1322         Counts.insert({*It, N});
1323       It = (N != 0) ? std::next(It) : CandSet.erase(It);
1324     }
1325     if (Counts.empty())
1326       break;
1327 
1328     // Find the best candidate with respect to the number of extenders covered.
1329     auto BestIt = std::max_element(Counts.begin(), Counts.end(),
1330                     [](const CMap::value_type &A, const CMap::value_type &B) {
1331                       return A.second < B.second ||
1332                              (A.second == B.second && A < B);
1333                     });
1334     int32_t Best = BestIt->first;
1335     ExtValue BestV(ER, Best);
1336     for (RangeTree::Node *N : Tree.nodesWith(Best)) {
1337       for (unsigned I : RangeMap[N->Range])
1338         IMap[{BestV,Extenders[I].Expr}].insert(I);
1339       Tree.erase(N);
1340     }
1341   }
1342 
1343   DEBUG(dbgs() << "IMap (before fixup) = " << PrintIMap(IMap, *HRI));
1344 
1345   // There is some ambiguity in what initializer should be used, if the
1346   // descriptor's subexpression is non-trivial: it can be the entire
1347   // subexpression (which is what has been done so far), or it can be
1348   // the extender's value itself, if all corresponding extenders have the
1349   // exact value of the initializer (i.e. require offset of 0).
1350 
1351   // To reduce the number of initializers, merge such special cases.
1352   for (std::pair<const ExtenderInit,IndexList> &P : IMap) {
1353     // Skip trivial initializers.
1354     if (P.first.second.trivial())
1355       continue;
1356     // If the corresponding trivial initializer does not exist, skip this
1357     // entry.
1358     const ExtValue &EV = P.first.first;
1359     AssignmentMap::iterator F = IMap.find({EV, ExtExpr()});
1360     if (F == IMap.end())
1361       continue;
1362     // Finally, check if all extenders have the same value as the initializer.
1363     auto SameValue = [&EV,this](unsigned I) {
1364       const ExtDesc &ED = Extenders[I];
1365       return ExtValue(ED).Offset == EV.Offset;
1366     };
1367     if (all_of(P.second, SameValue)) {
1368       F->second.insert(P.second.begin(), P.second.end());
1369       P.second.clear();
1370     }
1371   }
1372 
1373   DEBUG(dbgs() << "IMap (after fixup) = " << PrintIMap(IMap, *HRI));
1374 }
1375 
1376 void HCE::calculatePlacement(const ExtenderInit &ExtI, const IndexList &Refs,
1377       LocDefMap &Defs) {
1378   if (Refs.empty())
1379     return;
1380 
1381   // The placement calculation is somewhat simple right now: it finds a
1382   // single location for the def that dominates all refs. Since this may
1383   // place the def far from the uses, producing several locations for
1384   // defs that collectively dominate all refs could be better.
1385   // For now only do the single one.
1386   DenseSet<MachineBasicBlock*> Blocks;
1387   DenseSet<MachineInstr*> RefMIs;
1388   const ExtDesc &ED0 = Extenders[Refs[0]];
1389   MachineBasicBlock *DomB = ED0.UseMI->getParent();
1390   RefMIs.insert(ED0.UseMI);
1391   Blocks.insert(DomB);
1392   for (unsigned i = 1, e = Refs.size(); i != e; ++i) {
1393     const ExtDesc &ED = Extenders[Refs[i]];
1394     MachineBasicBlock *MBB = ED.UseMI->getParent();
1395     RefMIs.insert(ED.UseMI);
1396     DomB = MDT->findNearestCommonDominator(DomB, MBB);
1397     Blocks.insert(MBB);
1398   }
1399 
1400 #ifndef NDEBUG
1401   // The block DomB should be dominated by the def of each register used
1402   // in the initializer.
1403   Register Rs = ExtI.second.Rs;  // Only one reg allowed now.
1404   const MachineInstr *DefI = Rs.isVReg() ? MRI->getVRegDef(Rs.Reg) : nullptr;
1405 
1406   // This should be guaranteed given that the entire expression is used
1407   // at each instruction in Refs. Add an assertion just in case.
1408   assert(!DefI || MDT->dominates(DefI->getParent(), DomB));
1409 #endif
1410 
1411   MachineBasicBlock::iterator It;
1412   if (Blocks.count(DomB)) {
1413     // Try to find the latest possible location for the def.
1414     MachineBasicBlock::iterator End = DomB->end();
1415     for (It = DomB->begin(); It != End; ++It)
1416       if (RefMIs.count(&*It))
1417         break;
1418     assert(It != End && "Should have found a ref in DomB");
1419   } else {
1420     // DomB does not contain any refs.
1421     It = DomB->getFirstTerminator();
1422   }
1423   Loc DefLoc(DomB, It);
1424   Defs.emplace(DefLoc, Refs);
1425 }
1426 
1427 HCE::Register HCE::insertInitializer(Loc DefL, const ExtenderInit &ExtI) {
1428   unsigned DefR = MRI->createVirtualRegister(&Hexagon::IntRegsRegClass);
1429   MachineBasicBlock &MBB = *DefL.Block;
1430   MachineBasicBlock::iterator At = DefL.At;
1431   DebugLoc dl = DefL.Block->findDebugLoc(DefL.At);
1432   const ExtValue &EV = ExtI.first;
1433   MachineOperand ExtOp(EV);
1434 
1435   const ExtExpr &Ex = ExtI.second;
1436   const MachineInstr *InitI = nullptr;
1437 
1438   if (Ex.Rs.isSlot()) {
1439     assert(Ex.S == 0 && "Cannot have a shift of a stack slot");
1440     assert(!Ex.Neg && "Cannot subtract a stack slot");
1441     // DefR = PS_fi Rb,##EV
1442     InitI = BuildMI(MBB, At, dl, HII->get(Hexagon::PS_fi), DefR)
1443               .add(MachineOperand(Ex.Rs))
1444               .add(ExtOp);
1445   } else {
1446     assert((Ex.Rs.Reg == 0 || Ex.Rs.isVReg()) && "Expecting virtual register");
1447     if (Ex.trivial()) {
1448       // DefR = ##EV
1449       InitI = BuildMI(MBB, At, dl, HII->get(Hexagon::A2_tfrsi), DefR)
1450                 .add(ExtOp);
1451     } else if (Ex.S == 0) {
1452       if (Ex.Neg) {
1453         // DefR = sub(##EV,Rb)
1454         InitI = BuildMI(MBB, At, dl, HII->get(Hexagon::A2_subri), DefR)
1455                   .add(ExtOp)
1456                   .add(MachineOperand(Ex.Rs));
1457       } else {
1458         // DefR = add(Rb,##EV)
1459         InitI = BuildMI(MBB, At, dl, HII->get(Hexagon::A2_addi), DefR)
1460                   .add(MachineOperand(Ex.Rs))
1461                   .add(ExtOp);
1462       }
1463     } else {
1464       unsigned NewOpc = Ex.Neg ? Hexagon::S4_subi_asl_ri
1465                                : Hexagon::S4_addi_asl_ri;
1466       // DefR = add(##EV,asl(Rb,S))
1467       InitI = BuildMI(MBB, At, dl, HII->get(NewOpc), DefR)
1468                 .add(ExtOp)
1469                 .add(MachineOperand(Ex.Rs))
1470                 .addImm(Ex.S);
1471     }
1472   }
1473 
1474   assert(InitI);
1475   (void)InitI;
1476   DEBUG(dbgs() << "Inserted def in bb#" << MBB.getNumber()
1477                << " for initializer: " << PrintInit(ExtI, *HRI)
1478                << "\n  " << *InitI);
1479   return { DefR, 0 };
1480 }
1481 
1482 // Replace the extender at index Idx with the register ExtR.
1483 bool HCE::replaceInstrExact(const ExtDesc &ED, Register ExtR) {
1484   MachineInstr &MI = *ED.UseMI;
1485   MachineBasicBlock &MBB = *MI.getParent();
1486   MachineBasicBlock::iterator At = MI.getIterator();
1487   DebugLoc dl = MI.getDebugLoc();
1488   unsigned ExtOpc = MI.getOpcode();
1489 
1490   // With a few exceptions, direct replacement amounts to creating an
1491   // instruction with a corresponding register opcode, with all operands
1492   // the same, except for the register used in place of the extender.
1493   unsigned RegOpc = getDirectRegReplacement(ExtOpc);
1494 
1495   if (RegOpc == TargetOpcode::REG_SEQUENCE) {
1496     if (ExtOpc == Hexagon::A4_combineri)
1497       BuildMI(MBB, At, dl, HII->get(RegOpc))
1498         .add(MI.getOperand(0))
1499         .add(MI.getOperand(1))
1500         .addImm(Hexagon::isub_hi)
1501         .add(MachineOperand(ExtR))
1502         .addImm(Hexagon::isub_lo);
1503     else if (ExtOpc == Hexagon::A4_combineir)
1504       BuildMI(MBB, At, dl, HII->get(RegOpc))
1505         .add(MI.getOperand(0))
1506         .add(MachineOperand(ExtR))
1507         .addImm(Hexagon::isub_hi)
1508         .add(MI.getOperand(2))
1509         .addImm(Hexagon::isub_lo);
1510     else
1511       llvm_unreachable("Unexpected opcode became REG_SEQUENCE");
1512     MBB.erase(MI);
1513     return true;
1514   }
1515   if (ExtOpc == Hexagon::C2_cmpgei || ExtOpc == Hexagon::C2_cmpgeui) {
1516     unsigned NewOpc = ExtOpc == Hexagon::C2_cmpgei ? Hexagon::C2_cmplt
1517                                                    : Hexagon::C2_cmpltu;
1518     BuildMI(MBB, At, dl, HII->get(NewOpc))
1519       .add(MI.getOperand(0))
1520       .add(MachineOperand(ExtR))
1521       .add(MI.getOperand(1));
1522     MBB.erase(MI);
1523     return true;
1524   }
1525 
1526   if (RegOpc != 0) {
1527     MachineInstrBuilder MIB = BuildMI(MBB, At, dl, HII->get(RegOpc));
1528     unsigned RegN = ED.OpNum;
1529     // Copy all operands except the one that has the extender.
1530     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1531       if (i != RegN)
1532         MIB.add(MI.getOperand(i));
1533       else
1534         MIB.add(MachineOperand(ExtR));
1535     }
1536     MIB.setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
1537     MBB.erase(MI);
1538     return true;
1539   }
1540 
1541   if ((MI.mayLoad() || MI.mayStore()) && !isStoreImmediate(ExtOpc)) {
1542     // For memory instructions, there is an asymmetry in the addressing
1543     // modes. Addressing modes allowing extenders can be replaced with
1544     // addressing modes that use registers, but the order of operands
1545     // (or even their number) may be different.
1546     // Replacements:
1547     //   BaseImmOffset (io)  -> BaseRegOffset (rr)
1548     //   BaseLongOffset (ur) -> BaseRegOffset (rr)
1549     unsigned RegOpc, Shift;
1550     unsigned AM = HII->getAddrMode(MI);
1551     if (AM == HexagonII::BaseImmOffset) {
1552       RegOpc = HII->changeAddrMode_io_rr(ExtOpc);
1553       Shift = 0;
1554     } else if (AM == HexagonII::BaseLongOffset) {
1555       // Loads:  Rd = L4_loadri_ur Rs, S, ##
1556       // Stores: S4_storeri_ur Rs, S, ##, Rt
1557       RegOpc = HII->changeAddrMode_ur_rr(ExtOpc);
1558       Shift = MI.getOperand(MI.mayLoad() ? 2 : 1).getImm();
1559     } else {
1560       llvm_unreachable("Unexpected addressing mode");
1561     }
1562 #ifndef NDEBUG
1563     if (RegOpc == -1u) {
1564       dbgs() << "\nExtOpc: " << HII->getName(ExtOpc) << " has no rr version\n";
1565       llvm_unreachable("No corresponding rr instruction");
1566     }
1567 #endif
1568 
1569     unsigned BaseP, OffP;
1570     HII->getBaseAndOffsetPosition(MI, BaseP, OffP);
1571 
1572     // Build an rr instruction: (RegOff + RegBase<<0)
1573     MachineInstrBuilder MIB = BuildMI(MBB, At, dl, HII->get(RegOpc));
1574     // First, add the def for loads.
1575     if (MI.mayLoad())
1576       MIB.add(getLoadResultOp(MI));
1577     // Handle possible predication.
1578     if (HII->isPredicated(MI))
1579       MIB.add(getPredicateOp(MI));
1580     // Build the address.
1581     MIB.add(MachineOperand(ExtR));      // RegOff
1582     MIB.add(MI.getOperand(BaseP));      // RegBase
1583     MIB.addImm(Shift);                  // << Shift
1584     // Add the stored value for stores.
1585     if (MI.mayStore())
1586       MIB.add(getStoredValueOp(MI));
1587     MIB.setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
1588     MBB.erase(MI);
1589     return true;
1590   }
1591 
1592 #ifndef NDEBUG
1593   dbgs() << '\n' << MI;
1594 #endif
1595   llvm_unreachable("Unhandled exact replacement");
1596   return false;
1597 }
1598 
1599 // Replace the extender ED with a form corresponding to the initializer ExtI.
1600 bool HCE::replaceInstrExpr(const ExtDesc &ED, const ExtenderInit &ExtI,
1601       Register ExtR, int32_t &Diff) {
1602   MachineInstr &MI = *ED.UseMI;
1603   MachineBasicBlock &MBB = *MI.getParent();
1604   MachineBasicBlock::iterator At = MI.getIterator();
1605   DebugLoc dl = MI.getDebugLoc();
1606   unsigned ExtOpc = MI.getOpcode();
1607 
1608   if (ExtOpc == Hexagon::A2_tfrsi) {
1609     // A2_tfrsi is a special case: it's replaced with A2_addi, which introduces
1610     // another range. One range is the one that's common to all tfrsi's uses,
1611     // this one is the range of immediates in A2_addi. When calculating ranges,
1612     // the addi's 16-bit argument was included, so now we need to make it such
1613     // that the produced value is in the range for the uses alone.
1614     // Most of the time, simply adding Diff will make the addi produce exact
1615     // result, but if Diff is outside of the 16-bit range, some adjustment
1616     // will be needed.
1617     unsigned IdxOpc = getRegOffOpcode(ExtOpc);
1618     assert(IdxOpc == Hexagon::A2_addi);
1619 
1620     // Clamp Diff to the 16 bit range.
1621     int32_t D = isInt<16>(Diff) ? Diff : (Diff > 32767 ? 32767 : -32767);
1622     BuildMI(MBB, At, dl, HII->get(IdxOpc))
1623       .add(MI.getOperand(0))
1624       .add(MachineOperand(ExtR))
1625       .addImm(D);
1626     Diff -= D;
1627 #ifndef NDEBUG
1628     // Make sure the output is within allowable range for uses.
1629     OffsetRange Uses = getOffsetRange(MI.getOperand(0));
1630     if (!Uses.contains(Diff))
1631       dbgs() << "Diff: " << Diff << " out of range " << Uses
1632              << " for " << MI;
1633     assert(Uses.contains(Diff));
1634 #endif
1635     MBB.erase(MI);
1636     return true;
1637   }
1638 
1639   const ExtValue &EV = ExtI.first; (void)EV;
1640   const ExtExpr &Ex = ExtI.second; (void)Ex;
1641 
1642   if (ExtOpc == Hexagon::A2_addi || ExtOpc == Hexagon::A2_subri) {
1643     // If addi/subri are replaced with the exactly matching initializer,
1644     // they amount to COPY.
1645     // Check that the initializer is an exact match (for simplicity).
1646 #ifndef NDEBUG
1647     bool IsAddi = ExtOpc == Hexagon::A2_addi;
1648     const MachineOperand &RegOp = MI.getOperand(IsAddi ? 1 : 2);
1649     const MachineOperand &ImmOp = MI.getOperand(IsAddi ? 2 : 1);
1650     assert(Ex.Rs == RegOp && EV == ImmOp && Ex.Neg != IsAddi &&
1651            "Initializer mismatch");
1652 #endif
1653     BuildMI(MBB, At, dl, HII->get(TargetOpcode::COPY))
1654       .add(MI.getOperand(0))
1655       .add(MachineOperand(ExtR));
1656     Diff = 0;
1657     MBB.erase(MI);
1658     return true;
1659   }
1660   if (ExtOpc == Hexagon::M2_accii || ExtOpc == Hexagon::M2_naccii ||
1661       ExtOpc == Hexagon::S4_addaddi || ExtOpc == Hexagon::S4_subaddi) {
1662     // M2_accii:    add(Rt,add(Rs,V)) (tied)
1663     // M2_naccii:   sub(Rt,add(Rs,V))
1664     // S4_addaddi:  add(Rt,add(Rs,V))
1665     // S4_subaddi:  add(Rt,sub(V,Rs))
1666     // Check that Rs and V match the initializer expression. The Rs+V is the
1667     // combination that is considered "subexpression" for V, although Rx+V
1668     // would also be valid.
1669 #ifndef NDEBUG
1670     bool IsSub = ExtOpc == Hexagon::S4_subaddi;
1671     Register Rs = MI.getOperand(IsSub ? 3 : 2);
1672     ExtValue V = MI.getOperand(IsSub ? 2 : 3);
1673     assert(EV == V && Rs == Ex.Rs && IsSub == Ex.Neg && "Initializer mismatch");
1674 #endif
1675     unsigned NewOpc = ExtOpc == Hexagon::M2_naccii ? Hexagon::A2_sub
1676                                                    : Hexagon::A2_add;
1677     BuildMI(MBB, At, dl, HII->get(NewOpc))
1678       .add(MI.getOperand(0))
1679       .add(MI.getOperand(1))
1680       .add(MachineOperand(ExtR));
1681     MBB.erase(MI);
1682     return true;
1683   }
1684 
1685   if (MI.mayLoad() || MI.mayStore()) {
1686     unsigned IdxOpc = getRegOffOpcode(ExtOpc);
1687     assert(IdxOpc && "Expecting indexed opcode");
1688     MachineInstrBuilder MIB = BuildMI(MBB, At, dl, HII->get(IdxOpc));
1689     // Construct the new indexed instruction.
1690     // First, add the def for loads.
1691     if (MI.mayLoad())
1692       MIB.add(getLoadResultOp(MI));
1693     // Handle possible predication.
1694     if (HII->isPredicated(MI))
1695       MIB.add(getPredicateOp(MI));
1696     // Build the address.
1697     MIB.add(MachineOperand(ExtR));
1698     MIB.addImm(Diff);
1699     // Add the stored value for stores.
1700     if (MI.mayStore())
1701       MIB.add(getStoredValueOp(MI));
1702     MIB.setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
1703     MBB.erase(MI);
1704     return true;
1705   }
1706 
1707 #ifndef NDEBUG
1708   dbgs() << '\n' << PrintInit(ExtI, *HRI) << "  " << MI;
1709 #endif
1710   llvm_unreachable("Unhandled expr replacement");
1711   return false;
1712 }
1713 
1714 bool HCE::replaceInstr(unsigned Idx, Register ExtR, const ExtenderInit &ExtI) {
1715   if (ReplaceLimit.getNumOccurrences()) {
1716     if (ReplaceLimit <= ReplaceCounter)
1717       return false;
1718     ++ReplaceCounter;
1719   }
1720   const ExtDesc &ED = Extenders[Idx];
1721   assert((!ED.IsDef || ED.Rd.Reg != 0) && "Missing Rd for def");
1722   const ExtValue &DefV = ExtI.first;
1723   assert(ExtRoot(ExtValue(ED)) == ExtRoot(DefV) && "Extender root mismatch");
1724   const ExtExpr &DefEx = ExtI.second;
1725 
1726   ExtValue EV(ED);
1727   int32_t Diff = EV.Offset - DefV.Offset;
1728   const MachineInstr &MI = *ED.UseMI;
1729   DEBUG(dbgs() << __func__ << " Idx:" << Idx << " ExtR:"
1730                << PrintRegister(ExtR, *HRI) << " Diff:" << Diff << '\n');
1731 
1732   // These two addressing modes must be converted into indexed forms
1733   // regardless of what the initializer looks like.
1734   bool IsAbs = false, IsAbsSet = false;
1735   if (MI.mayLoad() || MI.mayStore()) {
1736     unsigned AM = HII->getAddrMode(MI);
1737     IsAbs = AM == HexagonII::Absolute;
1738     IsAbsSet = AM == HexagonII::AbsoluteSet;
1739   }
1740 
1741   // If it's a def, remember all operands that need to be updated.
1742   // If ED is a def, and Diff is not 0, then all uses of the register Rd
1743   // defined by ED must be in the form (Rd, imm), i.e. the immediate offset
1744   // must follow the Rd in the operand list.
1745   std::vector<std::pair<MachineInstr*,unsigned>> RegOps;
1746   if (ED.IsDef && Diff != 0) {
1747     for (MachineOperand &Op : MRI->use_operands(ED.Rd.Reg)) {
1748       MachineInstr &UI = *Op.getParent();
1749       RegOps.push_back({&UI, getOperandIndex(UI, Op)});
1750     }
1751   }
1752 
1753   // Replace the instruction.
1754   bool Replaced = false;
1755   if (Diff == 0 && DefEx.trivial() && !IsAbs && !IsAbsSet)
1756     Replaced = replaceInstrExact(ED, ExtR);
1757   else
1758     Replaced = replaceInstrExpr(ED, ExtI, ExtR, Diff);
1759 
1760   if (Diff != 0 && Replaced && ED.IsDef) {
1761     // Update offsets of the def's uses.
1762     for (std::pair<MachineInstr*,unsigned> P : RegOps) {
1763       unsigned J = P.second;
1764       assert(P.first->getNumOperands() > J+1 &&
1765              P.first->getOperand(J+1).isImm());
1766       MachineOperand &ImmOp = P.first->getOperand(J+1);
1767       ImmOp.setImm(ImmOp.getImm() + Diff);
1768     }
1769     // If it was an absolute-set instruction, the "set" part has been removed.
1770     // ExtR will now be the register with the extended value, and since all
1771     // users of Rd have been updated, all that needs to be done is to replace
1772     // Rd with ExtR.
1773     if (IsAbsSet) {
1774       assert(ED.Rd.Sub == 0 && ExtR.Sub == 0);
1775       MRI->replaceRegWith(ED.Rd.Reg, ExtR.Reg);
1776     }
1777   }
1778 
1779   return Replaced;
1780 }
1781 
1782 bool HCE::replaceExtenders(const AssignmentMap &IMap) {
1783   LocDefMap Defs;
1784   bool Changed = false;
1785 
1786   for (const std::pair<ExtenderInit,IndexList> &P : IMap) {
1787     const IndexList &Idxs = P.second;
1788     if (Idxs.size() < CountThreshold)
1789       continue;
1790 
1791     Defs.clear();
1792     calculatePlacement(P.first, Idxs, Defs);
1793     for (const std::pair<Loc,IndexList> &Q : Defs) {
1794       Register DefR = insertInitializer(Q.first, P.first);
1795       NewRegs.push_back(DefR.Reg);
1796       for (unsigned I : Q.second)
1797         Changed |= replaceInstr(I, DefR, P.first);
1798     }
1799   }
1800   return Changed;
1801 }
1802 
1803 unsigned HCE::getOperandIndex(const MachineInstr &MI,
1804       const MachineOperand &Op) const {
1805   for (unsigned i = 0, n = MI.getNumOperands(); i != n; ++i)
1806     if (&MI.getOperand(i) == &Op)
1807       return i;
1808   llvm_unreachable("Not an operand of MI");
1809 }
1810 
1811 const MachineOperand &HCE::getPredicateOp(const MachineInstr &MI) const {
1812   assert(HII->isPredicated(MI));
1813   for (const MachineOperand &Op : MI.operands()) {
1814     if (!Op.isReg() || !Op.isUse() ||
1815         MRI->getRegClass(Op.getReg()) != &Hexagon::PredRegsRegClass)
1816       continue;
1817     assert(Op.getSubReg() == 0 && "Predicate register with a subregister");
1818     return Op;
1819   }
1820   llvm_unreachable("Predicate operand not found");
1821 }
1822 
1823 const MachineOperand &HCE::getLoadResultOp(const MachineInstr &MI) const {
1824   assert(MI.mayLoad());
1825   return MI.getOperand(0);
1826 }
1827 
1828 const MachineOperand &HCE::getStoredValueOp(const MachineInstr &MI) const {
1829   assert(MI.mayStore());
1830   return MI.getOperand(MI.getNumExplicitOperands()-1);
1831 }
1832 
1833 bool HCE::runOnMachineFunction(MachineFunction &MF) {
1834   if (skipFunction(MF.getFunction()))
1835     return false;
1836   DEBUG(MF.print(dbgs() << "Before " << getPassName() << '\n', nullptr));
1837 
1838   HII = MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
1839   HRI = MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1840   MDT = &getAnalysis<MachineDominatorTree>();
1841   MRI = &MF.getRegInfo();
1842   AssignmentMap IMap;
1843 
1844   collect(MF);
1845   std::sort(Extenders.begin(), Extenders.end(),
1846     [](const ExtDesc &A, const ExtDesc &B) {
1847       return ExtValue(A) < ExtValue(B);
1848     });
1849 
1850   bool Changed = false;
1851   DEBUG(dbgs() << "Collected " << Extenders.size() << " extenders\n");
1852   for (unsigned I = 0, E = Extenders.size(); I != E; ) {
1853     unsigned B = I;
1854     const ExtRoot &T = Extenders[B].getOp();
1855     while (I != E && ExtRoot(Extenders[I].getOp()) == T)
1856       ++I;
1857 
1858     IMap.clear();
1859     assignInits(T, B, I, IMap);
1860     Changed |= replaceExtenders(IMap);
1861   }
1862 
1863   DEBUG({
1864     if (Changed)
1865       MF.print(dbgs() << "After " << getPassName() << '\n', nullptr);
1866     else
1867       dbgs() << "No changes\n";
1868   });
1869   return Changed;
1870 }
1871 
1872 FunctionPass *llvm::createHexagonConstExtenders() {
1873   return new HexagonConstExtenders();
1874 }
1875