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