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.push_back(RISCVMatInt::Inst(RISCV::LUI, Hi20));
66 
67     if (Lo12 || Hi20 == 0) {
68       unsigned AddiOpc = (IsRV64 && Hi20) ? RISCV::ADDIW : RISCV::ADDI;
69       Res.push_back(RISCVMatInt::Inst(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.push_back(RISCVMatInt::Inst(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   int64_t Hi52 = ((uint64_t)Val + 0x800ull) >> 12;
107   int ShiftAmount = 12 + findFirstSet((uint64_t)Hi52);
108   Hi52 = SignExtend64(Hi52 >> (ShiftAmount - 12), 64 - ShiftAmount);
109 
110   // If the remaining bits don't fit in 12 bits, we might be able to reduce the
111   // shift amount in order to use LUI which will zero the lower 12 bits.
112   bool Unsigned = false;
113   if (ShiftAmount > 12 && !isInt<12>(Hi52)) {
114     if (isInt<32>((uint64_t)Hi52 << 12)) {
115       // Reduce the shift amount and add zeros to the LSBs so it will match LUI.
116       ShiftAmount -= 12;
117       Hi52 = (uint64_t)Hi52 << 12;
118     } else if (isUInt<32>((uint64_t)Hi52 << 12) &&
119                ActiveFeatures[RISCV::FeatureStdExtZba]) {
120       // Reduce the shift amount and add zeros to the LSBs so it will match
121       // LUI, then shift left with SLLI.UW to clear the upper 32 set bits.
122       ShiftAmount -= 12;
123       Hi52 = ((uint64_t)Hi52 << 12) | (0xffffffffull << 32);
124       Unsigned = true;
125     }
126   }
127 
128   // Try to use SLLI_UW for Hi52 when it is uint32 but not int32.
129   if (isUInt<32>((uint64_t)Hi52) && !isInt<32>((uint64_t)Hi52) &&
130       ActiveFeatures[RISCV::FeatureStdExtZba]) {
131     // Use LUI+ADDI or LUI to compose, then clear the upper 32 bits with
132     // SLLI_UW.
133     Hi52 = ((uint64_t)Hi52) | (0xffffffffull << 32);
134     Unsigned = true;
135   }
136 
137   generateInstSeqImpl(Hi52, ActiveFeatures, Res);
138 
139   if (Unsigned)
140     Res.push_back(RISCVMatInt::Inst(RISCV::SLLI_UW, ShiftAmount));
141   else
142     Res.push_back(RISCVMatInt::Inst(RISCV::SLLI, ShiftAmount));
143   if (Lo12)
144     Res.push_back(RISCVMatInt::Inst(RISCV::ADDI, Lo12));
145 }
146 
147 static unsigned extractRotateInfo(int64_t Val) {
148   // for case: 0b111..1..xxxxxx1..1..
149   unsigned LeadingOnes = countLeadingOnes((uint64_t)Val);
150   unsigned TrailingOnes = countTrailingOnes((uint64_t)Val);
151   if (TrailingOnes > 0 && TrailingOnes < 64 &&
152       (LeadingOnes + TrailingOnes) > (64 - 12))
153     return 64 - TrailingOnes;
154 
155   // for case: 0bxxx1..1..1...xxx
156   unsigned UpperTrailingOnes = countTrailingOnes(Hi_32(Val));
157   unsigned LowerLeadingOnes = countLeadingOnes(Lo_32(Val));
158   if (UpperTrailingOnes < 32 &&
159       (UpperTrailingOnes + LowerLeadingOnes) > (64 - 12))
160     return 32 - UpperTrailingOnes;
161 
162   return 0;
163 }
164 
165 namespace llvm {
166 namespace RISCVMatInt {
167 InstSeq generateInstSeq(int64_t Val, const FeatureBitset &ActiveFeatures) {
168   RISCVMatInt::InstSeq Res;
169   generateInstSeqImpl(Val, ActiveFeatures, Res);
170 
171   // If there are trailing zeros, try generating a sign extended constant with
172   // no trailing zeros and use a final SLLI to restore them.
173   if ((Val & 1) == 0 && Res.size() > 2) {
174     unsigned TrailingZeros = countTrailingZeros((uint64_t)Val);
175     int64_t ShiftedVal = Val >> TrailingZeros;
176     RISCVMatInt::InstSeq TmpSeq;
177     generateInstSeqImpl(ShiftedVal, ActiveFeatures, TmpSeq);
178     TmpSeq.push_back(RISCVMatInt::Inst(RISCV::SLLI, TrailingZeros));
179 
180     // Keep the new sequence if it is an improvement.
181     if (TmpSeq.size() < Res.size()) {
182       Res = TmpSeq;
183       // A 2 instruction sequence is the best we can do.
184       if (Res.size() <= 2)
185         return Res;
186     }
187   }
188 
189   // If the constant is positive we might be able to generate a shifted constant
190   // with no leading zeros and use a final SRLI to restore them.
191   if (Val > 0 && Res.size() > 2) {
192     assert(ActiveFeatures[RISCV::Feature64Bit] &&
193            "Expected RV32 to only need 2 instructions");
194     unsigned LeadingZeros = countLeadingZeros((uint64_t)Val);
195     uint64_t ShiftedVal = (uint64_t)Val << LeadingZeros;
196     // Fill in the bits that will be shifted out with 1s. An example where this
197     // helps is trailing one masks with 32 or more ones. This will generate
198     // ADDI -1 and an SRLI.
199     ShiftedVal |= maskTrailingOnes<uint64_t>(LeadingZeros);
200 
201     RISCVMatInt::InstSeq TmpSeq;
202     generateInstSeqImpl(ShiftedVal, ActiveFeatures, TmpSeq);
203     TmpSeq.push_back(RISCVMatInt::Inst(RISCV::SRLI, LeadingZeros));
204 
205     // Keep the new sequence if it is an improvement.
206     if (TmpSeq.size() < Res.size()) {
207       Res = TmpSeq;
208       // A 2 instruction sequence is the best we can do.
209       if (Res.size() <= 2)
210         return Res;
211     }
212 
213     // Some cases can benefit from filling the lower bits with zeros instead.
214     ShiftedVal &= maskTrailingZeros<uint64_t>(LeadingZeros);
215     TmpSeq.clear();
216     generateInstSeqImpl(ShiftedVal, ActiveFeatures, TmpSeq);
217     TmpSeq.push_back(RISCVMatInt::Inst(RISCV::SRLI, LeadingZeros));
218 
219     // Keep the new sequence if it is an improvement.
220     if (TmpSeq.size() < Res.size()) {
221       Res = TmpSeq;
222       // A 2 instruction sequence is the best we can do.
223       if (Res.size() <= 2)
224         return Res;
225     }
226 
227     // If we have exactly 32 leading zeros and Zba, we can try using zext.w at
228     // the end of the sequence.
229     if (LeadingZeros == 32 && ActiveFeatures[RISCV::FeatureStdExtZba]) {
230       // Try replacing upper bits with 1.
231       uint64_t LeadingOnesVal = Val | maskLeadingOnes<uint64_t>(LeadingZeros);
232       TmpSeq.clear();
233       generateInstSeqImpl(LeadingOnesVal, ActiveFeatures, TmpSeq);
234       TmpSeq.push_back(RISCVMatInt::Inst(RISCV::ADD_UW, 0));
235 
236       // Keep the new sequence if it is an improvement.
237       if (TmpSeq.size() < Res.size()) {
238         Res = TmpSeq;
239         // A 2 instruction sequence is the best we can do.
240         if (Res.size() <= 2)
241           return Res;
242       }
243     }
244   }
245 
246   // Perform optimization with BCLRI/BSETI in the Zbs extension.
247   if (Res.size() > 2 && ActiveFeatures[RISCV::FeatureStdExtZbs]) {
248     assert(ActiveFeatures[RISCV::Feature64Bit] &&
249            "Expected RV32 to only need 2 instructions");
250 
251     // 1. For values in range 0xffffffff 7fffffff ~ 0xffffffff 00000000,
252     //    call generateInstSeqImpl with Val|0x80000000 (which is expected be
253     //    an int32), then emit (BCLRI r, 31).
254     // 2. For values in range 0x80000000 ~ 0xffffffff, call generateInstSeqImpl
255     //    with Val&~0x80000000 (which is expected to be an int32), then
256     //    emit (BSETI r, 31).
257     int64_t NewVal;
258     unsigned Opc;
259     if (Val < 0) {
260       Opc = RISCV::BCLRI;
261       NewVal = Val | 0x80000000ll;
262     } else {
263       Opc = RISCV::BSETI;
264       NewVal = Val & ~0x80000000ll;
265     }
266     if (isInt<32>(NewVal)) {
267       RISCVMatInt::InstSeq TmpSeq;
268       generateInstSeqImpl(NewVal, ActiveFeatures, TmpSeq);
269       TmpSeq.push_back(RISCVMatInt::Inst(Opc, 31));
270       if (TmpSeq.size() < Res.size())
271         Res = TmpSeq;
272     }
273 
274     // Try to use BCLRI for upper 32 bits if the original lower 32 bits are
275     // negative int32, or use BSETI for upper 32 bits if the original lower
276     // 32 bits are positive int32.
277     int32_t Lo = Val;
278     uint32_t Hi = Val >> 32;
279     Opc = 0;
280     RISCVMatInt::InstSeq TmpSeq;
281     generateInstSeqImpl(Lo, ActiveFeatures, TmpSeq);
282     // Check if it is profitable to use BCLRI/BSETI.
283     if (Lo > 0 && TmpSeq.size() + countPopulation(Hi) < Res.size()) {
284       Opc = RISCV::BSETI;
285     } else if (Lo < 0 && TmpSeq.size() + countPopulation(~Hi) < Res.size()) {
286       Opc = RISCV::BCLRI;
287       Hi = ~Hi;
288     }
289     // Search for each bit and build corresponding BCLRI/BSETI.
290     if (Opc > 0) {
291       while (Hi != 0) {
292         unsigned Bit = countTrailingZeros(Hi);
293         TmpSeq.push_back(RISCVMatInt::Inst(Opc, Bit + 32));
294         Hi &= ~(1 << Bit);
295       }
296       if (TmpSeq.size() < Res.size())
297         Res = TmpSeq;
298     }
299   }
300 
301   // Perform optimization with SH*ADD in the Zba extension.
302   if (Res.size() > 2 && ActiveFeatures[RISCV::FeatureStdExtZba]) {
303     assert(ActiveFeatures[RISCV::Feature64Bit] &&
304            "Expected RV32 to only need 2 instructions");
305     int64_t Div = 0;
306     unsigned Opc = 0;
307     RISCVMatInt::InstSeq TmpSeq;
308     // Select the opcode and divisor.
309     if ((Val % 3) == 0 && isInt<32>(Val / 3)) {
310       Div = 3;
311       Opc = RISCV::SH1ADD;
312     } else if ((Val % 5) == 0 && isInt<32>(Val / 5)) {
313       Div = 5;
314       Opc = RISCV::SH2ADD;
315     } else if ((Val % 9) == 0 && isInt<32>(Val / 9)) {
316       Div = 9;
317       Opc = RISCV::SH3ADD;
318     }
319     // Build the new instruction sequence.
320     if (Div > 0) {
321       generateInstSeqImpl(Val / Div, ActiveFeatures, TmpSeq);
322       TmpSeq.push_back(RISCVMatInt::Inst(Opc, 0));
323       if (TmpSeq.size() < Res.size())
324         Res = TmpSeq;
325     } else {
326       // Try to use LUI+SH*ADD+ADDI.
327       int64_t Hi52 = ((uint64_t)Val + 0x800ull) & ~0xfffull;
328       int64_t Lo12 = SignExtend64<12>(Val);
329       Div = 0;
330       if (isInt<32>(Hi52 / 3) && (Hi52 % 3) == 0) {
331         Div = 3;
332         Opc = RISCV::SH1ADD;
333       } else if (isInt<32>(Hi52 / 5) && (Hi52 % 5) == 0) {
334         Div = 5;
335         Opc = RISCV::SH2ADD;
336       } else if (isInt<32>(Hi52 / 9) && (Hi52 % 9) == 0) {
337         Div = 9;
338         Opc = RISCV::SH3ADD;
339       }
340       // Build the new instruction sequence.
341       if (Div > 0) {
342         // For Val that has zero Lo12 (implies Val equals to Hi52) should has
343         // already been processed to LUI+SH*ADD by previous optimization.
344         assert(Lo12 != 0 &&
345                "unexpected instruction sequence for immediate materialisation");
346         assert(TmpSeq.empty() && "Expected empty TmpSeq");
347         generateInstSeqImpl(Hi52 / Div, ActiveFeatures, TmpSeq);
348         TmpSeq.push_back(RISCVMatInt::Inst(Opc, 0));
349         TmpSeq.push_back(RISCVMatInt::Inst(RISCV::ADDI, Lo12));
350         if (TmpSeq.size() < Res.size())
351           Res = TmpSeq;
352       }
353     }
354   }
355 
356   // Perform optimization with rori in the Zbb extension.
357   if (Res.size() > 2 && ActiveFeatures[RISCV::FeatureStdExtZbb]) {
358     if (unsigned Rotate = extractRotateInfo(Val)) {
359       RISCVMatInt::InstSeq TmpSeq;
360       uint64_t NegImm12 =
361           ((uint64_t)Val >> (64 - Rotate)) | ((uint64_t)Val << Rotate);
362       assert(isInt<12>(NegImm12));
363       TmpSeq.push_back(RISCVMatInt::Inst(RISCV::ADDI, NegImm12));
364       TmpSeq.push_back(RISCVMatInt::Inst(RISCV::RORI, Rotate));
365       Res = TmpSeq;
366     }
367   }
368   return Res;
369 }
370 
371 int getIntMatCost(const APInt &Val, unsigned Size,
372                   const FeatureBitset &ActiveFeatures, bool CompressionCost) {
373   bool IsRV64 = ActiveFeatures[RISCV::Feature64Bit];
374   bool HasRVC = CompressionCost && ActiveFeatures[RISCV::FeatureStdExtC];
375   int PlatRegSize = IsRV64 ? 64 : 32;
376 
377   // Split the constant into platform register sized chunks, and calculate cost
378   // of each chunk.
379   int Cost = 0;
380   for (unsigned ShiftVal = 0; ShiftVal < Size; ShiftVal += PlatRegSize) {
381     APInt Chunk = Val.ashr(ShiftVal).sextOrTrunc(PlatRegSize);
382     InstSeq MatSeq = generateInstSeq(Chunk.getSExtValue(), ActiveFeatures);
383     Cost += getInstSeqCost(MatSeq, HasRVC);
384   }
385   return std::max(1, Cost);
386 }
387 } // namespace RISCVMatInt
388 } // namespace llvm
389