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