blob: 0bd1f9ca63918d253fe44f11c67198da294ad357 [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 Parkerfcd8ada2018-11-05 10:58:37 +0000129 void Cleanup(SmallPtrSetImpl<Instruction*> &Sinks);
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
183/// Some instructions can use 8- and 16-bit operands, and we don't need to
184/// promote anything larger. We disallow booleans to make life easier when
185/// dealing with icmps but allow any other integer that is <= 16 bits. Void
186/// types are accepted so we can handle switches.
187static bool isSupportedType(Value *V) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000188 Type *Ty = V->getType();
Sam Parker7def86b2018-08-15 07:52:35 +0000189
190 // Allow voids and pointers, these won't be promoted.
191 if (Ty->isVoidTy() || Ty->isPointerTy())
Sam Parker3828c6f2018-07-23 12:27:47 +0000192 return true;
193
Sam Parker8c4b9642018-08-10 13:57:13 +0000194 if (auto *Ld = dyn_cast<LoadInst>(V))
195 Ty = cast<PointerType>(Ld->getPointerOperandType())->getElementType();
196
197 const IntegerType *IntTy = dyn_cast<IntegerType>(Ty);
Sam Parkeraaec3c62018-09-13 15:14:12 +0000198 if (!IntTy)
Sam Parker3828c6f2018-07-23 12:27:47 +0000199 return false;
200
Sam Parker8c4b9642018-08-10 13:57:13 +0000201 return IntTy->getBitWidth() == ARMCodeGenPrepare::TypeSize;
202}
Sam Parker3828c6f2018-07-23 12:27:47 +0000203
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000204/// Return true if the given value is a source in the use-def chain, producing
Sam Parker8c4b9642018-08-10 13:57:13 +0000205/// a narrow (i8, i16) value. These values will be zext to start the promotion
206/// of the tree to i32. We guarantee that these won't populate the upper bits
207/// of the register. ZExt on the loads will be free, and the same for call
208/// return values because we only accept ones that guarantee a zeroext ret val.
209/// Many arguments will have the zeroext attribute too, so those would be free
210/// too.
211static bool isSource(Value *V) {
Sam Parker7def86b2018-08-15 07:52:35 +0000212 if (!isa<IntegerType>(V->getType()))
213 return false;
Volodymyr Sapsai703ab842018-09-18 00:11:55 +0000214 // TODO Allow zext to be sources.
215 if (isa<Argument>(V))
Sam Parker8c4b9642018-08-10 13:57:13 +0000216 return true;
Volodymyr Sapsai703ab842018-09-18 00:11:55 +0000217 else if (isa<LoadInst>(V))
218 return true;
219 else if (isa<BitCastInst>(V))
220 return true;
221 else if (auto *Call = dyn_cast<CallInst>(V))
222 return Call->hasRetAttr(Attribute::AttrKind::ZExt);
223 else if (auto *Trunc = dyn_cast<TruncInst>(V))
224 return isSupportedType(Trunc);
Sam Parker8c4b9642018-08-10 13:57:13 +0000225 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000226}
227
228/// Return true if V will require any promoted values to be truncated for the
Sam Parker8c4b9642018-08-10 13:57:13 +0000229/// the IR to remain valid. We can't mutate the value type of these
230/// instructions.
Sam Parker3828c6f2018-07-23 12:27:47 +0000231static bool isSink(Value *V) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000232 // TODO The truncate also isn't actually necessary because we would already
233 // proved that the data value is kept within the range of the original data
234 // type.
Sam Parker3828c6f2018-07-23 12:27:47 +0000235 auto UsesNarrowValue = [](Value *V) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000236 return V->getType()->getScalarSizeInBits() == ARMCodeGenPrepare::TypeSize;
Sam Parker3828c6f2018-07-23 12:27:47 +0000237 };
238
239 if (auto *Store = dyn_cast<StoreInst>(V))
240 return UsesNarrowValue(Store->getValueOperand());
241 if (auto *Return = dyn_cast<ReturnInst>(V))
242 return UsesNarrowValue(Return->getReturnValue());
Sam Parker8c4b9642018-08-10 13:57:13 +0000243 if (auto *Trunc = dyn_cast<TruncInst>(V))
244 return UsesNarrowValue(Trunc->getOperand(0));
Sam Parker0e2f0bd2018-08-16 11:54:09 +0000245 if (auto *ZExt = dyn_cast<ZExtInst>(V))
246 return UsesNarrowValue(ZExt->getOperand(0));
Sam Parker13567db2018-08-16 10:05:39 +0000247 if (auto *ICmp = dyn_cast<ICmpInst>(V))
248 return ICmp->isSigned();
Sam Parker3828c6f2018-07-23 12:27:47 +0000249
250 return isa<CallInst>(V);
251}
252
Sam Parker3828c6f2018-07-23 12:27:47 +0000253/// Return whether the instruction can be promoted within any modifications to
Sam Parker84a2f8b2018-11-01 15:23:42 +0000254/// its operands or result.
255bool ARMCodeGenPrepare::isSafeOverflow(Instruction *I) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000256 // FIXME Do we need NSW too?
Sam Parker3828c6f2018-07-23 12:27:47 +0000257 if (isa<OverflowingBinaryOperator>(I) && I->hasNoUnsignedWrap())
258 return true;
259
Sam Parker75aca942018-09-26 10:56:00 +0000260 // We can support a, potentially, overflowing instruction (I) if:
261 // - It is only used by an unsigned icmp.
262 // - The icmp uses a constant.
263 // - The overflowing value (I) is decreasing, i.e would underflow - wrapping
264 // around zero to become a larger number than before.
265 // - The underflowing instruction (I) also uses a constant.
266 //
267 // We can then use the two constants to calculate whether the result would
268 // wrap in respect to itself in the original bitwidth. If it doesn't wrap,
269 // just underflows the range, the icmp would give the same result whether the
270 // result has been truncated or not. We calculate this by:
271 // - Zero extending both constants, if needed, to 32-bits.
272 // - Take the absolute value of I's constant, adding this to the icmp const.
273 // - Check that this value is not out of range for small type. If it is, it
274 // means that it has underflowed enough to wrap around the icmp constant.
275 //
276 // For example:
277 //
278 // %sub = sub i8 %a, 2
279 // %cmp = icmp ule i8 %sub, 254
280 //
281 // If %a = 0, %sub = -2 == FE == 254
282 // But if this is evalulated as a i32
283 // %sub = -2 == FF FF FF FE == 4294967294
284 // So the unsigned compares (i8 and i32) would not yield the same result.
285 //
286 // Another way to look at it is:
287 // %a - 2 <= 254
288 // %a + 2 <= 254 + 2
289 // %a <= 256
290 // And we can't represent 256 in the i8 format, so we don't support it.
291 //
292 // Whereas:
293 //
294 // %sub i8 %a, 1
295 // %cmp = icmp ule i8 %sub, 254
296 //
297 // If %a = 0, %sub = -1 == FF == 255
298 // As i32:
299 // %sub = -1 == FF FF FF FF == 4294967295
300 //
301 // In this case, the unsigned compare results would be the same and this
302 // would also be true for ult, uge and ugt:
303 // - (255 < 254) == (0xFFFFFFFF < 254) == false
304 // - (255 <= 254) == (0xFFFFFFFF <= 254) == false
305 // - (255 > 254) == (0xFFFFFFFF > 254) == true
306 // - (255 >= 254) == (0xFFFFFFFF >= 254) == true
307 //
308 // To demonstrate why we can't handle increasing values:
309 //
310 // %add = add i8 %a, 2
311 // %cmp = icmp ult i8 %add, 127
312 //
313 // If %a = 254, %add = 256 == (i8 1)
314 // As i32:
315 // %add = 256
316 //
317 // (1 < 127) != (256 < 127)
318
Sam Parker3828c6f2018-07-23 12:27:47 +0000319 unsigned Opc = I->getOpcode();
Sam Parker75aca942018-09-26 10:56:00 +0000320 if (Opc != Instruction::Add && Opc != Instruction::Sub)
321 return false;
322
323 if (!I->hasOneUse() ||
324 !isa<ICmpInst>(*I->user_begin()) ||
325 !isa<ConstantInt>(I->getOperand(1)))
326 return false;
327
328 ConstantInt *OverflowConst = cast<ConstantInt>(I->getOperand(1));
329 bool NegImm = OverflowConst->isNegative();
330 bool IsDecreasing = ((Opc == Instruction::Sub) && !NegImm) ||
331 ((Opc == Instruction::Add) && NegImm);
332 if (!IsDecreasing)
333 return false;
334
335 // Don't support an icmp that deals with sign bits.
336 auto *CI = cast<ICmpInst>(*I->user_begin());
337 if (CI->isSigned() || CI->isEquality())
338 return false;
339
340 ConstantInt *ICmpConst = nullptr;
341 if (auto *Const = dyn_cast<ConstantInt>(CI->getOperand(0)))
342 ICmpConst = Const;
343 else if (auto *Const = dyn_cast<ConstantInt>(CI->getOperand(1)))
344 ICmpConst = Const;
345 else
346 return false;
347
348 // Now check that the result can't wrap on itself.
349 APInt Total = ICmpConst->getValue().getBitWidth() < 32 ?
350 ICmpConst->getValue().zext(32) : ICmpConst->getValue();
351
352 Total += OverflowConst->getValue().getBitWidth() < 32 ?
353 OverflowConst->getValue().abs().zext(32) : OverflowConst->getValue().abs();
354
355 APInt Max = APInt::getAllOnesValue(ARMCodeGenPrepare::TypeSize);
356
357 if (Total.getBitWidth() > Max.getBitWidth()) {
358 if (Total.ugt(Max.zext(Total.getBitWidth())))
Sam Parker3828c6f2018-07-23 12:27:47 +0000359 return false;
Sam Parker75aca942018-09-26 10:56:00 +0000360 } else if (Max.getBitWidth() > Total.getBitWidth()) {
361 if (Total.zext(Max.getBitWidth()).ugt(Max))
Sam Parker3828c6f2018-07-23 12:27:47 +0000362 return false;
Sam Parker75aca942018-09-26 10:56:00 +0000363 } else if (Total.ugt(Max))
364 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000365
Sam Parker75aca942018-09-26 10:56:00 +0000366 LLVM_DEBUG(dbgs() << "ARM CGP: Allowing safe overflow for " << *I << "\n");
367 return true;
Sam Parker3828c6f2018-07-23 12:27:47 +0000368}
369
370static bool shouldPromote(Value *V) {
Sam Parkeraaec3c62018-09-13 15:14:12 +0000371 if (!isa<IntegerType>(V->getType()) || isSink(V))
Sam Parker8c4b9642018-08-10 13:57:13 +0000372 return false;
373
374 if (isSource(V))
375 return true;
376
Sam Parker3828c6f2018-07-23 12:27:47 +0000377 auto *I = dyn_cast<Instruction>(V);
378 if (!I)
379 return false;
380
Sam Parker8c4b9642018-08-10 13:57:13 +0000381 if (isa<ICmpInst>(I))
Sam Parker3828c6f2018-07-23 12:27:47 +0000382 return false;
383
Sam Parker3828c6f2018-07-23 12:27:47 +0000384 return true;
385}
386
387/// Return whether we can safely mutate V's type to ExtTy without having to be
388/// concerned with zero extending or truncation.
389static bool isPromotedResultSafe(Value *V) {
390 if (!isa<Instruction>(V))
391 return true;
392
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000393 if (generateSignBits(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000394 return false;
395
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000396 return !isa<OverflowingBinaryOperator>(V);
Sam Parker3828c6f2018-07-23 12:27:47 +0000397}
398
399/// Return the intrinsic for the instruction that can perform the same
400/// operation but on a narrow type. This is using the parallel dsp intrinsics
401/// on scalar values.
Sam Parker8c4b9642018-08-10 13:57:13 +0000402static Intrinsic::ID getNarrowIntrinsic(Instruction *I) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000403 // Whether we use the signed or unsigned versions of these intrinsics
404 // doesn't matter because we're not using the GE bits that they set in
405 // the APSR.
406 switch(I->getOpcode()) {
407 default:
408 break;
409 case Instruction::Add:
Sam Parker8c4b9642018-08-10 13:57:13 +0000410 return ARMCodeGenPrepare::TypeSize == 16 ? Intrinsic::arm_uadd16 :
Sam Parker3828c6f2018-07-23 12:27:47 +0000411 Intrinsic::arm_uadd8;
412 case Instruction::Sub:
Sam Parker8c4b9642018-08-10 13:57:13 +0000413 return ARMCodeGenPrepare::TypeSize == 16 ? Intrinsic::arm_usub16 :
Sam Parker3828c6f2018-07-23 12:27:47 +0000414 Intrinsic::arm_usub8;
415 }
416 llvm_unreachable("unhandled opcode for narrow intrinsic");
417}
418
Sam Parker84a2f8b2018-11-01 15:23:42 +0000419static void ReplaceAllUsersOfWith(Value *From, Value *To) {
420 SmallVector<Instruction*, 4> Users;
421 Instruction *InstTo = dyn_cast<Instruction>(To);
422 for (Use &U : From->uses()) {
423 auto *User = cast<Instruction>(U.getUser());
424 if (InstTo && User->isIdenticalTo(InstTo))
425 continue;
426 Users.push_back(User);
427 }
428
429 for (auto *U : Users)
430 U->replaceUsesOfWith(From, To);
431}
432
433void
434IRPromoter::PrepareConstants(SmallPtrSetImpl<Value*> &Visited,
435 SmallPtrSetImpl<Instruction*> &SafeToPromote) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000436 IRBuilder<> Builder{Ctx};
Sam Parker84a2f8b2018-11-01 15:23:42 +0000437 // First step is to prepare the instructions for mutation. Most constants
438 // just need to be zero extended into their new type, but complications arise
439 // because:
440 // - For nuw binary operators, negative immediates would need sign extending;
441 // however, instead we'll change them to positive and zext them. We can do
442 // this because:
443 // > The operators that can wrap are: add, sub, mul and shl.
444 // > shl interprets its second operand as unsigned and if the first operand
445 // is an immediate, it will need zext to be nuw.
Sam Parkerfec793c2018-11-05 11:26:04 +0000446 // > I'm assuming mul has to interpret immediates as unsigned for nuw.
Sam Parker84a2f8b2018-11-01 15:23:42 +0000447 // > Which leaves the nuw add and sub to be handled; as with shl, if an
448 // immediate is used as operand 0, it will need zext to be nuw.
449 // - We also allow add and sub to safely overflow in certain circumstances
450 // and only when the value (operand 0) is being decreased.
451 //
452 // For adds and subs, that are either nuw or safely wrap and use a negative
453 // immediate as operand 1, we create an equivalent instruction using a
454 // positive immediate. That positive immediate can then be zext along with
455 // all the other immediates later.
456 for (auto *V : Visited) {
457 if (!isa<Instruction>(V))
458 continue;
Sam Parker3828c6f2018-07-23 12:27:47 +0000459
Sam Parker84a2f8b2018-11-01 15:23:42 +0000460 auto *I = cast<Instruction>(V);
461 if (SafeToPromote.count(I)) {
Sam Parker13567db2018-08-16 10:05:39 +0000462
Sam Parker84a2f8b2018-11-01 15:23:42 +0000463 if (!isa<OverflowingBinaryOperator>(I))
Sam Parker3828c6f2018-07-23 12:27:47 +0000464 continue;
Sam Parker84a2f8b2018-11-01 15:23:42 +0000465
466 if (auto *Const = dyn_cast<ConstantInt>(I->getOperand(1))) {
467 if (!Const->isNegative())
468 break;
469
470 unsigned Opc = I->getOpcode();
Sam Parkerfec793c2018-11-05 11:26:04 +0000471 if (Opc != Instruction::Add && Opc != Instruction::Sub)
472 continue;
Sam Parker84a2f8b2018-11-01 15:23:42 +0000473
474 LLVM_DEBUG(dbgs() << "ARM CGP: Adjusting " << *I << "\n");
475 auto *NewConst = ConstantInt::get(Ctx, Const->getValue().abs());
476 Builder.SetInsertPoint(I);
477 Value *NewVal = Opc == Instruction::Sub ?
478 Builder.CreateAdd(I->getOperand(0), NewConst) :
479 Builder.CreateSub(I->getOperand(0), NewConst);
480 LLVM_DEBUG(dbgs() << "ARM CGP: New equivalent: " << *NewVal << "\n");
481
482 if (auto *NewInst = dyn_cast<Instruction>(NewVal)) {
483 NewInst->copyIRFlags(I);
484 NewInsts.insert(NewInst);
485 }
486 InstsToRemove.push_back(I);
487 I->replaceAllUsesWith(NewVal);
488 }
Sam Parker3828c6f2018-07-23 12:27:47 +0000489 }
Sam Parker84a2f8b2018-11-01 15:23:42 +0000490 }
491 for (auto *I : NewInsts)
492 Visited.insert(I);
493}
Sam Parker3828c6f2018-07-23 12:27:47 +0000494
Sam Parker84a2f8b2018-11-01 15:23:42 +0000495void IRPromoter::ExtendSources(SmallPtrSetImpl<Value*> &Sources) {
496 IRBuilder<> Builder{Ctx};
Sam Parker3828c6f2018-07-23 12:27:47 +0000497
498 auto InsertZExt = [&](Value *V, Instruction *InsertPt) {
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000499 assert(V->getType() != ExtTy && "zext already extends to i32");
Sam Parker3828c6f2018-07-23 12:27:47 +0000500 LLVM_DEBUG(dbgs() << "ARM CGP: Inserting ZExt for " << *V << "\n");
501 Builder.SetInsertPoint(InsertPt);
502 if (auto *I = dyn_cast<Instruction>(V))
503 Builder.SetCurrentDebugLocation(I->getDebugLoc());
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000504
505 Value *ZExt = Builder.CreateZExt(V, ExtTy);
506 if (auto *I = dyn_cast<Instruction>(ZExt)) {
507 if (isa<Argument>(V))
508 I->moveBefore(InsertPt);
509 else
510 I->moveAfter(InsertPt);
511 NewInsts.insert(I);
512 }
Sam Parker3828c6f2018-07-23 12:27:47 +0000513 ReplaceAllUsersOfWith(V, ZExt);
Sam Parker13567db2018-08-16 10:05:39 +0000514 TruncTysMap[ZExt] = TruncTysMap[V];
Sam Parker3828c6f2018-07-23 12:27:47 +0000515 };
516
Sam Parker84a2f8b2018-11-01 15:23:42 +0000517 // Now, insert extending instructions between the sources and their users.
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000518 LLVM_DEBUG(dbgs() << "ARM CGP: Promoting sources:\n");
519 for (auto V : Sources) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000520 LLVM_DEBUG(dbgs() << " - " << *V << "\n");
Sam Parker8c4b9642018-08-10 13:57:13 +0000521 if (auto *I = dyn_cast<Instruction>(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000522 InsertZExt(I, I);
523 else if (auto *Arg = dyn_cast<Argument>(V)) {
524 BasicBlock &BB = Arg->getParent()->front();
525 InsertZExt(Arg, &*BB.getFirstInsertionPt());
526 } else {
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000527 llvm_unreachable("unhandled source that needs extending");
Sam Parker3828c6f2018-07-23 12:27:47 +0000528 }
529 Promoted.insert(V);
530 }
Sam Parker84a2f8b2018-11-01 15:23:42 +0000531}
Sam Parker3828c6f2018-07-23 12:27:47 +0000532
Sam Parker84a2f8b2018-11-01 15:23:42 +0000533void IRPromoter::PromoteTree(SmallPtrSetImpl<Value*> &Visited,
534 SmallPtrSetImpl<Value*> &Sources,
535 SmallPtrSetImpl<Instruction*> &Sinks,
536 SmallPtrSetImpl<Instruction*> &SafeToPromote) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000537 LLVM_DEBUG(dbgs() << "ARM CGP: Mutating the tree..\n");
Sam Parker84a2f8b2018-11-01 15:23:42 +0000538
539 IRBuilder<> Builder{Ctx};
540
541 // Mutate the types of the instructions within the tree. Here we handle
Sam Parker3828c6f2018-07-23 12:27:47 +0000542 // constant operands.
543 for (auto *V : Visited) {
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000544 if (Sources.count(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000545 continue;
546
Sam Parker3828c6f2018-07-23 12:27:47 +0000547 auto *I = cast<Instruction>(V);
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000548 if (Sinks.count(I))
Sam Parker3828c6f2018-07-23 12:27:47 +0000549 continue;
550
Sam Parker7def86b2018-08-15 07:52:35 +0000551 for (unsigned i = 0, e = I->getNumOperands(); i < e; ++i) {
552 Value *Op = I->getOperand(i);
553 if ((Op->getType() == ExtTy) || !isa<IntegerType>(Op->getType()))
Sam Parker3828c6f2018-07-23 12:27:47 +0000554 continue;
555
Sam Parker84a2f8b2018-11-01 15:23:42 +0000556 if (auto *Const = dyn_cast<ConstantInt>(Op)) {
557 Constant *NewConst = ConstantExpr::getZExt(Const, ExtTy);
558 I->setOperand(i, NewConst);
559 } else if (isa<UndefValue>(Op))
Sam Parker7def86b2018-08-15 07:52:35 +0000560 I->setOperand(i, UndefValue::get(ExtTy));
Sam Parker3828c6f2018-07-23 12:27:47 +0000561 }
562
563 if (shouldPromote(I)) {
564 I->mutateType(ExtTy);
565 Promoted.insert(I);
566 }
567 }
568
Sam Parker84a2f8b2018-11-01 15:23:42 +0000569 // Finally, any instructions that should be promoted but haven't yet been,
570 // need to be handled using intrinsics.
Sam Parker3828c6f2018-07-23 12:27:47 +0000571 for (auto *V : Visited) {
Sam Parker84a2f8b2018-11-01 15:23:42 +0000572 auto *I = dyn_cast<Instruction>(V);
573 if (!I)
Sam Parker3828c6f2018-07-23 12:27:47 +0000574 continue;
Sam Parker8c4b9642018-08-10 13:57:13 +0000575
Sam Parker84a2f8b2018-11-01 15:23:42 +0000576 if (Sources.count(I) || Sinks.count(I))
Sam Parker3828c6f2018-07-23 12:27:47 +0000577 continue;
578
Sam Parker84a2f8b2018-11-01 15:23:42 +0000579 if (!shouldPromote(I) || SafeToPromote.count(I) || NewInsts.count(I))
580 continue;
581
Sam Parker75aca942018-09-26 10:56:00 +0000582 assert(EnableDSP && "DSP intrinisc insertion not enabled!");
583
Sam Parker3828c6f2018-07-23 12:27:47 +0000584 // Replace unsafe instructions with appropriate intrinsic calls.
Sam Parker84a2f8b2018-11-01 15:23:42 +0000585 LLVM_DEBUG(dbgs() << "ARM CGP: Inserting DSP intrinsic for "
586 << *I << "\n");
587 Function *DSPInst =
588 Intrinsic::getDeclaration(M, getNarrowIntrinsic(I));
589 Builder.SetInsertPoint(I);
590 Builder.SetCurrentDebugLocation(I->getDebugLoc());
591 Value *Args[] = { I->getOperand(0), I->getOperand(1) };
592 CallInst *Call = Builder.CreateCall(DSPInst, Args);
593 ReplaceAllUsersOfWith(I, Call);
594 InstsToRemove.push_back(I);
595 NewInsts.insert(Call);
596 TruncTysMap[Call] = OrigTy;
Sam Parker3828c6f2018-07-23 12:27:47 +0000597 }
Sam Parker84a2f8b2018-11-01 15:23:42 +0000598}
599
600void IRPromoter::TruncateSinks(SmallPtrSetImpl<Value*> &Sources,
601 SmallPtrSetImpl<Instruction*> &Sinks) {
602 LLVM_DEBUG(dbgs() << "ARM CGP: Fixing up the sinks:\n");
603
604 IRBuilder<> Builder{Ctx};
Sam Parker3828c6f2018-07-23 12:27:47 +0000605
Sam Parker13567db2018-08-16 10:05:39 +0000606 auto InsertTrunc = [&](Value *V) -> Instruction* {
607 if (!isa<Instruction>(V) || !isa<IntegerType>(V->getType()))
608 return nullptr;
609
Sam Parker0e2f0bd2018-08-16 11:54:09 +0000610 if ((!Promoted.count(V) && !NewInsts.count(V)) || !TruncTysMap.count(V) ||
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000611 Sources.count(V))
Sam Parker13567db2018-08-16 10:05:39 +0000612 return nullptr;
613
614 Type *TruncTy = TruncTysMap[V];
615 if (TruncTy == ExtTy)
616 return nullptr;
617
618 LLVM_DEBUG(dbgs() << "ARM CGP: Creating " << *TruncTy << " Trunc for "
619 << *V << "\n");
620 Builder.SetInsertPoint(cast<Instruction>(V));
Sam Parker48fbf752018-11-01 16:44:45 +0000621 auto *Trunc = dyn_cast<Instruction>(Builder.CreateTrunc(V, TruncTy));
622 if (Trunc)
623 NewInsts.insert(Trunc);
Sam Parker13567db2018-08-16 10:05:39 +0000624 return Trunc;
625 };
626
Sam Parker3828c6f2018-07-23 12:27:47 +0000627 // Fix up any stores or returns that use the results of the promoted
628 // chain.
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000629 for (auto I : Sinks) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000630 LLVM_DEBUG(dbgs() << " - " << *I << "\n");
Sam Parker13567db2018-08-16 10:05:39 +0000631
632 // Handle calls separately as we need to iterate over arg operands.
633 if (auto *Call = dyn_cast<CallInst>(I)) {
634 for (unsigned i = 0; i < Call->getNumArgOperands(); ++i) {
635 Value *Arg = Call->getArgOperand(i);
636 if (Instruction *Trunc = InsertTrunc(Arg)) {
637 Trunc->moveBefore(Call);
638 Call->setArgOperand(i, Trunc);
639 }
640 }
641 continue;
Sam Parker3828c6f2018-07-23 12:27:47 +0000642 }
643
Sam Parker13567db2018-08-16 10:05:39 +0000644 // Now handle the others.
Sam Parker3828c6f2018-07-23 12:27:47 +0000645 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
Sam Parker13567db2018-08-16 10:05:39 +0000646 if (Instruction *Trunc = InsertTrunc(I->getOperand(i))) {
647 Trunc->moveBefore(I);
648 I->setOperand(i, Trunc);
Sam Parker3828c6f2018-07-23 12:27:47 +0000649 }
650 }
651 }
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000652
653}
654
655void IRPromoter::Cleanup(SmallPtrSetImpl<Instruction*> &Sinks) {
656 // Some zext sinks will now have become redundant, along with their trunc
657 // operands, so remove them.
658 for (auto I : Sinks) {
659 if (auto *ZExt = dyn_cast<ZExtInst>(I)) {
660 if (ZExt->getDestTy() != ExtTy)
661 continue;
662
663 Value *Src = ZExt->getOperand(0);
664 if (ZExt->getSrcTy() == ZExt->getDestTy()) {
665 LLVM_DEBUG(dbgs() << "ARM CGP: Removing unnecessary zext\n");
666 ReplaceAllUsersOfWith(ZExt, Src);
667 InstsToRemove.push_back(ZExt);
668 continue;
669 }
670
671 // For any truncs that we insert to handle zexts, we can replace the
672 // result of the zext with the input to the trunc.
673 if (NewInsts.count(Src) && isa<TruncInst>(Src)) {
674 auto *Trunc = cast<TruncInst>(Src);
675 assert(Trunc->getOperand(0)->getType() == ExtTy &&
676 "expected inserted trunc to be operating on i32");
677 LLVM_DEBUG(dbgs() << "ARM CGP: Replacing zext with trunc operand: "
678 << *Trunc->getOperand(0));
679 ReplaceAllUsersOfWith(ZExt, Trunc->getOperand(0));
680 InstsToRemove.push_back(ZExt);
681 }
682 }
683 }
684
685 for (auto *I : InstsToRemove) {
686 LLVM_DEBUG(dbgs() << "ARM CGP: Removing " << *I << "\n");
687 I->dropAllReferences();
688 I->eraseFromParent();
689 }
690
691 InstsToRemove.clear();
692 NewInsts.clear();
693 TruncTysMap.clear();
694 Promoted.clear();
Sam Parker84a2f8b2018-11-01 15:23:42 +0000695}
696
697void IRPromoter::Mutate(Type *OrigTy,
698 SmallPtrSetImpl<Value*> &Visited,
699 SmallPtrSetImpl<Value*> &Sources,
700 SmallPtrSetImpl<Instruction*> &Sinks,
701 SmallPtrSetImpl<Instruction*> &SafeToPromote) {
702 LLVM_DEBUG(dbgs() << "ARM CGP: Promoting use-def chains to from "
703 << ARMCodeGenPrepare::TypeSize << " to 32-bits\n");
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000704
705 assert(isa<IntegerType>(OrigTy) && "expected integer type");
706 this->OrigTy = cast<IntegerType>(OrigTy);
707 assert(OrigTy->getPrimitiveSizeInBits() < ExtTy->getPrimitiveSizeInBits() &&
708 "original type not smaller than extended type");
Sam Parker84a2f8b2018-11-01 15:23:42 +0000709
710 // Cache original types.
711 for (auto *V : Visited)
712 TruncTysMap[V] = V->getType();
713
714 // Convert adds and subs using negative immediates to equivalent instructions
715 // that use positive constants.
716 PrepareConstants(Visited, SafeToPromote);
717
718 // Insert zext instructions between sources and their users.
719 ExtendSources(Sources);
720
721 // Promote visited instructions, mutating their types in place. Also insert
722 // DSP intrinsics, if enabled, for adds and subs which would be unsafe to
723 // promote.
724 PromoteTree(Visited, Sources, Sinks, SafeToPromote);
725
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000726 // Insert trunc instructions for use by calls, stores etc...
Sam Parker84a2f8b2018-11-01 15:23:42 +0000727 TruncateSinks(Sources, Sinks);
728
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000729 // Finally, remove unecessary zexts and truncs, delete old instructions and
730 // clear the data structures.
731 Cleanup(Sinks);
732
Sam Parker0e2f0bd2018-08-16 11:54:09 +0000733 LLVM_DEBUG(dbgs() << "ARM CGP: Mutation complete:\n");
Sam Parkeraaec3c62018-09-13 15:14:12 +0000734 LLVM_DEBUG(dbgs();
735 for (auto *V : Sources)
736 V->dump();
737 for (auto *I : NewInsts)
738 I->dump();
739 for (auto *V : Visited) {
740 if (!Sources.count(V))
741 V->dump();
742 });
Sam Parker3828c6f2018-07-23 12:27:47 +0000743}
744
Sam Parker8c4b9642018-08-10 13:57:13 +0000745/// We accept most instructions, as well as Arguments and ConstantInsts. We
746/// Disallow casts other than zext and truncs and only allow calls if their
747/// return value is zeroext. We don't allow opcodes that can introduce sign
748/// bits.
749bool ARMCodeGenPrepare::isSupportedValue(Value *V) {
Sam Parker13567db2018-08-16 10:05:39 +0000750 if (isa<ICmpInst>(V))
751 return true;
Sam Parker8c4b9642018-08-10 13:57:13 +0000752
Volodymyr Sapsai703ab842018-09-18 00:11:55 +0000753 // Memory instructions
754 if (isa<StoreInst>(V) || isa<GetElementPtrInst>(V))
755 return true;
756
757 // Branches and targets.
758 if( isa<BranchInst>(V) || isa<SwitchInst>(V) || isa<BasicBlock>(V))
759 return true;
760
761 // Non-instruction values that we can handle.
762 if ((isa<Constant>(V) && !isa<ConstantExpr>(V)) || isa<Argument>(V))
763 return isSupportedType(V);
764
765 if (isa<PHINode>(V) || isa<SelectInst>(V) || isa<ReturnInst>(V) ||
766 isa<LoadInst>(V))
767 return isSupportedType(V);
768
769 // Truncs can be either sources or sinks.
770 if (auto *Trunc = dyn_cast<TruncInst>(V))
771 return isSupportedType(Trunc) || isSupportedType(Trunc->getOperand(0));
772
773 if (isa<CastInst>(V) && !isa<SExtInst>(V))
774 return isSupportedType(cast<CastInst>(V)->getOperand(0));
Sam Parker0e2f0bd2018-08-16 11:54:09 +0000775
Sam Parker8c4b9642018-08-10 13:57:13 +0000776 // Special cases for calls as we need to check for zeroext
777 // TODO We should accept calls even if they don't have zeroext, as they can
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000778 // still be sinks.
Sam Parker8c4b9642018-08-10 13:57:13 +0000779 if (auto *Call = dyn_cast<CallInst>(V))
780 return isSupportedType(Call) &&
781 Call->hasRetAttr(Attribute::AttrKind::ZExt);
782
Volodymyr Sapsai703ab842018-09-18 00:11:55 +0000783 if (!isa<BinaryOperator>(V))
784 return false;
785
786 if (!isSupportedType(V))
787 return false;
788
789 if (generateSignBits(V)) {
790 LLVM_DEBUG(dbgs() << "ARM CGP: No, instruction can generate sign bits.\n");
791 return false;
792 }
793 return true;
Sam Parker8c4b9642018-08-10 13:57:13 +0000794}
795
796/// Check that the type of V would be promoted and that the original type is
797/// smaller than the targeted promoted type. Check that we're not trying to
798/// promote something larger than our base 'TypeSize' type.
799bool ARMCodeGenPrepare::isLegalToPromote(Value *V) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000800
801 auto *I = dyn_cast<Instruction>(V);
802 if (!I)
Sam Parker84a2f8b2018-11-01 15:23:42 +0000803 return true;
804
805 if (SafeToPromote.count(I))
806 return true;
807
808 if (isPromotedResultSafe(V) || isSafeOverflow(I)) {
809 SafeToPromote.insert(I);
810 return true;
811 }
812
813 if (I->getOpcode() != Instruction::Add && I->getOpcode() != Instruction::Sub)
Sam Parker8c4b9642018-08-10 13:57:13 +0000814 return false;
815
816 // If promotion is not safe, can we use a DSP instruction to natively
817 // handle the narrow type?
Sam Parker3828c6f2018-07-23 12:27:47 +0000818 if (!ST->hasDSP() || !EnableDSP || !isSupportedType(I))
819 return false;
820
821 if (ST->isThumb() && !ST->hasThumb2())
822 return false;
823
Sam Parker3828c6f2018-07-23 12:27:47 +0000824 // TODO
825 // Would it be profitable? For Thumb code, these parallel DSP instructions
826 // are only Thumb-2, so we wouldn't be able to dual issue on Cortex-M33. For
827 // Cortex-A, specifically Cortex-A72, the latency is double and throughput is
828 // halved. They also do not take immediates as operands.
829 for (auto &Op : I->operands()) {
830 if (isa<Constant>(Op)) {
831 if (!EnableDSPWithImms)
832 return false;
833 }
834 }
Sam Parker84a2f8b2018-11-01 15:23:42 +0000835 LLVM_DEBUG(dbgs() << "ARM CGP: Will use an intrinsic for: " << *I << "\n");
Sam Parker3828c6f2018-07-23 12:27:47 +0000836 return true;
837}
838
Sam Parker3828c6f2018-07-23 12:27:47 +0000839bool ARMCodeGenPrepare::TryToPromote(Value *V) {
840 OrigTy = V->getType();
841 TypeSize = OrigTy->getPrimitiveSizeInBits();
Sam Parkerfabf7fe2018-08-15 13:29:50 +0000842 if (TypeSize > 16 || TypeSize < 8)
Sam Parker8c4b9642018-08-10 13:57:13 +0000843 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000844
Sam Parker84a2f8b2018-11-01 15:23:42 +0000845 SafeToPromote.clear();
846
Sam Parker3828c6f2018-07-23 12:27:47 +0000847 if (!isSupportedValue(V) || !shouldPromote(V) || !isLegalToPromote(V))
848 return false;
849
Sam Parker8c4b9642018-08-10 13:57:13 +0000850 LLVM_DEBUG(dbgs() << "ARM CGP: TryToPromote: " << *V << ", TypeSize = "
851 << TypeSize << "\n");
Sam Parker3828c6f2018-07-23 12:27:47 +0000852
853 SetVector<Value*> WorkList;
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000854 SmallPtrSet<Value*, 8> Sources;
855 SmallPtrSet<Instruction*, 4> Sinks;
Sam Parker3828c6f2018-07-23 12:27:47 +0000856 SmallPtrSet<Value*, 16> CurrentVisited;
Sam Parker84a2f8b2018-11-01 15:23:42 +0000857 WorkList.insert(V);
Sam Parker3828c6f2018-07-23 12:27:47 +0000858
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000859 // Return true if V was added to the worklist as a supported instruction,
860 // if it was already visited, or if we don't need to explore it (e.g.
861 // pointer values and GEPs), and false otherwise.
Sam Parker3828c6f2018-07-23 12:27:47 +0000862 auto AddLegalInst = [&](Value *V) {
863 if (CurrentVisited.count(V))
864 return true;
865
Sam Parker0d511972018-08-16 12:24:40 +0000866 // Ignore GEPs because they don't need promoting and the constant indices
867 // will prevent the transformation.
868 if (isa<GetElementPtrInst>(V))
869 return true;
870
Sam Parker3828c6f2018-07-23 12:27:47 +0000871 if (!isSupportedValue(V) || (shouldPromote(V) && !isLegalToPromote(V))) {
872 LLVM_DEBUG(dbgs() << "ARM CGP: Can't handle: " << *V << "\n");
873 return false;
874 }
875
876 WorkList.insert(V);
877 return true;
878 };
879
880 // Iterate through, and add to, a tree of operands and users in the use-def.
881 while (!WorkList.empty()) {
882 Value *V = WorkList.back();
883 WorkList.pop_back();
884 if (CurrentVisited.count(V))
885 continue;
886
Sam Parker7def86b2018-08-15 07:52:35 +0000887 // Ignore non-instructions, other than arguments.
Sam Parker3828c6f2018-07-23 12:27:47 +0000888 if (!isa<Instruction>(V) && !isSource(V))
889 continue;
890
891 // If we've already visited this value from somewhere, bail now because
892 // the tree has already been explored.
893 // TODO: This could limit the transform, ie if we try to promote something
894 // from an i8 and fail first, before trying an i16.
Sam Parkeraaec3c62018-09-13 15:14:12 +0000895 if (AllVisited.count(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000896 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000897
898 CurrentVisited.insert(V);
899 AllVisited.insert(V);
900
901 // Calls can be both sources and sinks.
902 if (isSink(V))
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000903 Sinks.insert(cast<Instruction>(V));
Sam Parker3828c6f2018-07-23 12:27:47 +0000904 if (isSource(V))
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000905 Sources.insert(V);
Sam Parker3828c6f2018-07-23 12:27:47 +0000906 else if (auto *I = dyn_cast<Instruction>(V)) {
907 // Visit operands of any instruction visited.
908 for (auto &U : I->operands()) {
909 if (!AddLegalInst(U))
910 return false;
911 }
912 }
913
914 // Don't visit users of a node which isn't going to be mutated unless its a
915 // source.
916 if (isSource(V) || shouldPromote(V)) {
917 for (Use &U : V->uses()) {
918 if (!AddLegalInst(U.getUser()))
919 return false;
920 }
921 }
922 }
923
Sam Parker3828c6f2018-07-23 12:27:47 +0000924 LLVM_DEBUG(dbgs() << "ARM CGP: Visited nodes:\n";
925 for (auto *I : CurrentVisited)
926 I->dump();
927 );
Sam Parker7def86b2018-08-15 07:52:35 +0000928 unsigned ToPromote = 0;
929 for (auto *V : CurrentVisited) {
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000930 if (Sources.count(V))
Sam Parker7def86b2018-08-15 07:52:35 +0000931 continue;
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000932 if (Sinks.count(cast<Instruction>(V)))
Sam Parker7def86b2018-08-15 07:52:35 +0000933 continue;
934 ++ToPromote;
935 }
936
937 if (ToPromote < 2)
938 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000939
Sam Parker84a2f8b2018-11-01 15:23:42 +0000940 Promoter->Mutate(OrigTy, CurrentVisited, Sources, Sinks, SafeToPromote);
Sam Parker3828c6f2018-07-23 12:27:47 +0000941 return true;
942}
943
944bool ARMCodeGenPrepare::doInitialization(Module &M) {
945 Promoter = new IRPromoter(&M);
946 return false;
947}
948
949bool ARMCodeGenPrepare::runOnFunction(Function &F) {
950 if (skipFunction(F) || DisableCGP)
951 return false;
952
953 auto *TPC = &getAnalysis<TargetPassConfig>();
954 if (!TPC)
955 return false;
956
957 const TargetMachine &TM = TPC->getTM<TargetMachine>();
958 ST = &TM.getSubtarget<ARMSubtarget>(F);
959 bool MadeChange = false;
960 LLVM_DEBUG(dbgs() << "ARM CGP: Running on " << F.getName() << "\n");
961
962 // Search up from icmps to try to promote their operands.
963 for (BasicBlock &BB : F) {
964 auto &Insts = BB.getInstList();
965 for (auto &I : Insts) {
966 if (AllVisited.count(&I))
967 continue;
968
969 if (isa<ICmpInst>(I)) {
970 auto &CI = cast<ICmpInst>(I);
971
972 // Skip signed or pointer compares
973 if (CI.isSigned() || !isa<IntegerType>(CI.getOperand(0)->getType()))
974 continue;
975
Sam Parker3828c6f2018-07-23 12:27:47 +0000976 for (auto &Op : CI.operands()) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000977 if (auto *I = dyn_cast<Instruction>(Op))
978 MadeChange |= TryToPromote(I);
Sam Parker3828c6f2018-07-23 12:27:47 +0000979 }
980 }
981 }
Sam Parker3828c6f2018-07-23 12:27:47 +0000982 LLVM_DEBUG(if (verifyFunction(F, &dbgs())) {
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000983 dbgs() << F;
Sam Parker3828c6f2018-07-23 12:27:47 +0000984 report_fatal_error("Broken function after type promotion");
985 });
986 }
987 if (MadeChange)
988 LLVM_DEBUG(dbgs() << "After ARMCodeGenPrepare: " << F << "\n");
989
990 return MadeChange;
991}
992
Matt Morehousea70685f2018-07-23 17:00:45 +0000993bool ARMCodeGenPrepare::doFinalization(Module &M) {
994 delete Promoter;
995 return false;
996}
997
Sam Parker3828c6f2018-07-23 12:27:47 +0000998INITIALIZE_PASS_BEGIN(ARMCodeGenPrepare, DEBUG_TYPE,
999 "ARM IR optimizations", false, false)
1000INITIALIZE_PASS_END(ARMCodeGenPrepare, DEBUG_TYPE, "ARM IR optimizations",
1001 false, false)
1002
1003char ARMCodeGenPrepare::ID = 0;
Sam Parker8c4b9642018-08-10 13:57:13 +00001004unsigned ARMCodeGenPrepare::TypeSize = 0;
Sam Parker3828c6f2018-07-23 12:27:47 +00001005
1006FunctionPass *llvm::createARMCodeGenPreparePass() {
1007 return new ARMCodeGenPrepare();
1008}