xref: /llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVMatInt.cpp (revision d6cfdf04406a18423dba1536e8770402667f0908)
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 RISCVMatInt::InstSeq
49 generateInstSeqImpl(int64_t Val, 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 Res;
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 Res;
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, ZB_Undefined);
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   Res = generateInstSeqImpl(Val, ActiveFeatures);
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   return Res;
155 }
156 
157 static unsigned extractRotateInfo(int64_t Val) {
158   // for case: 0b111..1..xxxxxx1..1..
159   unsigned LeadingOnes = countLeadingOnes((uint64_t)Val);
160   unsigned TrailingOnes = countTrailingOnes((uint64_t)Val);
161   if (TrailingOnes > 0 && TrailingOnes < 64 &&
162       (LeadingOnes + TrailingOnes) > (64 - 12))
163     return 64 - TrailingOnes;
164 
165   // for case: 0bxxx1..1..1...xxx
166   unsigned UpperTrailingOnes = countTrailingOnes(Hi_32(Val));
167   unsigned LowerLeadingOnes = countLeadingOnes(Lo_32(Val));
168   if (UpperTrailingOnes < 32 &&
169       (UpperTrailingOnes + LowerLeadingOnes) > (64 - 12))
170     return 32 - UpperTrailingOnes;
171 
172   return 0;
173 }
174 
175 namespace llvm::RISCVMatInt {
176 InstSeq generateInstSeq(int64_t Val, const FeatureBitset &ActiveFeatures) {
177   RISCVMatInt::InstSeq Res = generateInstSeqImpl(Val, ActiveFeatures);
178 
179   // If the low 12 bits are non-zero, the first expansion may end with an ADDI
180   // or ADDIW. If there are trailing zeros, try generating a sign extended
181   // constant with no trailing zeros and use a final SLLI to restore them.
182   if ((Val & 0xfff) != 0 && (Val & 1) == 0 && Res.size() >= 2) {
183     unsigned TrailingZeros = countTrailingZeros((uint64_t)Val, ZB_Undefined);
184     int64_t ShiftedVal = Val >> TrailingZeros;
185     // If we can use C.LI+C.SLLI instead of LUI+ADDI(W) prefer that since
186     // its more compressible. But only if LUI+ADDI(W) isn't fusable.
187     // NOTE: We don't check for C extension to minimize differences in generated
188     // code.
189     bool IsShiftedCompressible =
190               isInt<6>(ShiftedVal) && !ActiveFeatures[RISCV::TuneLUIADDIFusion];
191     auto TmpSeq = generateInstSeqImpl(ShiftedVal, ActiveFeatures);
192     TmpSeq.emplace_back(RISCV::SLLI, TrailingZeros);
193 
194     // Keep the new sequence if it is an improvement.
195     if (TmpSeq.size() < Res.size() || IsShiftedCompressible)
196       Res = TmpSeq;
197   }
198 
199   // If the constant is positive we might be able to generate a shifted constant
200   // with no leading zeros and use a final SRLI to restore them.
201   if (Val > 0 && Res.size() > 2) {
202     assert(ActiveFeatures[RISCV::Feature64Bit] &&
203            "Expected RV32 to only need 2 instructions");
204     unsigned LeadingZeros = countLeadingZeros((uint64_t)Val, ZB_Undefined);
205     uint64_t ShiftedVal = (uint64_t)Val << LeadingZeros;
206 
207     {
208       // Fill in the bits that will be shifted out with 1s. An example where
209       // this helps is trailing one masks with 32 or more ones. This will
210       // generate ADDI -1 and an SRLI.
211       ShiftedVal |= maskTrailingOnes<uint64_t>(LeadingZeros);
212       auto TmpSeq = generateInstSeqImpl(ShiftedVal, ActiveFeatures);
213       TmpSeq.emplace_back(RISCV::SRLI, LeadingZeros);
214 
215       // Keep the new sequence if it is an improvement.
216       if (TmpSeq.size() < Res.size())
217         Res = TmpSeq;
218     }
219 
220     {
221       // Some cases can benefit from filling the lower bits with zeros instead.
222       ShiftedVal &= maskTrailingZeros<uint64_t>(LeadingZeros);
223       auto TmpSeq = generateInstSeqImpl(ShiftedVal, ActiveFeatures);
224       TmpSeq.emplace_back(RISCV::SRLI, LeadingZeros);
225 
226       // Keep the new sequence if it is an improvement.
227       if (TmpSeq.size() < Res.size())
228         Res = TmpSeq;
229     }
230 
231     // If we have exactly 32 leading zeros and Zba, we can try using zext.w at
232     // the end of the sequence.
233     if (LeadingZeros == 32 && ActiveFeatures[RISCV::FeatureStdExtZba]) {
234       // Try replacing upper bits with 1.
235       uint64_t LeadingOnesVal = Val | maskLeadingOnes<uint64_t>(LeadingZeros);
236       auto TmpSeq = generateInstSeqImpl(LeadingOnesVal, ActiveFeatures);
237       TmpSeq.emplace_back(RISCV::ADD_UW, 0);
238 
239       // Keep the new sequence if it is an improvement.
240       if (TmpSeq.size() < Res.size())
241         Res = TmpSeq;
242     }
243   }
244 
245   // Perform optimization with BCLRI/BSETI in the Zbs extension.
246   if (Res.size() > 2 && ActiveFeatures[RISCV::FeatureStdExtZbs]) {
247     assert(ActiveFeatures[RISCV::Feature64Bit] &&
248            "Expected RV32 to only need 2 instructions");
249 
250     // 1. For values in range 0xffffffff 7fffffff ~ 0xffffffff 00000000,
251     //    call generateInstSeqImpl with Val|0x80000000 (which is expected be
252     //    an int32), then emit (BCLRI r, 31).
253     // 2. For values in range 0x80000000 ~ 0xffffffff, call generateInstSeqImpl
254     //    with Val&~0x80000000 (which is expected to be an int32), then
255     //    emit (BSETI r, 31).
256     int64_t NewVal;
257     unsigned Opc;
258     if (Val < 0) {
259       Opc = RISCV::BCLRI;
260       NewVal = Val | 0x80000000ll;
261     } else {
262       Opc = RISCV::BSETI;
263       NewVal = Val & ~0x80000000ll;
264     }
265     if (isInt<32>(NewVal)) {
266       auto TmpSeq = generateInstSeqImpl(NewVal, ActiveFeatures);
267       TmpSeq.emplace_back(Opc, 31);
268       if (TmpSeq.size() < Res.size())
269         Res = TmpSeq;
270     }
271 
272     // Try to use BCLRI for upper 32 bits if the original lower 32 bits are
273     // negative int32, or use BSETI for upper 32 bits if the original lower
274     // 32 bits are positive int32.
275     int32_t Lo = Lo_32(Val);
276     uint32_t Hi = Hi_32(Val);
277     Opc = 0;
278     auto TmpSeq = generateInstSeqImpl(Lo, ActiveFeatures);
279     // Check if it is profitable to use BCLRI/BSETI.
280     if (Lo > 0 && TmpSeq.size() + countPopulation(Hi) < Res.size()) {
281       Opc = RISCV::BSETI;
282     } else if (Lo < 0 && TmpSeq.size() + countPopulation(~Hi) < Res.size()) {
283       Opc = RISCV::BCLRI;
284       Hi = ~Hi;
285     }
286     // Search for each bit and build corresponding BCLRI/BSETI.
287     if (Opc > 0) {
288       while (Hi != 0) {
289         unsigned Bit = findFirstSet(Hi, ZB_Undefined);
290         TmpSeq.emplace_back(Opc, Bit + 32);
291         Hi &= (Hi - 1); // Clear lowest set bit.
292       }
293       if (TmpSeq.size() < Res.size())
294         Res = TmpSeq;
295     }
296   }
297 
298   // Perform optimization with SH*ADD in the Zba extension.
299   if (Res.size() > 2 && ActiveFeatures[RISCV::FeatureStdExtZba]) {
300     assert(ActiveFeatures[RISCV::Feature64Bit] &&
301            "Expected RV32 to only need 2 instructions");
302     int64_t Div = 0;
303     unsigned Opc = 0;
304     // Select the opcode and divisor.
305     if ((Val % 3) == 0 && isInt<32>(Val / 3)) {
306       Div = 3;
307       Opc = RISCV::SH1ADD;
308     } else if ((Val % 5) == 0 && isInt<32>(Val / 5)) {
309       Div = 5;
310       Opc = RISCV::SH2ADD;
311     } else if ((Val % 9) == 0 && isInt<32>(Val / 9)) {
312       Div = 9;
313       Opc = RISCV::SH3ADD;
314     }
315     // Build the new instruction sequence.
316     if (Div > 0) {
317       auto TmpSeq = generateInstSeqImpl(Val / Div, ActiveFeatures);
318       TmpSeq.emplace_back(Opc, 0);
319       if (TmpSeq.size() < Res.size())
320         Res = TmpSeq;
321     } else {
322       // Try to use LUI+SH*ADD+ADDI.
323       int64_t Hi52 = ((uint64_t)Val + 0x800ull) & ~0xfffull;
324       int64_t Lo12 = SignExtend64<12>(Val);
325       Div = 0;
326       if (isInt<32>(Hi52 / 3) && (Hi52 % 3) == 0) {
327         Div = 3;
328         Opc = RISCV::SH1ADD;
329       } else if (isInt<32>(Hi52 / 5) && (Hi52 % 5) == 0) {
330         Div = 5;
331         Opc = RISCV::SH2ADD;
332       } else if (isInt<32>(Hi52 / 9) && (Hi52 % 9) == 0) {
333         Div = 9;
334         Opc = RISCV::SH3ADD;
335       }
336       // Build the new instruction sequence.
337       if (Div > 0) {
338         // For Val that has zero Lo12 (implies Val equals to Hi52) should has
339         // already been processed to LUI+SH*ADD by previous optimization.
340         assert(Lo12 != 0 &&
341                "unexpected instruction sequence for immediate materialisation");
342         auto TmpSeq = generateInstSeqImpl(Hi52 / Div, ActiveFeatures);
343         TmpSeq.emplace_back(Opc, 0);
344         TmpSeq.emplace_back(RISCV::ADDI, Lo12);
345         if (TmpSeq.size() < Res.size())
346           Res = TmpSeq;
347       }
348     }
349   }
350 
351   // Perform optimization with rori in the Zbb extension.
352   if (Res.size() > 2 && ActiveFeatures[RISCV::FeatureStdExtZbb]) {
353     if (unsigned Rotate = extractRotateInfo(Val)) {
354       RISCVMatInt::InstSeq TmpSeq;
355       uint64_t NegImm12 =
356           ((uint64_t)Val >> (64 - Rotate)) | ((uint64_t)Val << Rotate);
357       assert(isInt<12>(NegImm12));
358       TmpSeq.emplace_back(RISCV::ADDI, NegImm12);
359       TmpSeq.emplace_back(RISCV::RORI, Rotate);
360       Res = TmpSeq;
361     }
362   }
363   return Res;
364 }
365 
366 int getIntMatCost(const APInt &Val, unsigned Size,
367                   const FeatureBitset &ActiveFeatures, bool CompressionCost) {
368   bool IsRV64 = ActiveFeatures[RISCV::Feature64Bit];
369   bool HasRVC = CompressionCost && ActiveFeatures[RISCV::FeatureStdExtC];
370   int PlatRegSize = IsRV64 ? 64 : 32;
371 
372   // Split the constant into platform register sized chunks, and calculate cost
373   // of each chunk.
374   int Cost = 0;
375   for (unsigned ShiftVal = 0; ShiftVal < Size; ShiftVal += PlatRegSize) {
376     APInt Chunk = Val.ashr(ShiftVal).sextOrTrunc(PlatRegSize);
377     InstSeq MatSeq = generateInstSeq(Chunk.getSExtValue(), ActiveFeatures);
378     Cost += getInstSeqCost(MatSeq, HasRVC);
379   }
380   return std::max(1, Cost);
381 }
382 
383 OpndKind Inst::getOpndKind() const {
384   switch (Opc) {
385   default:
386     llvm_unreachable("Unexpected opcode!");
387   case RISCV::LUI:
388     return RISCVMatInt::Imm;
389   case RISCV::ADD_UW:
390     return RISCVMatInt::RegX0;
391   case RISCV::SH1ADD:
392   case RISCV::SH2ADD:
393   case RISCV::SH3ADD:
394     return RISCVMatInt::RegReg;
395   case RISCV::ADDI:
396   case RISCV::ADDIW:
397   case RISCV::SLLI:
398   case RISCV::SRLI:
399   case RISCV::SLLI_UW:
400   case RISCV::RORI:
401   case RISCV::BSETI:
402   case RISCV::BCLRI:
403     return RISCVMatInt::RegImm;
404   }
405 }
406 
407 } // namespace llvm::RISCVMatInt
408