AArch64ExpandImm.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. //===- AArch64ExpandImm.h - AArch64 Immediate Expansion -------------------===//
  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. // This file implements the AArch64ExpandImm stuff.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "AArch64.h"
  13. #include "AArch64ExpandImm.h"
  14. #include "MCTargetDesc/AArch64AddressingModes.h"
  15. using namespace llvm;
  16. using namespace llvm::AArch64_IMM;
  17. /// Helper function which extracts the specified 16-bit chunk from a
  18. /// 64-bit value.
  19. static uint64_t getChunk(uint64_t Imm, unsigned ChunkIdx) {
  20. assert(ChunkIdx < 4 && "Out of range chunk index specified!");
  21. return (Imm >> (ChunkIdx * 16)) & 0xFFFF;
  22. }
  23. /// Check whether the given 16-bit chunk replicated to full 64-bit width
  24. /// can be materialized with an ORR instruction.
  25. static bool canUseOrr(uint64_t Chunk, uint64_t &Encoding) {
  26. Chunk = (Chunk << 48) | (Chunk << 32) | (Chunk << 16) | Chunk;
  27. return AArch64_AM::processLogicalImmediate(Chunk, 64, Encoding);
  28. }
  29. /// Check for identical 16-bit chunks within the constant and if so
  30. /// materialize them with a single ORR instruction. The remaining one or two
  31. /// 16-bit chunks will be materialized with MOVK instructions.
  32. ///
  33. /// This allows us to materialize constants like |A|B|A|A| or |A|B|C|A| (order
  34. /// of the chunks doesn't matter), assuming |A|A|A|A| can be materialized with
  35. /// an ORR instruction.
  36. static bool tryToreplicateChunks(uint64_t UImm,
  37. SmallVectorImpl<ImmInsnModel> &Insn) {
  38. using CountMap = DenseMap<uint64_t, unsigned>;
  39. CountMap Counts;
  40. // Scan the constant and count how often every chunk occurs.
  41. for (unsigned Idx = 0; Idx < 4; ++Idx)
  42. ++Counts[getChunk(UImm, Idx)];
  43. // Traverse the chunks to find one which occurs more than once.
  44. for (const auto &Chunk : Counts) {
  45. const uint64_t ChunkVal = Chunk.first;
  46. const unsigned Count = Chunk.second;
  47. uint64_t Encoding = 0;
  48. // We are looking for chunks which have two or three instances and can be
  49. // materialized with an ORR instruction.
  50. if ((Count != 2 && Count != 3) || !canUseOrr(ChunkVal, Encoding))
  51. continue;
  52. const bool CountThree = Count == 3;
  53. Insn.push_back({ AArch64::ORRXri, 0, Encoding });
  54. unsigned ShiftAmt = 0;
  55. uint64_t Imm16 = 0;
  56. // Find the first chunk not materialized with the ORR instruction.
  57. for (; ShiftAmt < 64; ShiftAmt += 16) {
  58. Imm16 = (UImm >> ShiftAmt) & 0xFFFF;
  59. if (Imm16 != ChunkVal)
  60. break;
  61. }
  62. // Create the first MOVK instruction.
  63. Insn.push_back({ AArch64::MOVKXi, Imm16,
  64. AArch64_AM::getShifterImm(AArch64_AM::LSL, ShiftAmt) });
  65. // In case we have three instances the whole constant is now materialized
  66. // and we can exit.
  67. if (CountThree)
  68. return true;
  69. // Find the remaining chunk which needs to be materialized.
  70. for (ShiftAmt += 16; ShiftAmt < 64; ShiftAmt += 16) {
  71. Imm16 = (UImm >> ShiftAmt) & 0xFFFF;
  72. if (Imm16 != ChunkVal)
  73. break;
  74. }
  75. Insn.push_back({ AArch64::MOVKXi, Imm16,
  76. AArch64_AM::getShifterImm(AArch64_AM::LSL, ShiftAmt) });
  77. return true;
  78. }
  79. return false;
  80. }
  81. /// Check whether this chunk matches the pattern '1...0...'. This pattern
  82. /// starts a contiguous sequence of ones if we look at the bits from the LSB
  83. /// towards the MSB.
  84. static bool isStartChunk(uint64_t Chunk) {
  85. if (Chunk == 0 || Chunk == std::numeric_limits<uint64_t>::max())
  86. return false;
  87. return isMask_64(~Chunk);
  88. }
  89. /// Check whether this chunk matches the pattern '0...1...' This pattern
  90. /// ends a contiguous sequence of ones if we look at the bits from the LSB
  91. /// towards the MSB.
  92. static bool isEndChunk(uint64_t Chunk) {
  93. if (Chunk == 0 || Chunk == std::numeric_limits<uint64_t>::max())
  94. return false;
  95. return isMask_64(Chunk);
  96. }
  97. /// Clear or set all bits in the chunk at the given index.
  98. static uint64_t updateImm(uint64_t Imm, unsigned Idx, bool Clear) {
  99. const uint64_t Mask = 0xFFFF;
  100. if (Clear)
  101. // Clear chunk in the immediate.
  102. Imm &= ~(Mask << (Idx * 16));
  103. else
  104. // Set all bits in the immediate for the particular chunk.
  105. Imm |= Mask << (Idx * 16);
  106. return Imm;
  107. }
  108. /// Check whether the constant contains a sequence of contiguous ones,
  109. /// which might be interrupted by one or two chunks. If so, materialize the
  110. /// sequence of contiguous ones with an ORR instruction.
  111. /// Materialize the chunks which are either interrupting the sequence or outside
  112. /// of the sequence with a MOVK instruction.
  113. ///
  114. /// Assuming S is a chunk which starts the sequence (1...0...), E is a chunk
  115. /// which ends the sequence (0...1...). Then we are looking for constants which
  116. /// contain at least one S and E chunk.
  117. /// E.g. |E|A|B|S|, |A|E|B|S| or |A|B|E|S|.
  118. ///
  119. /// We are also looking for constants like |S|A|B|E| where the contiguous
  120. /// sequence of ones wraps around the MSB into the LSB.
  121. static bool trySequenceOfOnes(uint64_t UImm,
  122. SmallVectorImpl<ImmInsnModel> &Insn) {
  123. const int NotSet = -1;
  124. const uint64_t Mask = 0xFFFF;
  125. int StartIdx = NotSet;
  126. int EndIdx = NotSet;
  127. // Try to find the chunks which start/end a contiguous sequence of ones.
  128. for (int Idx = 0; Idx < 4; ++Idx) {
  129. int64_t Chunk = getChunk(UImm, Idx);
  130. // Sign extend the 16-bit chunk to 64-bit.
  131. Chunk = (Chunk << 48) >> 48;
  132. if (isStartChunk(Chunk))
  133. StartIdx = Idx;
  134. else if (isEndChunk(Chunk))
  135. EndIdx = Idx;
  136. }
  137. // Early exit in case we can't find a start/end chunk.
  138. if (StartIdx == NotSet || EndIdx == NotSet)
  139. return false;
  140. // Outside of the contiguous sequence of ones everything needs to be zero.
  141. uint64_t Outside = 0;
  142. // Chunks between the start and end chunk need to have all their bits set.
  143. uint64_t Inside = Mask;
  144. // If our contiguous sequence of ones wraps around from the MSB into the LSB,
  145. // just swap indices and pretend we are materializing a contiguous sequence
  146. // of zeros surrounded by a contiguous sequence of ones.
  147. if (StartIdx > EndIdx) {
  148. std::swap(StartIdx, EndIdx);
  149. std::swap(Outside, Inside);
  150. }
  151. uint64_t OrrImm = UImm;
  152. int FirstMovkIdx = NotSet;
  153. int SecondMovkIdx = NotSet;
  154. // Find out which chunks we need to patch up to obtain a contiguous sequence
  155. // of ones.
  156. for (int Idx = 0; Idx < 4; ++Idx) {
  157. const uint64_t Chunk = getChunk(UImm, Idx);
  158. // Check whether we are looking at a chunk which is not part of the
  159. // contiguous sequence of ones.
  160. if ((Idx < StartIdx || EndIdx < Idx) && Chunk != Outside) {
  161. OrrImm = updateImm(OrrImm, Idx, Outside == 0);
  162. // Remember the index we need to patch.
  163. if (FirstMovkIdx == NotSet)
  164. FirstMovkIdx = Idx;
  165. else
  166. SecondMovkIdx = Idx;
  167. // Check whether we are looking a chunk which is part of the contiguous
  168. // sequence of ones.
  169. } else if (Idx > StartIdx && Idx < EndIdx && Chunk != Inside) {
  170. OrrImm = updateImm(OrrImm, Idx, Inside != Mask);
  171. // Remember the index we need to patch.
  172. if (FirstMovkIdx == NotSet)
  173. FirstMovkIdx = Idx;
  174. else
  175. SecondMovkIdx = Idx;
  176. }
  177. }
  178. assert(FirstMovkIdx != NotSet && "Constant materializable with single ORR!");
  179. // Create the ORR-immediate instruction.
  180. uint64_t Encoding = 0;
  181. AArch64_AM::processLogicalImmediate(OrrImm, 64, Encoding);
  182. Insn.push_back({ AArch64::ORRXri, 0, Encoding });
  183. const bool SingleMovk = SecondMovkIdx == NotSet;
  184. Insn.push_back({ AArch64::MOVKXi, getChunk(UImm, FirstMovkIdx),
  185. AArch64_AM::getShifterImm(AArch64_AM::LSL,
  186. FirstMovkIdx * 16) });
  187. // Early exit in case we only need to emit a single MOVK instruction.
  188. if (SingleMovk)
  189. return true;
  190. // Create the second MOVK instruction.
  191. Insn.push_back({ AArch64::MOVKXi, getChunk(UImm, SecondMovkIdx),
  192. AArch64_AM::getShifterImm(AArch64_AM::LSL,
  193. SecondMovkIdx * 16) });
  194. return true;
  195. }
  196. /// \brief Expand a MOVi32imm or MOVi64imm pseudo instruction to a
  197. /// MOVZ or MOVN of width BitSize followed by up to 3 MOVK instructions.
  198. static inline void expandMOVImmSimple(uint64_t Imm, unsigned BitSize,
  199. unsigned OneChunks, unsigned ZeroChunks,
  200. SmallVectorImpl<ImmInsnModel> &Insn) {
  201. const unsigned Mask = 0xFFFF;
  202. // Use a MOVZ or MOVN instruction to set the high bits, followed by one or
  203. // more MOVK instructions to insert additional 16-bit portions into the
  204. // lower bits.
  205. bool isNeg = false;
  206. // Use MOVN to materialize the high bits if we have more all one chunks
  207. // than all zero chunks.
  208. if (OneChunks > ZeroChunks) {
  209. isNeg = true;
  210. Imm = ~Imm;
  211. }
  212. unsigned FirstOpc;
  213. if (BitSize == 32) {
  214. Imm &= (1LL << 32) - 1;
  215. FirstOpc = (isNeg ? AArch64::MOVNWi : AArch64::MOVZWi);
  216. } else {
  217. FirstOpc = (isNeg ? AArch64::MOVNXi : AArch64::MOVZXi);
  218. }
  219. unsigned Shift = 0; // LSL amount for high bits with MOVZ/MOVN
  220. unsigned LastShift = 0; // LSL amount for last MOVK
  221. if (Imm != 0) {
  222. unsigned LZ = countLeadingZeros(Imm);
  223. unsigned TZ = countTrailingZeros(Imm);
  224. Shift = (TZ / 16) * 16;
  225. LastShift = ((63 - LZ) / 16) * 16;
  226. }
  227. unsigned Imm16 = (Imm >> Shift) & Mask;
  228. Insn.push_back({ FirstOpc, Imm16,
  229. AArch64_AM::getShifterImm(AArch64_AM::LSL, Shift) });
  230. if (Shift == LastShift)
  231. return;
  232. // If a MOVN was used for the high bits of a negative value, flip the rest
  233. // of the bits back for use with MOVK.
  234. if (isNeg)
  235. Imm = ~Imm;
  236. unsigned Opc = (BitSize == 32 ? AArch64::MOVKWi : AArch64::MOVKXi);
  237. while (Shift < LastShift) {
  238. Shift += 16;
  239. Imm16 = (Imm >> Shift) & Mask;
  240. if (Imm16 == (isNeg ? Mask : 0))
  241. continue; // This 16-bit portion is already set correctly.
  242. Insn.push_back({ Opc, Imm16,
  243. AArch64_AM::getShifterImm(AArch64_AM::LSL, Shift) });
  244. }
  245. }
  246. /// Expand a MOVi32imm or MOVi64imm pseudo instruction to one or more
  247. /// real move-immediate instructions to synthesize the immediate.
  248. void AArch64_IMM::expandMOVImm(uint64_t Imm, unsigned BitSize,
  249. SmallVectorImpl<ImmInsnModel> &Insn) {
  250. const unsigned Mask = 0xFFFF;
  251. // Scan the immediate and count the number of 16-bit chunks which are either
  252. // all ones or all zeros.
  253. unsigned OneChunks = 0;
  254. unsigned ZeroChunks = 0;
  255. for (unsigned Shift = 0; Shift < BitSize; Shift += 16) {
  256. const unsigned Chunk = (Imm >> Shift) & Mask;
  257. if (Chunk == Mask)
  258. OneChunks++;
  259. else if (Chunk == 0)
  260. ZeroChunks++;
  261. }
  262. // Prefer MOVZ/MOVN over ORR because of the rules for the "mov" alias.
  263. if ((BitSize / 16) - OneChunks <= 1 || (BitSize / 16) - ZeroChunks <= 1) {
  264. expandMOVImmSimple(Imm, BitSize, OneChunks, ZeroChunks, Insn);
  265. return;
  266. }
  267. // Try a single ORR.
  268. uint64_t UImm = Imm << (64 - BitSize) >> (64 - BitSize);
  269. uint64_t Encoding;
  270. if (AArch64_AM::processLogicalImmediate(UImm, BitSize, Encoding)) {
  271. unsigned Opc = (BitSize == 32 ? AArch64::ORRWri : AArch64::ORRXri);
  272. Insn.push_back({ Opc, 0, Encoding });
  273. return;
  274. }
  275. // One to up three instruction sequences.
  276. //
  277. // Prefer MOVZ/MOVN followed by MOVK; it's more readable, and possibly the
  278. // fastest sequence with fast literal generation.
  279. if (OneChunks >= (BitSize / 16) - 2 || ZeroChunks >= (BitSize / 16) - 2) {
  280. expandMOVImmSimple(Imm, BitSize, OneChunks, ZeroChunks, Insn);
  281. return;
  282. }
  283. assert(BitSize == 64 && "All 32-bit immediates can be expanded with a"
  284. "MOVZ/MOVK pair");
  285. // Try other two-instruction sequences.
  286. // 64-bit ORR followed by MOVK.
  287. // We try to construct the ORR immediate in three different ways: either we
  288. // zero out the chunk which will be replaced, we fill the chunk which will
  289. // be replaced with ones, or we take the bit pattern from the other half of
  290. // the 64-bit immediate. This is comprehensive because of the way ORR
  291. // immediates are constructed.
  292. for (unsigned Shift = 0; Shift < BitSize; Shift += 16) {
  293. uint64_t ShiftedMask = (0xFFFFULL << Shift);
  294. uint64_t ZeroChunk = UImm & ~ShiftedMask;
  295. uint64_t OneChunk = UImm | ShiftedMask;
  296. uint64_t RotatedImm = (UImm << 32) | (UImm >> 32);
  297. uint64_t ReplicateChunk = ZeroChunk | (RotatedImm & ShiftedMask);
  298. if (AArch64_AM::processLogicalImmediate(ZeroChunk, BitSize, Encoding) ||
  299. AArch64_AM::processLogicalImmediate(OneChunk, BitSize, Encoding) ||
  300. AArch64_AM::processLogicalImmediate(ReplicateChunk, BitSize,
  301. Encoding)) {
  302. // Create the ORR-immediate instruction.
  303. Insn.push_back({ AArch64::ORRXri, 0, Encoding });
  304. // Create the MOVK instruction.
  305. const unsigned Imm16 = getChunk(UImm, Shift / 16);
  306. Insn.push_back({ AArch64::MOVKXi, Imm16,
  307. AArch64_AM::getShifterImm(AArch64_AM::LSL, Shift) });
  308. return;
  309. }
  310. }
  311. // FIXME: Add more two-instruction sequences.
  312. // Three instruction sequences.
  313. //
  314. // Prefer MOVZ/MOVN followed by two MOVK; it's more readable, and possibly
  315. // the fastest sequence with fast literal generation. (If neither MOVK is
  316. // part of a fast literal generation pair, it could be slower than the
  317. // four-instruction sequence, but we won't worry about that for now.)
  318. if (OneChunks || ZeroChunks) {
  319. expandMOVImmSimple(Imm, BitSize, OneChunks, ZeroChunks, Insn);
  320. return;
  321. }
  322. // Check for identical 16-bit chunks within the constant and if so materialize
  323. // them with a single ORR instruction. The remaining one or two 16-bit chunks
  324. // will be materialized with MOVK instructions.
  325. if (BitSize == 64 && tryToreplicateChunks(UImm, Insn))
  326. return;
  327. // Check whether the constant contains a sequence of contiguous ones, which
  328. // might be interrupted by one or two chunks. If so, materialize the sequence
  329. // of contiguous ones with an ORR instruction. Materialize the chunks which
  330. // are either interrupting the sequence or outside of the sequence with a
  331. // MOVK instruction.
  332. if (BitSize == 64 && trySequenceOfOnes(UImm, Insn))
  333. return;
  334. // We found no possible two or three instruction sequence; use the general
  335. // four-instruction sequence.
  336. expandMOVImmSimple(Imm, BitSize, OneChunks, ZeroChunks, Insn);
  337. }