blob: 75c72df2f3e8ec8bcfbfec4f6a749c83a4d2066e [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;
112 SmallVector<Instruction*, 4> InstsToRemove;
Sam Parker84a2f8b2018-11-01 15:23:42 +0000113 DenseMap<Value*, Type*> TruncTysMap;
114 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 Parker84a2f8b2018-11-01 15:23:42 +0000119
120 void PrepareConstants(SmallPtrSetImpl<Value*> &Visited,
121 SmallPtrSetImpl<Instruction*> &SafeToPromote);
122 void ExtendSources(SmallPtrSetImpl<Value*> &Sources);
123 void PromoteTree(SmallPtrSetImpl<Value*> &Visited,
124 SmallPtrSetImpl<Value*> &Sources,
125 SmallPtrSetImpl<Instruction*> &Sinks,
126 SmallPtrSetImpl<Instruction*> &SafeToPromote);
127 void TruncateSinks(SmallPtrSetImpl<Value*> &Sources,
128 SmallPtrSetImpl<Instruction*> &Sinks);
Sam Parker08979cd2018-11-09 09:28:27 +0000129 void Cleanup(SmallPtrSetImpl<Value*> &Visited);
Sam Parker3828c6f2018-07-23 12:27:47 +0000130
131public:
Sam Parker84a2f8b2018-11-01 15:23:42 +0000132 IRPromoter(Module *M) : M(M), Ctx(M->getContext()),
133 ExtTy(Type::getInt32Ty(Ctx)) { }
Sam Parker3828c6f2018-07-23 12:27:47 +0000134
Sam Parker3828c6f2018-07-23 12:27:47 +0000135
136 void Mutate(Type *OrigTy,
137 SmallPtrSetImpl<Value*> &Visited,
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000138 SmallPtrSetImpl<Value*> &Sources,
Sam Parker84a2f8b2018-11-01 15:23:42 +0000139 SmallPtrSetImpl<Instruction*> &Sinks,
140 SmallPtrSetImpl<Instruction*> &SafeToPromote);
Sam Parker3828c6f2018-07-23 12:27:47 +0000141};
142
143class ARMCodeGenPrepare : public FunctionPass {
144 const ARMSubtarget *ST = nullptr;
145 IRPromoter *Promoter = nullptr;
146 std::set<Value*> AllVisited;
Sam Parker84a2f8b2018-11-01 15:23:42 +0000147 SmallPtrSet<Instruction*, 8> SafeToPromote;
Sam Parker3828c6f2018-07-23 12:27:47 +0000148
Sam Parker84a2f8b2018-11-01 15:23:42 +0000149 bool isSafeOverflow(Instruction *I);
Sam Parker3828c6f2018-07-23 12:27:47 +0000150 bool isSupportedValue(Value *V);
151 bool isLegalToPromote(Value *V);
152 bool TryToPromote(Value *V);
153
154public:
155 static char ID;
Sam Parker8c4b9642018-08-10 13:57:13 +0000156 static unsigned TypeSize;
157 Type *OrigTy = nullptr;
Sam Parker3828c6f2018-07-23 12:27:47 +0000158
159 ARMCodeGenPrepare() : FunctionPass(ID) {}
160
Sam Parker3828c6f2018-07-23 12:27:47 +0000161 void getAnalysisUsage(AnalysisUsage &AU) const override {
162 AU.addRequired<TargetPassConfig>();
163 }
164
165 StringRef getPassName() const override { return "ARM IR optimizations"; }
166
167 bool doInitialization(Module &M) override;
168 bool runOnFunction(Function &F) override;
Matt Morehousea70685f2018-07-23 17:00:45 +0000169 bool doFinalization(Module &M) override;
Sam Parker3828c6f2018-07-23 12:27:47 +0000170};
171
172}
173
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000174static bool generateSignBits(Value *V) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000175 if (!isa<Instruction>(V))
176 return false;
177
178 unsigned Opc = cast<Instruction>(V)->getOpcode();
179 return Opc == Instruction::AShr || Opc == Instruction::SDiv ||
180 Opc == Instruction::SRem;
181}
182
Sam Parker08979cd2018-11-09 09:28:27 +0000183static bool EqualTypeSize(Value *V) {
184 return V->getType()->getScalarSizeInBits() == ARMCodeGenPrepare::TypeSize;
185}
186
187static bool LessOrEqualTypeSize(Value *V) {
188 return V->getType()->getScalarSizeInBits() <= ARMCodeGenPrepare::TypeSize;
189}
190
191static bool GreaterThanTypeSize(Value *V) {
192 return V->getType()->getScalarSizeInBits() > ARMCodeGenPrepare::TypeSize;
193}
194
Sam Parker3828c6f2018-07-23 12:27:47 +0000195/// Some instructions can use 8- and 16-bit operands, and we don't need to
196/// promote anything larger. We disallow booleans to make life easier when
197/// dealing with icmps but allow any other integer that is <= 16 bits. Void
198/// types are accepted so we can handle switches.
199static bool isSupportedType(Value *V) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000200 Type *Ty = V->getType();
Sam Parker7def86b2018-08-15 07:52:35 +0000201
202 // Allow voids and pointers, these won't be promoted.
203 if (Ty->isVoidTy() || Ty->isPointerTy())
Sam Parker3828c6f2018-07-23 12:27:47 +0000204 return true;
205
Sam Parker8c4b9642018-08-10 13:57:13 +0000206 if (auto *Ld = dyn_cast<LoadInst>(V))
207 Ty = cast<PointerType>(Ld->getPointerOperandType())->getElementType();
208
Sam Parker2804f322018-11-09 15:06:33 +0000209 if (!isa<IntegerType>(Ty) ||
210 cast<IntegerType>(V->getType())->getBitWidth() == 1)
Sam Parker3828c6f2018-07-23 12:27:47 +0000211 return false;
212
Sam Parker08979cd2018-11-09 09:28:27 +0000213 return LessOrEqualTypeSize(V);
Sam Parker8c4b9642018-08-10 13:57:13 +0000214}
Sam Parker3828c6f2018-07-23 12:27:47 +0000215
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000216/// Return true if the given value is a source in the use-def chain, producing
Sam Parker8c4b9642018-08-10 13:57:13 +0000217/// a narrow (i8, i16) value. These values will be zext to start the promotion
218/// of the tree to i32. We guarantee that these won't populate the upper bits
219/// of the register. ZExt on the loads will be free, and the same for call
220/// return values because we only accept ones that guarantee a zeroext ret val.
221/// Many arguments will have the zeroext attribute too, so those would be free
222/// too.
223static bool isSource(Value *V) {
Sam Parker7def86b2018-08-15 07:52:35 +0000224 if (!isa<IntegerType>(V->getType()))
225 return false;
Sam Parker2804f322018-11-09 15:06:33 +0000226
Volodymyr Sapsai703ab842018-09-18 00:11:55 +0000227 // TODO Allow zext to be sources.
228 if (isa<Argument>(V))
Sam Parker8c4b9642018-08-10 13:57:13 +0000229 return true;
Volodymyr Sapsai703ab842018-09-18 00:11:55 +0000230 else if (isa<LoadInst>(V))
231 return true;
232 else if (isa<BitCastInst>(V))
233 return true;
234 else if (auto *Call = dyn_cast<CallInst>(V))
235 return Call->hasRetAttr(Attribute::AttrKind::ZExt);
236 else if (auto *Trunc = dyn_cast<TruncInst>(V))
Sam Parker08979cd2018-11-09 09:28:27 +0000237 return EqualTypeSize(Trunc);
Sam Parker8c4b9642018-08-10 13:57:13 +0000238 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000239}
240
241/// Return true if V will require any promoted values to be truncated for the
Sam Parker8c4b9642018-08-10 13:57:13 +0000242/// the IR to remain valid. We can't mutate the value type of these
243/// instructions.
Sam Parker3828c6f2018-07-23 12:27:47 +0000244static bool isSink(Value *V) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000245 // TODO The truncate also isn't actually necessary because we would already
246 // proved that the data value is kept within the range of the original data
247 // type.
Sam Parker3828c6f2018-07-23 12:27:47 +0000248
249 if (auto *Store = dyn_cast<StoreInst>(V))
Sam Parker08979cd2018-11-09 09:28:27 +0000250 return LessOrEqualTypeSize(Store->getValueOperand());
Sam Parker3828c6f2018-07-23 12:27:47 +0000251 if (auto *Return = dyn_cast<ReturnInst>(V))
Sam Parker08979cd2018-11-09 09:28:27 +0000252 return LessOrEqualTypeSize(Return->getReturnValue());
Sam Parker8c4b9642018-08-10 13:57:13 +0000253 if (auto *Trunc = dyn_cast<TruncInst>(V))
Sam Parker08979cd2018-11-09 09:28:27 +0000254 return EqualTypeSize(Trunc->getOperand(0));
Sam Parker0e2f0bd2018-08-16 11:54:09 +0000255 if (auto *ZExt = dyn_cast<ZExtInst>(V))
Sam Parker08979cd2018-11-09 09:28:27 +0000256 return GreaterThanTypeSize(ZExt);
Sam Parker13567db2018-08-16 10:05:39 +0000257 if (auto *ICmp = dyn_cast<ICmpInst>(V))
258 return ICmp->isSigned();
Sam Parker3828c6f2018-07-23 12:27:47 +0000259
260 return isa<CallInst>(V);
261}
262
Sam Parker3828c6f2018-07-23 12:27:47 +0000263/// Return whether the instruction can be promoted within any modifications to
Sam Parker84a2f8b2018-11-01 15:23:42 +0000264/// its operands or result.
265bool ARMCodeGenPrepare::isSafeOverflow(Instruction *I) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000266 // FIXME Do we need NSW too?
Sam Parker3828c6f2018-07-23 12:27:47 +0000267 if (isa<OverflowingBinaryOperator>(I) && I->hasNoUnsignedWrap())
268 return true;
269
Sam Parker75aca942018-09-26 10:56:00 +0000270 // We can support a, potentially, overflowing instruction (I) if:
271 // - It is only used by an unsigned icmp.
272 // - The icmp uses a constant.
273 // - The overflowing value (I) is decreasing, i.e would underflow - wrapping
274 // around zero to become a larger number than before.
275 // - The underflowing instruction (I) also uses a constant.
276 //
277 // We can then use the two constants to calculate whether the result would
278 // wrap in respect to itself in the original bitwidth. If it doesn't wrap,
279 // just underflows the range, the icmp would give the same result whether the
280 // result has been truncated or not. We calculate this by:
281 // - Zero extending both constants, if needed, to 32-bits.
282 // - Take the absolute value of I's constant, adding this to the icmp const.
283 // - Check that this value is not out of range for small type. If it is, it
284 // means that it has underflowed enough to wrap around the icmp constant.
285 //
286 // For example:
287 //
288 // %sub = sub i8 %a, 2
289 // %cmp = icmp ule i8 %sub, 254
290 //
291 // If %a = 0, %sub = -2 == FE == 254
292 // But if this is evalulated as a i32
293 // %sub = -2 == FF FF FF FE == 4294967294
294 // So the unsigned compares (i8 and i32) would not yield the same result.
295 //
296 // Another way to look at it is:
297 // %a - 2 <= 254
298 // %a + 2 <= 254 + 2
299 // %a <= 256
300 // And we can't represent 256 in the i8 format, so we don't support it.
301 //
302 // Whereas:
303 //
304 // %sub i8 %a, 1
305 // %cmp = icmp ule i8 %sub, 254
306 //
307 // If %a = 0, %sub = -1 == FF == 255
308 // As i32:
309 // %sub = -1 == FF FF FF FF == 4294967295
310 //
311 // In this case, the unsigned compare results would be the same and this
312 // would also be true for ult, uge and ugt:
313 // - (255 < 254) == (0xFFFFFFFF < 254) == false
314 // - (255 <= 254) == (0xFFFFFFFF <= 254) == false
315 // - (255 > 254) == (0xFFFFFFFF > 254) == true
316 // - (255 >= 254) == (0xFFFFFFFF >= 254) == true
317 //
318 // To demonstrate why we can't handle increasing values:
319 //
320 // %add = add i8 %a, 2
321 // %cmp = icmp ult i8 %add, 127
322 //
323 // If %a = 254, %add = 256 == (i8 1)
324 // As i32:
325 // %add = 256
326 //
327 // (1 < 127) != (256 < 127)
328
Sam Parker3828c6f2018-07-23 12:27:47 +0000329 unsigned Opc = I->getOpcode();
Sam Parker75aca942018-09-26 10:56:00 +0000330 if (Opc != Instruction::Add && Opc != Instruction::Sub)
331 return false;
332
333 if (!I->hasOneUse() ||
334 !isa<ICmpInst>(*I->user_begin()) ||
335 !isa<ConstantInt>(I->getOperand(1)))
336 return false;
337
338 ConstantInt *OverflowConst = cast<ConstantInt>(I->getOperand(1));
339 bool NegImm = OverflowConst->isNegative();
340 bool IsDecreasing = ((Opc == Instruction::Sub) && !NegImm) ||
341 ((Opc == Instruction::Add) && NegImm);
342 if (!IsDecreasing)
343 return false;
344
345 // Don't support an icmp that deals with sign bits.
346 auto *CI = cast<ICmpInst>(*I->user_begin());
347 if (CI->isSigned() || CI->isEquality())
348 return false;
349
350 ConstantInt *ICmpConst = nullptr;
351 if (auto *Const = dyn_cast<ConstantInt>(CI->getOperand(0)))
352 ICmpConst = Const;
353 else if (auto *Const = dyn_cast<ConstantInt>(CI->getOperand(1)))
354 ICmpConst = Const;
355 else
356 return false;
357
358 // Now check that the result can't wrap on itself.
359 APInt Total = ICmpConst->getValue().getBitWidth() < 32 ?
360 ICmpConst->getValue().zext(32) : ICmpConst->getValue();
361
362 Total += OverflowConst->getValue().getBitWidth() < 32 ?
363 OverflowConst->getValue().abs().zext(32) : OverflowConst->getValue().abs();
364
365 APInt Max = APInt::getAllOnesValue(ARMCodeGenPrepare::TypeSize);
366
367 if (Total.getBitWidth() > Max.getBitWidth()) {
368 if (Total.ugt(Max.zext(Total.getBitWidth())))
Sam Parker3828c6f2018-07-23 12:27:47 +0000369 return false;
Sam Parker75aca942018-09-26 10:56:00 +0000370 } else if (Max.getBitWidth() > Total.getBitWidth()) {
371 if (Total.zext(Max.getBitWidth()).ugt(Max))
Sam Parker3828c6f2018-07-23 12:27:47 +0000372 return false;
Sam Parker75aca942018-09-26 10:56:00 +0000373 } else if (Total.ugt(Max))
374 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000375
Sam Parker75aca942018-09-26 10:56:00 +0000376 LLVM_DEBUG(dbgs() << "ARM CGP: Allowing safe overflow for " << *I << "\n");
377 return true;
Sam Parker3828c6f2018-07-23 12:27:47 +0000378}
379
380static bool shouldPromote(Value *V) {
Sam Parkeraaec3c62018-09-13 15:14:12 +0000381 if (!isa<IntegerType>(V->getType()) || isSink(V))
Sam Parker8c4b9642018-08-10 13:57:13 +0000382 return false;
383
384 if (isSource(V))
385 return true;
386
Sam Parker3828c6f2018-07-23 12:27:47 +0000387 auto *I = dyn_cast<Instruction>(V);
388 if (!I)
389 return false;
390
Sam Parker8c4b9642018-08-10 13:57:13 +0000391 if (isa<ICmpInst>(I))
Sam Parker3828c6f2018-07-23 12:27:47 +0000392 return false;
393
Sam Parker3828c6f2018-07-23 12:27:47 +0000394 return true;
395}
396
397/// Return whether we can safely mutate V's type to ExtTy without having to be
398/// concerned with zero extending or truncation.
399static bool isPromotedResultSafe(Value *V) {
400 if (!isa<Instruction>(V))
401 return true;
402
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000403 if (generateSignBits(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000404 return false;
405
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000406 return !isa<OverflowingBinaryOperator>(V);
Sam Parker3828c6f2018-07-23 12:27:47 +0000407}
408
409/// Return the intrinsic for the instruction that can perform the same
410/// operation but on a narrow type. This is using the parallel dsp intrinsics
411/// on scalar values.
Sam Parker8c4b9642018-08-10 13:57:13 +0000412static Intrinsic::ID getNarrowIntrinsic(Instruction *I) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000413 // Whether we use the signed or unsigned versions of these intrinsics
414 // doesn't matter because we're not using the GE bits that they set in
415 // the APSR.
416 switch(I->getOpcode()) {
417 default:
418 break;
419 case Instruction::Add:
Sam Parker8c4b9642018-08-10 13:57:13 +0000420 return ARMCodeGenPrepare::TypeSize == 16 ? Intrinsic::arm_uadd16 :
Sam Parker3828c6f2018-07-23 12:27:47 +0000421 Intrinsic::arm_uadd8;
422 case Instruction::Sub:
Sam Parker8c4b9642018-08-10 13:57:13 +0000423 return ARMCodeGenPrepare::TypeSize == 16 ? Intrinsic::arm_usub16 :
Sam Parker3828c6f2018-07-23 12:27:47 +0000424 Intrinsic::arm_usub8;
425 }
426 llvm_unreachable("unhandled opcode for narrow intrinsic");
427}
428
Sam Parker84a2f8b2018-11-01 15:23:42 +0000429static void ReplaceAllUsersOfWith(Value *From, Value *To) {
430 SmallVector<Instruction*, 4> Users;
431 Instruction *InstTo = dyn_cast<Instruction>(To);
432 for (Use &U : From->uses()) {
433 auto *User = cast<Instruction>(U.getUser());
434 if (InstTo && User->isIdenticalTo(InstTo))
435 continue;
436 Users.push_back(User);
437 }
438
439 for (auto *U : Users)
440 U->replaceUsesOfWith(From, To);
441}
442
443void
444IRPromoter::PrepareConstants(SmallPtrSetImpl<Value*> &Visited,
445 SmallPtrSetImpl<Instruction*> &SafeToPromote) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000446 IRBuilder<> Builder{Ctx};
Sam Parker84a2f8b2018-11-01 15:23:42 +0000447 // First step is to prepare the instructions for mutation. Most constants
448 // just need to be zero extended into their new type, but complications arise
449 // because:
450 // - For nuw binary operators, negative immediates would need sign extending;
451 // however, instead we'll change them to positive and zext them. We can do
452 // this because:
453 // > The operators that can wrap are: add, sub, mul and shl.
454 // > shl interprets its second operand as unsigned and if the first operand
455 // is an immediate, it will need zext to be nuw.
Sam Parkerfec793c2018-11-05 11:26:04 +0000456 // > I'm assuming mul has to interpret immediates as unsigned for nuw.
Sam Parker84a2f8b2018-11-01 15:23:42 +0000457 // > Which leaves the nuw add and sub to be handled; as with shl, if an
458 // immediate is used as operand 0, it will need zext to be nuw.
459 // - We also allow add and sub to safely overflow in certain circumstances
460 // and only when the value (operand 0) is being decreased.
461 //
462 // For adds and subs, that are either nuw or safely wrap and use a negative
463 // immediate as operand 1, we create an equivalent instruction using a
464 // positive immediate. That positive immediate can then be zext along with
465 // all the other immediates later.
466 for (auto *V : Visited) {
467 if (!isa<Instruction>(V))
468 continue;
Sam Parker3828c6f2018-07-23 12:27:47 +0000469
Sam Parker84a2f8b2018-11-01 15:23:42 +0000470 auto *I = cast<Instruction>(V);
471 if (SafeToPromote.count(I)) {
Sam Parker13567db2018-08-16 10:05:39 +0000472
Sam Parker84a2f8b2018-11-01 15:23:42 +0000473 if (!isa<OverflowingBinaryOperator>(I))
Sam Parker3828c6f2018-07-23 12:27:47 +0000474 continue;
Sam Parker84a2f8b2018-11-01 15:23:42 +0000475
476 if (auto *Const = dyn_cast<ConstantInt>(I->getOperand(1))) {
477 if (!Const->isNegative())
478 break;
479
480 unsigned Opc = I->getOpcode();
Sam Parkerfec793c2018-11-05 11:26:04 +0000481 if (Opc != Instruction::Add && Opc != Instruction::Sub)
482 continue;
Sam Parker84a2f8b2018-11-01 15:23:42 +0000483
484 LLVM_DEBUG(dbgs() << "ARM CGP: Adjusting " << *I << "\n");
485 auto *NewConst = ConstantInt::get(Ctx, Const->getValue().abs());
486 Builder.SetInsertPoint(I);
487 Value *NewVal = Opc == Instruction::Sub ?
488 Builder.CreateAdd(I->getOperand(0), NewConst) :
489 Builder.CreateSub(I->getOperand(0), NewConst);
490 LLVM_DEBUG(dbgs() << "ARM CGP: New equivalent: " << *NewVal << "\n");
491
492 if (auto *NewInst = dyn_cast<Instruction>(NewVal)) {
493 NewInst->copyIRFlags(I);
494 NewInsts.insert(NewInst);
495 }
496 InstsToRemove.push_back(I);
497 I->replaceAllUsesWith(NewVal);
498 }
Sam Parker3828c6f2018-07-23 12:27:47 +0000499 }
Sam Parker84a2f8b2018-11-01 15:23:42 +0000500 }
501 for (auto *I : NewInsts)
502 Visited.insert(I);
503}
Sam Parker3828c6f2018-07-23 12:27:47 +0000504
Sam Parker84a2f8b2018-11-01 15:23:42 +0000505void IRPromoter::ExtendSources(SmallPtrSetImpl<Value*> &Sources) {
506 IRBuilder<> Builder{Ctx};
Sam Parker3828c6f2018-07-23 12:27:47 +0000507
508 auto InsertZExt = [&](Value *V, Instruction *InsertPt) {
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000509 assert(V->getType() != ExtTy && "zext already extends to i32");
Sam Parker3828c6f2018-07-23 12:27:47 +0000510 LLVM_DEBUG(dbgs() << "ARM CGP: Inserting ZExt for " << *V << "\n");
511 Builder.SetInsertPoint(InsertPt);
512 if (auto *I = dyn_cast<Instruction>(V))
513 Builder.SetCurrentDebugLocation(I->getDebugLoc());
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000514
515 Value *ZExt = Builder.CreateZExt(V, ExtTy);
516 if (auto *I = dyn_cast<Instruction>(ZExt)) {
517 if (isa<Argument>(V))
518 I->moveBefore(InsertPt);
519 else
520 I->moveAfter(InsertPt);
521 NewInsts.insert(I);
522 }
Sam Parker3828c6f2018-07-23 12:27:47 +0000523 ReplaceAllUsersOfWith(V, ZExt);
Sam Parker13567db2018-08-16 10:05:39 +0000524 TruncTysMap[ZExt] = TruncTysMap[V];
Sam Parker3828c6f2018-07-23 12:27:47 +0000525 };
526
Sam Parker84a2f8b2018-11-01 15:23:42 +0000527 // Now, insert extending instructions between the sources and their users.
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000528 LLVM_DEBUG(dbgs() << "ARM CGP: Promoting sources:\n");
529 for (auto V : Sources) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000530 LLVM_DEBUG(dbgs() << " - " << *V << "\n");
Sam Parker8c4b9642018-08-10 13:57:13 +0000531 if (auto *I = dyn_cast<Instruction>(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000532 InsertZExt(I, I);
533 else if (auto *Arg = dyn_cast<Argument>(V)) {
534 BasicBlock &BB = Arg->getParent()->front();
535 InsertZExt(Arg, &*BB.getFirstInsertionPt());
536 } else {
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000537 llvm_unreachable("unhandled source that needs extending");
Sam Parker3828c6f2018-07-23 12:27:47 +0000538 }
539 Promoted.insert(V);
540 }
Sam Parker84a2f8b2018-11-01 15:23:42 +0000541}
Sam Parker3828c6f2018-07-23 12:27:47 +0000542
Sam Parker84a2f8b2018-11-01 15:23:42 +0000543void IRPromoter::PromoteTree(SmallPtrSetImpl<Value*> &Visited,
544 SmallPtrSetImpl<Value*> &Sources,
545 SmallPtrSetImpl<Instruction*> &Sinks,
546 SmallPtrSetImpl<Instruction*> &SafeToPromote) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000547 LLVM_DEBUG(dbgs() << "ARM CGP: Mutating the tree..\n");
Sam Parker84a2f8b2018-11-01 15:23:42 +0000548
549 IRBuilder<> Builder{Ctx};
550
551 // Mutate the types of the instructions within the tree. Here we handle
Sam Parker3828c6f2018-07-23 12:27:47 +0000552 // constant operands.
553 for (auto *V : Visited) {
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000554 if (Sources.count(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000555 continue;
556
Sam Parker3828c6f2018-07-23 12:27:47 +0000557 auto *I = cast<Instruction>(V);
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000558 if (Sinks.count(I))
Sam Parker3828c6f2018-07-23 12:27:47 +0000559 continue;
560
Sam Parker7def86b2018-08-15 07:52:35 +0000561 for (unsigned i = 0, e = I->getNumOperands(); i < e; ++i) {
562 Value *Op = I->getOperand(i);
563 if ((Op->getType() == ExtTy) || !isa<IntegerType>(Op->getType()))
Sam Parker3828c6f2018-07-23 12:27:47 +0000564 continue;
565
Sam Parker84a2f8b2018-11-01 15:23:42 +0000566 if (auto *Const = dyn_cast<ConstantInt>(Op)) {
567 Constant *NewConst = ConstantExpr::getZExt(Const, ExtTy);
568 I->setOperand(i, NewConst);
569 } else if (isa<UndefValue>(Op))
Sam Parker7def86b2018-08-15 07:52:35 +0000570 I->setOperand(i, UndefValue::get(ExtTy));
Sam Parker3828c6f2018-07-23 12:27:47 +0000571 }
572
573 if (shouldPromote(I)) {
574 I->mutateType(ExtTy);
575 Promoted.insert(I);
576 }
577 }
578
Sam Parker84a2f8b2018-11-01 15:23:42 +0000579 // Finally, any instructions that should be promoted but haven't yet been,
580 // need to be handled using intrinsics.
Sam Parker3828c6f2018-07-23 12:27:47 +0000581 for (auto *V : Visited) {
Sam Parker84a2f8b2018-11-01 15:23:42 +0000582 auto *I = dyn_cast<Instruction>(V);
583 if (!I)
Sam Parker3828c6f2018-07-23 12:27:47 +0000584 continue;
Sam Parker8c4b9642018-08-10 13:57:13 +0000585
Sam Parker84a2f8b2018-11-01 15:23:42 +0000586 if (Sources.count(I) || Sinks.count(I))
Sam Parker3828c6f2018-07-23 12:27:47 +0000587 continue;
588
Sam Parker84a2f8b2018-11-01 15:23:42 +0000589 if (!shouldPromote(I) || SafeToPromote.count(I) || NewInsts.count(I))
590 continue;
591
Sam Parker75aca942018-09-26 10:56:00 +0000592 assert(EnableDSP && "DSP intrinisc insertion not enabled!");
593
Sam Parker3828c6f2018-07-23 12:27:47 +0000594 // Replace unsafe instructions with appropriate intrinsic calls.
Sam Parker84a2f8b2018-11-01 15:23:42 +0000595 LLVM_DEBUG(dbgs() << "ARM CGP: Inserting DSP intrinsic for "
596 << *I << "\n");
597 Function *DSPInst =
598 Intrinsic::getDeclaration(M, getNarrowIntrinsic(I));
599 Builder.SetInsertPoint(I);
600 Builder.SetCurrentDebugLocation(I->getDebugLoc());
601 Value *Args[] = { I->getOperand(0), I->getOperand(1) };
602 CallInst *Call = Builder.CreateCall(DSPInst, Args);
603 ReplaceAllUsersOfWith(I, Call);
604 InstsToRemove.push_back(I);
605 NewInsts.insert(Call);
606 TruncTysMap[Call] = OrigTy;
Sam Parker3828c6f2018-07-23 12:27:47 +0000607 }
Sam Parker84a2f8b2018-11-01 15:23:42 +0000608}
609
610void IRPromoter::TruncateSinks(SmallPtrSetImpl<Value*> &Sources,
611 SmallPtrSetImpl<Instruction*> &Sinks) {
612 LLVM_DEBUG(dbgs() << "ARM CGP: Fixing up the sinks:\n");
613
614 IRBuilder<> Builder{Ctx};
Sam Parker3828c6f2018-07-23 12:27:47 +0000615
Sam Parker13567db2018-08-16 10:05:39 +0000616 auto InsertTrunc = [&](Value *V) -> Instruction* {
617 if (!isa<Instruction>(V) || !isa<IntegerType>(V->getType()))
618 return nullptr;
619
Sam Parker0e2f0bd2018-08-16 11:54:09 +0000620 if ((!Promoted.count(V) && !NewInsts.count(V)) || !TruncTysMap.count(V) ||
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000621 Sources.count(V))
Sam Parker13567db2018-08-16 10:05:39 +0000622 return nullptr;
623
624 Type *TruncTy = TruncTysMap[V];
625 if (TruncTy == ExtTy)
626 return nullptr;
627
628 LLVM_DEBUG(dbgs() << "ARM CGP: Creating " << *TruncTy << " Trunc for "
629 << *V << "\n");
630 Builder.SetInsertPoint(cast<Instruction>(V));
Sam Parker48fbf752018-11-01 16:44:45 +0000631 auto *Trunc = dyn_cast<Instruction>(Builder.CreateTrunc(V, TruncTy));
632 if (Trunc)
633 NewInsts.insert(Trunc);
Sam Parker13567db2018-08-16 10:05:39 +0000634 return Trunc;
635 };
636
Sam Parker3828c6f2018-07-23 12:27:47 +0000637 // Fix up any stores or returns that use the results of the promoted
638 // chain.
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000639 for (auto I : Sinks) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000640 LLVM_DEBUG(dbgs() << " - " << *I << "\n");
Sam Parker13567db2018-08-16 10:05:39 +0000641
642 // Handle calls separately as we need to iterate over arg operands.
643 if (auto *Call = dyn_cast<CallInst>(I)) {
644 for (unsigned i = 0; i < Call->getNumArgOperands(); ++i) {
645 Value *Arg = Call->getArgOperand(i);
646 if (Instruction *Trunc = InsertTrunc(Arg)) {
647 Trunc->moveBefore(Call);
648 Call->setArgOperand(i, Trunc);
649 }
650 }
651 continue;
Sam Parker3828c6f2018-07-23 12:27:47 +0000652 }
653
Sam Parker13567db2018-08-16 10:05:39 +0000654 // Now handle the others.
Sam Parker3828c6f2018-07-23 12:27:47 +0000655 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
Sam Parker13567db2018-08-16 10:05:39 +0000656 if (Instruction *Trunc = InsertTrunc(I->getOperand(i))) {
657 Trunc->moveBefore(I);
658 I->setOperand(i, Trunc);
Sam Parker3828c6f2018-07-23 12:27:47 +0000659 }
660 }
661 }
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000662}
663
Sam Parker08979cd2018-11-09 09:28:27 +0000664void IRPromoter::Cleanup(SmallPtrSetImpl<Value*> &Visited) {
665 // Some zexts will now have become redundant, along with their trunc
666 // operands, so remove them
667 for (auto V : Visited) {
668 if (!isa<ZExtInst>(V))
669 continue;
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000670
Sam Parker08979cd2018-11-09 09:28:27 +0000671 auto ZExt = cast<ZExtInst>(V);
672 if (ZExt->getDestTy() != ExtTy)
673 continue;
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000674
Sam Parker08979cd2018-11-09 09:28:27 +0000675 Value *Src = ZExt->getOperand(0);
676 if (ZExt->getSrcTy() == ZExt->getDestTy()) {
677 LLVM_DEBUG(dbgs() << "ARM CGP: Removing unnecessary cast.\n");
678 ReplaceAllUsersOfWith(ZExt, Src);
679 InstsToRemove.push_back(ZExt);
680 continue;
681 }
682
683 // For any truncs that we insert to handle zexts, we can replace the
684 // result of the zext with the input to the trunc.
685 if (NewInsts.count(Src) && isa<TruncInst>(Src)) {
686 auto *Trunc = cast<TruncInst>(Src);
687 assert(Trunc->getOperand(0)->getType() == ExtTy &&
688 "expected inserted trunc to be operating on i32");
689 LLVM_DEBUG(dbgs() << "ARM CGP: Replacing zext with trunc operand: "
690 << *Trunc->getOperand(0));
691 ReplaceAllUsersOfWith(ZExt, Trunc->getOperand(0));
692 InstsToRemove.push_back(ZExt);
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000693 }
694 }
695
696 for (auto *I : InstsToRemove) {
697 LLVM_DEBUG(dbgs() << "ARM CGP: Removing " << *I << "\n");
698 I->dropAllReferences();
699 I->eraseFromParent();
700 }
701
702 InstsToRemove.clear();
703 NewInsts.clear();
704 TruncTysMap.clear();
705 Promoted.clear();
Sam Parker84a2f8b2018-11-01 15:23:42 +0000706}
707
708void IRPromoter::Mutate(Type *OrigTy,
709 SmallPtrSetImpl<Value*> &Visited,
710 SmallPtrSetImpl<Value*> &Sources,
711 SmallPtrSetImpl<Instruction*> &Sinks,
712 SmallPtrSetImpl<Instruction*> &SafeToPromote) {
713 LLVM_DEBUG(dbgs() << "ARM CGP: Promoting use-def chains to from "
714 << ARMCodeGenPrepare::TypeSize << " to 32-bits\n");
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000715
716 assert(isa<IntegerType>(OrigTy) && "expected integer type");
717 this->OrigTy = cast<IntegerType>(OrigTy);
718 assert(OrigTy->getPrimitiveSizeInBits() < ExtTy->getPrimitiveSizeInBits() &&
719 "original type not smaller than extended type");
Sam Parker84a2f8b2018-11-01 15:23:42 +0000720
721 // Cache original types.
722 for (auto *V : Visited)
723 TruncTysMap[V] = V->getType();
724
725 // Convert adds and subs using negative immediates to equivalent instructions
726 // that use positive constants.
727 PrepareConstants(Visited, SafeToPromote);
728
729 // Insert zext instructions between sources and their users.
730 ExtendSources(Sources);
731
732 // Promote visited instructions, mutating their types in place. Also insert
733 // DSP intrinsics, if enabled, for adds and subs which would be unsafe to
734 // promote.
735 PromoteTree(Visited, Sources, Sinks, SafeToPromote);
736
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000737 // Insert trunc instructions for use by calls, stores etc...
Sam Parker84a2f8b2018-11-01 15:23:42 +0000738 TruncateSinks(Sources, Sinks);
739
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000740 // Finally, remove unecessary zexts and truncs, delete old instructions and
741 // clear the data structures.
Sam Parker08979cd2018-11-09 09:28:27 +0000742 Cleanup(Visited);
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000743
Sam Parker08979cd2018-11-09 09:28:27 +0000744 LLVM_DEBUG(dbgs() << "ARM CGP: Mutation complete\n");
Sam Parker3828c6f2018-07-23 12:27:47 +0000745}
746
Sam Parker8c4b9642018-08-10 13:57:13 +0000747/// We accept most instructions, as well as Arguments and ConstantInsts. We
748/// Disallow casts other than zext and truncs and only allow calls if their
749/// return value is zeroext. We don't allow opcodes that can introduce sign
750/// bits.
751bool ARMCodeGenPrepare::isSupportedValue(Value *V) {
Sam Parker08979cd2018-11-09 09:28:27 +0000752 if (auto *I = dyn_cast<ICmpInst>(V)) {
753 // Now that we allow small types than TypeSize, only allow icmp of
754 // TypeSize because they will require a trunc to be legalised.
755 // TODO: Allow icmp of smaller types, and calculate at the end
756 // whether the transform would be beneficial.
757 if (isa<PointerType>(I->getOperand(0)->getType()))
758 return true;
759 return EqualTypeSize(I->getOperand(0));
760 }
Sam Parker8c4b9642018-08-10 13:57:13 +0000761
Volodymyr Sapsai703ab842018-09-18 00:11:55 +0000762 // Memory instructions
763 if (isa<StoreInst>(V) || isa<GetElementPtrInst>(V))
764 return true;
765
766 // Branches and targets.
767 if( isa<BranchInst>(V) || isa<SwitchInst>(V) || isa<BasicBlock>(V))
768 return true;
769
770 // Non-instruction values that we can handle.
771 if ((isa<Constant>(V) && !isa<ConstantExpr>(V)) || isa<Argument>(V))
772 return isSupportedType(V);
773
774 if (isa<PHINode>(V) || isa<SelectInst>(V) || isa<ReturnInst>(V) ||
775 isa<LoadInst>(V))
776 return isSupportedType(V);
777
Sam Parker08979cd2018-11-09 09:28:27 +0000778 if (isa<SExtInst>(V))
779 return false;
Volodymyr Sapsai703ab842018-09-18 00:11:55 +0000780
Sam Parker08979cd2018-11-09 09:28:27 +0000781 if (auto *Cast = dyn_cast<CastInst>(V))
782 return isSupportedType(Cast) || isSupportedType(Cast->getOperand(0));
Sam Parker0e2f0bd2018-08-16 11:54:09 +0000783
Sam Parker8c4b9642018-08-10 13:57:13 +0000784 // Special cases for calls as we need to check for zeroext
785 // TODO We should accept calls even if they don't have zeroext, as they can
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000786 // still be sinks.
Sam Parker8c4b9642018-08-10 13:57:13 +0000787 if (auto *Call = dyn_cast<CallInst>(V))
788 return isSupportedType(Call) &&
789 Call->hasRetAttr(Attribute::AttrKind::ZExt);
790
Volodymyr Sapsai703ab842018-09-18 00:11:55 +0000791 if (!isa<BinaryOperator>(V))
792 return false;
793
794 if (!isSupportedType(V))
795 return false;
796
797 if (generateSignBits(V)) {
798 LLVM_DEBUG(dbgs() << "ARM CGP: No, instruction can generate sign bits.\n");
799 return false;
800 }
801 return true;
Sam Parker8c4b9642018-08-10 13:57:13 +0000802}
803
804/// Check that the type of V would be promoted and that the original type is
805/// smaller than the targeted promoted type. Check that we're not trying to
806/// promote something larger than our base 'TypeSize' type.
807bool ARMCodeGenPrepare::isLegalToPromote(Value *V) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000808
809 auto *I = dyn_cast<Instruction>(V);
810 if (!I)
Sam Parker84a2f8b2018-11-01 15:23:42 +0000811 return true;
812
813 if (SafeToPromote.count(I))
814 return true;
815
816 if (isPromotedResultSafe(V) || isSafeOverflow(I)) {
817 SafeToPromote.insert(I);
818 return true;
819 }
820
821 if (I->getOpcode() != Instruction::Add && I->getOpcode() != Instruction::Sub)
Sam Parker8c4b9642018-08-10 13:57:13 +0000822 return false;
823
824 // If promotion is not safe, can we use a DSP instruction to natively
825 // handle the narrow type?
Sam Parker3828c6f2018-07-23 12:27:47 +0000826 if (!ST->hasDSP() || !EnableDSP || !isSupportedType(I))
827 return false;
828
829 if (ST->isThumb() && !ST->hasThumb2())
830 return false;
831
Sam Parker3828c6f2018-07-23 12:27:47 +0000832 // TODO
833 // Would it be profitable? For Thumb code, these parallel DSP instructions
834 // are only Thumb-2, so we wouldn't be able to dual issue on Cortex-M33. For
835 // Cortex-A, specifically Cortex-A72, the latency is double and throughput is
836 // halved. They also do not take immediates as operands.
837 for (auto &Op : I->operands()) {
838 if (isa<Constant>(Op)) {
839 if (!EnableDSPWithImms)
840 return false;
841 }
842 }
Sam Parker84a2f8b2018-11-01 15:23:42 +0000843 LLVM_DEBUG(dbgs() << "ARM CGP: Will use an intrinsic for: " << *I << "\n");
Sam Parker3828c6f2018-07-23 12:27:47 +0000844 return true;
845}
846
Sam Parker3828c6f2018-07-23 12:27:47 +0000847bool ARMCodeGenPrepare::TryToPromote(Value *V) {
848 OrigTy = V->getType();
849 TypeSize = OrigTy->getPrimitiveSizeInBits();
Sam Parkerfabf7fe2018-08-15 13:29:50 +0000850 if (TypeSize > 16 || TypeSize < 8)
Sam Parker8c4b9642018-08-10 13:57:13 +0000851 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000852
Sam Parker84a2f8b2018-11-01 15:23:42 +0000853 SafeToPromote.clear();
854
Sam Parker3828c6f2018-07-23 12:27:47 +0000855 if (!isSupportedValue(V) || !shouldPromote(V) || !isLegalToPromote(V))
856 return false;
857
Sam Parker8c4b9642018-08-10 13:57:13 +0000858 LLVM_DEBUG(dbgs() << "ARM CGP: TryToPromote: " << *V << ", TypeSize = "
859 << TypeSize << "\n");
Sam Parker3828c6f2018-07-23 12:27:47 +0000860
861 SetVector<Value*> WorkList;
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000862 SmallPtrSet<Value*, 8> Sources;
863 SmallPtrSet<Instruction*, 4> Sinks;
Sam Parker3828c6f2018-07-23 12:27:47 +0000864 SmallPtrSet<Value*, 16> CurrentVisited;
Sam Parker84a2f8b2018-11-01 15:23:42 +0000865 WorkList.insert(V);
Sam Parker3828c6f2018-07-23 12:27:47 +0000866
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000867 // Return true if V was added to the worklist as a supported instruction,
868 // if it was already visited, or if we don't need to explore it (e.g.
869 // pointer values and GEPs), and false otherwise.
Sam Parker3828c6f2018-07-23 12:27:47 +0000870 auto AddLegalInst = [&](Value *V) {
871 if (CurrentVisited.count(V))
872 return true;
873
Sam Parker0d511972018-08-16 12:24:40 +0000874 // Ignore GEPs because they don't need promoting and the constant indices
875 // will prevent the transformation.
876 if (isa<GetElementPtrInst>(V))
877 return true;
878
Sam Parker3828c6f2018-07-23 12:27:47 +0000879 if (!isSupportedValue(V) || (shouldPromote(V) && !isLegalToPromote(V))) {
880 LLVM_DEBUG(dbgs() << "ARM CGP: Can't handle: " << *V << "\n");
881 return false;
882 }
883
884 WorkList.insert(V);
885 return true;
886 };
887
888 // Iterate through, and add to, a tree of operands and users in the use-def.
889 while (!WorkList.empty()) {
890 Value *V = WorkList.back();
891 WorkList.pop_back();
892 if (CurrentVisited.count(V))
893 continue;
894
Sam Parker7def86b2018-08-15 07:52:35 +0000895 // Ignore non-instructions, other than arguments.
Sam Parker3828c6f2018-07-23 12:27:47 +0000896 if (!isa<Instruction>(V) && !isSource(V))
897 continue;
898
899 // If we've already visited this value from somewhere, bail now because
900 // the tree has already been explored.
901 // TODO: This could limit the transform, ie if we try to promote something
902 // from an i8 and fail first, before trying an i16.
Sam Parkeraaec3c62018-09-13 15:14:12 +0000903 if (AllVisited.count(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000904 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000905
906 CurrentVisited.insert(V);
907 AllVisited.insert(V);
908
909 // Calls can be both sources and sinks.
910 if (isSink(V))
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000911 Sinks.insert(cast<Instruction>(V));
Sam Parker08979cd2018-11-09 09:28:27 +0000912
Sam Parker3828c6f2018-07-23 12:27:47 +0000913 if (isSource(V))
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000914 Sources.insert(V);
Sam Parker08979cd2018-11-09 09:28:27 +0000915
916 if (!isSink(V) && !isSource(V)) {
917 if (auto *I = dyn_cast<Instruction>(V)) {
918 // Visit operands of any instruction visited.
919 for (auto &U : I->operands()) {
920 if (!AddLegalInst(U))
921 return false;
922 }
Sam Parker3828c6f2018-07-23 12:27:47 +0000923 }
924 }
925
926 // Don't visit users of a node which isn't going to be mutated unless its a
927 // source.
928 if (isSource(V) || shouldPromote(V)) {
929 for (Use &U : V->uses()) {
930 if (!AddLegalInst(U.getUser()))
931 return false;
932 }
933 }
934 }
935
Sam Parker3828c6f2018-07-23 12:27:47 +0000936 LLVM_DEBUG(dbgs() << "ARM CGP: Visited nodes:\n";
937 for (auto *I : CurrentVisited)
938 I->dump();
939 );
Sam Parker7def86b2018-08-15 07:52:35 +0000940 unsigned ToPromote = 0;
941 for (auto *V : CurrentVisited) {
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000942 if (Sources.count(V))
Sam Parker7def86b2018-08-15 07:52:35 +0000943 continue;
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000944 if (Sinks.count(cast<Instruction>(V)))
Sam Parker7def86b2018-08-15 07:52:35 +0000945 continue;
946 ++ToPromote;
947 }
948
949 if (ToPromote < 2)
950 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000951
Sam Parker84a2f8b2018-11-01 15:23:42 +0000952 Promoter->Mutate(OrigTy, CurrentVisited, Sources, Sinks, SafeToPromote);
Sam Parker3828c6f2018-07-23 12:27:47 +0000953 return true;
954}
955
956bool ARMCodeGenPrepare::doInitialization(Module &M) {
957 Promoter = new IRPromoter(&M);
958 return false;
959}
960
961bool ARMCodeGenPrepare::runOnFunction(Function &F) {
962 if (skipFunction(F) || DisableCGP)
963 return false;
964
965 auto *TPC = &getAnalysis<TargetPassConfig>();
966 if (!TPC)
967 return false;
968
969 const TargetMachine &TM = TPC->getTM<TargetMachine>();
970 ST = &TM.getSubtarget<ARMSubtarget>(F);
971 bool MadeChange = false;
972 LLVM_DEBUG(dbgs() << "ARM CGP: Running on " << F.getName() << "\n");
973
974 // Search up from icmps to try to promote their operands.
975 for (BasicBlock &BB : F) {
976 auto &Insts = BB.getInstList();
977 for (auto &I : Insts) {
978 if (AllVisited.count(&I))
979 continue;
980
981 if (isa<ICmpInst>(I)) {
982 auto &CI = cast<ICmpInst>(I);
983
984 // Skip signed or pointer compares
985 if (CI.isSigned() || !isa<IntegerType>(CI.getOperand(0)->getType()))
986 continue;
987
Sam Parker08979cd2018-11-09 09:28:27 +0000988 LLVM_DEBUG(dbgs() << "ARM CGP: Searching from: " << CI << "\n");
989
Sam Parker3828c6f2018-07-23 12:27:47 +0000990 for (auto &Op : CI.operands()) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000991 if (auto *I = dyn_cast<Instruction>(Op))
992 MadeChange |= TryToPromote(I);
Sam Parker3828c6f2018-07-23 12:27:47 +0000993 }
994 }
995 }
Sam Parker3828c6f2018-07-23 12:27:47 +0000996 LLVM_DEBUG(if (verifyFunction(F, &dbgs())) {
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000997 dbgs() << F;
Sam Parker3828c6f2018-07-23 12:27:47 +0000998 report_fatal_error("Broken function after type promotion");
999 });
1000 }
1001 if (MadeChange)
1002 LLVM_DEBUG(dbgs() << "After ARMCodeGenPrepare: " << F << "\n");
1003
1004 return MadeChange;
1005}
1006
Matt Morehousea70685f2018-07-23 17:00:45 +00001007bool ARMCodeGenPrepare::doFinalization(Module &M) {
1008 delete Promoter;
1009 return false;
1010}
1011
Sam Parker3828c6f2018-07-23 12:27:47 +00001012INITIALIZE_PASS_BEGIN(ARMCodeGenPrepare, DEBUG_TYPE,
1013 "ARM IR optimizations", false, false)
1014INITIALIZE_PASS_END(ARMCodeGenPrepare, DEBUG_TYPE, "ARM IR optimizations",
1015 false, false)
1016
1017char ARMCodeGenPrepare::ID = 0;
Sam Parker8c4b9642018-08-10 13:57:13 +00001018unsigned ARMCodeGenPrepare::TypeSize = 0;
Sam Parker3828c6f2018-07-23 12:27:47 +00001019
1020FunctionPass *llvm::createARMCodeGenPreparePass() {
1021 return new ARMCodeGenPrepare();
1022}