xref: /llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVMatInt.cpp (revision dd3fe52492e90a67e63d9f33b5fafaeb3942066d)
1 //===- RISCVMatInt.cpp - Immediate materialisation -------------*- C++ -*--===//
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 #include "RISCVMatInt.h"
10 #include "MCTargetDesc/RISCVMCTargetDesc.h"
11 #include "llvm/ADT/APInt.h"
12 #include "llvm/Support/MathExtras.h"
13 using namespace llvm;
14 
15 static int getInstSeqCost(RISCVMatInt::InstSeq &Res, bool HasRVC) {
16   if (!HasRVC)
17     return Res.size();
18 
19   int Cost = 0;
20   for (auto Instr : Res) {
21     // Assume instructions that aren't listed aren't compressible.
22     bool Compressed = false;
23     switch (Instr.Opc) {
24     case RISCV::SLLI:
25     case RISCV::SRLI:
26       Compressed = true;
27       break;
28     case RISCV::ADDI:
29     case RISCV::ADDIW:
30     case RISCV::LUI:
31       Compressed = isInt<6>(Instr.Imm);
32       break;
33     }
34     // Two RVC instructions take the same space as one RVI instruction, but
35     // can take longer to execute than the single RVI instruction. Thus, we
36     // consider that two RVC instruction are slightly more costly than one
37     // RVI instruction. For longer sequences of RVC instructions the space
38     // savings can be worth it, though. The costs below try to model that.
39     if (!Compressed)
40       Cost += 100; // Baseline cost of one RVI instruction: 100%.
41     else
42       Cost += 70; // 70% cost of baseline.
43   }
44   return Cost;
45 }
46 
47 // Recursively generate a sequence for materializing an integer.
48 static void generateInstSeqImpl(int64_t Val,
49                                 const FeatureBitset &ActiveFeatures,
50                                 RISCVMatInt::InstSeq &Res) {
51   bool IsRV64 = ActiveFeatures[RISCV::Feature64Bit];
52 
53   if (isInt<32>(Val)) {
54     // Depending on the active bits in the immediate Value v, the following
55     // instruction sequences are emitted:
56     //
57     // v == 0                        : ADDI
58     // v[0,12) != 0 && v[12,32) == 0 : ADDI
59     // v[0,12) == 0 && v[12,32) != 0 : LUI
60     // v[0,32) != 0                  : LUI+ADDI(W)
61     int64_t Hi20 = ((Val + 0x800) >> 12) & 0xFFFFF;
62     int64_t Lo12 = SignExtend64<12>(Val);
63 
64     if (Hi20)
65       Res.emplace_back(RISCV::LUI, Hi20);
66 
67     if (Lo12 || Hi20 == 0) {
68       unsigned AddiOpc = (IsRV64 && Hi20) ? RISCV::ADDIW : RISCV::ADDI;
69       Res.emplace_back(AddiOpc, Lo12);
70     }
71     return;
72   }
73 
74   assert(IsRV64 && "Can't emit >32-bit imm for non-RV64 target");
75 
76   // Use BSETI for a single bit.
77   if (ActiveFeatures[RISCV::FeatureStdExtZbs] && isPowerOf2_64(Val)) {
78     Res.emplace_back(RISCV::BSETI, Log2_64(Val));
79     return;
80   }
81 
82   // In the worst case, for a full 64-bit constant, a sequence of 8 instructions
83   // (i.e., LUI+ADDIW+SLLI+ADDI+SLLI+ADDI+SLLI+ADDI) has to be emitted. Note
84   // that the first two instructions (LUI+ADDIW) can contribute up to 32 bits
85   // while the following ADDI instructions contribute up to 12 bits each.
86   //
87   // On the first glance, implementing this seems to be possible by simply
88   // emitting the most significant 32 bits (LUI+ADDIW) followed by as many left
89   // shift (SLLI) and immediate additions (ADDI) as needed. However, due to the
90   // fact that ADDI performs a sign extended addition, doing it like that would
91   // only be possible when at most 11 bits of the ADDI instructions are used.
92   // Using all 12 bits of the ADDI instructions, like done by GAS, actually
93   // requires that the constant is processed starting with the least significant
94   // bit.
95   //
96   // In the following, constants are processed from LSB to MSB but instruction
97   // emission is performed from MSB to LSB by recursively calling
98   // generateInstSeq. In each recursion, first the lowest 12 bits are removed
99   // from the constant and the optimal shift amount, which can be greater than
100   // 12 bits if the constant is sparse, is determined. Then, the shifted
101   // remaining constant is processed recursively and gets emitted as soon as it
102   // fits into 32 bits. The emission of the shifts and additions is subsequently
103   // performed when the recursion returns.
104 
105   int64_t Lo12 = SignExtend64<12>(Val);
106   Val = (uint64_t)Val - (uint64_t)Lo12;
107 
108   int ShiftAmount = 0;
109   bool Unsigned = false;
110 
111   // Val might now be valid for LUI without needing a shift.
112   if (!isInt<32>(Val)) {
113     ShiftAmount = findFirstSet((uint64_t)Val);
114     Val >>= ShiftAmount;
115 
116     // If the remaining bits don't fit in 12 bits, we might be able to reduce the
117     // shift amount in order to use LUI which will zero the lower 12 bits.
118     if (ShiftAmount > 12 && !isInt<12>(Val)) {
119       if (isInt<32>((uint64_t)Val << 12)) {
120         // Reduce the shift amount and add zeros to the LSBs so it will match LUI.
121         ShiftAmount -= 12;
122         Val = (uint64_t)Val << 12;
123       } else if (isUInt<32>((uint64_t)Val << 12) &&
124                  ActiveFeatures[RISCV::FeatureStdExtZba]) {
125         // Reduce the shift amount and add zeros to the LSBs so it will match
126         // LUI, then shift left with SLLI.UW to clear the upper 32 set bits.
127         ShiftAmount -= 12;
128         Val = ((uint64_t)Val << 12) | (0xffffffffull << 32);
129         Unsigned = true;
130       }
131     }
132 
133     // Try to use SLLI_UW for Val when it is uint32 but not int32.
134     if (isUInt<32>((uint64_t)Val) && !isInt<32>((uint64_t)Val) &&
135         ActiveFeatures[RISCV::FeatureStdExtZba]) {
136       // Use LUI+ADDI or LUI to compose, then clear the upper 32 bits with
137       // SLLI_UW.
138       Val = ((uint64_t)Val) | (0xffffffffull << 32);
139       Unsigned = true;
140     }
141   }
142 
143   generateInstSeqImpl(Val, ActiveFeatures, Res);
144 
145   // Skip shift if we were able to use LUI directly.
146   if (ShiftAmount) {
147     unsigned Opc = Unsigned ? RISCV::SLLI_UW : RISCV::SLLI;
148     Res.emplace_back(Opc, ShiftAmount);
149   }
150 
151   if (Lo12)
152     Res.emplace_back(RISCV::ADDI, Lo12);
153 }
154 
155 static unsigned extractRotateInfo(int64_t Val) {
156   // for case: 0b111..1..xxxxxx1..1..
157   unsigned LeadingOnes = countLeadingOnes((uint64_t)Val);
158   unsigned TrailingOnes = countTrailingOnes((uint64_t)Val);
159   if (TrailingOnes > 0 && TrailingOnes < 64 &&
160       (LeadingOnes + TrailingOnes) > (64 - 12))
161     return 64 - TrailingOnes;
162 
163   // for case: 0bxxx1..1..1...xxx
164   unsigned UpperTrailingOnes = countTrailingOnes(Hi_32(Val));
165   unsigned LowerLeadingOnes = countLeadingOnes(Lo_32(Val));
166   if (UpperTrailingOnes < 32 &&
167       (UpperTrailingOnes + LowerLeadingOnes) > (64 - 12))
168     return 32 - UpperTrailingOnes;
169 
170   return 0;
171 }
172 
173 namespace llvm::RISCVMatInt {
174 InstSeq generateInstSeq(int64_t Val, const FeatureBitset &ActiveFeatures) {
175   RISCVMatInt::InstSeq Res;
176   generateInstSeqImpl(Val, ActiveFeatures, Res);
177 
178   // If there are trailing zeros, try generating a sign extended constant with
179   // no trailing zeros and use a final SLLI to restore them.
180   if ((Val & 1) == 0 && Res.size() > 2) {
181     unsigned TrailingZeros = countTrailingZeros((uint64_t)Val);
182     int64_t ShiftedVal = Val >> TrailingZeros;
183     RISCVMatInt::InstSeq TmpSeq;
184     generateInstSeqImpl(ShiftedVal, ActiveFeatures, TmpSeq);
185     TmpSeq.emplace_back(RISCV::SLLI, TrailingZeros);
186 
187     // Keep the new sequence if it is an improvement.
188     if (TmpSeq.size() < Res.size())
189       Res = TmpSeq;
190   }
191 
192   // If the constant is positive we might be able to generate a shifted constant
193   // with no leading zeros and use a final SRLI to restore them.
194   if (Val > 0 && Res.size() > 2) {
195     assert(ActiveFeatures[RISCV::Feature64Bit] &&
196            "Expected RV32 to only need 2 instructions");
197     unsigned LeadingZeros = countLeadingZeros((uint64_t)Val);
198     uint64_t ShiftedVal = (uint64_t)Val << LeadingZeros;
199     // Fill in the bits that will be shifted out with 1s. An example where this
200     // helps is trailing one masks with 32 or more ones. This will generate
201     // ADDI -1 and an SRLI.
202     ShiftedVal |= maskTrailingOnes<uint64_t>(LeadingZeros);
203 
204     RISCVMatInt::InstSeq TmpSeq;
205     generateInstSeqImpl(ShiftedVal, ActiveFeatures, TmpSeq);
206     TmpSeq.emplace_back(RISCV::SRLI, LeadingZeros);
207 
208     // Keep the new sequence if it is an improvement.
209     if (TmpSeq.size() < Res.size())
210       Res = TmpSeq;
211 
212     // Some cases can benefit from filling the lower bits with zeros instead.
213     ShiftedVal &= maskTrailingZeros<uint64_t>(LeadingZeros);
214     TmpSeq.clear();
215     generateInstSeqImpl(ShiftedVal, ActiveFeatures, TmpSeq);
216     TmpSeq.emplace_back(RISCV::SRLI, LeadingZeros);
217 
218     // Keep the new sequence if it is an improvement.
219     if (TmpSeq.size() < Res.size())
220       Res = TmpSeq;
221 
222     // If we have exactly 32 leading zeros and Zba, we can try using zext.w at
223     // the end of the sequence.
224     if (LeadingZeros == 32 && ActiveFeatures[RISCV::FeatureStdExtZba]) {
225       // Try replacing upper bits with 1.
226       uint64_t LeadingOnesVal = Val | maskLeadingOnes<uint64_t>(LeadingZeros);
227       TmpSeq.clear();
228       generateInstSeqImpl(LeadingOnesVal, ActiveFeatures, TmpSeq);
229       TmpSeq.emplace_back(RISCV::ADD_UW, 0);
230 
231       // Keep the new sequence if it is an improvement.
232       if (TmpSeq.size() < Res.size())
233         Res = TmpSeq;
234     }
235   }
236 
237   // Perform optimization with BCLRI/BSETI in the Zbs extension.
238   if (Res.size() > 2 && ActiveFeatures[RISCV::FeatureStdExtZbs]) {
239     assert(ActiveFeatures[RISCV::Feature64Bit] &&
240            "Expected RV32 to only need 2 instructions");
241 
242     // 1. For values in range 0xffffffff 7fffffff ~ 0xffffffff 00000000,
243     //    call generateInstSeqImpl with Val|0x80000000 (which is expected be
244     //    an int32), then emit (BCLRI r, 31).
245     // 2. For values in range 0x80000000 ~ 0xffffffff, call generateInstSeqImpl
246     //    with Val&~0x80000000 (which is expected to be an int32), then
247     //    emit (BSETI r, 31).
248     int64_t NewVal;
249     unsigned Opc;
250     if (Val < 0) {
251       Opc = RISCV::BCLRI;
252       NewVal = Val | 0x80000000ll;
253     } else {
254       Opc = RISCV::BSETI;
255       NewVal = Val & ~0x80000000ll;
256     }
257     if (isInt<32>(NewVal)) {
258       RISCVMatInt::InstSeq TmpSeq;
259       generateInstSeqImpl(NewVal, ActiveFeatures, TmpSeq);
260       TmpSeq.emplace_back(Opc, 31);
261       if (TmpSeq.size() < Res.size())
262         Res = TmpSeq;
263     }
264 
265     // Try to use BCLRI for upper 32 bits if the original lower 32 bits are
266     // negative int32, or use BSETI for upper 32 bits if the original lower
267     // 32 bits are positive int32.
268     int32_t Lo = Lo_32(Val);
269     uint32_t Hi = Hi_32(Val);
270     Opc = 0;
271     RISCVMatInt::InstSeq TmpSeq;
272     generateInstSeqImpl(Lo, ActiveFeatures, TmpSeq);
273     // Check if it is profitable to use BCLRI/BSETI.
274     if (Lo > 0 && TmpSeq.size() + countPopulation(Hi) < Res.size()) {
275       Opc = RISCV::BSETI;
276     } else if (Lo < 0 && TmpSeq.size() + countPopulation(~Hi) < Res.size()) {
277       Opc = RISCV::BCLRI;
278       Hi = ~Hi;
279     }
280     // Search for each bit and build corresponding BCLRI/BSETI.
281     if (Opc > 0) {
282       while (Hi != 0) {
283         unsigned Bit = findFirstSet(Hi, ZB_Undefined);
284         TmpSeq.emplace_back(Opc, Bit + 32);
285         Hi &= (Hi - 1); // Clear lowest set bit.
286       }
287       if (TmpSeq.size() < Res.size())
288         Res = TmpSeq;
289     }
290   }
291 
292   // Perform optimization with SH*ADD in the Zba extension.
293   if (Res.size() > 2 && ActiveFeatures[RISCV::FeatureStdExtZba]) {
294     assert(ActiveFeatures[RISCV::Feature64Bit] &&
295            "Expected RV32 to only need 2 instructions");
296     int64_t Div = 0;
297     unsigned Opc = 0;
298     RISCVMatInt::InstSeq TmpSeq;
299     // Select the opcode and divisor.
300     if ((Val % 3) == 0 && isInt<32>(Val / 3)) {
301       Div = 3;
302       Opc = RISCV::SH1ADD;
303     } else if ((Val % 5) == 0 && isInt<32>(Val / 5)) {
304       Div = 5;
305       Opc = RISCV::SH2ADD;
306     } else if ((Val % 9) == 0 && isInt<32>(Val / 9)) {
307       Div = 9;
308       Opc = RISCV::SH3ADD;
309     }
310     // Build the new instruction sequence.
311     if (Div > 0) {
312       generateInstSeqImpl(Val / Div, ActiveFeatures, TmpSeq);
313       TmpSeq.emplace_back(Opc, 0);
314       if (TmpSeq.size() < Res.size())
315         Res = TmpSeq;
316     } else {
317       // Try to use LUI+SH*ADD+ADDI.
318       int64_t Hi52 = ((uint64_t)Val + 0x800ull) & ~0xfffull;
319       int64_t Lo12 = SignExtend64<12>(Val);
320       Div = 0;
321       if (isInt<32>(Hi52 / 3) && (Hi52 % 3) == 0) {
322         Div = 3;
323         Opc = RISCV::SH1ADD;
324       } else if (isInt<32>(Hi52 / 5) && (Hi52 % 5) == 0) {
325         Div = 5;
326         Opc = RISCV::SH2ADD;
327       } else if (isInt<32>(Hi52 / 9) && (Hi52 % 9) == 0) {
328         Div = 9;
329         Opc = RISCV::SH3ADD;
330       }
331       // Build the new instruction sequence.
332       if (Div > 0) {
333         // For Val that has zero Lo12 (implies Val equals to Hi52) should has
334         // already been processed to LUI+SH*ADD by previous optimization.
335         assert(Lo12 != 0 &&
336                "unexpected instruction sequence for immediate materialisation");
337         assert(TmpSeq.empty() && "Expected empty TmpSeq");
338         generateInstSeqImpl(Hi52 / Div, ActiveFeatures, TmpSeq);
339         TmpSeq.emplace_back(Opc, 0);
340         TmpSeq.emplace_back(RISCV::ADDI, Lo12);
341         if (TmpSeq.size() < Res.size())
342           Res = TmpSeq;
343       }
344     }
345   }
346 
347   // Perform optimization with rori in the Zbb extension.
348   if (Res.size() > 2 && ActiveFeatures[RISCV::FeatureStdExtZbb]) {
349     if (unsigned Rotate = extractRotateInfo(Val)) {
350       RISCVMatInt::InstSeq TmpSeq;
351       uint64_t NegImm12 =
352           ((uint64_t)Val >> (64 - Rotate)) | ((uint64_t)Val << Rotate);
353       assert(isInt<12>(NegImm12));
354       TmpSeq.emplace_back(RISCV::ADDI, NegImm12);
355       TmpSeq.emplace_back(RISCV::RORI, Rotate);
356       Res = TmpSeq;
357     }
358   }
359   return Res;
360 }
361 
362 int getIntMatCost(const APInt &Val, unsigned Size,
363                   const FeatureBitset &ActiveFeatures, bool CompressionCost) {
364   bool IsRV64 = ActiveFeatures[RISCV::Feature64Bit];
365   bool HasRVC = CompressionCost && ActiveFeatures[RISCV::FeatureStdExtC];
366   int PlatRegSize = IsRV64 ? 64 : 32;
367 
368   // Split the constant into platform register sized chunks, and calculate cost
369   // of each chunk.
370   int Cost = 0;
371   for (unsigned ShiftVal = 0; ShiftVal < Size; ShiftVal += PlatRegSize) {
372     APInt Chunk = Val.ashr(ShiftVal).sextOrTrunc(PlatRegSize);
373     InstSeq MatSeq = generateInstSeq(Chunk.getSExtValue(), ActiveFeatures);
374     Cost += getInstSeqCost(MatSeq, HasRVC);
375   }
376   return std::max(1, Cost);
377 }
378 
379 OpndKind Inst::getOpndKind() const {
380   switch (Opc) {
381   default:
382     llvm_unreachable("Unexpected opcode!");
383   case RISCV::LUI:
384     return RISCVMatInt::Imm;
385   case RISCV::ADD_UW:
386     return RISCVMatInt::RegX0;
387   case RISCV::SH1ADD:
388   case RISCV::SH2ADD:
389   case RISCV::SH3ADD:
390     return RISCVMatInt::RegReg;
391   case RISCV::ADDI:
392   case RISCV::ADDIW:
393   case RISCV::SLLI:
394   case RISCV::SRLI:
395   case RISCV::SLLI_UW:
396   case RISCV::RORI:
397   case RISCV::BSETI:
398   case RISCV::BCLRI:
399     return RISCVMatInt::RegImm;
400   }
401 }
402 
403 } // namespace llvm::RISCVMatInt
404