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