blob: f7df39ac385e8f4eafcf8d40349aa94ad588ab95 [file] [log] [blame]
Sam Parker3828c6f2018-07-23 12:27:47 +00001//===----- ARMCodeGenPrepare.cpp ------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10/// \file
11/// This pass inserts intrinsics to handle small types that would otherwise be
12/// promoted during legalization. Here we can manually promote types or insert
13/// intrinsics which can handle narrow types that aren't supported by the
14/// register classes.
15//
16//===----------------------------------------------------------------------===//
17
18#include "ARM.h"
19#include "ARMSubtarget.h"
20#include "ARMTargetMachine.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/CodeGen/Passes.h"
23#include "llvm/CodeGen/TargetPassConfig.h"
24#include "llvm/IR/Attributes.h"
25#include "llvm/IR/BasicBlock.h"
26#include "llvm/IR/IRBuilder.h"
27#include "llvm/IR/Constants.h"
28#include "llvm/IR/InstrTypes.h"
29#include "llvm/IR/Instruction.h"
30#include "llvm/IR/Instructions.h"
31#include "llvm/IR/IntrinsicInst.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/Type.h"
34#include "llvm/IR/Value.h"
35#include "llvm/IR/Verifier.h"
36#include "llvm/Pass.h"
37#include "llvm/Support/Casting.h"
38#include "llvm/Support/CommandLine.h"
39
40#define DEBUG_TYPE "arm-codegenprepare"
41
42using namespace llvm;
43
44static cl::opt<bool>
Sam Parker945604d2018-09-11 12:45:43 +000045DisableCGP("arm-disable-cgp", cl::Hidden, cl::init(false),
Sam Parker3828c6f2018-07-23 12:27:47 +000046 cl::desc("Disable ARM specific CodeGenPrepare pass"));
47
48static cl::opt<bool>
49EnableDSP("arm-enable-scalar-dsp", cl::Hidden, cl::init(false),
50 cl::desc("Use DSP instructions for scalar operations"));
51
52static cl::opt<bool>
53EnableDSPWithImms("arm-enable-scalar-dsp-imms", cl::Hidden, cl::init(false),
54 cl::desc("Use DSP instructions for scalar operations\
55 with immediate operands"));
56
Sjoerd Meijer31239a42018-08-17 07:34:01 +000057// The goal of this pass is to enable more efficient code generation for
58// operations on narrow types (i.e. types with < 32-bits) and this is a
59// motivating IR code example:
60//
61// define hidden i32 @cmp(i8 zeroext) {
62// %2 = add i8 %0, -49
63// %3 = icmp ult i8 %2, 3
64// ..
65// }
66//
67// The issue here is that i8 is type-legalized to i32 because i8 is not a
68// legal type. Thus, arithmetic is done in integer-precision, but then the
69// byte value is masked out as follows:
70//
71// t19: i32 = add t4, Constant:i32<-49>
72// t24: i32 = and t19, Constant:i32<255>
73//
74// Consequently, we generate code like this:
75//
76// subs r0, #49
77// uxtb r1, r0
78// cmp r1, #3
79//
80// This shows that masking out the byte value results in generation of
81// the UXTB instruction. This is not optimal as r0 already contains the byte
82// value we need, and so instead we can just generate:
83//
84// sub.w r1, r0, #49
85// cmp r1, #3
86//
87// We achieve this by type promoting the IR to i32 like so for this example:
88//
89// define i32 @cmp(i8 zeroext %c) {
90// %0 = zext i8 %c to i32
91// %c.off = add i32 %0, -49
92// %1 = icmp ult i32 %c.off, 3
93// ..
94// }
95//
96// For this to be valid and legal, we need to prove that the i32 add is
97// producing the same value as the i8 addition, and that e.g. no overflow
98// happens.
99//
100// A brief sketch of the algorithm and some terminology.
101// We pattern match interesting IR patterns:
102// - which have "sources": instructions producing narrow values (i8, i16), and
103// - they have "sinks": instructions consuming these narrow values.
104//
105// We collect all instruction connecting sources and sinks in a worklist, so
106// that we can mutate these instruction and perform type promotion when it is
107// legal to do so.
Sam Parker3828c6f2018-07-23 12:27:47 +0000108
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000109namespace {
Sam Parker3828c6f2018-07-23 12:27:47 +0000110class IRPromoter {
111 SmallPtrSet<Value*, 8> NewInsts;
112 SmallVector<Instruction*, 4> InstsToRemove;
113 Module *M = nullptr;
114 LLVMContext &Ctx;
115
116public:
117 IRPromoter(Module *M) : M(M), Ctx(M->getContext()) { }
118
119 void Cleanup() {
120 for (auto *I : InstsToRemove) {
121 LLVM_DEBUG(dbgs() << "ARM CGP: Removing " << *I << "\n");
122 I->dropAllReferences();
123 I->eraseFromParent();
124 }
125 InstsToRemove.clear();
126 NewInsts.clear();
127 }
128
129 void Mutate(Type *OrigTy,
130 SmallPtrSetImpl<Value*> &Visited,
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000131 SmallPtrSetImpl<Value*> &Sources,
132 SmallPtrSetImpl<Instruction*> &Sinks);
Sam Parker3828c6f2018-07-23 12:27:47 +0000133};
134
135class ARMCodeGenPrepare : public FunctionPass {
136 const ARMSubtarget *ST = nullptr;
137 IRPromoter *Promoter = nullptr;
138 std::set<Value*> AllVisited;
Sam Parker3828c6f2018-07-23 12:27:47 +0000139
Sam Parker3828c6f2018-07-23 12:27:47 +0000140 bool isSupportedValue(Value *V);
141 bool isLegalToPromote(Value *V);
142 bool TryToPromote(Value *V);
143
144public:
145 static char ID;
Sam Parker8c4b9642018-08-10 13:57:13 +0000146 static unsigned TypeSize;
147 Type *OrigTy = nullptr;
Sam Parker3828c6f2018-07-23 12:27:47 +0000148
149 ARMCodeGenPrepare() : FunctionPass(ID) {}
150
Sam Parker3828c6f2018-07-23 12:27:47 +0000151 void getAnalysisUsage(AnalysisUsage &AU) const override {
152 AU.addRequired<TargetPassConfig>();
153 }
154
155 StringRef getPassName() const override { return "ARM IR optimizations"; }
156
157 bool doInitialization(Module &M) override;
158 bool runOnFunction(Function &F) override;
Matt Morehousea70685f2018-07-23 17:00:45 +0000159 bool doFinalization(Module &M) override;
Sam Parker3828c6f2018-07-23 12:27:47 +0000160};
161
162}
163
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000164static bool generateSignBits(Value *V) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000165 if (!isa<Instruction>(V))
166 return false;
167
168 unsigned Opc = cast<Instruction>(V)->getOpcode();
169 return Opc == Instruction::AShr || Opc == Instruction::SDiv ||
170 Opc == Instruction::SRem;
171}
172
173/// Some instructions can use 8- and 16-bit operands, and we don't need to
174/// promote anything larger. We disallow booleans to make life easier when
175/// dealing with icmps but allow any other integer that is <= 16 bits. Void
176/// types are accepted so we can handle switches.
177static bool isSupportedType(Value *V) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000178 LLVM_DEBUG(dbgs() << "ARM CGP: isSupportedType: " << *V << "\n");
179 Type *Ty = V->getType();
Sam Parker7def86b2018-08-15 07:52:35 +0000180
181 // Allow voids and pointers, these won't be promoted.
182 if (Ty->isVoidTy() || Ty->isPointerTy())
Sam Parker3828c6f2018-07-23 12:27:47 +0000183 return true;
184
Sam Parker8c4b9642018-08-10 13:57:13 +0000185 if (auto *Ld = dyn_cast<LoadInst>(V))
186 Ty = cast<PointerType>(Ld->getPointerOperandType())->getElementType();
187
188 const IntegerType *IntTy = dyn_cast<IntegerType>(Ty);
189 if (!IntTy) {
190 LLVM_DEBUG(dbgs() << "ARM CGP: No, not an integer.\n");
Sam Parker3828c6f2018-07-23 12:27:47 +0000191 return false;
Sam Parker8c4b9642018-08-10 13:57:13 +0000192 }
Sam Parker3828c6f2018-07-23 12:27:47 +0000193
Sam Parker8c4b9642018-08-10 13:57:13 +0000194 return IntTy->getBitWidth() == ARMCodeGenPrepare::TypeSize;
195}
Sam Parker3828c6f2018-07-23 12:27:47 +0000196
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000197/// Return true if the given value is a source in the use-def chain, producing
Sam Parker8c4b9642018-08-10 13:57:13 +0000198/// a narrow (i8, i16) value. These values will be zext to start the promotion
199/// of the tree to i32. We guarantee that these won't populate the upper bits
200/// of the register. ZExt on the loads will be free, and the same for call
201/// return values because we only accept ones that guarantee a zeroext ret val.
202/// Many arguments will have the zeroext attribute too, so those would be free
203/// too.
204static bool isSource(Value *V) {
Sam Parker7def86b2018-08-15 07:52:35 +0000205 if (!isa<IntegerType>(V->getType()))
206 return false;
Sam Parker8c4b9642018-08-10 13:57:13 +0000207 // TODO Allow truncs and zext to be sources.
208 if (isa<Argument>(V))
209 return true;
210 else if (isa<LoadInst>(V))
211 return true;
212 else if (auto *Call = dyn_cast<CallInst>(V))
213 return Call->hasRetAttr(Attribute::AttrKind::ZExt);
214 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000215}
216
217/// Return true if V will require any promoted values to be truncated for the
Sam Parker8c4b9642018-08-10 13:57:13 +0000218/// the IR to remain valid. We can't mutate the value type of these
219/// instructions.
Sam Parker3828c6f2018-07-23 12:27:47 +0000220static bool isSink(Value *V) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000221 // TODO The truncate also isn't actually necessary because we would already
222 // proved that the data value is kept within the range of the original data
223 // type.
Sam Parker3828c6f2018-07-23 12:27:47 +0000224 auto UsesNarrowValue = [](Value *V) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000225 return V->getType()->getScalarSizeInBits() == ARMCodeGenPrepare::TypeSize;
Sam Parker3828c6f2018-07-23 12:27:47 +0000226 };
227
228 if (auto *Store = dyn_cast<StoreInst>(V))
229 return UsesNarrowValue(Store->getValueOperand());
230 if (auto *Return = dyn_cast<ReturnInst>(V))
231 return UsesNarrowValue(Return->getReturnValue());
Sam Parker8c4b9642018-08-10 13:57:13 +0000232 if (auto *Trunc = dyn_cast<TruncInst>(V))
233 return UsesNarrowValue(Trunc->getOperand(0));
Sam Parker0e2f0bd2018-08-16 11:54:09 +0000234 if (auto *ZExt = dyn_cast<ZExtInst>(V))
235 return UsesNarrowValue(ZExt->getOperand(0));
Sam Parker13567db2018-08-16 10:05:39 +0000236 if (auto *ICmp = dyn_cast<ICmpInst>(V))
237 return ICmp->isSigned();
Sam Parker3828c6f2018-07-23 12:27:47 +0000238
239 return isa<CallInst>(V);
240}
241
Sam Parker3828c6f2018-07-23 12:27:47 +0000242/// Return whether the instruction can be promoted within any modifications to
243/// it's operands or result.
244static bool isSafeOverflow(Instruction *I) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000245 // FIXME Do we need NSW too?
Sam Parker3828c6f2018-07-23 12:27:47 +0000246 if (isa<OverflowingBinaryOperator>(I) && I->hasNoUnsignedWrap())
247 return true;
248
249 unsigned Opc = I->getOpcode();
250 if (Opc == Instruction::Add || Opc == Instruction::Sub) {
251 // We don't care if the add or sub could wrap if the value is decreasing
252 // and is only being used by an unsigned compare.
253 if (!I->hasOneUse() ||
254 !isa<ICmpInst>(*I->user_begin()) ||
255 !isa<ConstantInt>(I->getOperand(1)))
256 return false;
257
258 auto *CI = cast<ICmpInst>(*I->user_begin());
259 if (CI->isSigned())
260 return false;
261
262 bool NegImm = cast<ConstantInt>(I->getOperand(1))->isNegative();
263 bool IsDecreasing = ((Opc == Instruction::Sub) && !NegImm) ||
264 ((Opc == Instruction::Add) && NegImm);
265 if (!IsDecreasing)
266 return false;
267
268 LLVM_DEBUG(dbgs() << "ARM CGP: Allowing safe overflow for " << *I << "\n");
269 return true;
270 }
271
272 // Otherwise, if an instruction is using a negative immediate we will need
273 // to fix it up during the promotion.
274 for (auto &Op : I->operands()) {
275 if (auto *Const = dyn_cast<ConstantInt>(Op))
276 if (Const->isNegative())
277 return false;
278 }
279 return false;
280}
281
282static bool shouldPromote(Value *V) {
Sam Parker7def86b2018-08-15 07:52:35 +0000283 if (!isa<IntegerType>(V->getType()) || isSink(V)) {
284 LLVM_DEBUG(dbgs() << "ARM CGP: Don't need to promote: " << *V << "\n");
Sam Parker8c4b9642018-08-10 13:57:13 +0000285 return false;
Sam Parker7def86b2018-08-15 07:52:35 +0000286 }
Sam Parker8c4b9642018-08-10 13:57:13 +0000287
288 if (isSource(V))
289 return true;
290
Sam Parker3828c6f2018-07-23 12:27:47 +0000291 auto *I = dyn_cast<Instruction>(V);
292 if (!I)
293 return false;
294
Sam Parker8c4b9642018-08-10 13:57:13 +0000295 if (isa<ICmpInst>(I))
Sam Parker3828c6f2018-07-23 12:27:47 +0000296 return false;
297
Sam Parker3828c6f2018-07-23 12:27:47 +0000298 return true;
299}
300
301/// Return whether we can safely mutate V's type to ExtTy without having to be
302/// concerned with zero extending or truncation.
303static bool isPromotedResultSafe(Value *V) {
304 if (!isa<Instruction>(V))
305 return true;
306
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000307 if (generateSignBits(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000308 return false;
309
310 // If I is only being used by something that will require its value to be
311 // truncated, then we don't care about the promoted result.
312 auto *I = cast<Instruction>(V);
313 if (I->hasOneUse() && isSink(*I->use_begin()))
314 return true;
315
316 if (isa<OverflowingBinaryOperator>(I))
317 return isSafeOverflow(I);
318 return true;
319}
320
321/// Return the intrinsic for the instruction that can perform the same
322/// operation but on a narrow type. This is using the parallel dsp intrinsics
323/// on scalar values.
Sam Parker8c4b9642018-08-10 13:57:13 +0000324static Intrinsic::ID getNarrowIntrinsic(Instruction *I) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000325 // Whether we use the signed or unsigned versions of these intrinsics
326 // doesn't matter because we're not using the GE bits that they set in
327 // the APSR.
328 switch(I->getOpcode()) {
329 default:
330 break;
331 case Instruction::Add:
Sam Parker8c4b9642018-08-10 13:57:13 +0000332 return ARMCodeGenPrepare::TypeSize == 16 ? Intrinsic::arm_uadd16 :
Sam Parker3828c6f2018-07-23 12:27:47 +0000333 Intrinsic::arm_uadd8;
334 case Instruction::Sub:
Sam Parker8c4b9642018-08-10 13:57:13 +0000335 return ARMCodeGenPrepare::TypeSize == 16 ? Intrinsic::arm_usub16 :
Sam Parker3828c6f2018-07-23 12:27:47 +0000336 Intrinsic::arm_usub8;
337 }
338 llvm_unreachable("unhandled opcode for narrow intrinsic");
339}
340
341void IRPromoter::Mutate(Type *OrigTy,
342 SmallPtrSetImpl<Value*> &Visited,
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000343 SmallPtrSetImpl<Value*> &Sources,
344 SmallPtrSetImpl<Instruction*> &Sinks) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000345 IRBuilder<> Builder{Ctx};
346 Type *ExtTy = Type::getInt32Ty(M->getContext());
Sam Parker3828c6f2018-07-23 12:27:47 +0000347 SmallPtrSet<Value*, 8> Promoted;
Sam Parker8c4b9642018-08-10 13:57:13 +0000348 LLVM_DEBUG(dbgs() << "ARM CGP: Promoting use-def chains to from "
349 << ARMCodeGenPrepare::TypeSize << " to 32-bits\n");
Sam Parker3828c6f2018-07-23 12:27:47 +0000350
Sam Parker13567db2018-08-16 10:05:39 +0000351 // Cache original types.
352 DenseMap<Value*, Type*> TruncTysMap;
353 for (auto *V : Visited)
354 TruncTysMap[V] = V->getType();
355
Sam Parker3828c6f2018-07-23 12:27:47 +0000356 auto ReplaceAllUsersOfWith = [&](Value *From, Value *To) {
357 SmallVector<Instruction*, 4> Users;
358 Instruction *InstTo = dyn_cast<Instruction>(To);
359 for (Use &U : From->uses()) {
360 auto *User = cast<Instruction>(U.getUser());
361 if (InstTo && User->isIdenticalTo(InstTo))
362 continue;
363 Users.push_back(User);
364 }
365
366 for (auto &U : Users)
367 U->replaceUsesOfWith(From, To);
368 };
369
370 auto FixConst = [&](ConstantInt *Const, Instruction *I) {
371 Constant *NewConst = nullptr;
372 if (isSafeOverflow(I)) {
373 NewConst = (Const->isNegative()) ?
374 ConstantExpr::getSExt(Const, ExtTy) :
375 ConstantExpr::getZExt(Const, ExtTy);
376 } else {
377 uint64_t NewVal = *Const->getValue().getRawData();
378 if (Const->getType() == Type::getInt16Ty(Ctx))
379 NewVal &= 0xFFFF;
380 else
381 NewVal &= 0xFF;
382 NewConst = ConstantInt::get(ExtTy, NewVal);
383 }
384 I->replaceUsesOfWith(Const, NewConst);
385 };
386
387 auto InsertDSPIntrinsic = [&](Instruction *I) {
388 LLVM_DEBUG(dbgs() << "ARM CGP: Inserting DSP intrinsic for "
389 << *I << "\n");
390 Function *DSPInst =
Sam Parker8c4b9642018-08-10 13:57:13 +0000391 Intrinsic::getDeclaration(M, getNarrowIntrinsic(I));
Sam Parker3828c6f2018-07-23 12:27:47 +0000392 Builder.SetInsertPoint(I);
393 Builder.SetCurrentDebugLocation(I->getDebugLoc());
394 Value *Args[] = { I->getOperand(0), I->getOperand(1) };
395 CallInst *Call = Builder.CreateCall(DSPInst, Args);
396 ReplaceAllUsersOfWith(I, Call);
397 InstsToRemove.push_back(I);
398 NewInsts.insert(Call);
Sam Parker13567db2018-08-16 10:05:39 +0000399 TruncTysMap[Call] = OrigTy;
Sam Parker3828c6f2018-07-23 12:27:47 +0000400 };
401
402 auto InsertZExt = [&](Value *V, Instruction *InsertPt) {
403 LLVM_DEBUG(dbgs() << "ARM CGP: Inserting ZExt for " << *V << "\n");
404 Builder.SetInsertPoint(InsertPt);
405 if (auto *I = dyn_cast<Instruction>(V))
406 Builder.SetCurrentDebugLocation(I->getDebugLoc());
407 auto *ZExt = cast<Instruction>(Builder.CreateZExt(V, ExtTy));
408 if (isa<Argument>(V))
409 ZExt->moveBefore(InsertPt);
410 else
411 ZExt->moveAfter(InsertPt);
412 ReplaceAllUsersOfWith(V, ZExt);
413 NewInsts.insert(ZExt);
Sam Parker13567db2018-08-16 10:05:39 +0000414 TruncTysMap[ZExt] = TruncTysMap[V];
Sam Parker3828c6f2018-07-23 12:27:47 +0000415 };
416
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000417 // First, insert extending instructions between the sources and their users.
418 LLVM_DEBUG(dbgs() << "ARM CGP: Promoting sources:\n");
419 for (auto V : Sources) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000420 LLVM_DEBUG(dbgs() << " - " << *V << "\n");
Sam Parker8c4b9642018-08-10 13:57:13 +0000421 if (auto *I = dyn_cast<Instruction>(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000422 InsertZExt(I, I);
423 else if (auto *Arg = dyn_cast<Argument>(V)) {
424 BasicBlock &BB = Arg->getParent()->front();
425 InsertZExt(Arg, &*BB.getFirstInsertionPt());
426 } else {
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000427 llvm_unreachable("unhandled source that needs extending");
Sam Parker3828c6f2018-07-23 12:27:47 +0000428 }
429 Promoted.insert(V);
430 }
431
432 LLVM_DEBUG(dbgs() << "ARM CGP: Mutating the tree..\n");
433 // Then mutate the types of the instructions within the tree. Here we handle
434 // constant operands.
435 for (auto *V : Visited) {
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000436 if (Sources.count(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000437 continue;
438
Sam Parker3828c6f2018-07-23 12:27:47 +0000439 auto *I = cast<Instruction>(V);
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000440 if (Sinks.count(I))
Sam Parker3828c6f2018-07-23 12:27:47 +0000441 continue;
442
Sam Parker7def86b2018-08-15 07:52:35 +0000443 for (unsigned i = 0, e = I->getNumOperands(); i < e; ++i) {
444 Value *Op = I->getOperand(i);
445 if ((Op->getType() == ExtTy) || !isa<IntegerType>(Op->getType()))
Sam Parker3828c6f2018-07-23 12:27:47 +0000446 continue;
447
Sam Parker7def86b2018-08-15 07:52:35 +0000448 if (auto *Const = dyn_cast<ConstantInt>(Op))
Sam Parker3828c6f2018-07-23 12:27:47 +0000449 FixConst(Const, I);
Sam Parker7def86b2018-08-15 07:52:35 +0000450 else if (isa<UndefValue>(Op))
451 I->setOperand(i, UndefValue::get(ExtTy));
Sam Parker3828c6f2018-07-23 12:27:47 +0000452 }
453
454 if (shouldPromote(I)) {
455 I->mutateType(ExtTy);
456 Promoted.insert(I);
457 }
458 }
459
460 // Now we need to remove any zexts that have become unnecessary, as well
461 // as insert any intrinsics.
462 for (auto *V : Visited) {
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000463 if (Sources.count(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000464 continue;
Sam Parker8c4b9642018-08-10 13:57:13 +0000465
Sam Parker3828c6f2018-07-23 12:27:47 +0000466 if (!shouldPromote(V) || isPromotedResultSafe(V))
467 continue;
468
469 // Replace unsafe instructions with appropriate intrinsic calls.
470 InsertDSPIntrinsic(cast<Instruction>(V));
471 }
472
Sam Parker13567db2018-08-16 10:05:39 +0000473 auto InsertTrunc = [&](Value *V) -> Instruction* {
474 if (!isa<Instruction>(V) || !isa<IntegerType>(V->getType()))
475 return nullptr;
476
Sam Parker0e2f0bd2018-08-16 11:54:09 +0000477 if ((!Promoted.count(V) && !NewInsts.count(V)) || !TruncTysMap.count(V) ||
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000478 Sources.count(V))
Sam Parker13567db2018-08-16 10:05:39 +0000479 return nullptr;
480
481 Type *TruncTy = TruncTysMap[V];
482 if (TruncTy == ExtTy)
483 return nullptr;
484
485 LLVM_DEBUG(dbgs() << "ARM CGP: Creating " << *TruncTy << " Trunc for "
486 << *V << "\n");
487 Builder.SetInsertPoint(cast<Instruction>(V));
488 auto *Trunc = cast<Instruction>(Builder.CreateTrunc(V, TruncTy));
489 NewInsts.insert(Trunc);
490 return Trunc;
491 };
492
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000493 LLVM_DEBUG(dbgs() << "ARM CGP: Fixing up the sinks:\n");
Sam Parker3828c6f2018-07-23 12:27:47 +0000494 // Fix up any stores or returns that use the results of the promoted
495 // chain.
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000496 for (auto I : Sinks) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000497 LLVM_DEBUG(dbgs() << " - " << *I << "\n");
Sam Parker13567db2018-08-16 10:05:39 +0000498
499 // Handle calls separately as we need to iterate over arg operands.
500 if (auto *Call = dyn_cast<CallInst>(I)) {
501 for (unsigned i = 0; i < Call->getNumArgOperands(); ++i) {
502 Value *Arg = Call->getArgOperand(i);
503 if (Instruction *Trunc = InsertTrunc(Arg)) {
504 Trunc->moveBefore(Call);
505 Call->setArgOperand(i, Trunc);
506 }
507 }
508 continue;
Sam Parker3828c6f2018-07-23 12:27:47 +0000509 }
510
Sam Parker13567db2018-08-16 10:05:39 +0000511 // Now handle the others.
Sam Parker3828c6f2018-07-23 12:27:47 +0000512 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
Sam Parker13567db2018-08-16 10:05:39 +0000513 if (Instruction *Trunc = InsertTrunc(I->getOperand(i))) {
514 Trunc->moveBefore(I);
515 I->setOperand(i, Trunc);
Sam Parker3828c6f2018-07-23 12:27:47 +0000516 }
517 }
518 }
Sam Parker0e2f0bd2018-08-16 11:54:09 +0000519 LLVM_DEBUG(dbgs() << "ARM CGP: Mutation complete:\n");
Sam Parker3828c6f2018-07-23 12:27:47 +0000520}
521
Sam Parker8c4b9642018-08-10 13:57:13 +0000522/// We accept most instructions, as well as Arguments and ConstantInsts. We
523/// Disallow casts other than zext and truncs and only allow calls if their
524/// return value is zeroext. We don't allow opcodes that can introduce sign
525/// bits.
526bool ARMCodeGenPrepare::isSupportedValue(Value *V) {
527 LLVM_DEBUG(dbgs() << "ARM CGP: Is " << *V << " supported?\n");
528
Sam Parker13567db2018-08-16 10:05:39 +0000529 if (isa<ICmpInst>(V))
530 return true;
Sam Parker8c4b9642018-08-10 13:57:13 +0000531
532 // Memory instructions
533 if (isa<StoreInst>(V) || isa<GetElementPtrInst>(V))
534 return true;
535
536 // Branches and targets.
537 if( isa<BranchInst>(V) || isa<SwitchInst>(V) || isa<BasicBlock>(V))
538 return true;
539
540 // Non-instruction values that we can handle.
Sam Parker7def86b2018-08-15 07:52:35 +0000541 if ((isa<Constant>(V) && !isa<ConstantExpr>(V)) || isa<Argument>(V))
Sam Parker8c4b9642018-08-10 13:57:13 +0000542 return isSupportedType(V);
543
544 if (isa<PHINode>(V) || isa<SelectInst>(V) || isa<ReturnInst>(V) ||
545 isa<LoadInst>(V))
546 return isSupportedType(V);
547
Sam Parker8c4b9642018-08-10 13:57:13 +0000548 if (auto *Trunc = dyn_cast<TruncInst>(V))
549 return isSupportedType(Trunc->getOperand(0));
550
Sam Parker0e2f0bd2018-08-16 11:54:09 +0000551 if (auto *ZExt = dyn_cast<ZExtInst>(V))
552 return isSupportedType(ZExt->getOperand(0));
553
Sam Parker8c4b9642018-08-10 13:57:13 +0000554 // Special cases for calls as we need to check for zeroext
555 // TODO We should accept calls even if they don't have zeroext, as they can
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000556 // still be sinks.
Sam Parker8c4b9642018-08-10 13:57:13 +0000557 if (auto *Call = dyn_cast<CallInst>(V))
558 return isSupportedType(Call) &&
559 Call->hasRetAttr(Attribute::AttrKind::ZExt);
560
561 if (!isa<BinaryOperator>(V)) {
562 LLVM_DEBUG(dbgs() << "ARM CGP: No, not a binary operator.\n");
563 return false;
564 }
565 if (!isSupportedType(V))
566 return false;
567
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000568 if (generateSignBits(V)) {
569 LLVM_DEBUG(dbgs() << "ARM CGP: No, instruction can generate sign bits.\n");
570 return false;
571 }
572 return true;
Sam Parker8c4b9642018-08-10 13:57:13 +0000573}
574
575/// Check that the type of V would be promoted and that the original type is
576/// smaller than the targeted promoted type. Check that we're not trying to
577/// promote something larger than our base 'TypeSize' type.
578bool ARMCodeGenPrepare::isLegalToPromote(Value *V) {
579 if (isPromotedResultSafe(V))
580 return true;
581
582 auto *I = dyn_cast<Instruction>(V);
583 if (!I)
584 return false;
585
586 // If promotion is not safe, can we use a DSP instruction to natively
587 // handle the narrow type?
Sam Parker3828c6f2018-07-23 12:27:47 +0000588 if (!ST->hasDSP() || !EnableDSP || !isSupportedType(I))
589 return false;
590
591 if (ST->isThumb() && !ST->hasThumb2())
592 return false;
593
594 if (I->getOpcode() != Instruction::Add && I->getOpcode() != Instruction::Sub)
595 return false;
596
597 // TODO
598 // Would it be profitable? For Thumb code, these parallel DSP instructions
599 // are only Thumb-2, so we wouldn't be able to dual issue on Cortex-M33. For
600 // Cortex-A, specifically Cortex-A72, the latency is double and throughput is
601 // halved. They also do not take immediates as operands.
602 for (auto &Op : I->operands()) {
603 if (isa<Constant>(Op)) {
604 if (!EnableDSPWithImms)
605 return false;
606 }
607 }
608 return true;
609}
610
Sam Parker3828c6f2018-07-23 12:27:47 +0000611bool ARMCodeGenPrepare::TryToPromote(Value *V) {
612 OrigTy = V->getType();
613 TypeSize = OrigTy->getPrimitiveSizeInBits();
Sam Parkerfabf7fe2018-08-15 13:29:50 +0000614 if (TypeSize > 16 || TypeSize < 8)
Sam Parker8c4b9642018-08-10 13:57:13 +0000615 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000616
617 if (!isSupportedValue(V) || !shouldPromote(V) || !isLegalToPromote(V))
618 return false;
619
Sam Parker8c4b9642018-08-10 13:57:13 +0000620 LLVM_DEBUG(dbgs() << "ARM CGP: TryToPromote: " << *V << ", TypeSize = "
621 << TypeSize << "\n");
Sam Parker3828c6f2018-07-23 12:27:47 +0000622
623 SetVector<Value*> WorkList;
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000624 SmallPtrSet<Value*, 8> Sources;
625 SmallPtrSet<Instruction*, 4> Sinks;
Sam Parker3828c6f2018-07-23 12:27:47 +0000626 WorkList.insert(V);
627 SmallPtrSet<Value*, 16> CurrentVisited;
628 CurrentVisited.clear();
629
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000630 // Return true if V was added to the worklist as a supported instruction,
631 // if it was already visited, or if we don't need to explore it (e.g.
632 // pointer values and GEPs), and false otherwise.
Sam Parker3828c6f2018-07-23 12:27:47 +0000633 auto AddLegalInst = [&](Value *V) {
634 if (CurrentVisited.count(V))
635 return true;
636
Sam Parker0d511972018-08-16 12:24:40 +0000637 // Ignore GEPs because they don't need promoting and the constant indices
638 // will prevent the transformation.
639 if (isa<GetElementPtrInst>(V))
640 return true;
641
Sam Parker3828c6f2018-07-23 12:27:47 +0000642 if (!isSupportedValue(V) || (shouldPromote(V) && !isLegalToPromote(V))) {
643 LLVM_DEBUG(dbgs() << "ARM CGP: Can't handle: " << *V << "\n");
644 return false;
645 }
646
647 WorkList.insert(V);
648 return true;
649 };
650
651 // Iterate through, and add to, a tree of operands and users in the use-def.
652 while (!WorkList.empty()) {
653 Value *V = WorkList.back();
654 WorkList.pop_back();
655 if (CurrentVisited.count(V))
656 continue;
657
Sam Parker7def86b2018-08-15 07:52:35 +0000658 // Ignore non-instructions, other than arguments.
Sam Parker3828c6f2018-07-23 12:27:47 +0000659 if (!isa<Instruction>(V) && !isSource(V))
660 continue;
661
662 // If we've already visited this value from somewhere, bail now because
663 // the tree has already been explored.
664 // TODO: This could limit the transform, ie if we try to promote something
665 // from an i8 and fail first, before trying an i16.
666 if (AllVisited.count(V)) {
667 LLVM_DEBUG(dbgs() << "ARM CGP: Already visited this: " << *V << "\n");
668 return false;
669 }
670
671 CurrentVisited.insert(V);
672 AllVisited.insert(V);
673
674 // Calls can be both sources and sinks.
675 if (isSink(V))
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000676 Sinks.insert(cast<Instruction>(V));
Sam Parker3828c6f2018-07-23 12:27:47 +0000677 if (isSource(V))
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000678 Sources.insert(V);
Sam Parker3828c6f2018-07-23 12:27:47 +0000679 else if (auto *I = dyn_cast<Instruction>(V)) {
680 // Visit operands of any instruction visited.
681 for (auto &U : I->operands()) {
682 if (!AddLegalInst(U))
683 return false;
684 }
685 }
686
687 // Don't visit users of a node which isn't going to be mutated unless its a
688 // source.
689 if (isSource(V) || shouldPromote(V)) {
690 for (Use &U : V->uses()) {
691 if (!AddLegalInst(U.getUser()))
692 return false;
693 }
694 }
695 }
696
Sam Parker3828c6f2018-07-23 12:27:47 +0000697 LLVM_DEBUG(dbgs() << "ARM CGP: Visited nodes:\n";
698 for (auto *I : CurrentVisited)
699 I->dump();
700 );
Sam Parker7def86b2018-08-15 07:52:35 +0000701 unsigned ToPromote = 0;
702 for (auto *V : CurrentVisited) {
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000703 if (Sources.count(V))
Sam Parker7def86b2018-08-15 07:52:35 +0000704 continue;
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000705 if (Sinks.count(cast<Instruction>(V)))
Sam Parker7def86b2018-08-15 07:52:35 +0000706 continue;
707 ++ToPromote;
708 }
709
710 if (ToPromote < 2)
711 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000712
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000713 Promoter->Mutate(OrigTy, CurrentVisited, Sources, Sinks);
Sam Parker3828c6f2018-07-23 12:27:47 +0000714 return true;
715}
716
717bool ARMCodeGenPrepare::doInitialization(Module &M) {
718 Promoter = new IRPromoter(&M);
719 return false;
720}
721
722bool ARMCodeGenPrepare::runOnFunction(Function &F) {
723 if (skipFunction(F) || DisableCGP)
724 return false;
725
726 auto *TPC = &getAnalysis<TargetPassConfig>();
727 if (!TPC)
728 return false;
729
730 const TargetMachine &TM = TPC->getTM<TargetMachine>();
731 ST = &TM.getSubtarget<ARMSubtarget>(F);
732 bool MadeChange = false;
733 LLVM_DEBUG(dbgs() << "ARM CGP: Running on " << F.getName() << "\n");
734
735 // Search up from icmps to try to promote their operands.
736 for (BasicBlock &BB : F) {
737 auto &Insts = BB.getInstList();
738 for (auto &I : Insts) {
739 if (AllVisited.count(&I))
740 continue;
741
742 if (isa<ICmpInst>(I)) {
743 auto &CI = cast<ICmpInst>(I);
744
745 // Skip signed or pointer compares
746 if (CI.isSigned() || !isa<IntegerType>(CI.getOperand(0)->getType()))
747 continue;
748
749 LLVM_DEBUG(dbgs() << "ARM CGP: Searching from: " << CI << "\n");
750 for (auto &Op : CI.operands()) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000751 if (auto *I = dyn_cast<Instruction>(Op))
752 MadeChange |= TryToPromote(I);
Sam Parker3828c6f2018-07-23 12:27:47 +0000753 }
754 }
755 }
756 Promoter->Cleanup();
757 LLVM_DEBUG(if (verifyFunction(F, &dbgs())) {
758 dbgs();
759 report_fatal_error("Broken function after type promotion");
760 });
761 }
762 if (MadeChange)
763 LLVM_DEBUG(dbgs() << "After ARMCodeGenPrepare: " << F << "\n");
764
765 return MadeChange;
766}
767
Matt Morehousea70685f2018-07-23 17:00:45 +0000768bool ARMCodeGenPrepare::doFinalization(Module &M) {
769 delete Promoter;
770 return false;
771}
772
Sam Parker3828c6f2018-07-23 12:27:47 +0000773INITIALIZE_PASS_BEGIN(ARMCodeGenPrepare, DEBUG_TYPE,
774 "ARM IR optimizations", false, false)
775INITIALIZE_PASS_END(ARMCodeGenPrepare, DEBUG_TYPE, "ARM IR optimizations",
776 false, false)
777
778char ARMCodeGenPrepare::ID = 0;
Sam Parker8c4b9642018-08-10 13:57:13 +0000779unsigned ARMCodeGenPrepare::TypeSize = 0;
Sam Parker3828c6f2018-07-23 12:27:47 +0000780
781FunctionPass *llvm::createARMCodeGenPreparePass() {
782 return new ARMCodeGenPrepare();
783}