1 //===- HexagonGenExtract.cpp ----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/ADT/APInt.h"
11 #include "llvm/ADT/GraphTraits.h"
12 #include "llvm/IR/BasicBlock.h"
13 #include "llvm/IR/CFG.h"
14 #include "llvm/IR/Constants.h"
15 #include "llvm/IR/Dominators.h"
16 #include "llvm/IR/Function.h"
17 #include "llvm/IR/IRBuilder.h"
18 #include "llvm/IR/Instruction.h"
19 #include "llvm/IR/Instructions.h"
20 #include "llvm/IR/Intrinsics.h"
21 #include "llvm/IR/PatternMatch.h"
22 #include "llvm/IR/Type.h"
23 #include "llvm/IR/Value.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Support/CommandLine.h"
32 static cl::opt<unsigned> ExtractCutoff("extract-cutoff", cl::init(~0U),
33 cl::Hidden, cl::desc("Cutoff for generating \"extract\""
36 // This prevents generating extract instructions that have the offset of 0.
37 // One of the reasons for "extract" is to put a sequence of bits in a regis-
38 // ter, starting at offset 0 (so that these bits can then be used by an
39 // "insert"). If the bits are already at offset 0, it is better not to gene-
40 // rate "extract", since logical bit operations can be merged into compound
41 // instructions (as opposed to "extract").
42 static cl::opt<bool> NoSR0("extract-nosr0", cl::init(true), cl::Hidden,
43 cl::desc("No extract instruction with offset 0"));
45 static cl::opt<bool> NeedAnd("extract-needand", cl::init(true), cl::Hidden,
46 cl::desc("Require & in extract patterns"));
50 void initializeHexagonGenExtractPass(PassRegistry&);
51 FunctionPass *createHexagonGenExtract();
53 } // end namespace llvm
57 class HexagonGenExtract : public FunctionPass {
61 HexagonGenExtract() : FunctionPass(ID) {
62 initializeHexagonGenExtractPass(*PassRegistry::getPassRegistry());
65 StringRef getPassName() const override {
66 return "Hexagon generate \"extract\" instructions";
69 bool runOnFunction(Function &F) override;
71 void getAnalysisUsage(AnalysisUsage &AU) const override {
72 AU.addRequired<DominatorTreeWrapperPass>();
73 AU.addPreserved<DominatorTreeWrapperPass>();
74 FunctionPass::getAnalysisUsage(AU);
78 bool visitBlock(BasicBlock *B);
79 bool convert(Instruction *In);
81 unsigned ExtractCount = 0;
85 } // end anonymous namespace
87 char HexagonGenExtract::ID = 0;
89 INITIALIZE_PASS_BEGIN(HexagonGenExtract, "hextract", "Hexagon generate "
90 "\"extract\" instructions", false, false)
91 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
92 INITIALIZE_PASS_END(HexagonGenExtract, "hextract", "Hexagon generate "
93 "\"extract\" instructions", false, false)
95 bool HexagonGenExtract::convert(Instruction *In) {
96 using namespace PatternMatch;
99 ConstantInt *CSL = nullptr, *CSR = nullptr, *CM = nullptr;
100 BasicBlock *BB = In->getParent();
101 LLVMContext &Ctx = BB->getContext();
104 // (and (shl (lshr x, #sr), #sl), #m)
106 bool Match = match(In, m_And(m_Shl(m_LShr(m_Value(BF), m_ConstantInt(CSR)),
111 // (and (shl (ashr x, #sr), #sl), #m)
113 Match = match(In, m_And(m_Shl(m_AShr(m_Value(BF), m_ConstantInt(CSR)),
118 // (and (shl x, #sl), #m)
120 CSR = ConstantInt::get(Type::getInt32Ty(Ctx), 0);
121 Match = match(In, m_And(m_Shl(m_Value(BF), m_ConstantInt(CSL)),
127 // (and (lshr x, #sr), #m)
129 CSL = ConstantInt::get(Type::getInt32Ty(Ctx), 0);
130 Match = match(In, m_And(m_LShr(m_Value(BF), m_ConstantInt(CSR)),
134 // (and (ashr x, #sr), #m)
136 CSL = ConstantInt::get(Type::getInt32Ty(Ctx), 0);
137 Match = match(In, m_And(m_AShr(m_Value(BF), m_ConstantInt(CSR)),
142 // (shl (lshr x, #sr), #sl)
144 Match = match(In, m_Shl(m_LShr(m_Value(BF), m_ConstantInt(CSR)),
145 m_ConstantInt(CSL)));
149 // (shl (ashr x, #sr), #sl)
151 Match = match(In, m_Shl(m_AShr(m_Value(BF), m_ConstantInt(CSR)),
152 m_ConstantInt(CSL)));
157 Type *Ty = BF->getType();
158 if (!Ty->isIntegerTy())
160 unsigned BW = Ty->getPrimitiveSizeInBits();
161 if (BW != 32 && BW != 64)
164 uint32_t SR = CSR->getZExtValue();
165 uint32_t SL = CSL->getZExtValue();
168 // If there was no and, and the shift left did not remove all potential
169 // sign bits created by the shift right, then extractu cannot reproduce
171 if (!LogicalSR && (SR > SL))
173 APInt A = APInt(BW, ~0ULL).lshr(SR).shl(SL);
174 CM = ConstantInt::get(Ctx, A);
177 // CM is the shifted-left mask. Shift it back right to remove the zero
178 // bits on least-significant positions.
179 APInt M = CM->getValue().lshr(SL);
180 uint32_t T = M.countTrailingOnes();
182 // During the shifts some of the bits will be lost. Calculate how many
183 // of the original value will remain after shift right and then left.
184 uint32_t U = BW - std::max(SL, SR);
185 // The width of the extracted field is the minimum of the original bits
186 // that remain after the shifts and the number of contiguous 1s in the mask.
187 uint32_t W = std::min(U, T);
191 // Check if the extracted bits are contained within the mask that it is
192 // and-ed with. The extract operation will copy these bits, and so the
193 // mask cannot any holes in it that would clear any of the bits of the
196 // If the shift right was arithmetic, it could have included some 1 bits.
197 // It is still ok to generate extract, but only if the mask eliminates
198 // those bits (i.e. M does not have any bits set beyond U).
199 APInt C = APInt::getHighBitsSet(BW, BW-U);
200 if (M.intersects(C) || !M.isMask(W))
203 // Check if M starts with a contiguous sequence of W times 1 bits. Get
204 // the low U bits of M (which eliminates the 0 bits shifted in on the
205 // left), and check if the result is APInt's "mask":
206 if (!M.getLoBits(U).isMask(W))
211 Intrinsic::ID IntId = (BW == 32) ? Intrinsic::hexagon_S2_extractu
212 : Intrinsic::hexagon_S2_extractup;
213 Module *Mod = BB->getParent()->getParent();
214 Value *ExtF = Intrinsic::getDeclaration(Mod, IntId);
215 Value *NewIn = IRB.CreateCall(ExtF, {BF, IRB.getInt32(W), IRB.getInt32(SR)});
217 NewIn = IRB.CreateShl(NewIn, SL, CSL->getName());
218 In->replaceAllUsesWith(NewIn);
222 bool HexagonGenExtract::visitBlock(BasicBlock *B) {
223 // Depth-first, bottom-up traversal.
224 for (auto *DTN : children<DomTreeNode*>(DT->getNode(B)))
225 visitBlock(DTN->getBlock());
227 // Allow limiting the number of generated extracts for debugging purposes.
228 bool HasCutoff = ExtractCutoff.getPosition();
229 unsigned Cutoff = ExtractCutoff;
231 bool Changed = false;
232 BasicBlock::iterator I = std::prev(B->end()), NextI, Begin = B->begin();
234 if (HasCutoff && (ExtractCount >= Cutoff))
236 bool Last = (I == Begin);
238 NextI = std::prev(I);
239 Instruction *In = &*I;
240 bool Done = convert(In);
241 if (HasCutoff && Done)
251 bool HexagonGenExtract::runOnFunction(Function &F) {
255 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
258 // Traverse the function bottom-up, to see super-expressions before their
260 BasicBlock *Entry = GraphTraits<Function*>::getEntryNode(&F);
261 Changed = visitBlock(Entry);
266 FunctionPass *llvm::createHexagonGenExtract() {
267 return new HexagonGenExtract();