LLVM 24.0.0git
RISCVMergeBaseOffset.cpp
Go to the documentation of this file.
1//===----- RISCVMergeBaseOffset.cpp - Optimise address calculations ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Merge the offset of address calculation into the offset field
10// of instructions in a global address lowering sequence.
11//
12//===----------------------------------------------------------------------===//
13
14#include "RISCV.h"
15#include "RISCVTargetMachine.h"
17#include "llvm/CodeGen/Passes.h"
19#include "llvm/Support/Debug.h"
21#include <optional>
22using namespace llvm;
23
24#define DEBUG_TYPE "riscv-merge-base-offset"
25#define RISCV_MERGE_BASE_OFFSET_NAME "RISC-V Merge Base Offset"
26namespace {
27
28class RISCVMergeBaseOffsetOpt : public MachineFunctionPass {
29 const RISCVSubtarget *ST = nullptr;
31
32public:
33 static char ID;
34 bool runOnMachineFunction(MachineFunction &Fn) override;
35 bool detectFoldable(MachineInstr &Hi, MachineInstr *&Lo);
36
37 bool detectAndFoldOffset(MachineInstr &Hi, MachineInstr &Lo);
38 bool foldOffset(MachineInstr &Hi, MachineInstr &Lo, MachineInstr &Tail,
39 int64_t Offset);
40 bool foldLargeOffset(MachineInstr &Hi, MachineInstr &Lo,
41 MachineInstr &TailAdd, Register GSReg);
42 bool foldShiftedOffset(MachineInstr &Hi, MachineInstr &Lo,
43 MachineInstr &TailShXAdd, Register GSReg);
44
45 bool foldIntoMemoryOps(MachineInstr &Hi, MachineInstr &Lo);
46 bool foldShxaddIntoScaledMemory(MachineInstr &Hi, MachineInstr &Lo);
47
48 RISCVMergeBaseOffsetOpt() : MachineFunctionPass(ID) {}
49
50 MachineFunctionProperties getRequiredProperties() const override {
51 return MachineFunctionProperties().setIsSSA();
52 }
53
54 void getAnalysisUsage(AnalysisUsage &AU) const override {
55 AU.setPreservesCFG();
57 }
58
59 StringRef getPassName() const override {
61 }
62};
63} // end anonymous namespace
64
65char RISCVMergeBaseOffsetOpt::ID = 0;
66INITIALIZE_PASS(RISCVMergeBaseOffsetOpt, DEBUG_TYPE,
67 RISCV_MERGE_BASE_OFFSET_NAME, false, false)
68
69// Detect either of the patterns:
70//
71// 1. (medlow pattern):
72// a. lui vreg1, %hi(s)
73// addi vreg2, vreg1, %lo(s)
74//
75// b. qc.e.li vreg1, s
76//
77// 2. (medany pattern):
78// .Lpcrel_hi1:
79// auipc vreg1, %pcrel_hi(s)
80// addi vreg2, vreg1, %pcrel_lo(.Lpcrel_hi1)
81//
82// The pattern is only accepted if:
83// 1) The first instruction has only one use, which is the ADDI.
84// 2) The address operands have the appropriate type, reflecting the
85// lowering of a global address or constant pool using medlow or medany.
86// 3) The offset value in the Global Address or Constant Pool is 0.
87bool RISCVMergeBaseOffsetOpt::detectFoldable(MachineInstr &Hi,
88 MachineInstr *&Lo) {
89 auto HiOpc = Hi.getOpcode();
90 if (HiOpc != RISCV::LUI && HiOpc != RISCV::AUIPC &&
91 HiOpc != RISCV::PseudoMovAddr && HiOpc != RISCV::QC_E_LI)
92 return false;
93
94 const MachineOperand &HiOp1 = Hi.getOperand(1);
95 unsigned ExpectedFlags = HiOpc == RISCV::AUIPC ? RISCVII::MO_PCREL_HI
96 : HiOpc == RISCV::QC_E_LI ? RISCVII::MO_None
98 if (HiOp1.getTargetFlags() != ExpectedFlags)
99 return false;
100
101 if (!(HiOp1.isGlobal() || HiOp1.isCPI() || HiOp1.isBlockAddress()) ||
102 HiOp1.getOffset() != 0)
103 return false;
104
105 if (HiOpc == RISCV::PseudoMovAddr || HiOpc == RISCV::QC_E_LI) {
106 // Most of the code should handle it correctly without modification by
107 // setting Lo and Hi both point to PseudoMovAddr/QC_E_LI
108 Lo = &Hi;
109 } else {
110 Register HiDestReg = Hi.getOperand(0).getReg();
111 if (!MRI->hasOneUse(HiDestReg))
112 return false;
113
114 Lo = &*MRI->use_instr_begin(HiDestReg);
115 if (Lo->getOpcode() != RISCV::ADDI)
116 return false;
117 }
118
119 if (HiOpc != RISCV::QC_E_LI) {
120 const MachineOperand &LoOp2 = Lo->getOperand(2);
121 if (HiOpc == RISCV::LUI || HiOpc == RISCV::PseudoMovAddr) {
122 if (LoOp2.getTargetFlags() != RISCVII::MO_LO ||
123 !(LoOp2.isGlobal() || LoOp2.isCPI() || LoOp2.isBlockAddress()) ||
124 LoOp2.getOffset() != 0)
125 return false;
126 } else {
127 assert(HiOpc == RISCV::AUIPC);
128 if (LoOp2.getTargetFlags() != RISCVII::MO_PCREL_LO ||
130 return false;
131 }
132 }
133
134 if (HiOp1.isGlobal()) {
135 LLVM_DEBUG(dbgs() << " Found lowered global address: "
136 << *HiOp1.getGlobal() << "\n");
137 } else if (HiOp1.isBlockAddress()) {
138 LLVM_DEBUG(dbgs() << " Found lowered basic address: "
139 << *HiOp1.getBlockAddress() << "\n");
140 } else if (HiOp1.isCPI()) {
141 LLVM_DEBUG(dbgs() << " Found lowered constant pool: " << HiOp1.getIndex()
142 << "\n");
143 }
144
145 return true;
146}
147
148// Update the offset in Hi and Lo instructions.
149// Delete the tail instruction and update all the uses to use the
150// output from Lo.
151bool RISCVMergeBaseOffsetOpt::foldOffset(MachineInstr &Hi, MachineInstr &Lo,
152 MachineInstr &Tail, int64_t Offset) {
153 assert(isInt<32>(Offset) && "Unexpected offset");
154
155 // If Hi is an AUIPC, don't fold the offset if it is outside the bounds of
156 // the global object. The object may be within 2GB of the PC, but addresses
157 // outside of the object might not be.
158 auto HiOpc = Hi.getOpcode();
159 if (HiOpc == RISCV::AUIPC && Hi.getOperand(1).isGlobal()) {
160 const GlobalValue *GV = Hi.getOperand(1).getGlobal();
161 Type *Ty = GV->getValueType();
162 if (!Ty->isSized() || Offset < 0 ||
164 return false;
165 }
166
167 // Put the offset back in Hi and the Lo
168 Hi.getOperand(1).setOffset(Offset);
169 if (Hi.getOpcode() != RISCV::AUIPC && Hi.getOpcode() != RISCV::QC_E_LI)
170 Lo.getOperand(2).setOffset(Offset);
171 // Delete the tail instruction.
172 Register LoOp0Reg = Lo.getOperand(0).getReg();
173 Register TailOp0Reg = Tail.getOperand(0).getReg();
174 MRI->constrainRegClass(LoOp0Reg, MRI->getRegClass(TailOp0Reg));
175 MRI->replaceRegWith(TailOp0Reg, LoOp0Reg);
176 Tail.eraseFromParent();
177 LLVM_DEBUG(dbgs() << " Merged offset " << Offset << " into base.\n"
178 << " " << Hi << " " << Lo;);
179 return true;
180}
181
182// Detect patterns for large offsets that are passed into an ADD instruction.
183// If the pattern is found, updates the offset in Hi and Lo instructions
184// and deletes TailAdd and the instructions that produced the offset.
185//
186// Base address lowering is of the form:
187// Hi: lui vreg1, %hi(s)
188// Lo: addi vreg2, vreg1, %lo(s)
189// / \
190// / \
191// / \
192// / The large offset can be of two forms: \
193// 1) Offset that has non zero bits in lower 2) Offset that has non zero
194// 12 bits and upper 20 bits bits in upper 20 bits only
195// OffseLUI: lui vreg3, 4
196// OffsetTail: addi voff, vreg3, 188 OffsetTail: lui voff, 128
197// \ /
198// \ /
199// \ /
200// \ /
201// TailAdd: add vreg4, vreg2, voff
202bool RISCVMergeBaseOffsetOpt::foldLargeOffset(MachineInstr &Hi,
203 MachineInstr &Lo,
204 MachineInstr &TailAdd,
205 Register GAReg) {
206 assert((TailAdd.getOpcode() == RISCV::ADD) && "Expected ADD instruction!");
207 Register Rs = TailAdd.getOperand(1).getReg();
208 Register Rt = TailAdd.getOperand(2).getReg();
209 Register Reg = Rs == GAReg ? Rt : Rs;
210
211 // Can't fold if the register has more than one use.
212 if (!Reg.isVirtual() || !MRI->hasOneUse(Reg))
213 return false;
214 // This can point to an ADDI(W) or a LUI:
215 MachineInstr &OffsetTail = *MRI->getVRegDef(Reg);
216 auto OffsetTailOpc = OffsetTail.getOpcode();
217 if (OffsetTailOpc == RISCV::ADDI || OffsetTailOpc == RISCV::ADDIW) {
218 // The offset value has non zero bits in both %hi and %lo parts.
219 // Detect an ADDI that feeds from a LUI instruction.
220 MachineOperand &AddiImmOp = OffsetTail.getOperand(2);
221 if (AddiImmOp.getTargetFlags() != RISCVII::MO_None)
222 return false;
223 // Make sure this isn't something weird like a frame index.
224 if (!OffsetTail.getOperand(1).isReg())
225 return false;
226 Register AddiReg = OffsetTail.getOperand(1).getReg();
227 int64_t OffLo = AddiImmOp.getImm();
228
229 // Handle rs1 of ADDI is X0.
230 if (AddiReg == RISCV::X0) {
231 LLVM_DEBUG(dbgs() << " Offset Instrs: " << OffsetTail);
232 if (!foldOffset(Hi, Lo, TailAdd, OffLo))
233 return false;
234 OffsetTail.eraseFromParent();
235 return true;
236 }
237
238 MachineInstr &OffsetLui = *MRI->getVRegDef(AddiReg);
239 MachineOperand &LuiImmOp = OffsetLui.getOperand(1);
240 if (OffsetLui.getOpcode() != RISCV::LUI ||
241 LuiImmOp.getTargetFlags() != RISCVII::MO_None ||
242 !MRI->hasOneUse(OffsetLui.getOperand(0).getReg()))
243 return false;
244 int64_t Offset = SignExtend64<32>(LuiImmOp.getImm() << 12);
245 Offset += OffLo;
246 // RV32 ignores the upper 32 bits. ADDIW sign extends the result.
247 if (!ST->is64Bit() || OffsetTailOpc == RISCV::ADDIW)
249 // We can only fold simm32 offsets.
250 if (!isInt<32>(Offset))
251 return false;
252 LLVM_DEBUG(dbgs() << " Offset Instrs: " << OffsetTail
253 << " " << OffsetLui);
254 if (!foldOffset(Hi, Lo, TailAdd, Offset))
255 return false;
256 OffsetTail.eraseFromParent();
257 OffsetLui.eraseFromParent();
258 return true;
259 } else if (OffsetTailOpc == RISCV::LUI) {
260 // The offset value has all zero bits in the lower 12 bits. Only LUI
261 // exists.
262 LLVM_DEBUG(dbgs() << " Offset Instr: " << OffsetTail);
263 int64_t Offset = SignExtend64<32>(OffsetTail.getOperand(1).getImm() << 12);
264 if (!foldOffset(Hi, Lo, TailAdd, Offset))
265 return false;
266 OffsetTail.eraseFromParent();
267 return true;
268 }
269 return false;
270}
271
272// Detect patterns for offsets that are passed into a SHXADD instruction.
273// The offset has 1, 2, or 3 trailing zeros and fits in simm13, simm14, simm15.
274// The constant is created with addi voff, x0, C, and shXadd is used to
275// fill insert the trailing zeros and do the addition.
276// If the pattern is found, updates the offset in Hi and Lo instructions
277// and deletes TailShXAdd and the instructions that produced the offset.
278//
279// Hi: lui vreg1, %hi(s)
280// Lo: addi vreg2, vreg1, %lo(s)
281// OffsetTail: addi voff, x0, C
282// TailAdd: shXadd vreg4, voff, vreg2
283bool RISCVMergeBaseOffsetOpt::foldShiftedOffset(MachineInstr &Hi,
284 MachineInstr &Lo,
285 MachineInstr &TailShXAdd,
286 Register GAReg) {
287 assert((TailShXAdd.getOpcode() == RISCV::SH1ADD ||
288 TailShXAdd.getOpcode() == RISCV::SH2ADD ||
289 TailShXAdd.getOpcode() == RISCV::SH3ADD) &&
290 "Expected SHXADD instruction!");
291
292 if (GAReg != TailShXAdd.getOperand(2).getReg())
293 return false;
294
295 // The first source is the shifted operand.
296 Register Rs1 = TailShXAdd.getOperand(1).getReg();
297
298 // Can't fold if the register has more than one use.
299 if (!Rs1.isVirtual() || !MRI->hasOneUse(Rs1))
300 return false;
301 // This can point to an ADDI X0, C.
302 MachineInstr &OffsetTail = *MRI->getVRegDef(Rs1);
303 if (OffsetTail.getOpcode() != RISCV::ADDI)
304 return false;
305 if (!OffsetTail.getOperand(1).isReg() ||
306 OffsetTail.getOperand(1).getReg() != RISCV::X0 ||
307 !OffsetTail.getOperand(2).isImm())
308 return false;
309
310 int64_t Offset = OffsetTail.getOperand(2).getImm();
311 assert(isInt<12>(Offset) && "Unexpected offset");
312
313 unsigned ShAmt;
314 switch (TailShXAdd.getOpcode()) {
315 default: llvm_unreachable("Unexpected opcode");
316 case RISCV::SH1ADD: ShAmt = 1; break;
317 case RISCV::SH2ADD: ShAmt = 2; break;
318 case RISCV::SH3ADD: ShAmt = 3; break;
319 }
320
321 Offset = (uint64_t)Offset << ShAmt;
322
323 LLVM_DEBUG(dbgs() << " Offset Instr: " << OffsetTail);
324 if (!foldOffset(Hi, Lo, TailShXAdd, Offset))
325 return false;
326 OffsetTail.eraseFromParent();
327 return true;
328}
329
330bool RISCVMergeBaseOffsetOpt::detectAndFoldOffset(MachineInstr &Hi,
331 MachineInstr &Lo) {
332 Register DestReg = Lo.getOperand(0).getReg();
333
334 // Look for arithmetic instructions we can get an offset from.
335 // We might be able to remove the arithmetic instructions by folding the
336 // offset into the LUI+ADDI.
337 if (!MRI->hasOneUse(DestReg))
338 return false;
339
340 // Lo has only one use.
341 MachineInstr &Tail = *MRI->use_instr_begin(DestReg);
342 switch (Tail.getOpcode()) {
343 default:
344 LLVM_DEBUG(dbgs() << "Don't know how to get offset from this instr: "
345 << Tail);
346 break;
347 case RISCV::ADDI:
348 case RISCV::QC_E_ADDI:
349 case RISCV::QC_E_ADDAI: {
350 // Offset is simply an immediate operand.
351 int64_t Offset = Tail.getOperand(2).getImm();
352 if (Tail.getOpcode() == RISCV::ADDI) {
353 // We might have two ADDIs in a row.
354 Register TailDestReg = Tail.getOperand(0).getReg();
355 if (MRI->hasOneUse(TailDestReg)) {
356 MachineInstr &TailTail = *MRI->use_instr_begin(TailDestReg);
357 if (TailTail.getOpcode() == RISCV::ADDI) {
358 Offset += TailTail.getOperand(2).getImm();
359 LLVM_DEBUG(dbgs() << " Offset Instrs: " << Tail << TailTail);
360 if (!foldOffset(Hi, Lo, TailTail, Offset))
361 return false;
362 Tail.eraseFromParent();
363 return true;
364 }
365 }
366 }
367
368 LLVM_DEBUG(dbgs() << " Offset Instr: " << Tail);
369 return foldOffset(Hi, Lo, Tail, Offset);
370 }
371 case RISCV::ADD:
372 // The offset is too large to fit in the immediate field of ADDI.
373 // This can be in two forms:
374 // 1) LUI hi_Offset followed by:
375 // ADDI lo_offset
376 // This happens in case the offset has non zero bits in
377 // both hi 20 and lo 12 bits.
378 // 2) LUI (offset20)
379 // This happens in case the lower 12 bits of the offset are zeros.
380 return foldLargeOffset(Hi, Lo, Tail, DestReg);
381 case RISCV::SH1ADD:
382 case RISCV::SH2ADD:
383 case RISCV::SH3ADD:
384 // The offset is too large to fit in the immediate field of ADDI.
385 // It may be encoded as (SH2ADD (ADDI X0, C), DestReg) or
386 // (SH3ADD (ADDI X0, C), DestReg).
387 return foldShiftedOffset(Hi, Lo, Tail, DestReg);
388 }
389
390 return false;
391}
392
394 const MachineOperand &ImmOp) {
395 switch (ImmOp.getType()) {
397 MO.ChangeToCPI(ImmOp.getIndex(), ImmOp.getOffset(), ImmOp.getTargetFlags());
398 break;
400 MO.ChangeToGA(ImmOp.getGlobal(), ImmOp.getOffset(), ImmOp.getTargetFlags());
401 break;
403 MO.ChangeToMCSymbol(ImmOp.getMCSymbol(), ImmOp.getTargetFlags());
404 MO.setOffset(ImmOp.getOffset());
405 break;
407 MO.ChangeToBA(ImmOp.getBlockAddress(), ImmOp.getOffset(),
408 ImmOp.getTargetFlags());
409 break;
410 default:
411 report_fatal_error("unsupported machine operand type");
412 break;
413 }
414}
415
416bool RISCVMergeBaseOffsetOpt::foldIntoMemoryOps(MachineInstr &Hi,
417 MachineInstr &Lo) {
418 Register DestReg = Lo.getOperand(0).getReg();
419
420 // If all the uses are memory ops with the same offset, we can transform:
421 //
422 // 1. (medlow pattern):
423 // a. Hi: lui vreg1, %hi(foo) ---> lui vreg1, %hi(foo+8)
424 // Lo: addi vreg2, vreg1, %lo(foo) ---> lw vreg3, lo(foo+8)(vreg1)
425 // Tail: lw vreg3, 8(vreg2)
426 //
427 // b. Hi: qc.e.li vreg1, foo ---> qc.e.li vreg1, foo+8
428 // Tail: lw vreg2, 8(vreg1) ---> lw vreg2, 0(vreg1)
429 //
430 // 2. (medany pattern):
431 // Hi: 1:auipc vreg1, %pcrel_hi(s) ---> auipc vreg1, %pcrel_hi(foo+8)
432 // Lo: addi vreg2, vreg1, %pcrel_lo(1b) ---> lw vreg3, %pcrel_lo(1b)(vreg1)
433 // Tail: lw vreg3, 8(vreg2)
434
435 std::optional<int64_t> CommonOffset;
436 DenseMap<const MachineInstr *, SmallVector<unsigned>>
437 InlineAsmMemoryOpIndexesMap;
438 for (const MachineInstr &UseMI : MRI->use_nodbg_instructions(DestReg)) {
439 switch (UseMI.getOpcode()) {
440 default:
441 LLVM_DEBUG(dbgs() << "Not a load or store instruction: " << UseMI);
442 return false;
443 case RISCV::LB:
444 case RISCV::LH:
445 case RISCV::LH_INX:
446 case RISCV::LW:
447 case RISCV::LW_INX:
448 case RISCV::LBU:
449 case RISCV::LHU:
450 case RISCV::LWU:
451 case RISCV::LD:
452 case RISCV::LD_RV32:
453 case RISCV::FLH:
454 case RISCV::FLW:
455 case RISCV::FLD:
456 case RISCV::SB:
457 case RISCV::SH:
458 case RISCV::SH_INX:
459 case RISCV::SW:
460 case RISCV::SW_INX:
461 case RISCV::SD:
462 case RISCV::SD_RV32:
463 case RISCV::FSH:
464 case RISCV::FSW:
465 case RISCV::FSD: {
466 if (UseMI.getOperand(1).isFI())
467 return false;
468 // Register defined by Lo should not be the value register.
469 if (DestReg == UseMI.getOperand(0).getReg())
470 return false;
471 assert(DestReg == UseMI.getOperand(1).getReg() &&
472 "Expected base address use");
473 // All load/store instructions must use the same offset.
474 int64_t Offset = UseMI.getOperand(2).getImm();
475 if (CommonOffset && Offset != CommonOffset)
476 return false;
477 CommonOffset = Offset;
478 break;
479 }
480 case RISCV::PseudoCCLD:
481 case RISCV::PseudoCCLW:
482 case RISCV::PseudoCCLWU:
483 case RISCV::PseudoCCLH:
484 case RISCV::PseudoCCLHU:
485 case RISCV::PseudoCCLB:
486 case RISCV::PseudoCCLBU: {
487 // The SFB Pseudos are like their non-SFB counterparts but have more
488 // operands.
489 if (UseMI.getOperand(2).isFI())
490 return false;
491 // Register defined by Lo should not be the (tied) false value, or a
492 // register used in the branch predicate.
493 if (DestReg == UseMI.getOperand(1).getReg() ||
494 DestReg == UseMI.getOperand(5).getReg())
495 return false;
496 if (UseMI.getOperand(6).isReg() &&
497 DestReg == UseMI.getOperand(6).getReg())
498 return false;
499 assert(DestReg == UseMI.getOperand(2).getReg() &&
500 "Expected base address use");
501 // All load/store instructions must use the same offset.
502 int64_t Offset = UseMI.getOperand(3).getImm();
503 if (CommonOffset && Offset != CommonOffset)
504 return false;
505 CommonOffset = Offset;
506 break;
507 }
508 case RISCV::INLINEASM:
509 case RISCV::INLINEASM_BR: {
510 SmallVector<unsigned> InlineAsmMemoryOpIndexes;
511 unsigned NumOps = 0;
512 for (unsigned I = InlineAsm::MIOp_FirstOperand;
513 I < UseMI.getNumOperands(); I += 1 + NumOps) {
514 const MachineOperand &FlagsMO = UseMI.getOperand(I);
515 // Should be an imm.
516 if (!FlagsMO.isImm())
517 continue;
518
519 const InlineAsm::Flag Flags(FlagsMO.getImm());
520 NumOps = Flags.getNumOperandRegisters();
521
522 // Memory constraints have two operands.
523 if (NumOps != 2 || !Flags.isMemKind()) {
524 // If the register is used by something other than a memory
525 // constraint, we should not fold.
526 for (unsigned J = 0; J < NumOps; ++J) {
527 const MachineOperand &MO = UseMI.getOperand(I + 1 + J);
528 if (MO.isReg() && MO.getReg() == DestReg)
529 return false;
530 }
531 continue;
532 }
533
534 // We can't do this for constraint A because AMO instructions don't have
535 // an immediate offset field.
536 if (Flags.getMemoryConstraintID() == InlineAsm::ConstraintCode::A)
537 return false;
538
539 const MachineOperand &AddrMO = UseMI.getOperand(I + 1);
540 if (!AddrMO.isReg() || AddrMO.getReg() != DestReg)
541 continue;
542
543 const MachineOperand &OffsetMO = UseMI.getOperand(I + 2);
544 if (!OffsetMO.isImm())
545 continue;
546
547 // All inline asm memory operands must use the same offset.
548 int64_t Offset = OffsetMO.getImm();
549 if (CommonOffset && Offset != CommonOffset)
550 return false;
551 CommonOffset = Offset;
552 InlineAsmMemoryOpIndexes.push_back(I + 1);
553 }
554 InlineAsmMemoryOpIndexesMap.insert(
555 std::make_pair(&UseMI, InlineAsmMemoryOpIndexes));
556 break;
557 }
558 }
559 }
560
561 if (!CommonOffset)
562 return false;
563
564 // We found a common offset.
565 // Update the offsets in global address lowering.
566 // We may have already folded some arithmetic so we need to add to any
567 // existing offset.
568 int64_t NewOffset = Hi.getOperand(1).getOffset() + *CommonOffset;
569 // RV32 ignores the upper 32 bits.
570 if (!ST->is64Bit())
571 NewOffset = SignExtend64<32>(NewOffset);
572 // We can only fold simm32 offsets.
573 if (!isInt<32>(NewOffset))
574 return false;
575
576 // Folding changes the value represented by DestReg, so its debug users can
577 // no longer describe the same address.
578 MRI->markUsesInDebugValueAsUndef(DestReg);
579
580 Hi.getOperand(1).setOffset(NewOffset);
581 MachineOperand &ImmOp =
582 Hi.getOpcode() == RISCV::QC_E_LI ? Lo.getOperand(1) : Lo.getOperand(2);
583 auto HiOpc = Hi.getOpcode();
584 // Expand PseudoMovAddr into LUI
585 if (HiOpc == RISCV::PseudoMovAddr) {
586 auto *TII = ST->getInstrInfo();
587 Hi.setDesc(TII->get(RISCV::LUI));
588 Hi.removeOperand(2);
589 }
590
591 if (HiOpc != RISCV::AUIPC)
592 ImmOp.setOffset(NewOffset);
593
594 // Update the immediate in the load/store instructions to add the offset.
595 for (MachineInstr &UseMI :
597 if (UseMI.getOpcode() == RISCV::INLINEASM ||
598 UseMI.getOpcode() == RISCV::INLINEASM_BR) {
599 auto &InlineAsmMemoryOpIndexes = InlineAsmMemoryOpIndexesMap[&UseMI];
600 for (unsigned I : InlineAsmMemoryOpIndexes) {
601 MachineOperand &MO = UseMI.getOperand(I + 1);
603 }
604 } else {
605 unsigned ImmIdx;
606 switch (UseMI.getOpcode()) {
607 case RISCV::INLINEASM:
608 case RISCV::INLINEASM_BR:
609 llvm_unreachable("Should have been dealt with before this else");
610 case RISCV::PseudoCCLD:
611 case RISCV::PseudoCCLW:
612 case RISCV::PseudoCCLWU:
613 case RISCV::PseudoCCLH:
614 case RISCV::PseudoCCLHU:
615 case RISCV::PseudoCCLB:
616 case RISCV::PseudoCCLBU:
617 ImmIdx = 3;
618 break;
619 case RISCV::LB:
620 case RISCV::LH:
621 case RISCV::LH_INX:
622 case RISCV::LW:
623 case RISCV::LW_INX:
624 case RISCV::LBU:
625 case RISCV::LHU:
626 case RISCV::LWU:
627 case RISCV::LD:
628 case RISCV::LD_RV32:
629 case RISCV::FLH:
630 case RISCV::FLW:
631 case RISCV::FLD:
632 case RISCV::SB:
633 case RISCV::SH:
634 case RISCV::SH_INX:
635 case RISCV::SW:
636 case RISCV::SW_INX:
637 case RISCV::SD:
638 case RISCV::SD_RV32:
639 case RISCV::FSH:
640 case RISCV::FSW:
641 case RISCV::FSD:
642 ImmIdx = 2;
643 break;
644 default:
645 llvm_unreachable("Unknown Instruction");
646 }
647
648 MachineOperand &MO = UseMI.getOperand(ImmIdx);
649 if (Hi.getOpcode() == RISCV::QC_E_LI) {
650 MO.ChangeToImmediate(0);
651 } else {
653 }
654 }
655 }
656
657 // Prevent Lo (originally PseudoMovAddr, which is also pointed by Hi) from
658 // being erased
659 if (&Lo == &Hi)
660 return true;
661
662 MRI->replaceRegWith(Lo.getOperand(0).getReg(), Hi.getOperand(0).getReg());
663 Lo.eraseFromParent();
664 return true;
665}
666
667// Try to fold sequences of the form:
668// Hi/lo: qc.e.li vreg1, s -> qc.e.li vreg1, s+imm
669// TailAdd: shxadd vreg2, vreg3, vreg1 -> deleted
670// Tail: lx vreg4, imm(vreg2) -> qc.lrx vreg4, vreg1, vreg3, (1-7)
671bool RISCVMergeBaseOffsetOpt::foldShxaddIntoScaledMemory(MachineInstr &Hi,
672 MachineInstr &Lo) {
673 if (!ST->hasVendorXqcisls() || ST->is64Bit())
674 return false;
675
676 if (Hi.getOpcode() != RISCV::QC_E_LI)
677 return false;
678
679 Register BaseReg = Hi.getOperand(0).getReg();
680 if (!BaseReg.isVirtual() || !MRI->hasOneUse(BaseReg))
681 return false;
682
683 MachineInstr &ShxAdd = *MRI->use_instr_begin(BaseReg);
684 unsigned ShxOpc = ShxAdd.getOpcode();
685 unsigned ShAmt = 0;
686 switch (ShxOpc) {
687 default:
688 return false;
689 case RISCV::SH1ADD:
690 ShAmt = 1;
691 break;
692 case RISCV::SH2ADD:
693 ShAmt = 2;
694 break;
695 case RISCV::SH3ADD:
696 ShAmt = 3;
697 break;
698 case RISCV::QC_SHLADD:
699 uint8_t ShlImm = ShxAdd.getOperand(3).getImm();
700 if (ShlImm > 7)
701 return false;
702 ShAmt = ShlImm;
703 break;
704 }
705
706 // shxadd Rd, Rs1, Rs2
707 Register ScaledReg = ShxAdd.getOperand(0).getReg();
708 Register IndexReg = ShxAdd.getOperand(1).getReg();
709
710 if (!IndexReg.isVirtual())
711 return false;
712
713 if (ShxAdd.getOperand(2).getReg() != BaseReg)
714 return false;
715
716 if (!ScaledReg.isVirtual() || !MRI->hasOneUse(ScaledReg))
717 return false;
718
719 MachineInstr &TailMem = *MRI->use_instr_begin(ScaledReg);
720 unsigned Opc = TailMem.getOpcode();
721 unsigned NewOpc = 0;
722
723 switch (Opc) {
724 case RISCV::LB:
725 NewOpc = RISCV::QC_LRB;
726 break;
727 case RISCV::LBU:
728 NewOpc = RISCV::QC_LRBU;
729 break;
730 case RISCV::LH:
731 NewOpc = RISCV::QC_LRH;
732 break;
733 case RISCV::LHU:
734 NewOpc = RISCV::QC_LRHU;
735 break;
736 case RISCV::LW:
737 NewOpc = RISCV::QC_LRW;
738 break;
739 case RISCV::SB:
740 NewOpc = RISCV::QC_SRB;
741 break;
742 case RISCV::SH:
743 NewOpc = RISCV::QC_SRH;
744 break;
745 case RISCV::SW:
746 NewOpc = RISCV::QC_SRW;
747 break;
748 default:
749 return false;
750 }
751
752 if (!TailMem.getOperand(1).isReg() ||
753 TailMem.getOperand(1).getReg() != ScaledReg)
754 return false;
755 if (!TailMem.getOperand(2).isImm())
756 return false;
757 int64_t Imm = TailMem.getOperand(2).getImm();
758
759 // Update QC_E_LI offset.
760 int64_t NewOffset = SignExtend64<32>(Hi.getOperand(1).getOffset() + Imm);
761
762 Hi.getOperand(1).setOffset(NewOffset);
763
764 // Build scaled load/store.
765 auto *TII = ST->getInstrInfo();
766 auto *MBB = TailMem.getParent();
767
768 // Ensure index register satisfies GPRNoX0 class required by QC_LR*/QC_SR*.
769 MRI->constrainRegClass(IndexReg, &RISCV::GPRNoX0RegClass);
770
771 BuildMI(*MBB, TailMem, TailMem.getDebugLoc(), TII->get(NewOpc))
772 .add(TailMem.getOperand(0))
773 .addReg(BaseReg, getKillRegState(ShxAdd.getOperand(2).isKill()))
774 .addReg(IndexReg, getKillRegState(ShxAdd.getOperand(1).isKill()))
775 .addImm(ShAmt)
776 .cloneMemRefs(TailMem);
777
778 TailMem.eraseFromParent();
779 ShxAdd.eraseFromParent();
780 return true;
781}
782
783bool RISCVMergeBaseOffsetOpt::runOnMachineFunction(MachineFunction &Fn) {
784 if (skipFunction(Fn.getFunction()))
785 return false;
786
787 ST = &Fn.getSubtarget<RISCVSubtarget>();
788
789 bool MadeChange = false;
790 MRI = &Fn.getRegInfo();
791 for (MachineBasicBlock &MBB : Fn) {
792 LLVM_DEBUG(dbgs() << "MBB: " << MBB.getName() << "\n");
793 for (MachineInstr &Hi : MBB) {
794 MachineInstr *Lo = nullptr;
795 if (!detectFoldable(Hi, Lo))
796 continue;
797 MadeChange |= detectAndFoldOffset(Hi, *Lo);
798 MadeChange |= foldIntoMemoryOps(Hi, *Lo);
799 MadeChange |= foldShxaddIntoScaledMemory(Hi, *Lo);
800 }
801 }
802
803 return MadeChange;
804}
805
806/// Returns an instance of the Merge Base Offset Optimization pass.
808 return new RISCVMergeBaseOffsetOpt();
809}
MachineInstrBuilder & UseMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned Imm
unsigned uint64_t
MachineBasicBlock & MBB
#define DEBUG_TYPE
const HexagonInstrInfo * TII
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Promote Memory to Register
Definition Mem2Reg.cpp:110
if(PassOpts->AAPipeline)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static void overwriteMachineOperandInPlace(MachineOperand &MO, const MachineOperand &ImmOp)
#define RISCV_MERGE_BASE_OFFSET_NAME
#define LLVM_DEBUG(...)
Definition Debug.h:119
Represent the analysis usage information of a pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:278
LLVM_ABI TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:843
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Definition Globals.cpp:205
Type * getValueType() const
LLVM_ABI StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Properties which a MachineFunction may have at a given point in time.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Register getReg(unsigned Idx) const
Get the register for the operand index.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & cloneMemRefs(const MachineInstr &OtherMI) const
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
MachineOperand class - Representation of each machine instruction operand.
const GlobalValue * getGlobal() const
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isCPI() const
isCPI - Tests if this is a MO_ConstantPoolIndex operand.
LLVM_ABI void ChangeToMCSymbol(MCSymbol *Sym, unsigned TargetFlags=0)
ChangeToMCSymbol - Replace this operand with a new MC symbol operand.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
LLVM_ABI void ChangeToImmediate(int64_t ImmVal, unsigned TargetFlags=0)
ChangeToImmediate - Replace this operand with a new immediate operand of the specified value.
LLVM_ABI void ChangeToGA(const GlobalValue *GV, int64_t Offset, unsigned TargetFlags=0)
ChangeToGA - Replace this operand with a new global address operand.
LLVM_ABI void ChangeToBA(const BlockAddress *BA, int64_t Offset, unsigned TargetFlags=0)
ChangeToBA - Replace this operand with a new block address operand.
const BlockAddress * getBlockAddress() const
void setOffset(int64_t Offset)
unsigned getTargetFlags() const
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
bool isBlockAddress() const
isBlockAddress - Tests if this is a MO_BlockAddress operand.
Register getReg() const
getReg - Returns the register number.
LLVM_ABI void ChangeToCPI(unsigned Idx, int Offset, unsigned TargetFlags=0)
ChangeToCPI - Replace this operand with a new constant pool index operand.
MCSymbol * getMCSymbol() const
@ MO_ConstantPoolIndex
Address of indexed Constant in Constant Pool.
@ MO_MCSymbol
MCSymbol reference (for debug/eh info)
@ MO_GlobalAddress
Address of a global value.
@ MO_BlockAddress
Address of a basic block.
int64_t getOffset() const
Return the offset from the symbol in this operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI void markUsesInDebugValueAsUndef(Register Reg) const
markUsesInDebugValueAsUndef - Mark every DBG_VALUE referencing the specified register as undefined wh...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
use_instr_iterator use_instr_begin(Register RegNo) const
bool hasOneUse(Register RegNo) const
hasOneUse - Return true if there is exactly one instruction using the specified register.
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(Register Reg) const
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
const RISCVInstrInfo * getInstrInfo() const override
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
void push_back(const T &Elt)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
Definition CallingConv.h:76
BaseReg
Stack frame base register. Bit 0 of FREInfo.Info.
Definition SFrame.h:77
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
constexpr RegState getKillRegState(bool B)
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
FunctionPass * createRISCVMergeBaseOffsetOptPass()
Returns an instance of the Merge Base Offset Optimization pass.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition MathExtras.h:567