blob: b631c2bc687b05cd3e63f3a94dbf31489242598d [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>
Hans Wennborg5555c002018-09-24 11:40:07 +000045DisableCGP("arm-disable-cgp", cl::Hidden, cl::init(true),
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;
Sam Parkere7c42dd2018-11-19 11:34:40 +0000112 SmallPtrSet<Instruction*, 4> InstsToRemove;
113 DenseMap<Value*, SmallVector<Type*, 4>> TruncTysMap;
Sam Parker84a2f8b2018-11-01 15:23:42 +0000114 SmallPtrSet<Value*, 8> Promoted;
Sam Parker3828c6f2018-07-23 12:27:47 +0000115 Module *M = nullptr;
116 LLVMContext &Ctx;
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000117 IntegerType *ExtTy = nullptr;
118 IntegerType *OrigTy = nullptr;
Sam Parkere7c42dd2018-11-19 11:34:40 +0000119 SmallPtrSetImpl<Value*> *Visited;
120 SmallPtrSetImpl<Value*> *Sources;
121 SmallPtrSetImpl<Instruction*> *Sinks;
122 SmallPtrSetImpl<Instruction*> *SafeToPromote;
Sam Parker84a2f8b2018-11-01 15:23:42 +0000123
Sam Parkere7c42dd2018-11-19 11:34:40 +0000124 void ReplaceAllUsersOfWith(Value *From, Value *To);
125 void PrepareConstants(void);
126 void ExtendSources(void);
127 void ConvertTruncs(void);
128 void PromoteTree(void);
129 void TruncateSinks(void);
130 void Cleanup(void);
Sam Parker3828c6f2018-07-23 12:27:47 +0000131
132public:
Sam Parker84a2f8b2018-11-01 15:23:42 +0000133 IRPromoter(Module *M) : M(M), Ctx(M->getContext()),
134 ExtTy(Type::getInt32Ty(Ctx)) { }
Sam Parker3828c6f2018-07-23 12:27:47 +0000135
Sam Parker3828c6f2018-07-23 12:27:47 +0000136
137 void Mutate(Type *OrigTy,
138 SmallPtrSetImpl<Value*> &Visited,
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000139 SmallPtrSetImpl<Value*> &Sources,
Sam Parker84a2f8b2018-11-01 15:23:42 +0000140 SmallPtrSetImpl<Instruction*> &Sinks,
141 SmallPtrSetImpl<Instruction*> &SafeToPromote);
Sam Parker3828c6f2018-07-23 12:27:47 +0000142};
143
144class ARMCodeGenPrepare : public FunctionPass {
145 const ARMSubtarget *ST = nullptr;
146 IRPromoter *Promoter = nullptr;
147 std::set<Value*> AllVisited;
Sam Parker84a2f8b2018-11-01 15:23:42 +0000148 SmallPtrSet<Instruction*, 8> SafeToPromote;
Sam Parker3828c6f2018-07-23 12:27:47 +0000149
Sam Parker84a2f8b2018-11-01 15:23:42 +0000150 bool isSafeOverflow(Instruction *I);
Sam Parker3828c6f2018-07-23 12:27:47 +0000151 bool isSupportedValue(Value *V);
152 bool isLegalToPromote(Value *V);
153 bool TryToPromote(Value *V);
154
155public:
156 static char ID;
Sam Parker8c4b9642018-08-10 13:57:13 +0000157 static unsigned TypeSize;
158 Type *OrigTy = nullptr;
Sam Parker3828c6f2018-07-23 12:27:47 +0000159
160 ARMCodeGenPrepare() : FunctionPass(ID) {}
161
Sam Parker3828c6f2018-07-23 12:27:47 +0000162 void getAnalysisUsage(AnalysisUsage &AU) const override {
163 AU.addRequired<TargetPassConfig>();
164 }
165
166 StringRef getPassName() const override { return "ARM IR optimizations"; }
167
168 bool doInitialization(Module &M) override;
169 bool runOnFunction(Function &F) override;
Matt Morehousea70685f2018-07-23 17:00:45 +0000170 bool doFinalization(Module &M) override;
Sam Parker3828c6f2018-07-23 12:27:47 +0000171};
172
173}
174
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000175static bool generateSignBits(Value *V) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000176 if (!isa<Instruction>(V))
177 return false;
178
179 unsigned Opc = cast<Instruction>(V)->getOpcode();
180 return Opc == Instruction::AShr || Opc == Instruction::SDiv ||
181 Opc == Instruction::SRem;
182}
183
Sam Parker08979cd2018-11-09 09:28:27 +0000184static bool EqualTypeSize(Value *V) {
185 return V->getType()->getScalarSizeInBits() == ARMCodeGenPrepare::TypeSize;
186}
187
188static bool LessOrEqualTypeSize(Value *V) {
189 return V->getType()->getScalarSizeInBits() <= ARMCodeGenPrepare::TypeSize;
190}
191
192static bool GreaterThanTypeSize(Value *V) {
193 return V->getType()->getScalarSizeInBits() > ARMCodeGenPrepare::TypeSize;
194}
195
Sam Parkere7c42dd2018-11-19 11:34:40 +0000196static bool LessThanTypeSize(Value *V) {
197 return V->getType()->getScalarSizeInBits() < ARMCodeGenPrepare::TypeSize;
198}
199
Sam Parker3828c6f2018-07-23 12:27:47 +0000200/// Some instructions can use 8- and 16-bit operands, and we don't need to
201/// promote anything larger. We disallow booleans to make life easier when
202/// dealing with icmps but allow any other integer that is <= 16 bits. Void
203/// types are accepted so we can handle switches.
204static bool isSupportedType(Value *V) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000205 Type *Ty = V->getType();
Sam Parker7def86b2018-08-15 07:52:35 +0000206
207 // Allow voids and pointers, these won't be promoted.
208 if (Ty->isVoidTy() || Ty->isPointerTy())
Sam Parker3828c6f2018-07-23 12:27:47 +0000209 return true;
210
Sam Parker8c4b9642018-08-10 13:57:13 +0000211 if (auto *Ld = dyn_cast<LoadInst>(V))
212 Ty = cast<PointerType>(Ld->getPointerOperandType())->getElementType();
213
Sam Parker2804f322018-11-09 15:06:33 +0000214 if (!isa<IntegerType>(Ty) ||
215 cast<IntegerType>(V->getType())->getBitWidth() == 1)
Sam Parker3828c6f2018-07-23 12:27:47 +0000216 return false;
217
Sam Parker08979cd2018-11-09 09:28:27 +0000218 return LessOrEqualTypeSize(V);
Sam Parker8c4b9642018-08-10 13:57:13 +0000219}
Sam Parker3828c6f2018-07-23 12:27:47 +0000220
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000221/// Return true if the given value is a source in the use-def chain, producing
Sam Parkere7c42dd2018-11-19 11:34:40 +0000222/// a narrow 'TypeSize' value. These values will be zext to start the promotion
Sam Parker8c4b9642018-08-10 13:57:13 +0000223/// of the tree to i32. We guarantee that these won't populate the upper bits
224/// of the register. ZExt on the loads will be free, and the same for call
225/// return values because we only accept ones that guarantee a zeroext ret val.
226/// Many arguments will have the zeroext attribute too, so those would be free
227/// too.
228static bool isSource(Value *V) {
Sam Parker7def86b2018-08-15 07:52:35 +0000229 if (!isa<IntegerType>(V->getType()))
230 return false;
Sam Parker2804f322018-11-09 15:06:33 +0000231
Volodymyr Sapsai703ab842018-09-18 00:11:55 +0000232 // TODO Allow zext to be sources.
233 if (isa<Argument>(V))
Sam Parker8c4b9642018-08-10 13:57:13 +0000234 return true;
Volodymyr Sapsai703ab842018-09-18 00:11:55 +0000235 else if (isa<LoadInst>(V))
236 return true;
237 else if (isa<BitCastInst>(V))
238 return true;
239 else if (auto *Call = dyn_cast<CallInst>(V))
240 return Call->hasRetAttr(Attribute::AttrKind::ZExt);
241 else if (auto *Trunc = dyn_cast<TruncInst>(V))
Sam Parker08979cd2018-11-09 09:28:27 +0000242 return EqualTypeSize(Trunc);
Sam Parker8c4b9642018-08-10 13:57:13 +0000243 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000244}
245
246/// Return true if V will require any promoted values to be truncated for the
Sam Parker8c4b9642018-08-10 13:57:13 +0000247/// the IR to remain valid. We can't mutate the value type of these
248/// instructions.
Sam Parker3828c6f2018-07-23 12:27:47 +0000249static bool isSink(Value *V) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000250 // TODO The truncate also isn't actually necessary because we would already
251 // proved that the data value is kept within the range of the original data
252 // type.
Sam Parker3828c6f2018-07-23 12:27:47 +0000253
Sam Parkere7c42dd2018-11-19 11:34:40 +0000254 // Sinks are:
255 // - points where the value in the register is being observed, such as an
256 // icmp, switch or store.
257 // - points where value types have to match, such as calls and returns.
258 // - zext are included to ease the transformation and are generally removed
259 // later on.
Sam Parker3828c6f2018-07-23 12:27:47 +0000260 if (auto *Store = dyn_cast<StoreInst>(V))
Sam Parker08979cd2018-11-09 09:28:27 +0000261 return LessOrEqualTypeSize(Store->getValueOperand());
Sam Parker3828c6f2018-07-23 12:27:47 +0000262 if (auto *Return = dyn_cast<ReturnInst>(V))
Sam Parker08979cd2018-11-09 09:28:27 +0000263 return LessOrEqualTypeSize(Return->getReturnValue());
Sam Parker0e2f0bd2018-08-16 11:54:09 +0000264 if (auto *ZExt = dyn_cast<ZExtInst>(V))
Sam Parker08979cd2018-11-09 09:28:27 +0000265 return GreaterThanTypeSize(ZExt);
Sam Parkere7c42dd2018-11-19 11:34:40 +0000266 if (auto *Switch = dyn_cast<SwitchInst>(V))
267 return LessThanTypeSize(Switch->getCondition());
Sam Parker13567db2018-08-16 10:05:39 +0000268 if (auto *ICmp = dyn_cast<ICmpInst>(V))
Sam Parkere7c42dd2018-11-19 11:34:40 +0000269 return ICmp->isSigned() || LessThanTypeSize(ICmp->getOperand(0));
Sam Parker3828c6f2018-07-23 12:27:47 +0000270
271 return isa<CallInst>(V);
272}
273
Sam Parker3828c6f2018-07-23 12:27:47 +0000274/// Return whether the instruction can be promoted within any modifications to
Sam Parker84a2f8b2018-11-01 15:23:42 +0000275/// its operands or result.
276bool ARMCodeGenPrepare::isSafeOverflow(Instruction *I) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000277 // FIXME Do we need NSW too?
Sam Parker3828c6f2018-07-23 12:27:47 +0000278 if (isa<OverflowingBinaryOperator>(I) && I->hasNoUnsignedWrap())
279 return true;
280
Sam Parker75aca942018-09-26 10:56:00 +0000281 // We can support a, potentially, overflowing instruction (I) if:
282 // - It is only used by an unsigned icmp.
283 // - The icmp uses a constant.
284 // - The overflowing value (I) is decreasing, i.e would underflow - wrapping
285 // around zero to become a larger number than before.
286 // - The underflowing instruction (I) also uses a constant.
287 //
288 // We can then use the two constants to calculate whether the result would
289 // wrap in respect to itself in the original bitwidth. If it doesn't wrap,
290 // just underflows the range, the icmp would give the same result whether the
291 // result has been truncated or not. We calculate this by:
292 // - Zero extending both constants, if needed, to 32-bits.
293 // - Take the absolute value of I's constant, adding this to the icmp const.
294 // - Check that this value is not out of range for small type. If it is, it
295 // means that it has underflowed enough to wrap around the icmp constant.
296 //
297 // For example:
298 //
299 // %sub = sub i8 %a, 2
300 // %cmp = icmp ule i8 %sub, 254
301 //
302 // If %a = 0, %sub = -2 == FE == 254
303 // But if this is evalulated as a i32
304 // %sub = -2 == FF FF FF FE == 4294967294
305 // So the unsigned compares (i8 and i32) would not yield the same result.
306 //
307 // Another way to look at it is:
308 // %a - 2 <= 254
309 // %a + 2 <= 254 + 2
310 // %a <= 256
311 // And we can't represent 256 in the i8 format, so we don't support it.
312 //
313 // Whereas:
314 //
315 // %sub i8 %a, 1
316 // %cmp = icmp ule i8 %sub, 254
317 //
318 // If %a = 0, %sub = -1 == FF == 255
319 // As i32:
320 // %sub = -1 == FF FF FF FF == 4294967295
321 //
322 // In this case, the unsigned compare results would be the same and this
323 // would also be true for ult, uge and ugt:
324 // - (255 < 254) == (0xFFFFFFFF < 254) == false
325 // - (255 <= 254) == (0xFFFFFFFF <= 254) == false
326 // - (255 > 254) == (0xFFFFFFFF > 254) == true
327 // - (255 >= 254) == (0xFFFFFFFF >= 254) == true
328 //
329 // To demonstrate why we can't handle increasing values:
330 //
331 // %add = add i8 %a, 2
332 // %cmp = icmp ult i8 %add, 127
333 //
334 // If %a = 254, %add = 256 == (i8 1)
335 // As i32:
336 // %add = 256
337 //
338 // (1 < 127) != (256 < 127)
339
Sam Parker3828c6f2018-07-23 12:27:47 +0000340 unsigned Opc = I->getOpcode();
Sam Parker75aca942018-09-26 10:56:00 +0000341 if (Opc != Instruction::Add && Opc != Instruction::Sub)
342 return false;
343
344 if (!I->hasOneUse() ||
345 !isa<ICmpInst>(*I->user_begin()) ||
346 !isa<ConstantInt>(I->getOperand(1)))
347 return false;
348
349 ConstantInt *OverflowConst = cast<ConstantInt>(I->getOperand(1));
350 bool NegImm = OverflowConst->isNegative();
351 bool IsDecreasing = ((Opc == Instruction::Sub) && !NegImm) ||
352 ((Opc == Instruction::Add) && NegImm);
353 if (!IsDecreasing)
354 return false;
355
356 // Don't support an icmp that deals with sign bits.
357 auto *CI = cast<ICmpInst>(*I->user_begin());
358 if (CI->isSigned() || CI->isEquality())
359 return false;
360
361 ConstantInt *ICmpConst = nullptr;
362 if (auto *Const = dyn_cast<ConstantInt>(CI->getOperand(0)))
363 ICmpConst = Const;
364 else if (auto *Const = dyn_cast<ConstantInt>(CI->getOperand(1)))
365 ICmpConst = Const;
366 else
367 return false;
368
369 // Now check that the result can't wrap on itself.
370 APInt Total = ICmpConst->getValue().getBitWidth() < 32 ?
371 ICmpConst->getValue().zext(32) : ICmpConst->getValue();
372
373 Total += OverflowConst->getValue().getBitWidth() < 32 ?
374 OverflowConst->getValue().abs().zext(32) : OverflowConst->getValue().abs();
375
376 APInt Max = APInt::getAllOnesValue(ARMCodeGenPrepare::TypeSize);
377
378 if (Total.getBitWidth() > Max.getBitWidth()) {
379 if (Total.ugt(Max.zext(Total.getBitWidth())))
Sam Parker3828c6f2018-07-23 12:27:47 +0000380 return false;
Sam Parker75aca942018-09-26 10:56:00 +0000381 } else if (Max.getBitWidth() > Total.getBitWidth()) {
382 if (Total.zext(Max.getBitWidth()).ugt(Max))
Sam Parker3828c6f2018-07-23 12:27:47 +0000383 return false;
Sam Parker75aca942018-09-26 10:56:00 +0000384 } else if (Total.ugt(Max))
385 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000386
Sam Parker75aca942018-09-26 10:56:00 +0000387 LLVM_DEBUG(dbgs() << "ARM CGP: Allowing safe overflow for " << *I << "\n");
388 return true;
Sam Parker3828c6f2018-07-23 12:27:47 +0000389}
390
391static bool shouldPromote(Value *V) {
Sam Parkeraaec3c62018-09-13 15:14:12 +0000392 if (!isa<IntegerType>(V->getType()) || isSink(V))
Sam Parker8c4b9642018-08-10 13:57:13 +0000393 return false;
394
395 if (isSource(V))
396 return true;
397
Sam Parker3828c6f2018-07-23 12:27:47 +0000398 auto *I = dyn_cast<Instruction>(V);
399 if (!I)
400 return false;
401
Sam Parker8c4b9642018-08-10 13:57:13 +0000402 if (isa<ICmpInst>(I))
Sam Parker3828c6f2018-07-23 12:27:47 +0000403 return false;
404
Sam Parker3828c6f2018-07-23 12:27:47 +0000405 return true;
406}
407
408/// Return whether we can safely mutate V's type to ExtTy without having to be
409/// concerned with zero extending or truncation.
410static bool isPromotedResultSafe(Value *V) {
411 if (!isa<Instruction>(V))
412 return true;
413
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000414 if (generateSignBits(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000415 return false;
416
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000417 return !isa<OverflowingBinaryOperator>(V);
Sam Parker3828c6f2018-07-23 12:27:47 +0000418}
419
420/// Return the intrinsic for the instruction that can perform the same
421/// operation but on a narrow type. This is using the parallel dsp intrinsics
422/// on scalar values.
Sam Parker8c4b9642018-08-10 13:57:13 +0000423static Intrinsic::ID getNarrowIntrinsic(Instruction *I) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000424 // Whether we use the signed or unsigned versions of these intrinsics
425 // doesn't matter because we're not using the GE bits that they set in
426 // the APSR.
427 switch(I->getOpcode()) {
428 default:
429 break;
430 case Instruction::Add:
Sam Parker8c4b9642018-08-10 13:57:13 +0000431 return ARMCodeGenPrepare::TypeSize == 16 ? Intrinsic::arm_uadd16 :
Sam Parker3828c6f2018-07-23 12:27:47 +0000432 Intrinsic::arm_uadd8;
433 case Instruction::Sub:
Sam Parker8c4b9642018-08-10 13:57:13 +0000434 return ARMCodeGenPrepare::TypeSize == 16 ? Intrinsic::arm_usub16 :
Sam Parker3828c6f2018-07-23 12:27:47 +0000435 Intrinsic::arm_usub8;
436 }
437 llvm_unreachable("unhandled opcode for narrow intrinsic");
438}
439
Sam Parkere7c42dd2018-11-19 11:34:40 +0000440void IRPromoter::ReplaceAllUsersOfWith(Value *From, Value *To) {
Sam Parker84a2f8b2018-11-01 15:23:42 +0000441 SmallVector<Instruction*, 4> Users;
442 Instruction *InstTo = dyn_cast<Instruction>(To);
Sam Parkere7c42dd2018-11-19 11:34:40 +0000443 bool ReplacedAll = true;
444
445 LLVM_DEBUG(dbgs() << "ARM CGP: Replacing " << *From << " with " << *To
446 << "\n");
447
Sam Parker84a2f8b2018-11-01 15:23:42 +0000448 for (Use &U : From->uses()) {
449 auto *User = cast<Instruction>(U.getUser());
Sam Parkere7c42dd2018-11-19 11:34:40 +0000450 if (InstTo && User->isIdenticalTo(InstTo)) {
451 ReplacedAll = false;
Sam Parker84a2f8b2018-11-01 15:23:42 +0000452 continue;
Sam Parkere7c42dd2018-11-19 11:34:40 +0000453 }
Sam Parker84a2f8b2018-11-01 15:23:42 +0000454 Users.push_back(User);
455 }
456
457 for (auto *U : Users)
458 U->replaceUsesOfWith(From, To);
Sam Parkere7c42dd2018-11-19 11:34:40 +0000459
460 if (ReplacedAll)
461 if (auto *I = dyn_cast<Instruction>(From))
462 InstsToRemove.insert(I);
Sam Parker84a2f8b2018-11-01 15:23:42 +0000463}
464
Sam Parkere7c42dd2018-11-19 11:34:40 +0000465void IRPromoter::PrepareConstants() {
Sam Parker3828c6f2018-07-23 12:27:47 +0000466 IRBuilder<> Builder{Ctx};
Sam Parker84a2f8b2018-11-01 15:23:42 +0000467 // First step is to prepare the instructions for mutation. Most constants
468 // just need to be zero extended into their new type, but complications arise
469 // because:
470 // - For nuw binary operators, negative immediates would need sign extending;
471 // however, instead we'll change them to positive and zext them. We can do
472 // this because:
473 // > The operators that can wrap are: add, sub, mul and shl.
474 // > shl interprets its second operand as unsigned and if the first operand
475 // is an immediate, it will need zext to be nuw.
Sam Parkerfec793c2018-11-05 11:26:04 +0000476 // > I'm assuming mul has to interpret immediates as unsigned for nuw.
Sam Parker84a2f8b2018-11-01 15:23:42 +0000477 // > Which leaves the nuw add and sub to be handled; as with shl, if an
478 // immediate is used as operand 0, it will need zext to be nuw.
479 // - We also allow add and sub to safely overflow in certain circumstances
480 // and only when the value (operand 0) is being decreased.
481 //
482 // For adds and subs, that are either nuw or safely wrap and use a negative
483 // immediate as operand 1, we create an equivalent instruction using a
484 // positive immediate. That positive immediate can then be zext along with
485 // all the other immediates later.
Sam Parkere7c42dd2018-11-19 11:34:40 +0000486 for (auto *V : *Visited) {
Sam Parker84a2f8b2018-11-01 15:23:42 +0000487 if (!isa<Instruction>(V))
488 continue;
Sam Parker3828c6f2018-07-23 12:27:47 +0000489
Sam Parker84a2f8b2018-11-01 15:23:42 +0000490 auto *I = cast<Instruction>(V);
Sam Parkere7c42dd2018-11-19 11:34:40 +0000491 if (SafeToPromote->count(I)) {
Sam Parker13567db2018-08-16 10:05:39 +0000492
Sam Parker84a2f8b2018-11-01 15:23:42 +0000493 if (!isa<OverflowingBinaryOperator>(I))
Sam Parker3828c6f2018-07-23 12:27:47 +0000494 continue;
Sam Parker84a2f8b2018-11-01 15:23:42 +0000495
496 if (auto *Const = dyn_cast<ConstantInt>(I->getOperand(1))) {
497 if (!Const->isNegative())
498 break;
499
500 unsigned Opc = I->getOpcode();
Sam Parkerfec793c2018-11-05 11:26:04 +0000501 if (Opc != Instruction::Add && Opc != Instruction::Sub)
502 continue;
Sam Parker84a2f8b2018-11-01 15:23:42 +0000503
504 LLVM_DEBUG(dbgs() << "ARM CGP: Adjusting " << *I << "\n");
505 auto *NewConst = ConstantInt::get(Ctx, Const->getValue().abs());
506 Builder.SetInsertPoint(I);
507 Value *NewVal = Opc == Instruction::Sub ?
508 Builder.CreateAdd(I->getOperand(0), NewConst) :
509 Builder.CreateSub(I->getOperand(0), NewConst);
510 LLVM_DEBUG(dbgs() << "ARM CGP: New equivalent: " << *NewVal << "\n");
511
512 if (auto *NewInst = dyn_cast<Instruction>(NewVal)) {
513 NewInst->copyIRFlags(I);
514 NewInsts.insert(NewInst);
515 }
Sam Parkere7c42dd2018-11-19 11:34:40 +0000516 InstsToRemove.insert(I);
Sam Parker84a2f8b2018-11-01 15:23:42 +0000517 I->replaceAllUsesWith(NewVal);
518 }
Sam Parker3828c6f2018-07-23 12:27:47 +0000519 }
Sam Parker84a2f8b2018-11-01 15:23:42 +0000520 }
521 for (auto *I : NewInsts)
Sam Parkere7c42dd2018-11-19 11:34:40 +0000522 Visited->insert(I);
Sam Parker84a2f8b2018-11-01 15:23:42 +0000523}
Sam Parker3828c6f2018-07-23 12:27:47 +0000524
Sam Parkere7c42dd2018-11-19 11:34:40 +0000525void IRPromoter::ExtendSources() {
Sam Parker84a2f8b2018-11-01 15:23:42 +0000526 IRBuilder<> Builder{Ctx};
Sam Parker3828c6f2018-07-23 12:27:47 +0000527
528 auto InsertZExt = [&](Value *V, Instruction *InsertPt) {
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000529 assert(V->getType() != ExtTy && "zext already extends to i32");
Sam Parker3828c6f2018-07-23 12:27:47 +0000530 LLVM_DEBUG(dbgs() << "ARM CGP: Inserting ZExt for " << *V << "\n");
531 Builder.SetInsertPoint(InsertPt);
532 if (auto *I = dyn_cast<Instruction>(V))
533 Builder.SetCurrentDebugLocation(I->getDebugLoc());
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000534
535 Value *ZExt = Builder.CreateZExt(V, ExtTy);
536 if (auto *I = dyn_cast<Instruction>(ZExt)) {
537 if (isa<Argument>(V))
538 I->moveBefore(InsertPt);
539 else
540 I->moveAfter(InsertPt);
541 NewInsts.insert(I);
542 }
Sam Parkere7c42dd2018-11-19 11:34:40 +0000543
Sam Parker3828c6f2018-07-23 12:27:47 +0000544 ReplaceAllUsersOfWith(V, ZExt);
Sam Parker3828c6f2018-07-23 12:27:47 +0000545 };
546
Sam Parker84a2f8b2018-11-01 15:23:42 +0000547 // Now, insert extending instructions between the sources and their users.
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000548 LLVM_DEBUG(dbgs() << "ARM CGP: Promoting sources:\n");
Sam Parkere7c42dd2018-11-19 11:34:40 +0000549 for (auto V : *Sources) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000550 LLVM_DEBUG(dbgs() << " - " << *V << "\n");
Sam Parker8c4b9642018-08-10 13:57:13 +0000551 if (auto *I = dyn_cast<Instruction>(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000552 InsertZExt(I, I);
553 else if (auto *Arg = dyn_cast<Argument>(V)) {
554 BasicBlock &BB = Arg->getParent()->front();
555 InsertZExt(Arg, &*BB.getFirstInsertionPt());
556 } else {
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000557 llvm_unreachable("unhandled source that needs extending");
Sam Parker3828c6f2018-07-23 12:27:47 +0000558 }
559 Promoted.insert(V);
560 }
Sam Parker84a2f8b2018-11-01 15:23:42 +0000561}
Sam Parker3828c6f2018-07-23 12:27:47 +0000562
Sam Parkere7c42dd2018-11-19 11:34:40 +0000563void IRPromoter::PromoteTree() {
Sam Parker3828c6f2018-07-23 12:27:47 +0000564 LLVM_DEBUG(dbgs() << "ARM CGP: Mutating the tree..\n");
Sam Parker84a2f8b2018-11-01 15:23:42 +0000565
566 IRBuilder<> Builder{Ctx};
567
568 // Mutate the types of the instructions within the tree. Here we handle
Sam Parker3828c6f2018-07-23 12:27:47 +0000569 // constant operands.
Sam Parkere7c42dd2018-11-19 11:34:40 +0000570 for (auto *V : *Visited) {
571 if (Sources->count(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000572 continue;
573
Sam Parker3828c6f2018-07-23 12:27:47 +0000574 auto *I = cast<Instruction>(V);
Sam Parkere7c42dd2018-11-19 11:34:40 +0000575 if (Sinks->count(I))
Sam Parker3828c6f2018-07-23 12:27:47 +0000576 continue;
577
Sam Parker7def86b2018-08-15 07:52:35 +0000578 for (unsigned i = 0, e = I->getNumOperands(); i < e; ++i) {
579 Value *Op = I->getOperand(i);
580 if ((Op->getType() == ExtTy) || !isa<IntegerType>(Op->getType()))
Sam Parker3828c6f2018-07-23 12:27:47 +0000581 continue;
582
Sam Parker84a2f8b2018-11-01 15:23:42 +0000583 if (auto *Const = dyn_cast<ConstantInt>(Op)) {
584 Constant *NewConst = ConstantExpr::getZExt(Const, ExtTy);
585 I->setOperand(i, NewConst);
586 } else if (isa<UndefValue>(Op))
Sam Parker7def86b2018-08-15 07:52:35 +0000587 I->setOperand(i, UndefValue::get(ExtTy));
Sam Parker3828c6f2018-07-23 12:27:47 +0000588 }
589
590 if (shouldPromote(I)) {
591 I->mutateType(ExtTy);
592 Promoted.insert(I);
593 }
594 }
595
Sam Parker84a2f8b2018-11-01 15:23:42 +0000596 // Finally, any instructions that should be promoted but haven't yet been,
597 // need to be handled using intrinsics.
Sam Parkere7c42dd2018-11-19 11:34:40 +0000598 for (auto *V : *Visited) {
Sam Parker84a2f8b2018-11-01 15:23:42 +0000599 auto *I = dyn_cast<Instruction>(V);
600 if (!I)
Sam Parker3828c6f2018-07-23 12:27:47 +0000601 continue;
Sam Parker8c4b9642018-08-10 13:57:13 +0000602
Sam Parkere7c42dd2018-11-19 11:34:40 +0000603 if (Sources->count(I) || Sinks->count(I))
Sam Parker3828c6f2018-07-23 12:27:47 +0000604 continue;
605
Sam Parkere7c42dd2018-11-19 11:34:40 +0000606 if (!shouldPromote(I) || SafeToPromote->count(I) || NewInsts.count(I))
Sam Parker84a2f8b2018-11-01 15:23:42 +0000607 continue;
608
Sam Parker75aca942018-09-26 10:56:00 +0000609 assert(EnableDSP && "DSP intrinisc insertion not enabled!");
610
Sam Parker3828c6f2018-07-23 12:27:47 +0000611 // Replace unsafe instructions with appropriate intrinsic calls.
Sam Parker84a2f8b2018-11-01 15:23:42 +0000612 LLVM_DEBUG(dbgs() << "ARM CGP: Inserting DSP intrinsic for "
613 << *I << "\n");
614 Function *DSPInst =
615 Intrinsic::getDeclaration(M, getNarrowIntrinsic(I));
616 Builder.SetInsertPoint(I);
617 Builder.SetCurrentDebugLocation(I->getDebugLoc());
618 Value *Args[] = { I->getOperand(0), I->getOperand(1) };
619 CallInst *Call = Builder.CreateCall(DSPInst, Args);
Sam Parker84a2f8b2018-11-01 15:23:42 +0000620 NewInsts.insert(Call);
Sam Parkere7c42dd2018-11-19 11:34:40 +0000621 ReplaceAllUsersOfWith(I, Call);
Sam Parker3828c6f2018-07-23 12:27:47 +0000622 }
Sam Parker84a2f8b2018-11-01 15:23:42 +0000623}
624
Sam Parkere7c42dd2018-11-19 11:34:40 +0000625void IRPromoter::TruncateSinks() {
Sam Parker84a2f8b2018-11-01 15:23:42 +0000626 LLVM_DEBUG(dbgs() << "ARM CGP: Fixing up the sinks:\n");
627
628 IRBuilder<> Builder{Ctx};
Sam Parker3828c6f2018-07-23 12:27:47 +0000629
Sam Parkere7c42dd2018-11-19 11:34:40 +0000630 auto InsertTrunc = [&](Value *V, Type *TruncTy) -> Instruction* {
Sam Parker13567db2018-08-16 10:05:39 +0000631 if (!isa<Instruction>(V) || !isa<IntegerType>(V->getType()))
632 return nullptr;
633
Sam Parkere7c42dd2018-11-19 11:34:40 +0000634 if ((!Promoted.count(V) && !NewInsts.count(V)) || Sources->count(V))
Sam Parker13567db2018-08-16 10:05:39 +0000635 return nullptr;
636
637 LLVM_DEBUG(dbgs() << "ARM CGP: Creating " << *TruncTy << " Trunc for "
638 << *V << "\n");
639 Builder.SetInsertPoint(cast<Instruction>(V));
Sam Parker48fbf752018-11-01 16:44:45 +0000640 auto *Trunc = dyn_cast<Instruction>(Builder.CreateTrunc(V, TruncTy));
641 if (Trunc)
642 NewInsts.insert(Trunc);
Sam Parker13567db2018-08-16 10:05:39 +0000643 return Trunc;
644 };
645
Sam Parker3828c6f2018-07-23 12:27:47 +0000646 // Fix up any stores or returns that use the results of the promoted
647 // chain.
Sam Parkere7c42dd2018-11-19 11:34:40 +0000648 for (auto I : *Sinks) {
649 LLVM_DEBUG(dbgs() << "ARM CGP: For Sink: " << *I << "\n");
Sam Parker13567db2018-08-16 10:05:39 +0000650
651 // Handle calls separately as we need to iterate over arg operands.
652 if (auto *Call = dyn_cast<CallInst>(I)) {
653 for (unsigned i = 0; i < Call->getNumArgOperands(); ++i) {
654 Value *Arg = Call->getArgOperand(i);
Sam Parkere7c42dd2018-11-19 11:34:40 +0000655 Type *Ty = TruncTysMap[Call][i];
656 if (Instruction *Trunc = InsertTrunc(Arg, Ty)) {
Sam Parker13567db2018-08-16 10:05:39 +0000657 Trunc->moveBefore(Call);
658 Call->setArgOperand(i, Trunc);
659 }
660 }
661 continue;
Sam Parker3828c6f2018-07-23 12:27:47 +0000662 }
663
Sam Parkere7c42dd2018-11-19 11:34:40 +0000664 // Special case switches because we need to truncate the condition.
665 if (auto *Switch = dyn_cast<SwitchInst>(I)) {
666 Type *Ty = TruncTysMap[Switch][0];
667 if (Instruction *Trunc = InsertTrunc(Switch->getCondition(), Ty)) {
668 Trunc->moveBefore(Switch);
669 Switch->setCondition(Trunc);
670 }
671 continue;
672 }
673
Sam Parker13567db2018-08-16 10:05:39 +0000674 // Now handle the others.
Sam Parker3828c6f2018-07-23 12:27:47 +0000675 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
Sam Parkere7c42dd2018-11-19 11:34:40 +0000676 Type *Ty = TruncTysMap[I][i];
677 if (Instruction *Trunc = InsertTrunc(I->getOperand(i), Ty)) {
Sam Parker13567db2018-08-16 10:05:39 +0000678 Trunc->moveBefore(I);
679 I->setOperand(i, Trunc);
Sam Parker3828c6f2018-07-23 12:27:47 +0000680 }
681 }
682 }
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000683}
684
Sam Parkere7c42dd2018-11-19 11:34:40 +0000685void IRPromoter::Cleanup() {
Sam Parker08979cd2018-11-09 09:28:27 +0000686 // Some zexts will now have become redundant, along with their trunc
687 // operands, so remove them
Sam Parkere7c42dd2018-11-19 11:34:40 +0000688 for (auto V : *Visited) {
689 if (!isa<CastInst>(V))
Sam Parker08979cd2018-11-09 09:28:27 +0000690 continue;
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000691
Sam Parkere7c42dd2018-11-19 11:34:40 +0000692 auto ZExt = cast<CastInst>(V);
Sam Parker08979cd2018-11-09 09:28:27 +0000693 if (ZExt->getDestTy() != ExtTy)
694 continue;
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000695
Sam Parker08979cd2018-11-09 09:28:27 +0000696 Value *Src = ZExt->getOperand(0);
697 if (ZExt->getSrcTy() == ZExt->getDestTy()) {
Sam Parkere7c42dd2018-11-19 11:34:40 +0000698 LLVM_DEBUG(dbgs() << "ARM CGP: Removing unnecessary cast: " << *ZExt
699 << "\n");
Sam Parker08979cd2018-11-09 09:28:27 +0000700 ReplaceAllUsersOfWith(ZExt, Src);
Sam Parker08979cd2018-11-09 09:28:27 +0000701 continue;
702 }
703
704 // For any truncs that we insert to handle zexts, we can replace the
705 // result of the zext with the input to the trunc.
Sam Parkere7c42dd2018-11-19 11:34:40 +0000706 if (NewInsts.count(Src) && isa<ZExtInst>(V) && isa<TruncInst>(Src)) {
Sam Parker08979cd2018-11-09 09:28:27 +0000707 auto *Trunc = cast<TruncInst>(Src);
708 assert(Trunc->getOperand(0)->getType() == ExtTy &&
709 "expected inserted trunc to be operating on i32");
Sam Parker08979cd2018-11-09 09:28:27 +0000710 ReplaceAllUsersOfWith(ZExt, Trunc->getOperand(0));
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000711 }
712 }
713
714 for (auto *I : InstsToRemove) {
715 LLVM_DEBUG(dbgs() << "ARM CGP: Removing " << *I << "\n");
716 I->dropAllReferences();
717 I->eraseFromParent();
718 }
719
720 InstsToRemove.clear();
721 NewInsts.clear();
722 TruncTysMap.clear();
723 Promoted.clear();
Sam Parker84a2f8b2018-11-01 15:23:42 +0000724}
725
Sam Parkere7c42dd2018-11-19 11:34:40 +0000726void IRPromoter::ConvertTruncs() {
727 IRBuilder<> Builder{Ctx};
728
729 for (auto *V : *Visited) {
730 if (!isa<TruncInst>(V) || Sources->count(V))
731 continue;
732
733 auto *Trunc = cast<TruncInst>(V);
734 assert(LessThanTypeSize(Trunc) && "expected narrow trunc");
735
736 Builder.SetInsertPoint(Trunc);
737 unsigned NumBits =
738 cast<IntegerType>(Trunc->getType())->getScalarSizeInBits();
739 ConstantInt *Mask = ConstantInt::get(Ctx, APInt::getMaxValue(NumBits));
740 Value *Masked = Builder.CreateAnd(Trunc->getOperand(0), Mask);
741
742 if (auto *I = dyn_cast<Instruction>(Masked))
743 NewInsts.insert(I);
744
745 ReplaceAllUsersOfWith(Trunc, Masked);
746 }
747}
748
Sam Parker84a2f8b2018-11-01 15:23:42 +0000749void IRPromoter::Mutate(Type *OrigTy,
750 SmallPtrSetImpl<Value*> &Visited,
751 SmallPtrSetImpl<Value*> &Sources,
752 SmallPtrSetImpl<Instruction*> &Sinks,
753 SmallPtrSetImpl<Instruction*> &SafeToPromote) {
754 LLVM_DEBUG(dbgs() << "ARM CGP: Promoting use-def chains to from "
755 << ARMCodeGenPrepare::TypeSize << " to 32-bits\n");
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000756
757 assert(isa<IntegerType>(OrigTy) && "expected integer type");
758 this->OrigTy = cast<IntegerType>(OrigTy);
759 assert(OrigTy->getPrimitiveSizeInBits() < ExtTy->getPrimitiveSizeInBits() &&
760 "original type not smaller than extended type");
Sam Parker84a2f8b2018-11-01 15:23:42 +0000761
Sam Parkere7c42dd2018-11-19 11:34:40 +0000762 this->Visited = &Visited;
763 this->Sources = &Sources;
764 this->Sinks = &Sinks;
765 this->SafeToPromote = &SafeToPromote;
766
767 // Cache original types of the values that will likely need truncating
768 for (auto *I : Sinks) {
769 if (auto *Call = dyn_cast<CallInst>(I)) {
770 for (unsigned i = 0; i < Call->getNumArgOperands(); ++i) {
771 Value *Arg = Call->getArgOperand(i);
772 TruncTysMap[Call].push_back(Arg->getType());
773 }
774 } else if (auto *Switch = dyn_cast<SwitchInst>(I))
775 TruncTysMap[I].push_back(Switch->getCondition()->getType());
776 else {
777 for (unsigned i = 0; i < I->getNumOperands(); ++i)
778 TruncTysMap[I].push_back(I->getOperand(i)->getType());
779 }
780 }
Sam Parker84a2f8b2018-11-01 15:23:42 +0000781
782 // Convert adds and subs using negative immediates to equivalent instructions
783 // that use positive constants.
Sam Parkere7c42dd2018-11-19 11:34:40 +0000784 PrepareConstants();
Sam Parker84a2f8b2018-11-01 15:23:42 +0000785
786 // Insert zext instructions between sources and their users.
Sam Parkere7c42dd2018-11-19 11:34:40 +0000787 ExtendSources();
788
789 // Convert any truncs, that aren't sources, into AND masks.
790 ConvertTruncs();
Sam Parker84a2f8b2018-11-01 15:23:42 +0000791
792 // Promote visited instructions, mutating their types in place. Also insert
793 // DSP intrinsics, if enabled, for adds and subs which would be unsafe to
794 // promote.
Sam Parkere7c42dd2018-11-19 11:34:40 +0000795 PromoteTree();
Sam Parker84a2f8b2018-11-01 15:23:42 +0000796
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000797 // Insert trunc instructions for use by calls, stores etc...
Sam Parkere7c42dd2018-11-19 11:34:40 +0000798 TruncateSinks();
Sam Parker84a2f8b2018-11-01 15:23:42 +0000799
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000800 // Finally, remove unecessary zexts and truncs, delete old instructions and
801 // clear the data structures.
Sam Parkere7c42dd2018-11-19 11:34:40 +0000802 Cleanup();
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000803
Sam Parker08979cd2018-11-09 09:28:27 +0000804 LLVM_DEBUG(dbgs() << "ARM CGP: Mutation complete\n");
Sam Parker3828c6f2018-07-23 12:27:47 +0000805}
806
Sam Parker8c4b9642018-08-10 13:57:13 +0000807/// We accept most instructions, as well as Arguments and ConstantInsts. We
808/// Disallow casts other than zext and truncs and only allow calls if their
809/// return value is zeroext. We don't allow opcodes that can introduce sign
810/// bits.
811bool ARMCodeGenPrepare::isSupportedValue(Value *V) {
Sam Parker08979cd2018-11-09 09:28:27 +0000812 if (auto *I = dyn_cast<ICmpInst>(V)) {
813 // Now that we allow small types than TypeSize, only allow icmp of
814 // TypeSize because they will require a trunc to be legalised.
815 // TODO: Allow icmp of smaller types, and calculate at the end
816 // whether the transform would be beneficial.
817 if (isa<PointerType>(I->getOperand(0)->getType()))
818 return true;
819 return EqualTypeSize(I->getOperand(0));
820 }
Sam Parker8c4b9642018-08-10 13:57:13 +0000821
Volodymyr Sapsai703ab842018-09-18 00:11:55 +0000822 // Memory instructions
823 if (isa<StoreInst>(V) || isa<GetElementPtrInst>(V))
824 return true;
825
826 // Branches and targets.
827 if( isa<BranchInst>(V) || isa<SwitchInst>(V) || isa<BasicBlock>(V))
828 return true;
829
830 // Non-instruction values that we can handle.
831 if ((isa<Constant>(V) && !isa<ConstantExpr>(V)) || isa<Argument>(V))
832 return isSupportedType(V);
833
834 if (isa<PHINode>(V) || isa<SelectInst>(V) || isa<ReturnInst>(V) ||
835 isa<LoadInst>(V))
836 return isSupportedType(V);
837
Sam Parker08979cd2018-11-09 09:28:27 +0000838 if (isa<SExtInst>(V))
839 return false;
Volodymyr Sapsai703ab842018-09-18 00:11:55 +0000840
Sam Parker08979cd2018-11-09 09:28:27 +0000841 if (auto *Cast = dyn_cast<CastInst>(V))
842 return isSupportedType(Cast) || isSupportedType(Cast->getOperand(0));
Sam Parker0e2f0bd2018-08-16 11:54:09 +0000843
Sam Parker8c4b9642018-08-10 13:57:13 +0000844 // Special cases for calls as we need to check for zeroext
845 // TODO We should accept calls even if they don't have zeroext, as they can
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000846 // still be sinks.
Sam Parker8c4b9642018-08-10 13:57:13 +0000847 if (auto *Call = dyn_cast<CallInst>(V))
848 return isSupportedType(Call) &&
849 Call->hasRetAttr(Attribute::AttrKind::ZExt);
850
Volodymyr Sapsai703ab842018-09-18 00:11:55 +0000851 if (!isa<BinaryOperator>(V))
852 return false;
853
854 if (!isSupportedType(V))
855 return false;
856
857 if (generateSignBits(V)) {
858 LLVM_DEBUG(dbgs() << "ARM CGP: No, instruction can generate sign bits.\n");
859 return false;
860 }
861 return true;
Sam Parker8c4b9642018-08-10 13:57:13 +0000862}
863
864/// Check that the type of V would be promoted and that the original type is
865/// smaller than the targeted promoted type. Check that we're not trying to
866/// promote something larger than our base 'TypeSize' type.
867bool ARMCodeGenPrepare::isLegalToPromote(Value *V) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000868
869 auto *I = dyn_cast<Instruction>(V);
870 if (!I)
Sam Parker84a2f8b2018-11-01 15:23:42 +0000871 return true;
872
873 if (SafeToPromote.count(I))
874 return true;
875
876 if (isPromotedResultSafe(V) || isSafeOverflow(I)) {
877 SafeToPromote.insert(I);
878 return true;
879 }
880
881 if (I->getOpcode() != Instruction::Add && I->getOpcode() != Instruction::Sub)
Sam Parker8c4b9642018-08-10 13:57:13 +0000882 return false;
883
884 // If promotion is not safe, can we use a DSP instruction to natively
885 // handle the narrow type?
Sam Parker3828c6f2018-07-23 12:27:47 +0000886 if (!ST->hasDSP() || !EnableDSP || !isSupportedType(I))
887 return false;
888
889 if (ST->isThumb() && !ST->hasThumb2())
890 return false;
891
Sam Parker3828c6f2018-07-23 12:27:47 +0000892 // TODO
893 // Would it be profitable? For Thumb code, these parallel DSP instructions
894 // are only Thumb-2, so we wouldn't be able to dual issue on Cortex-M33. For
895 // Cortex-A, specifically Cortex-A72, the latency is double and throughput is
896 // halved. They also do not take immediates as operands.
897 for (auto &Op : I->operands()) {
898 if (isa<Constant>(Op)) {
899 if (!EnableDSPWithImms)
900 return false;
901 }
902 }
Sam Parker84a2f8b2018-11-01 15:23:42 +0000903 LLVM_DEBUG(dbgs() << "ARM CGP: Will use an intrinsic for: " << *I << "\n");
Sam Parker3828c6f2018-07-23 12:27:47 +0000904 return true;
905}
906
Sam Parker3828c6f2018-07-23 12:27:47 +0000907bool ARMCodeGenPrepare::TryToPromote(Value *V) {
908 OrigTy = V->getType();
909 TypeSize = OrigTy->getPrimitiveSizeInBits();
Sam Parkerfabf7fe2018-08-15 13:29:50 +0000910 if (TypeSize > 16 || TypeSize < 8)
Sam Parker8c4b9642018-08-10 13:57:13 +0000911 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000912
Sam Parker84a2f8b2018-11-01 15:23:42 +0000913 SafeToPromote.clear();
914
Sam Parker3828c6f2018-07-23 12:27:47 +0000915 if (!isSupportedValue(V) || !shouldPromote(V) || !isLegalToPromote(V))
916 return false;
917
Sam Parker8c4b9642018-08-10 13:57:13 +0000918 LLVM_DEBUG(dbgs() << "ARM CGP: TryToPromote: " << *V << ", TypeSize = "
919 << TypeSize << "\n");
Sam Parker3828c6f2018-07-23 12:27:47 +0000920
921 SetVector<Value*> WorkList;
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000922 SmallPtrSet<Value*, 8> Sources;
923 SmallPtrSet<Instruction*, 4> Sinks;
Sam Parker3828c6f2018-07-23 12:27:47 +0000924 SmallPtrSet<Value*, 16> CurrentVisited;
Sam Parker84a2f8b2018-11-01 15:23:42 +0000925 WorkList.insert(V);
Sam Parker3828c6f2018-07-23 12:27:47 +0000926
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000927 // Return true if V was added to the worklist as a supported instruction,
928 // if it was already visited, or if we don't need to explore it (e.g.
929 // pointer values and GEPs), and false otherwise.
Sam Parker3828c6f2018-07-23 12:27:47 +0000930 auto AddLegalInst = [&](Value *V) {
931 if (CurrentVisited.count(V))
932 return true;
933
Sam Parker0d511972018-08-16 12:24:40 +0000934 // Ignore GEPs because they don't need promoting and the constant indices
935 // will prevent the transformation.
936 if (isa<GetElementPtrInst>(V))
937 return true;
938
Sam Parker3828c6f2018-07-23 12:27:47 +0000939 if (!isSupportedValue(V) || (shouldPromote(V) && !isLegalToPromote(V))) {
940 LLVM_DEBUG(dbgs() << "ARM CGP: Can't handle: " << *V << "\n");
941 return false;
942 }
943
944 WorkList.insert(V);
945 return true;
946 };
947
948 // Iterate through, and add to, a tree of operands and users in the use-def.
949 while (!WorkList.empty()) {
950 Value *V = WorkList.back();
951 WorkList.pop_back();
952 if (CurrentVisited.count(V))
953 continue;
954
Sam Parker7def86b2018-08-15 07:52:35 +0000955 // Ignore non-instructions, other than arguments.
Sam Parker3828c6f2018-07-23 12:27:47 +0000956 if (!isa<Instruction>(V) && !isSource(V))
957 continue;
958
959 // If we've already visited this value from somewhere, bail now because
960 // the tree has already been explored.
961 // TODO: This could limit the transform, ie if we try to promote something
962 // from an i8 and fail first, before trying an i16.
Sam Parkeraaec3c62018-09-13 15:14:12 +0000963 if (AllVisited.count(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000964 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000965
966 CurrentVisited.insert(V);
967 AllVisited.insert(V);
968
969 // Calls can be both sources and sinks.
970 if (isSink(V))
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000971 Sinks.insert(cast<Instruction>(V));
Sam Parker08979cd2018-11-09 09:28:27 +0000972
Sam Parker3828c6f2018-07-23 12:27:47 +0000973 if (isSource(V))
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000974 Sources.insert(V);
Sam Parker08979cd2018-11-09 09:28:27 +0000975
976 if (!isSink(V) && !isSource(V)) {
977 if (auto *I = dyn_cast<Instruction>(V)) {
978 // Visit operands of any instruction visited.
979 for (auto &U : I->operands()) {
980 if (!AddLegalInst(U))
981 return false;
982 }
Sam Parker3828c6f2018-07-23 12:27:47 +0000983 }
984 }
985
986 // Don't visit users of a node which isn't going to be mutated unless its a
987 // source.
988 if (isSource(V) || shouldPromote(V)) {
989 for (Use &U : V->uses()) {
990 if (!AddLegalInst(U.getUser()))
991 return false;
992 }
993 }
994 }
995
Sam Parker3828c6f2018-07-23 12:27:47 +0000996 LLVM_DEBUG(dbgs() << "ARM CGP: Visited nodes:\n";
997 for (auto *I : CurrentVisited)
998 I->dump();
999 );
Sam Parker7def86b2018-08-15 07:52:35 +00001000 unsigned ToPromote = 0;
1001 for (auto *V : CurrentVisited) {
Sjoerd Meijer31239a42018-08-17 07:34:01 +00001002 if (Sources.count(V))
Sam Parker7def86b2018-08-15 07:52:35 +00001003 continue;
Sjoerd Meijer31239a42018-08-17 07:34:01 +00001004 if (Sinks.count(cast<Instruction>(V)))
Sam Parker7def86b2018-08-15 07:52:35 +00001005 continue;
1006 ++ToPromote;
1007 }
1008
1009 if (ToPromote < 2)
1010 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +00001011
Sam Parker84a2f8b2018-11-01 15:23:42 +00001012 Promoter->Mutate(OrigTy, CurrentVisited, Sources, Sinks, SafeToPromote);
Sam Parker3828c6f2018-07-23 12:27:47 +00001013 return true;
1014}
1015
1016bool ARMCodeGenPrepare::doInitialization(Module &M) {
1017 Promoter = new IRPromoter(&M);
1018 return false;
1019}
1020
1021bool ARMCodeGenPrepare::runOnFunction(Function &F) {
1022 if (skipFunction(F) || DisableCGP)
1023 return false;
1024
1025 auto *TPC = &getAnalysis<TargetPassConfig>();
1026 if (!TPC)
1027 return false;
1028
1029 const TargetMachine &TM = TPC->getTM<TargetMachine>();
1030 ST = &TM.getSubtarget<ARMSubtarget>(F);
1031 bool MadeChange = false;
1032 LLVM_DEBUG(dbgs() << "ARM CGP: Running on " << F.getName() << "\n");
1033
1034 // Search up from icmps to try to promote their operands.
1035 for (BasicBlock &BB : F) {
1036 auto &Insts = BB.getInstList();
1037 for (auto &I : Insts) {
1038 if (AllVisited.count(&I))
1039 continue;
1040
1041 if (isa<ICmpInst>(I)) {
1042 auto &CI = cast<ICmpInst>(I);
1043
1044 // Skip signed or pointer compares
1045 if (CI.isSigned() || !isa<IntegerType>(CI.getOperand(0)->getType()))
1046 continue;
1047
Sam Parker08979cd2018-11-09 09:28:27 +00001048 LLVM_DEBUG(dbgs() << "ARM CGP: Searching from: " << CI << "\n");
1049
Sam Parker3828c6f2018-07-23 12:27:47 +00001050 for (auto &Op : CI.operands()) {
Sam Parker8c4b9642018-08-10 13:57:13 +00001051 if (auto *I = dyn_cast<Instruction>(Op))
1052 MadeChange |= TryToPromote(I);
Sam Parker3828c6f2018-07-23 12:27:47 +00001053 }
1054 }
1055 }
Sam Parker3828c6f2018-07-23 12:27:47 +00001056 LLVM_DEBUG(if (verifyFunction(F, &dbgs())) {
Sam Parkerfcd8ada2018-11-05 10:58:37 +00001057 dbgs() << F;
Sam Parker3828c6f2018-07-23 12:27:47 +00001058 report_fatal_error("Broken function after type promotion");
1059 });
1060 }
1061 if (MadeChange)
1062 LLVM_DEBUG(dbgs() << "After ARMCodeGenPrepare: " << F << "\n");
1063
1064 return MadeChange;
1065}
1066
Matt Morehousea70685f2018-07-23 17:00:45 +00001067bool ARMCodeGenPrepare::doFinalization(Module &M) {
1068 delete Promoter;
1069 return false;
1070}
1071
Sam Parker3828c6f2018-07-23 12:27:47 +00001072INITIALIZE_PASS_BEGIN(ARMCodeGenPrepare, DEBUG_TYPE,
1073 "ARM IR optimizations", false, false)
1074INITIALIZE_PASS_END(ARMCodeGenPrepare, DEBUG_TYPE, "ARM IR optimizations",
1075 false, false)
1076
1077char ARMCodeGenPrepare::ID = 0;
Sam Parker8c4b9642018-08-10 13:57:13 +00001078unsigned ARMCodeGenPrepare::TypeSize = 0;
Sam Parker3828c6f2018-07-23 12:27:47 +00001079
1080FunctionPass *llvm::createARMCodeGenPreparePass() {
1081 return new ARMCodeGenPrepare();
1082}