blob: cb23f9b481540c58b3a2a286e70f32b8121e3398 [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
Krzysztof Parzyszek74671192017-10-16 00:29:47 +0000407 LLVM_ATTRIBUTE_UNUSED
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +0000408 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
Krzysztof Parzyszek74671192017-10-16 00:29:47 +0000422 LLVM_ATTRIBUTE_UNUSED
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +0000423 raw_ostream &operator<< (raw_ostream &OS, const PrintRegister &P) {
424 if (P.Rs.Reg != 0)
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +0000425 OS << printReg(P.Rs.Reg, &P.HRI, P.Rs.Sub);
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +0000426 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
Krzysztof Parzyszek74671192017-10-16 00:29:47 +0000438 LLVM_ATTRIBUTE_UNUSED
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +0000439 raw_ostream &operator<< (raw_ostream &OS, const PrintExpr &P) {
440 OS << "## " << (P.Ex.Neg ? "- " : "+ ");
441 if (P.Ex.Rs.Reg != 0)
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +0000442 OS << printReg(P.Ex.Rs.Reg, &P.HRI, P.Ex.Rs.Sub);
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +0000443 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
Krzysztof Parzyszek74671192017-10-16 00:29:47 +0000456 LLVM_ATTRIBUTE_UNUSED
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +0000457 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
Krzysztof Parzyszek74671192017-10-16 00:29:47 +0000463 LLVM_ATTRIBUTE_UNUSED
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +0000464 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)
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +0000471 OS << printReg(ED.Rd.Reg, &HRI, ED.Rd.Sub);
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +0000472 else
473 OS << "__";
474 OS << " = " << PrintExpr(ED.Expr, HRI);
475 if (ED.IsDef)
476 OS << ", def";
477 return OS;
478 }
479
Krzysztof Parzyszek74671192017-10-16 00:29:47 +0000480 LLVM_ATTRIBUTE_UNUSED
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +0000481 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
Krzysztof Parzyszek74671192017-10-16 00:29:47 +0000514 LLVM_ATTRIBUTE_UNUSED
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +0000515 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
Krzysztof Parzyszek74671192017-10-16 00:29:47 +0000527 LLVM_ATTRIBUTE_UNUSED
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +0000528 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
541INITIALIZE_PASS_BEGIN(HexagonConstExtenders, "hexagon-cext-opt",
542 "Hexagon constant-extender optimization", false, false)
543INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
544INITIALIZE_PASS_END(HexagonConstExtenders, "hexagon-cext-opt",
545 "Hexagon constant-extender optimization", false, false)
546
547static unsigned ReplaceCounter = 0;
548
549char HCE::ID = 0;
550
Eric Christopher3148a1b2017-11-16 03:18:15 +0000551#ifndef NDEBUG
Davide Italiano76067582017-10-14 23:46:01 +0000552LLVM_DUMP_METHOD void RangeTree::dump() const {
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +0000553 dbgs() << "Root: " << Root << '\n';
554 if (Root)
555 dump(Root);
556}
557
Eric Christopher3148a1b2017-11-16 03:18:15 +0000558LLVM_DUMP_METHOD void RangeTree::dump(const Node *N) const {
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +0000559 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}
Eric Christopher3148a1b2017-11-16 03:18:15 +0000572#endif
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +0000573
574void 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
582void 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
594RangeTree::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
610RangeTree::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
637RangeTree::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
652RangeTree::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
668HCE::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
690bool 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
721HCE::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
733bool 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
740HCE::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
765bool 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
783bool 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
832unsigned 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
932unsigned 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
Krzysztof Parzyszek1a1edbf2018-01-26 19:20:50 +00001002// Return the allowable deviation from the current value of Rb (i.e. the
1003// range of values that can be added to the current value) which the
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001004// instruction MI can accommodate.
1005// The instruction MI is a user of register Rb, which is defined via an
1006// extender. It may be possible for MI to be tweaked to work for a register
1007// defined with a slightly different value. For example
Krzysztof Parzyszek1a1edbf2018-01-26 19:20:50 +00001008// ... = L2_loadrub_io Rb, 1
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001009// can be modifed to be
Krzysztof Parzyszek1a1edbf2018-01-26 19:20:50 +00001010// ... = L2_loadrub_io Rb', 0
1011// if Rb' = Rb+1.
1012// The range for Rb would be [Min+1, Max+1], where [Min, Max] is a range
1013// for L2_loadrub with offset 0. That means that Rb could be replaced with
1014// Rc, where Rc-Rb belongs to [Min+1, Max+1].
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001015OffsetRange HCE::getOffsetRange(Register Rb, const MachineInstr &MI) const {
1016 unsigned Opc = MI.getOpcode();
1017 // Instructions that are constant-extended may be replaced with something
1018 // else that no longer offers the same range as the original.
1019 if (!isRegOffOpcode(Opc) || HII->isConstExtended(MI))
1020 return OffsetRange::zero();
1021
1022 if (Opc == Hexagon::A2_addi) {
1023 const MachineOperand &Op1 = MI.getOperand(1), &Op2 = MI.getOperand(2);
1024 if (Rb != Register(Op1) || !Op2.isImm())
1025 return OffsetRange::zero();
1026 OffsetRange R = { -(1<<15)+1, (1<<15)-1, 1 };
1027 return R.shift(Op2.getImm());
1028 }
1029
1030 // HII::getBaseAndOffsetPosition returns the increment position as "offset".
1031 if (HII->isPostIncrement(MI))
1032 return OffsetRange::zero();
1033
1034 const MCInstrDesc &D = HII->get(Opc);
1035 assert(D.mayLoad() || D.mayStore());
1036
1037 unsigned BaseP, OffP;
1038 if (!HII->getBaseAndOffsetPosition(MI, BaseP, OffP) ||
1039 Rb != Register(MI.getOperand(BaseP)) ||
1040 !MI.getOperand(OffP).isImm())
1041 return OffsetRange::zero();
1042
1043 uint64_t F = (D.TSFlags >> HexagonII::MemAccessSizePos) &
1044 HexagonII::MemAccesSizeMask;
1045 uint8_t A = HexagonII::getMemAccessSizeInBytes(HexagonII::MemAccessSize(F));
1046 unsigned L = Log2_32(A);
1047 unsigned S = 10+L; // sint11_L
1048 int32_t Min = -alignDown((1<<S)-1, A);
Krzysztof Parzyszek27056da2017-10-25 18:46:40 +00001049
1050 // The range will be shifted by Off. To prefer non-negative offsets,
1051 // adjust Max accordingly.
1052 int32_t Off = MI.getOperand(OffP).getImm();
1053 int32_t Max = Off >= 0 ? 0 : -Off;
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001054
1055 OffsetRange R = { Min, Max, A };
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001056 return R.shift(Off);
1057}
1058
1059// Return the allowable deviation from the current value of the extender ED,
1060// for which the instruction corresponding to ED can be modified without
1061// using an extender.
1062// The instruction uses the extender directly. It will be replaced with
1063// another instruction, say MJ, where the extender will be replaced with a
1064// register. MJ can allow some variability with respect to the value of
1065// that register, as is the case with indexed memory instructions.
1066OffsetRange HCE::getOffsetRange(const ExtDesc &ED) const {
1067 // The only way that there can be a non-zero range available is if
1068 // the instruction using ED will be converted to an indexed memory
1069 // instruction.
1070 unsigned IdxOpc = getRegOffOpcode(ED.UseMI->getOpcode());
1071 switch (IdxOpc) {
1072 case 0:
1073 return OffsetRange::zero();
1074 case Hexagon::A2_addi: // s16
1075 return { -32767, 32767, 1 };
1076 case Hexagon::A2_subri: // s10
1077 return { -511, 511, 1 };
1078 }
1079
1080 if (!ED.UseMI->mayLoad() && !ED.UseMI->mayStore())
1081 return OffsetRange::zero();
1082 const MCInstrDesc &D = HII->get(IdxOpc);
1083 uint64_t F = (D.TSFlags >> HexagonII::MemAccessSizePos) &
1084 HexagonII::MemAccesSizeMask;
1085 uint8_t A = HexagonII::getMemAccessSizeInBytes(HexagonII::MemAccessSize(F));
1086 unsigned L = Log2_32(A);
1087 unsigned S = 10+L; // sint11_L
1088 int32_t Min = -alignDown((1<<S)-1, A);
1089 int32_t Max = 0; // Force non-negative offsets.
1090 return { Min, Max, A };
1091}
1092
1093// Get the allowable deviation from the current value of Rd by checking
1094// all uses of Rd.
1095OffsetRange HCE::getOffsetRange(Register Rd) const {
1096 OffsetRange Range;
1097 for (const MachineOperand &Op : MRI->use_operands(Rd.Reg)) {
1098 // Make sure that the register being used by this operand is identical
1099 // to the register that was defined: using a different subregister
1100 // precludes any non-trivial range.
1101 if (Rd != Register(Op))
1102 return OffsetRange::zero();
1103 Range.intersect(getOffsetRange(Rd, *Op.getParent()));
1104 }
1105 return Range;
1106}
1107
1108void HCE::recordExtender(MachineInstr &MI, unsigned OpNum) {
1109 unsigned Opc = MI.getOpcode();
1110 ExtDesc ED;
1111 ED.OpNum = OpNum;
1112
1113 bool IsLoad = MI.mayLoad();
1114 bool IsStore = MI.mayStore();
1115
1116 if (IsLoad || IsStore) {
1117 unsigned AM = HII->getAddrMode(MI);
1118 switch (AM) {
1119 // (Re: ##Off + Rb<<S) = Rd: ##Val
1120 case HexagonII::Absolute: // (__: ## + __<<_)
1121 break;
1122 case HexagonII::AbsoluteSet: // (Rd: ## + __<<_)
1123 ED.Rd = MI.getOperand(OpNum-1);
1124 ED.IsDef = true;
1125 break;
1126 case HexagonII::BaseImmOffset: // (__: ## + Rs<<0)
1127 // Store-immediates are treated as non-memory operations, since
1128 // it's the value being stored that is extended (as opposed to
1129 // a part of the address).
1130 if (!isStoreImmediate(Opc))
1131 ED.Expr.Rs = MI.getOperand(OpNum-1);
1132 break;
1133 case HexagonII::BaseLongOffset: // (__: ## + Rs<<S)
1134 ED.Expr.Rs = MI.getOperand(OpNum-2);
1135 ED.Expr.S = MI.getOperand(OpNum-1).getImm();
1136 break;
1137 default:
1138 llvm_unreachable("Unhandled memory instruction");
1139 }
1140 } else {
1141 switch (Opc) {
1142 case Hexagon::A2_tfrsi: // (Rd: ## + __<<_)
1143 ED.Rd = MI.getOperand(0);
1144 ED.IsDef = true;
1145 break;
1146 case Hexagon::A2_combineii: // (Rd: ## + __<<_)
1147 case Hexagon::A4_combineir:
1148 ED.Rd = { MI.getOperand(0).getReg(), Hexagon::isub_hi };
1149 ED.IsDef = true;
1150 break;
1151 case Hexagon::A4_combineri: // (Rd: ## + __<<_)
1152 ED.Rd = { MI.getOperand(0).getReg(), Hexagon::isub_lo };
1153 ED.IsDef = true;
1154 break;
1155 case Hexagon::A2_addi: // (Rd: ## + Rs<<0)
1156 ED.Rd = MI.getOperand(0);
1157 ED.Expr.Rs = MI.getOperand(OpNum-1);
1158 break;
1159 case Hexagon::M2_accii: // (__: ## + Rs<<0)
1160 case Hexagon::M2_naccii:
1161 case Hexagon::S4_addaddi:
1162 ED.Expr.Rs = MI.getOperand(OpNum-1);
1163 break;
1164 case Hexagon::A2_subri: // (Rd: ## - Rs<<0)
1165 ED.Rd = MI.getOperand(0);
1166 ED.Expr.Rs = MI.getOperand(OpNum+1);
1167 ED.Expr.Neg = true;
1168 break;
1169 case Hexagon::S4_subaddi: // (__: ## - Rs<<0)
1170 ED.Expr.Rs = MI.getOperand(OpNum+1);
1171 ED.Expr.Neg = true;
1172 default: // (__: ## + __<<_)
1173 break;
1174 }
1175 }
1176
1177 ED.UseMI = &MI;
1178 Extenders.push_back(ED);
1179}
1180
1181void HCE::collectInstr(MachineInstr &MI) {
1182 if (!HII->isConstExtended(MI))
1183 return;
1184
1185 // Skip some non-convertible instructions.
1186 unsigned Opc = MI.getOpcode();
1187 switch (Opc) {
1188 case Hexagon::M2_macsin: // There is no Rx -= mpyi(Rs,Rt).
1189 case Hexagon::C4_addipc:
1190 case Hexagon::S4_or_andi:
1191 case Hexagon::S4_or_andix:
1192 case Hexagon::S4_or_ori:
1193 return;
1194 }
1195 recordExtender(MI, HII->getCExtOpNum(MI));
1196}
1197
1198void HCE::collect(MachineFunction &MF) {
1199 Extenders.clear();
1200 for (MachineBasicBlock &MBB : MF)
1201 for (MachineInstr &MI : MBB)
1202 collectInstr(MI);
1203}
1204
1205void HCE::assignInits(const ExtRoot &ER, unsigned Begin, unsigned End,
1206 AssignmentMap &IMap) {
1207 // Sanity check: make sure that all extenders in the range [Begin..End)
1208 // share the same root ER.
1209 for (unsigned I = Begin; I != End; ++I)
1210 assert(ER == ExtRoot(Extenders[I].getOp()));
1211
1212 // Construct the list of ranges, such that for each P in Ranges[I],
1213 // a register Reg = ER+P can be used in place of Extender[I]. If the
1214 // instruction allows, uses in the form of Reg+Off are considered
1215 // (here, Off = required_value - P).
1216 std::vector<OffsetRange> Ranges(End-Begin);
1217
1218 // For each extender that is a def, visit all uses of the defined register,
1219 // and produce an offset range that works for all uses. The def doesn't
1220 // have to be checked, because it can become dead if all uses can be updated
1221 // to use a different reg/offset.
1222 for (unsigned I = Begin; I != End; ++I) {
1223 const ExtDesc &ED = Extenders[I];
1224 if (!ED.IsDef)
1225 continue;
1226 ExtValue EV(ED);
1227 DEBUG(dbgs() << " =" << I << ". " << EV << " " << ED << '\n');
1228 assert(ED.Rd.Reg != 0);
1229 Ranges[I-Begin] = getOffsetRange(ED.Rd).shift(EV.Offset);
1230 // A2_tfrsi is a special case: it will be replaced with A2_addi, which
1231 // has a 16-bit signed offset. This means that A2_tfrsi not only has a
1232 // range coming from its uses, but also from the fact that its replacement
1233 // has a range as well.
1234 if (ED.UseMI->getOpcode() == Hexagon::A2_tfrsi) {
1235 int32_t D = alignDown(32767, Ranges[I-Begin].Align); // XXX hardcoded
1236 Ranges[I-Begin].extendBy(-D).extendBy(D);
1237 }
1238 }
1239
1240 // Visit all non-def extenders. For each one, determine the offset range
1241 // available for it.
1242 for (unsigned I = Begin; I != End; ++I) {
1243 const ExtDesc &ED = Extenders[I];
1244 if (ED.IsDef)
1245 continue;
1246 ExtValue EV(ED);
1247 DEBUG(dbgs() << " " << I << ". " << EV << " " << ED << '\n');
1248 OffsetRange Dev = getOffsetRange(ED);
1249 Ranges[I-Begin].intersect(Dev.shift(EV.Offset));
1250 }
1251
1252 // Here for each I there is a corresponding Range[I]. Construct the
1253 // inverse map, that to each range will assign the set of indexes in
1254 // [Begin..End) that this range corresponds to.
1255 std::map<OffsetRange, IndexList> RangeMap;
1256 for (unsigned I = Begin; I != End; ++I)
1257 RangeMap[Ranges[I-Begin]].insert(I);
1258
1259 DEBUG({
1260 dbgs() << "Ranges\n";
1261 for (unsigned I = Begin; I != End; ++I)
1262 dbgs() << " " << I << ". " << Ranges[I-Begin] << '\n';
1263 dbgs() << "RangeMap\n";
1264 for (auto &P : RangeMap) {
1265 dbgs() << " " << P.first << " ->";
1266 for (unsigned I : P.second)
1267 dbgs() << ' ' << I;
1268 dbgs() << '\n';
1269 }
1270 });
1271
1272 // Select the definition points, and generate the assignment between
1273 // these points and the uses.
1274
1275 // For each candidate offset, keep a pair CandData consisting of
1276 // the total number of ranges containing that candidate, and the
1277 // vector of corresponding RangeTree nodes.
1278 using CandData = std::pair<unsigned, SmallVector<RangeTree::Node*,8>>;
1279 std::map<int32_t, CandData> CandMap;
1280
1281 RangeTree Tree;
1282 for (const OffsetRange &R : Ranges)
1283 Tree.add(R);
1284 SmallVector<RangeTree::Node*,8> Nodes;
1285 Tree.order(Nodes);
1286
1287 auto MaxAlign = [](const SmallVectorImpl<RangeTree::Node*> &Nodes) {
1288 uint8_t Align = 1;
1289 for (RangeTree::Node *N : Nodes)
1290 Align = std::max(Align, N->Range.Align);
1291 return Align;
1292 };
1293
1294 // Construct the set of all potential definition points from the endpoints
1295 // of the ranges. If a given endpoint also belongs to a different range,
1296 // but with a higher alignment, also consider the more-highly-aligned
1297 // value of this endpoint.
1298 std::set<int32_t> CandSet;
1299 for (RangeTree::Node *N : Nodes) {
1300 const OffsetRange &R = N->Range;
1301 uint8_t A0 = MaxAlign(Tree.nodesWith(R.Min, false));
1302 CandSet.insert(R.Min);
1303 if (R.Align < A0)
1304 CandSet.insert(R.Min < 0 ? -alignDown(-R.Min, A0) : alignTo(R.Min, A0));
1305 uint8_t A1 = MaxAlign(Tree.nodesWith(R.Max, false));
1306 CandSet.insert(R.Max);
1307 if (R.Align < A1)
1308 CandSet.insert(R.Max < 0 ? -alignTo(-R.Max, A1) : alignDown(R.Max, A1));
1309 }
1310
1311 // Build the assignment map: candidate C -> { list of extender indexes }.
1312 // This has to be done iteratively:
1313 // - pick the candidate that covers the maximum number of extenders,
1314 // - add the candidate to the map,
1315 // - remove the extenders from the pool.
1316 while (true) {
1317 using CMap = std::map<int32_t,unsigned>;
1318 CMap Counts;
1319 for (auto It = CandSet.begin(), Et = CandSet.end(); It != Et; ) {
1320 auto &&V = Tree.nodesWith(*It);
1321 unsigned N = std::accumulate(V.begin(), V.end(), 0u,
1322 [](unsigned Acc, const RangeTree::Node *N) {
1323 return Acc + N->Count;
1324 });
1325 if (N != 0)
1326 Counts.insert({*It, N});
1327 It = (N != 0) ? std::next(It) : CandSet.erase(It);
1328 }
1329 if (Counts.empty())
1330 break;
1331
1332 // Find the best candidate with respect to the number of extenders covered.
1333 auto BestIt = std::max_element(Counts.begin(), Counts.end(),
1334 [](const CMap::value_type &A, const CMap::value_type &B) {
1335 return A.second < B.second ||
1336 (A.second == B.second && A < B);
1337 });
1338 int32_t Best = BestIt->first;
1339 ExtValue BestV(ER, Best);
1340 for (RangeTree::Node *N : Tree.nodesWith(Best)) {
1341 for (unsigned I : RangeMap[N->Range])
1342 IMap[{BestV,Extenders[I].Expr}].insert(I);
1343 Tree.erase(N);
1344 }
1345 }
1346
1347 DEBUG(dbgs() << "IMap (before fixup) = " << PrintIMap(IMap, *HRI));
1348
1349 // There is some ambiguity in what initializer should be used, if the
1350 // descriptor's subexpression is non-trivial: it can be the entire
1351 // subexpression (which is what has been done so far), or it can be
1352 // the extender's value itself, if all corresponding extenders have the
1353 // exact value of the initializer (i.e. require offset of 0).
1354
1355 // To reduce the number of initializers, merge such special cases.
1356 for (std::pair<const ExtenderInit,IndexList> &P : IMap) {
1357 // Skip trivial initializers.
1358 if (P.first.second.trivial())
1359 continue;
1360 // If the corresponding trivial initializer does not exist, skip this
1361 // entry.
1362 const ExtValue &EV = P.first.first;
1363 AssignmentMap::iterator F = IMap.find({EV, ExtExpr()});
1364 if (F == IMap.end())
1365 continue;
1366 // Finally, check if all extenders have the same value as the initializer.
1367 auto SameValue = [&EV,this](unsigned I) {
1368 const ExtDesc &ED = Extenders[I];
1369 return ExtValue(ED).Offset == EV.Offset;
1370 };
1371 if (all_of(P.second, SameValue)) {
1372 F->second.insert(P.second.begin(), P.second.end());
1373 P.second.clear();
1374 }
1375 }
1376
1377 DEBUG(dbgs() << "IMap (after fixup) = " << PrintIMap(IMap, *HRI));
1378}
1379
1380void HCE::calculatePlacement(const ExtenderInit &ExtI, const IndexList &Refs,
1381 LocDefMap &Defs) {
1382 if (Refs.empty())
1383 return;
1384
1385 // The placement calculation is somewhat simple right now: it finds a
1386 // single location for the def that dominates all refs. Since this may
1387 // place the def far from the uses, producing several locations for
1388 // defs that collectively dominate all refs could be better.
1389 // For now only do the single one.
1390 DenseSet<MachineBasicBlock*> Blocks;
1391 DenseSet<MachineInstr*> RefMIs;
1392 const ExtDesc &ED0 = Extenders[Refs[0]];
1393 MachineBasicBlock *DomB = ED0.UseMI->getParent();
1394 RefMIs.insert(ED0.UseMI);
1395 Blocks.insert(DomB);
1396 for (unsigned i = 1, e = Refs.size(); i != e; ++i) {
1397 const ExtDesc &ED = Extenders[Refs[i]];
1398 MachineBasicBlock *MBB = ED.UseMI->getParent();
1399 RefMIs.insert(ED.UseMI);
1400 DomB = MDT->findNearestCommonDominator(DomB, MBB);
1401 Blocks.insert(MBB);
1402 }
1403
1404#ifndef NDEBUG
1405 // The block DomB should be dominated by the def of each register used
1406 // in the initializer.
1407 Register Rs = ExtI.second.Rs; // Only one reg allowed now.
1408 const MachineInstr *DefI = Rs.isVReg() ? MRI->getVRegDef(Rs.Reg) : nullptr;
1409
1410 // This should be guaranteed given that the entire expression is used
1411 // at each instruction in Refs. Add an assertion just in case.
1412 assert(!DefI || MDT->dominates(DefI->getParent(), DomB));
1413#endif
1414
1415 MachineBasicBlock::iterator It;
1416 if (Blocks.count(DomB)) {
1417 // Try to find the latest possible location for the def.
1418 MachineBasicBlock::iterator End = DomB->end();
1419 for (It = DomB->begin(); It != End; ++It)
1420 if (RefMIs.count(&*It))
1421 break;
1422 assert(It != End && "Should have found a ref in DomB");
1423 } else {
1424 // DomB does not contain any refs.
1425 It = DomB->getFirstTerminator();
1426 }
1427 Loc DefLoc(DomB, It);
1428 Defs.emplace(DefLoc, Refs);
1429}
1430
1431HCE::Register HCE::insertInitializer(Loc DefL, const ExtenderInit &ExtI) {
1432 unsigned DefR = MRI->createVirtualRegister(&Hexagon::IntRegsRegClass);
1433 MachineBasicBlock &MBB = *DefL.Block;
1434 MachineBasicBlock::iterator At = DefL.At;
1435 DebugLoc dl = DefL.Block->findDebugLoc(DefL.At);
1436 const ExtValue &EV = ExtI.first;
1437 MachineOperand ExtOp(EV);
1438
1439 const ExtExpr &Ex = ExtI.second;
1440 const MachineInstr *InitI = nullptr;
1441
1442 if (Ex.Rs.isSlot()) {
1443 assert(Ex.S == 0 && "Cannot have a shift of a stack slot");
1444 assert(!Ex.Neg && "Cannot subtract a stack slot");
1445 // DefR = PS_fi Rb,##EV
1446 InitI = BuildMI(MBB, At, dl, HII->get(Hexagon::PS_fi), DefR)
1447 .add(MachineOperand(Ex.Rs))
1448 .add(ExtOp);
1449 } else {
1450 assert((Ex.Rs.Reg == 0 || Ex.Rs.isVReg()) && "Expecting virtual register");
1451 if (Ex.trivial()) {
1452 // DefR = ##EV
1453 InitI = BuildMI(MBB, At, dl, HII->get(Hexagon::A2_tfrsi), DefR)
1454 .add(ExtOp);
1455 } else if (Ex.S == 0) {
1456 if (Ex.Neg) {
1457 // DefR = sub(##EV,Rb)
1458 InitI = BuildMI(MBB, At, dl, HII->get(Hexagon::A2_subri), DefR)
1459 .add(ExtOp)
1460 .add(MachineOperand(Ex.Rs));
1461 } else {
1462 // DefR = add(Rb,##EV)
1463 InitI = BuildMI(MBB, At, dl, HII->get(Hexagon::A2_addi), DefR)
1464 .add(MachineOperand(Ex.Rs))
1465 .add(ExtOp);
1466 }
1467 } else {
1468 unsigned NewOpc = Ex.Neg ? Hexagon::S4_subi_asl_ri
1469 : Hexagon::S4_addi_asl_ri;
1470 // DefR = add(##EV,asl(Rb,S))
1471 InitI = BuildMI(MBB, At, dl, HII->get(NewOpc), DefR)
1472 .add(ExtOp)
1473 .add(MachineOperand(Ex.Rs))
1474 .addImm(Ex.S);
1475 }
1476 }
1477
1478 assert(InitI);
1479 (void)InitI;
1480 DEBUG(dbgs() << "Inserted def in bb#" << MBB.getNumber()
1481 << " for initializer: " << PrintInit(ExtI, *HRI)
1482 << "\n " << *InitI);
1483 return { DefR, 0 };
1484}
1485
1486// Replace the extender at index Idx with the register ExtR.
1487bool HCE::replaceInstrExact(const ExtDesc &ED, Register ExtR) {
1488 MachineInstr &MI = *ED.UseMI;
1489 MachineBasicBlock &MBB = *MI.getParent();
1490 MachineBasicBlock::iterator At = MI.getIterator();
1491 DebugLoc dl = MI.getDebugLoc();
1492 unsigned ExtOpc = MI.getOpcode();
1493
1494 // With a few exceptions, direct replacement amounts to creating an
1495 // instruction with a corresponding register opcode, with all operands
1496 // the same, except for the register used in place of the extender.
1497 unsigned RegOpc = getDirectRegReplacement(ExtOpc);
1498
1499 if (RegOpc == TargetOpcode::REG_SEQUENCE) {
1500 if (ExtOpc == Hexagon::A4_combineri)
1501 BuildMI(MBB, At, dl, HII->get(RegOpc))
1502 .add(MI.getOperand(0))
1503 .add(MI.getOperand(1))
1504 .addImm(Hexagon::isub_hi)
1505 .add(MachineOperand(ExtR))
1506 .addImm(Hexagon::isub_lo);
1507 else if (ExtOpc == Hexagon::A4_combineir)
1508 BuildMI(MBB, At, dl, HII->get(RegOpc))
1509 .add(MI.getOperand(0))
1510 .add(MachineOperand(ExtR))
1511 .addImm(Hexagon::isub_hi)
1512 .add(MI.getOperand(2))
1513 .addImm(Hexagon::isub_lo);
1514 else
1515 llvm_unreachable("Unexpected opcode became REG_SEQUENCE");
1516 MBB.erase(MI);
1517 return true;
1518 }
1519 if (ExtOpc == Hexagon::C2_cmpgei || ExtOpc == Hexagon::C2_cmpgeui) {
1520 unsigned NewOpc = ExtOpc == Hexagon::C2_cmpgei ? Hexagon::C2_cmplt
1521 : Hexagon::C2_cmpltu;
1522 BuildMI(MBB, At, dl, HII->get(NewOpc))
1523 .add(MI.getOperand(0))
1524 .add(MachineOperand(ExtR))
1525 .add(MI.getOperand(1));
1526 MBB.erase(MI);
1527 return true;
1528 }
1529
1530 if (RegOpc != 0) {
1531 MachineInstrBuilder MIB = BuildMI(MBB, At, dl, HII->get(RegOpc));
1532 unsigned RegN = ED.OpNum;
1533 // Copy all operands except the one that has the extender.
1534 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1535 if (i != RegN)
1536 MIB.add(MI.getOperand(i));
1537 else
1538 MIB.add(MachineOperand(ExtR));
1539 }
1540 MIB.setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
1541 MBB.erase(MI);
1542 return true;
1543 }
1544
1545 if ((MI.mayLoad() || MI.mayStore()) && !isStoreImmediate(ExtOpc)) {
1546 // For memory instructions, there is an asymmetry in the addressing
1547 // modes. Addressing modes allowing extenders can be replaced with
1548 // addressing modes that use registers, but the order of operands
1549 // (or even their number) may be different.
1550 // Replacements:
1551 // BaseImmOffset (io) -> BaseRegOffset (rr)
1552 // BaseLongOffset (ur) -> BaseRegOffset (rr)
1553 unsigned RegOpc, Shift;
1554 unsigned AM = HII->getAddrMode(MI);
1555 if (AM == HexagonII::BaseImmOffset) {
1556 RegOpc = HII->changeAddrMode_io_rr(ExtOpc);
1557 Shift = 0;
1558 } else if (AM == HexagonII::BaseLongOffset) {
1559 // Loads: Rd = L4_loadri_ur Rs, S, ##
1560 // Stores: S4_storeri_ur Rs, S, ##, Rt
1561 RegOpc = HII->changeAddrMode_ur_rr(ExtOpc);
1562 Shift = MI.getOperand(MI.mayLoad() ? 2 : 1).getImm();
1563 } else {
1564 llvm_unreachable("Unexpected addressing mode");
1565 }
1566#ifndef NDEBUG
1567 if (RegOpc == -1u) {
1568 dbgs() << "\nExtOpc: " << HII->getName(ExtOpc) << " has no rr version\n";
1569 llvm_unreachable("No corresponding rr instruction");
1570 }
1571#endif
1572
1573 unsigned BaseP, OffP;
1574 HII->getBaseAndOffsetPosition(MI, BaseP, OffP);
1575
1576 // Build an rr instruction: (RegOff + RegBase<<0)
1577 MachineInstrBuilder MIB = BuildMI(MBB, At, dl, HII->get(RegOpc));
1578 // First, add the def for loads.
1579 if (MI.mayLoad())
1580 MIB.add(getLoadResultOp(MI));
1581 // Handle possible predication.
1582 if (HII->isPredicated(MI))
1583 MIB.add(getPredicateOp(MI));
1584 // Build the address.
1585 MIB.add(MachineOperand(ExtR)); // RegOff
1586 MIB.add(MI.getOperand(BaseP)); // RegBase
1587 MIB.addImm(Shift); // << Shift
1588 // Add the stored value for stores.
1589 if (MI.mayStore())
1590 MIB.add(getStoredValueOp(MI));
1591 MIB.setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
1592 MBB.erase(MI);
1593 return true;
1594 }
1595
1596#ifndef NDEBUG
1597 dbgs() << '\n' << MI;
1598#endif
1599 llvm_unreachable("Unhandled exact replacement");
1600 return false;
1601}
1602
1603// Replace the extender ED with a form corresponding to the initializer ExtI.
1604bool HCE::replaceInstrExpr(const ExtDesc &ED, const ExtenderInit &ExtI,
1605 Register ExtR, int32_t &Diff) {
1606 MachineInstr &MI = *ED.UseMI;
1607 MachineBasicBlock &MBB = *MI.getParent();
1608 MachineBasicBlock::iterator At = MI.getIterator();
1609 DebugLoc dl = MI.getDebugLoc();
1610 unsigned ExtOpc = MI.getOpcode();
1611
1612 if (ExtOpc == Hexagon::A2_tfrsi) {
1613 // A2_tfrsi is a special case: it's replaced with A2_addi, which introduces
1614 // another range. One range is the one that's common to all tfrsi's uses,
1615 // this one is the range of immediates in A2_addi. When calculating ranges,
1616 // the addi's 16-bit argument was included, so now we need to make it such
1617 // that the produced value is in the range for the uses alone.
1618 // Most of the time, simply adding Diff will make the addi produce exact
1619 // result, but if Diff is outside of the 16-bit range, some adjustment
1620 // will be needed.
1621 unsigned IdxOpc = getRegOffOpcode(ExtOpc);
1622 assert(IdxOpc == Hexagon::A2_addi);
1623
1624 // Clamp Diff to the 16 bit range.
Krzysztof Parzyszek1a1edbf2018-01-26 19:20:50 +00001625 int32_t D = isInt<16>(Diff) ? Diff : (Diff > 0 ? 32767 : -32768);
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001626 BuildMI(MBB, At, dl, HII->get(IdxOpc))
1627 .add(MI.getOperand(0))
1628 .add(MachineOperand(ExtR))
1629 .addImm(D);
1630 Diff -= D;
1631#ifndef NDEBUG
1632 // Make sure the output is within allowable range for uses.
Krzysztof Parzyszek1a1edbf2018-01-26 19:20:50 +00001633 // "Diff" is a difference in the "opposite direction", i.e. Ext - DefV,
1634 // not DefV - Ext, as the getOffsetRange would calculate.
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001635 OffsetRange Uses = getOffsetRange(MI.getOperand(0));
Krzysztof Parzyszek1a1edbf2018-01-26 19:20:50 +00001636 if (!Uses.contains(-Diff))
1637 dbgs() << "Diff: " << -Diff << " out of range " << Uses
Krzysztof Parzyszek27056da2017-10-25 18:46:40 +00001638 << " for " << MI;
Krzysztof Parzyszek1a1edbf2018-01-26 19:20:50 +00001639 assert(Uses.contains(-Diff));
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001640#endif
1641 MBB.erase(MI);
1642 return true;
1643 }
1644
1645 const ExtValue &EV = ExtI.first; (void)EV;
1646 const ExtExpr &Ex = ExtI.second; (void)Ex;
1647
1648 if (ExtOpc == Hexagon::A2_addi || ExtOpc == Hexagon::A2_subri) {
1649 // If addi/subri are replaced with the exactly matching initializer,
1650 // they amount to COPY.
1651 // Check that the initializer is an exact match (for simplicity).
Benjamin Kramer9f21ca62017-10-13 20:46:14 +00001652#ifndef NDEBUG
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001653 bool IsAddi = ExtOpc == Hexagon::A2_addi;
1654 const MachineOperand &RegOp = MI.getOperand(IsAddi ? 1 : 2);
1655 const MachineOperand &ImmOp = MI.getOperand(IsAddi ? 2 : 1);
1656 assert(Ex.Rs == RegOp && EV == ImmOp && Ex.Neg != IsAddi &&
1657 "Initializer mismatch");
Benjamin Kramer9f21ca62017-10-13 20:46:14 +00001658#endif
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001659 BuildMI(MBB, At, dl, HII->get(TargetOpcode::COPY))
1660 .add(MI.getOperand(0))
1661 .add(MachineOperand(ExtR));
1662 Diff = 0;
1663 MBB.erase(MI);
1664 return true;
1665 }
1666 if (ExtOpc == Hexagon::M2_accii || ExtOpc == Hexagon::M2_naccii ||
1667 ExtOpc == Hexagon::S4_addaddi || ExtOpc == Hexagon::S4_subaddi) {
1668 // M2_accii: add(Rt,add(Rs,V)) (tied)
1669 // M2_naccii: sub(Rt,add(Rs,V))
1670 // S4_addaddi: add(Rt,add(Rs,V))
1671 // S4_subaddi: add(Rt,sub(V,Rs))
1672 // Check that Rs and V match the initializer expression. The Rs+V is the
1673 // combination that is considered "subexpression" for V, although Rx+V
1674 // would also be valid.
Benjamin Kramer9f21ca62017-10-13 20:46:14 +00001675#ifndef NDEBUG
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001676 bool IsSub = ExtOpc == Hexagon::S4_subaddi;
1677 Register Rs = MI.getOperand(IsSub ? 3 : 2);
1678 ExtValue V = MI.getOperand(IsSub ? 2 : 3);
1679 assert(EV == V && Rs == Ex.Rs && IsSub == Ex.Neg && "Initializer mismatch");
Benjamin Kramer9f21ca62017-10-13 20:46:14 +00001680#endif
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001681 unsigned NewOpc = ExtOpc == Hexagon::M2_naccii ? Hexagon::A2_sub
1682 : Hexagon::A2_add;
1683 BuildMI(MBB, At, dl, HII->get(NewOpc))
1684 .add(MI.getOperand(0))
1685 .add(MI.getOperand(1))
1686 .add(MachineOperand(ExtR));
1687 MBB.erase(MI);
1688 return true;
1689 }
1690
1691 if (MI.mayLoad() || MI.mayStore()) {
1692 unsigned IdxOpc = getRegOffOpcode(ExtOpc);
1693 assert(IdxOpc && "Expecting indexed opcode");
1694 MachineInstrBuilder MIB = BuildMI(MBB, At, dl, HII->get(IdxOpc));
1695 // Construct the new indexed instruction.
1696 // First, add the def for loads.
1697 if (MI.mayLoad())
1698 MIB.add(getLoadResultOp(MI));
1699 // Handle possible predication.
1700 if (HII->isPredicated(MI))
1701 MIB.add(getPredicateOp(MI));
1702 // Build the address.
1703 MIB.add(MachineOperand(ExtR));
1704 MIB.addImm(Diff);
1705 // Add the stored value for stores.
1706 if (MI.mayStore())
1707 MIB.add(getStoredValueOp(MI));
1708 MIB.setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
1709 MBB.erase(MI);
1710 return true;
1711 }
1712
1713#ifndef NDEBUG
1714 dbgs() << '\n' << PrintInit(ExtI, *HRI) << " " << MI;
1715#endif
1716 llvm_unreachable("Unhandled expr replacement");
1717 return false;
1718}
1719
1720bool HCE::replaceInstr(unsigned Idx, Register ExtR, const ExtenderInit &ExtI) {
1721 if (ReplaceLimit.getNumOccurrences()) {
1722 if (ReplaceLimit <= ReplaceCounter)
1723 return false;
1724 ++ReplaceCounter;
1725 }
1726 const ExtDesc &ED = Extenders[Idx];
1727 assert((!ED.IsDef || ED.Rd.Reg != 0) && "Missing Rd for def");
1728 const ExtValue &DefV = ExtI.first;
1729 assert(ExtRoot(ExtValue(ED)) == ExtRoot(DefV) && "Extender root mismatch");
1730 const ExtExpr &DefEx = ExtI.second;
1731
1732 ExtValue EV(ED);
1733 int32_t Diff = EV.Offset - DefV.Offset;
1734 const MachineInstr &MI = *ED.UseMI;
1735 DEBUG(dbgs() << __func__ << " Idx:" << Idx << " ExtR:"
1736 << PrintRegister(ExtR, *HRI) << " Diff:" << Diff << '\n');
1737
1738 // These two addressing modes must be converted into indexed forms
1739 // regardless of what the initializer looks like.
1740 bool IsAbs = false, IsAbsSet = false;
1741 if (MI.mayLoad() || MI.mayStore()) {
1742 unsigned AM = HII->getAddrMode(MI);
1743 IsAbs = AM == HexagonII::Absolute;
1744 IsAbsSet = AM == HexagonII::AbsoluteSet;
1745 }
1746
1747 // If it's a def, remember all operands that need to be updated.
1748 // If ED is a def, and Diff is not 0, then all uses of the register Rd
1749 // defined by ED must be in the form (Rd, imm), i.e. the immediate offset
1750 // must follow the Rd in the operand list.
1751 std::vector<std::pair<MachineInstr*,unsigned>> RegOps;
1752 if (ED.IsDef && Diff != 0) {
1753 for (MachineOperand &Op : MRI->use_operands(ED.Rd.Reg)) {
1754 MachineInstr &UI = *Op.getParent();
1755 RegOps.push_back({&UI, getOperandIndex(UI, Op)});
1756 }
1757 }
1758
1759 // Replace the instruction.
1760 bool Replaced = false;
1761 if (Diff == 0 && DefEx.trivial() && !IsAbs && !IsAbsSet)
1762 Replaced = replaceInstrExact(ED, ExtR);
1763 else
1764 Replaced = replaceInstrExpr(ED, ExtI, ExtR, Diff);
1765
1766 if (Diff != 0 && Replaced && ED.IsDef) {
1767 // Update offsets of the def's uses.
1768 for (std::pair<MachineInstr*,unsigned> P : RegOps) {
1769 unsigned J = P.second;
Krzysztof Parzyszek92a26352017-10-27 18:52:28 +00001770 assert(P.first->getNumOperands() > J+1 &&
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001771 P.first->getOperand(J+1).isImm());
1772 MachineOperand &ImmOp = P.first->getOperand(J+1);
1773 ImmOp.setImm(ImmOp.getImm() + Diff);
1774 }
1775 // If it was an absolute-set instruction, the "set" part has been removed.
1776 // ExtR will now be the register with the extended value, and since all
1777 // users of Rd have been updated, all that needs to be done is to replace
1778 // Rd with ExtR.
1779 if (IsAbsSet) {
1780 assert(ED.Rd.Sub == 0 && ExtR.Sub == 0);
1781 MRI->replaceRegWith(ED.Rd.Reg, ExtR.Reg);
1782 }
1783 }
1784
1785 return Replaced;
1786}
1787
1788bool HCE::replaceExtenders(const AssignmentMap &IMap) {
1789 LocDefMap Defs;
1790 bool Changed = false;
1791
1792 for (const std::pair<ExtenderInit,IndexList> &P : IMap) {
1793 const IndexList &Idxs = P.second;
1794 if (Idxs.size() < CountThreshold)
1795 continue;
1796
1797 Defs.clear();
1798 calculatePlacement(P.first, Idxs, Defs);
1799 for (const std::pair<Loc,IndexList> &Q : Defs) {
1800 Register DefR = insertInitializer(Q.first, P.first);
1801 NewRegs.push_back(DefR.Reg);
1802 for (unsigned I : Q.second)
1803 Changed |= replaceInstr(I, DefR, P.first);
1804 }
1805 }
1806 return Changed;
1807}
1808
1809unsigned HCE::getOperandIndex(const MachineInstr &MI,
1810 const MachineOperand &Op) const {
1811 for (unsigned i = 0, n = MI.getNumOperands(); i != n; ++i)
1812 if (&MI.getOperand(i) == &Op)
1813 return i;
1814 llvm_unreachable("Not an operand of MI");
1815}
1816
1817const MachineOperand &HCE::getPredicateOp(const MachineInstr &MI) const {
1818 assert(HII->isPredicated(MI));
1819 for (const MachineOperand &Op : MI.operands()) {
1820 if (!Op.isReg() || !Op.isUse() ||
1821 MRI->getRegClass(Op.getReg()) != &Hexagon::PredRegsRegClass)
1822 continue;
1823 assert(Op.getSubReg() == 0 && "Predicate register with a subregister");
1824 return Op;
1825 }
1826 llvm_unreachable("Predicate operand not found");
1827}
1828
1829const MachineOperand &HCE::getLoadResultOp(const MachineInstr &MI) const {
1830 assert(MI.mayLoad());
1831 return MI.getOperand(0);
1832}
1833
1834const MachineOperand &HCE::getStoredValueOp(const MachineInstr &MI) const {
1835 assert(MI.mayStore());
1836 return MI.getOperand(MI.getNumExplicitOperands()-1);
1837}
1838
1839bool HCE::runOnMachineFunction(MachineFunction &MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +00001840 if (skipFunction(MF.getFunction()))
Krzysztof Parzyszek7c9c0582017-10-13 19:02:59 +00001841 return false;
1842 DEBUG(MF.print(dbgs() << "Before " << getPassName() << '\n', nullptr));
1843
1844 HII = MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
1845 HRI = MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1846 MDT = &getAnalysis<MachineDominatorTree>();
1847 MRI = &MF.getRegInfo();
1848 AssignmentMap IMap;
1849
1850 collect(MF);
1851 std::sort(Extenders.begin(), Extenders.end(),
1852 [](const ExtDesc &A, const ExtDesc &B) {
1853 return ExtValue(A) < ExtValue(B);
1854 });
1855
1856 bool Changed = false;
1857 DEBUG(dbgs() << "Collected " << Extenders.size() << " extenders\n");
1858 for (unsigned I = 0, E = Extenders.size(); I != E; ) {
1859 unsigned B = I;
1860 const ExtRoot &T = Extenders[B].getOp();
1861 while (I != E && ExtRoot(Extenders[I].getOp()) == T)
1862 ++I;
1863
1864 IMap.clear();
1865 assignInits(T, B, I, IMap);
1866 Changed |= replaceExtenders(IMap);
1867 }
1868
1869 DEBUG({
1870 if (Changed)
1871 MF.print(dbgs() << "After " << getPassName() << '\n', nullptr);
1872 else
1873 dbgs() << "No changes\n";
1874 });
1875 return Changed;
1876}
1877
1878FunctionPass *llvm::createHexagonConstExtenders() {
1879 return new HexagonConstExtenders();
1880}