blob: 06949bea70ae54c488fe195cf0072d4a7829bfbf [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 Parker08979cd2018-11-09 09:28:27 +0000209 if (!isa<IntegerType>(Ty))
Sam Parker3828c6f2018-07-23 12:27:47 +0000210 return false;
211
Sam Parker08979cd2018-11-09 09:28:27 +0000212 return LessOrEqualTypeSize(V);
Sam Parker8c4b9642018-08-10 13:57:13 +0000213}
Sam Parker3828c6f2018-07-23 12:27:47 +0000214
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000215/// Return true if the given value is a source in the use-def chain, producing
Sam Parker8c4b9642018-08-10 13:57:13 +0000216/// a narrow (i8, i16) value. These values will be zext to start the promotion
217/// of the tree to i32. We guarantee that these won't populate the upper bits
218/// of the register. ZExt on the loads will be free, and the same for call
219/// return values because we only accept ones that guarantee a zeroext ret val.
220/// Many arguments will have the zeroext attribute too, so those would be free
221/// too.
222static bool isSource(Value *V) {
Sam Parker7def86b2018-08-15 07:52:35 +0000223 if (!isa<IntegerType>(V->getType()))
224 return false;
Volodymyr Sapsai703ab842018-09-18 00:11:55 +0000225 // TODO Allow zext to be sources.
226 if (isa<Argument>(V))
Sam Parker8c4b9642018-08-10 13:57:13 +0000227 return true;
Volodymyr Sapsai703ab842018-09-18 00:11:55 +0000228 else if (isa<LoadInst>(V))
229 return true;
230 else if (isa<BitCastInst>(V))
231 return true;
232 else if (auto *Call = dyn_cast<CallInst>(V))
233 return Call->hasRetAttr(Attribute::AttrKind::ZExt);
234 else if (auto *Trunc = dyn_cast<TruncInst>(V))
Sam Parker08979cd2018-11-09 09:28:27 +0000235 return EqualTypeSize(Trunc);
Sam Parker8c4b9642018-08-10 13:57:13 +0000236 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000237}
238
239/// Return true if V will require any promoted values to be truncated for the
Sam Parker8c4b9642018-08-10 13:57:13 +0000240/// the IR to remain valid. We can't mutate the value type of these
241/// instructions.
Sam Parker3828c6f2018-07-23 12:27:47 +0000242static bool isSink(Value *V) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000243 // TODO The truncate also isn't actually necessary because we would already
244 // proved that the data value is kept within the range of the original data
245 // type.
Sam Parker3828c6f2018-07-23 12:27:47 +0000246
247 if (auto *Store = dyn_cast<StoreInst>(V))
Sam Parker08979cd2018-11-09 09:28:27 +0000248 return LessOrEqualTypeSize(Store->getValueOperand());
Sam Parker3828c6f2018-07-23 12:27:47 +0000249 if (auto *Return = dyn_cast<ReturnInst>(V))
Sam Parker08979cd2018-11-09 09:28:27 +0000250 return LessOrEqualTypeSize(Return->getReturnValue());
Sam Parker8c4b9642018-08-10 13:57:13 +0000251 if (auto *Trunc = dyn_cast<TruncInst>(V))
Sam Parker08979cd2018-11-09 09:28:27 +0000252 return EqualTypeSize(Trunc->getOperand(0));
Sam Parker0e2f0bd2018-08-16 11:54:09 +0000253 if (auto *ZExt = dyn_cast<ZExtInst>(V))
Sam Parker08979cd2018-11-09 09:28:27 +0000254 return GreaterThanTypeSize(ZExt);
Sam Parker13567db2018-08-16 10:05:39 +0000255 if (auto *ICmp = dyn_cast<ICmpInst>(V))
256 return ICmp->isSigned();
Sam Parker3828c6f2018-07-23 12:27:47 +0000257
258 return isa<CallInst>(V);
259}
260
Sam Parker3828c6f2018-07-23 12:27:47 +0000261/// Return whether the instruction can be promoted within any modifications to
Sam Parker84a2f8b2018-11-01 15:23:42 +0000262/// its operands or result.
263bool ARMCodeGenPrepare::isSafeOverflow(Instruction *I) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000264 // FIXME Do we need NSW too?
Sam Parker3828c6f2018-07-23 12:27:47 +0000265 if (isa<OverflowingBinaryOperator>(I) && I->hasNoUnsignedWrap())
266 return true;
267
Sam Parker75aca942018-09-26 10:56:00 +0000268 // We can support a, potentially, overflowing instruction (I) if:
269 // - It is only used by an unsigned icmp.
270 // - The icmp uses a constant.
271 // - The overflowing value (I) is decreasing, i.e would underflow - wrapping
272 // around zero to become a larger number than before.
273 // - The underflowing instruction (I) also uses a constant.
274 //
275 // We can then use the two constants to calculate whether the result would
276 // wrap in respect to itself in the original bitwidth. If it doesn't wrap,
277 // just underflows the range, the icmp would give the same result whether the
278 // result has been truncated or not. We calculate this by:
279 // - Zero extending both constants, if needed, to 32-bits.
280 // - Take the absolute value of I's constant, adding this to the icmp const.
281 // - Check that this value is not out of range for small type. If it is, it
282 // means that it has underflowed enough to wrap around the icmp constant.
283 //
284 // For example:
285 //
286 // %sub = sub i8 %a, 2
287 // %cmp = icmp ule i8 %sub, 254
288 //
289 // If %a = 0, %sub = -2 == FE == 254
290 // But if this is evalulated as a i32
291 // %sub = -2 == FF FF FF FE == 4294967294
292 // So the unsigned compares (i8 and i32) would not yield the same result.
293 //
294 // Another way to look at it is:
295 // %a - 2 <= 254
296 // %a + 2 <= 254 + 2
297 // %a <= 256
298 // And we can't represent 256 in the i8 format, so we don't support it.
299 //
300 // Whereas:
301 //
302 // %sub i8 %a, 1
303 // %cmp = icmp ule i8 %sub, 254
304 //
305 // If %a = 0, %sub = -1 == FF == 255
306 // As i32:
307 // %sub = -1 == FF FF FF FF == 4294967295
308 //
309 // In this case, the unsigned compare results would be the same and this
310 // would also be true for ult, uge and ugt:
311 // - (255 < 254) == (0xFFFFFFFF < 254) == false
312 // - (255 <= 254) == (0xFFFFFFFF <= 254) == false
313 // - (255 > 254) == (0xFFFFFFFF > 254) == true
314 // - (255 >= 254) == (0xFFFFFFFF >= 254) == true
315 //
316 // To demonstrate why we can't handle increasing values:
317 //
318 // %add = add i8 %a, 2
319 // %cmp = icmp ult i8 %add, 127
320 //
321 // If %a = 254, %add = 256 == (i8 1)
322 // As i32:
323 // %add = 256
324 //
325 // (1 < 127) != (256 < 127)
326
Sam Parker3828c6f2018-07-23 12:27:47 +0000327 unsigned Opc = I->getOpcode();
Sam Parker75aca942018-09-26 10:56:00 +0000328 if (Opc != Instruction::Add && Opc != Instruction::Sub)
329 return false;
330
331 if (!I->hasOneUse() ||
332 !isa<ICmpInst>(*I->user_begin()) ||
333 !isa<ConstantInt>(I->getOperand(1)))
334 return false;
335
336 ConstantInt *OverflowConst = cast<ConstantInt>(I->getOperand(1));
337 bool NegImm = OverflowConst->isNegative();
338 bool IsDecreasing = ((Opc == Instruction::Sub) && !NegImm) ||
339 ((Opc == Instruction::Add) && NegImm);
340 if (!IsDecreasing)
341 return false;
342
343 // Don't support an icmp that deals with sign bits.
344 auto *CI = cast<ICmpInst>(*I->user_begin());
345 if (CI->isSigned() || CI->isEquality())
346 return false;
347
348 ConstantInt *ICmpConst = nullptr;
349 if (auto *Const = dyn_cast<ConstantInt>(CI->getOperand(0)))
350 ICmpConst = Const;
351 else if (auto *Const = dyn_cast<ConstantInt>(CI->getOperand(1)))
352 ICmpConst = Const;
353 else
354 return false;
355
356 // Now check that the result can't wrap on itself.
357 APInt Total = ICmpConst->getValue().getBitWidth() < 32 ?
358 ICmpConst->getValue().zext(32) : ICmpConst->getValue();
359
360 Total += OverflowConst->getValue().getBitWidth() < 32 ?
361 OverflowConst->getValue().abs().zext(32) : OverflowConst->getValue().abs();
362
363 APInt Max = APInt::getAllOnesValue(ARMCodeGenPrepare::TypeSize);
364
365 if (Total.getBitWidth() > Max.getBitWidth()) {
366 if (Total.ugt(Max.zext(Total.getBitWidth())))
Sam Parker3828c6f2018-07-23 12:27:47 +0000367 return false;
Sam Parker75aca942018-09-26 10:56:00 +0000368 } else if (Max.getBitWidth() > Total.getBitWidth()) {
369 if (Total.zext(Max.getBitWidth()).ugt(Max))
Sam Parker3828c6f2018-07-23 12:27:47 +0000370 return false;
Sam Parker75aca942018-09-26 10:56:00 +0000371 } else if (Total.ugt(Max))
372 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000373
Sam Parker75aca942018-09-26 10:56:00 +0000374 LLVM_DEBUG(dbgs() << "ARM CGP: Allowing safe overflow for " << *I << "\n");
375 return true;
Sam Parker3828c6f2018-07-23 12:27:47 +0000376}
377
378static bool shouldPromote(Value *V) {
Sam Parkeraaec3c62018-09-13 15:14:12 +0000379 if (!isa<IntegerType>(V->getType()) || isSink(V))
Sam Parker8c4b9642018-08-10 13:57:13 +0000380 return false;
381
382 if (isSource(V))
383 return true;
384
Sam Parker3828c6f2018-07-23 12:27:47 +0000385 auto *I = dyn_cast<Instruction>(V);
386 if (!I)
387 return false;
388
Sam Parker8c4b9642018-08-10 13:57:13 +0000389 if (isa<ICmpInst>(I))
Sam Parker3828c6f2018-07-23 12:27:47 +0000390 return false;
391
Sam Parker3828c6f2018-07-23 12:27:47 +0000392 return true;
393}
394
395/// Return whether we can safely mutate V's type to ExtTy without having to be
396/// concerned with zero extending or truncation.
397static bool isPromotedResultSafe(Value *V) {
398 if (!isa<Instruction>(V))
399 return true;
400
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000401 if (generateSignBits(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000402 return false;
403
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000404 return !isa<OverflowingBinaryOperator>(V);
Sam Parker3828c6f2018-07-23 12:27:47 +0000405}
406
407/// Return the intrinsic for the instruction that can perform the same
408/// operation but on a narrow type. This is using the parallel dsp intrinsics
409/// on scalar values.
Sam Parker8c4b9642018-08-10 13:57:13 +0000410static Intrinsic::ID getNarrowIntrinsic(Instruction *I) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000411 // Whether we use the signed or unsigned versions of these intrinsics
412 // doesn't matter because we're not using the GE bits that they set in
413 // the APSR.
414 switch(I->getOpcode()) {
415 default:
416 break;
417 case Instruction::Add:
Sam Parker8c4b9642018-08-10 13:57:13 +0000418 return ARMCodeGenPrepare::TypeSize == 16 ? Intrinsic::arm_uadd16 :
Sam Parker3828c6f2018-07-23 12:27:47 +0000419 Intrinsic::arm_uadd8;
420 case Instruction::Sub:
Sam Parker8c4b9642018-08-10 13:57:13 +0000421 return ARMCodeGenPrepare::TypeSize == 16 ? Intrinsic::arm_usub16 :
Sam Parker3828c6f2018-07-23 12:27:47 +0000422 Intrinsic::arm_usub8;
423 }
424 llvm_unreachable("unhandled opcode for narrow intrinsic");
425}
426
Sam Parker84a2f8b2018-11-01 15:23:42 +0000427static void ReplaceAllUsersOfWith(Value *From, Value *To) {
428 SmallVector<Instruction*, 4> Users;
429 Instruction *InstTo = dyn_cast<Instruction>(To);
430 for (Use &U : From->uses()) {
431 auto *User = cast<Instruction>(U.getUser());
432 if (InstTo && User->isIdenticalTo(InstTo))
433 continue;
434 Users.push_back(User);
435 }
436
437 for (auto *U : Users)
438 U->replaceUsesOfWith(From, To);
439}
440
441void
442IRPromoter::PrepareConstants(SmallPtrSetImpl<Value*> &Visited,
443 SmallPtrSetImpl<Instruction*> &SafeToPromote) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000444 IRBuilder<> Builder{Ctx};
Sam Parker84a2f8b2018-11-01 15:23:42 +0000445 // First step is to prepare the instructions for mutation. Most constants
446 // just need to be zero extended into their new type, but complications arise
447 // because:
448 // - For nuw binary operators, negative immediates would need sign extending;
449 // however, instead we'll change them to positive and zext them. We can do
450 // this because:
451 // > The operators that can wrap are: add, sub, mul and shl.
452 // > shl interprets its second operand as unsigned and if the first operand
453 // is an immediate, it will need zext to be nuw.
Sam Parkerfec793c2018-11-05 11:26:04 +0000454 // > I'm assuming mul has to interpret immediates as unsigned for nuw.
Sam Parker84a2f8b2018-11-01 15:23:42 +0000455 // > Which leaves the nuw add and sub to be handled; as with shl, if an
456 // immediate is used as operand 0, it will need zext to be nuw.
457 // - We also allow add and sub to safely overflow in certain circumstances
458 // and only when the value (operand 0) is being decreased.
459 //
460 // For adds and subs, that are either nuw or safely wrap and use a negative
461 // immediate as operand 1, we create an equivalent instruction using a
462 // positive immediate. That positive immediate can then be zext along with
463 // all the other immediates later.
464 for (auto *V : Visited) {
465 if (!isa<Instruction>(V))
466 continue;
Sam Parker3828c6f2018-07-23 12:27:47 +0000467
Sam Parker84a2f8b2018-11-01 15:23:42 +0000468 auto *I = cast<Instruction>(V);
469 if (SafeToPromote.count(I)) {
Sam Parker13567db2018-08-16 10:05:39 +0000470
Sam Parker84a2f8b2018-11-01 15:23:42 +0000471 if (!isa<OverflowingBinaryOperator>(I))
Sam Parker3828c6f2018-07-23 12:27:47 +0000472 continue;
Sam Parker84a2f8b2018-11-01 15:23:42 +0000473
474 if (auto *Const = dyn_cast<ConstantInt>(I->getOperand(1))) {
475 if (!Const->isNegative())
476 break;
477
478 unsigned Opc = I->getOpcode();
Sam Parkerfec793c2018-11-05 11:26:04 +0000479 if (Opc != Instruction::Add && Opc != Instruction::Sub)
480 continue;
Sam Parker84a2f8b2018-11-01 15:23:42 +0000481
482 LLVM_DEBUG(dbgs() << "ARM CGP: Adjusting " << *I << "\n");
483 auto *NewConst = ConstantInt::get(Ctx, Const->getValue().abs());
484 Builder.SetInsertPoint(I);
485 Value *NewVal = Opc == Instruction::Sub ?
486 Builder.CreateAdd(I->getOperand(0), NewConst) :
487 Builder.CreateSub(I->getOperand(0), NewConst);
488 LLVM_DEBUG(dbgs() << "ARM CGP: New equivalent: " << *NewVal << "\n");
489
490 if (auto *NewInst = dyn_cast<Instruction>(NewVal)) {
491 NewInst->copyIRFlags(I);
492 NewInsts.insert(NewInst);
493 }
494 InstsToRemove.push_back(I);
495 I->replaceAllUsesWith(NewVal);
496 }
Sam Parker3828c6f2018-07-23 12:27:47 +0000497 }
Sam Parker84a2f8b2018-11-01 15:23:42 +0000498 }
499 for (auto *I : NewInsts)
500 Visited.insert(I);
501}
Sam Parker3828c6f2018-07-23 12:27:47 +0000502
Sam Parker84a2f8b2018-11-01 15:23:42 +0000503void IRPromoter::ExtendSources(SmallPtrSetImpl<Value*> &Sources) {
504 IRBuilder<> Builder{Ctx};
Sam Parker3828c6f2018-07-23 12:27:47 +0000505
506 auto InsertZExt = [&](Value *V, Instruction *InsertPt) {
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000507 assert(V->getType() != ExtTy && "zext already extends to i32");
Sam Parker3828c6f2018-07-23 12:27:47 +0000508 LLVM_DEBUG(dbgs() << "ARM CGP: Inserting ZExt for " << *V << "\n");
509 Builder.SetInsertPoint(InsertPt);
510 if (auto *I = dyn_cast<Instruction>(V))
511 Builder.SetCurrentDebugLocation(I->getDebugLoc());
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000512
513 Value *ZExt = Builder.CreateZExt(V, ExtTy);
514 if (auto *I = dyn_cast<Instruction>(ZExt)) {
515 if (isa<Argument>(V))
516 I->moveBefore(InsertPt);
517 else
518 I->moveAfter(InsertPt);
519 NewInsts.insert(I);
520 }
Sam Parker3828c6f2018-07-23 12:27:47 +0000521 ReplaceAllUsersOfWith(V, ZExt);
Sam Parker13567db2018-08-16 10:05:39 +0000522 TruncTysMap[ZExt] = TruncTysMap[V];
Sam Parker3828c6f2018-07-23 12:27:47 +0000523 };
524
Sam Parker84a2f8b2018-11-01 15:23:42 +0000525 // Now, insert extending instructions between the sources and their users.
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000526 LLVM_DEBUG(dbgs() << "ARM CGP: Promoting sources:\n");
527 for (auto V : Sources) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000528 LLVM_DEBUG(dbgs() << " - " << *V << "\n");
Sam Parker8c4b9642018-08-10 13:57:13 +0000529 if (auto *I = dyn_cast<Instruction>(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000530 InsertZExt(I, I);
531 else if (auto *Arg = dyn_cast<Argument>(V)) {
532 BasicBlock &BB = Arg->getParent()->front();
533 InsertZExt(Arg, &*BB.getFirstInsertionPt());
534 } else {
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000535 llvm_unreachable("unhandled source that needs extending");
Sam Parker3828c6f2018-07-23 12:27:47 +0000536 }
537 Promoted.insert(V);
538 }
Sam Parker84a2f8b2018-11-01 15:23:42 +0000539}
Sam Parker3828c6f2018-07-23 12:27:47 +0000540
Sam Parker84a2f8b2018-11-01 15:23:42 +0000541void IRPromoter::PromoteTree(SmallPtrSetImpl<Value*> &Visited,
542 SmallPtrSetImpl<Value*> &Sources,
543 SmallPtrSetImpl<Instruction*> &Sinks,
544 SmallPtrSetImpl<Instruction*> &SafeToPromote) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000545 LLVM_DEBUG(dbgs() << "ARM CGP: Mutating the tree..\n");
Sam Parker84a2f8b2018-11-01 15:23:42 +0000546
547 IRBuilder<> Builder{Ctx};
548
549 // Mutate the types of the instructions within the tree. Here we handle
Sam Parker3828c6f2018-07-23 12:27:47 +0000550 // constant operands.
551 for (auto *V : Visited) {
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000552 if (Sources.count(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000553 continue;
554
Sam Parker3828c6f2018-07-23 12:27:47 +0000555 auto *I = cast<Instruction>(V);
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000556 if (Sinks.count(I))
Sam Parker3828c6f2018-07-23 12:27:47 +0000557 continue;
558
Sam Parker7def86b2018-08-15 07:52:35 +0000559 for (unsigned i = 0, e = I->getNumOperands(); i < e; ++i) {
560 Value *Op = I->getOperand(i);
561 if ((Op->getType() == ExtTy) || !isa<IntegerType>(Op->getType()))
Sam Parker3828c6f2018-07-23 12:27:47 +0000562 continue;
563
Sam Parker84a2f8b2018-11-01 15:23:42 +0000564 if (auto *Const = dyn_cast<ConstantInt>(Op)) {
565 Constant *NewConst = ConstantExpr::getZExt(Const, ExtTy);
566 I->setOperand(i, NewConst);
567 } else if (isa<UndefValue>(Op))
Sam Parker7def86b2018-08-15 07:52:35 +0000568 I->setOperand(i, UndefValue::get(ExtTy));
Sam Parker3828c6f2018-07-23 12:27:47 +0000569 }
570
571 if (shouldPromote(I)) {
572 I->mutateType(ExtTy);
573 Promoted.insert(I);
574 }
575 }
576
Sam Parker84a2f8b2018-11-01 15:23:42 +0000577 // Finally, any instructions that should be promoted but haven't yet been,
578 // need to be handled using intrinsics.
Sam Parker3828c6f2018-07-23 12:27:47 +0000579 for (auto *V : Visited) {
Sam Parker84a2f8b2018-11-01 15:23:42 +0000580 auto *I = dyn_cast<Instruction>(V);
581 if (!I)
Sam Parker3828c6f2018-07-23 12:27:47 +0000582 continue;
Sam Parker8c4b9642018-08-10 13:57:13 +0000583
Sam Parker84a2f8b2018-11-01 15:23:42 +0000584 if (Sources.count(I) || Sinks.count(I))
Sam Parker3828c6f2018-07-23 12:27:47 +0000585 continue;
586
Sam Parker84a2f8b2018-11-01 15:23:42 +0000587 if (!shouldPromote(I) || SafeToPromote.count(I) || NewInsts.count(I))
588 continue;
589
Sam Parker75aca942018-09-26 10:56:00 +0000590 assert(EnableDSP && "DSP intrinisc insertion not enabled!");
591
Sam Parker3828c6f2018-07-23 12:27:47 +0000592 // Replace unsafe instructions with appropriate intrinsic calls.
Sam Parker84a2f8b2018-11-01 15:23:42 +0000593 LLVM_DEBUG(dbgs() << "ARM CGP: Inserting DSP intrinsic for "
594 << *I << "\n");
595 Function *DSPInst =
596 Intrinsic::getDeclaration(M, getNarrowIntrinsic(I));
597 Builder.SetInsertPoint(I);
598 Builder.SetCurrentDebugLocation(I->getDebugLoc());
599 Value *Args[] = { I->getOperand(0), I->getOperand(1) };
600 CallInst *Call = Builder.CreateCall(DSPInst, Args);
601 ReplaceAllUsersOfWith(I, Call);
602 InstsToRemove.push_back(I);
603 NewInsts.insert(Call);
604 TruncTysMap[Call] = OrigTy;
Sam Parker3828c6f2018-07-23 12:27:47 +0000605 }
Sam Parker84a2f8b2018-11-01 15:23:42 +0000606}
607
608void IRPromoter::TruncateSinks(SmallPtrSetImpl<Value*> &Sources,
609 SmallPtrSetImpl<Instruction*> &Sinks) {
610 LLVM_DEBUG(dbgs() << "ARM CGP: Fixing up the sinks:\n");
611
612 IRBuilder<> Builder{Ctx};
Sam Parker3828c6f2018-07-23 12:27:47 +0000613
Sam Parker13567db2018-08-16 10:05:39 +0000614 auto InsertTrunc = [&](Value *V) -> Instruction* {
615 if (!isa<Instruction>(V) || !isa<IntegerType>(V->getType()))
616 return nullptr;
617
Sam Parker0e2f0bd2018-08-16 11:54:09 +0000618 if ((!Promoted.count(V) && !NewInsts.count(V)) || !TruncTysMap.count(V) ||
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000619 Sources.count(V))
Sam Parker13567db2018-08-16 10:05:39 +0000620 return nullptr;
621
622 Type *TruncTy = TruncTysMap[V];
623 if (TruncTy == ExtTy)
624 return nullptr;
625
626 LLVM_DEBUG(dbgs() << "ARM CGP: Creating " << *TruncTy << " Trunc for "
627 << *V << "\n");
628 Builder.SetInsertPoint(cast<Instruction>(V));
Sam Parker48fbf752018-11-01 16:44:45 +0000629 auto *Trunc = dyn_cast<Instruction>(Builder.CreateTrunc(V, TruncTy));
630 if (Trunc)
631 NewInsts.insert(Trunc);
Sam Parker13567db2018-08-16 10:05:39 +0000632 return Trunc;
633 };
634
Sam Parker3828c6f2018-07-23 12:27:47 +0000635 // Fix up any stores or returns that use the results of the promoted
636 // chain.
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000637 for (auto I : Sinks) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000638 LLVM_DEBUG(dbgs() << " - " << *I << "\n");
Sam Parker13567db2018-08-16 10:05:39 +0000639
640 // Handle calls separately as we need to iterate over arg operands.
641 if (auto *Call = dyn_cast<CallInst>(I)) {
642 for (unsigned i = 0; i < Call->getNumArgOperands(); ++i) {
643 Value *Arg = Call->getArgOperand(i);
644 if (Instruction *Trunc = InsertTrunc(Arg)) {
645 Trunc->moveBefore(Call);
646 Call->setArgOperand(i, Trunc);
647 }
648 }
649 continue;
Sam Parker3828c6f2018-07-23 12:27:47 +0000650 }
651
Sam Parker13567db2018-08-16 10:05:39 +0000652 // Now handle the others.
Sam Parker3828c6f2018-07-23 12:27:47 +0000653 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
Sam Parker13567db2018-08-16 10:05:39 +0000654 if (Instruction *Trunc = InsertTrunc(I->getOperand(i))) {
655 Trunc->moveBefore(I);
656 I->setOperand(i, Trunc);
Sam Parker3828c6f2018-07-23 12:27:47 +0000657 }
658 }
659 }
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000660}
661
Sam Parker08979cd2018-11-09 09:28:27 +0000662void IRPromoter::Cleanup(SmallPtrSetImpl<Value*> &Visited) {
663 // Some zexts will now have become redundant, along with their trunc
664 // operands, so remove them
665 for (auto V : Visited) {
666 if (!isa<ZExtInst>(V))
667 continue;
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000668
Sam Parker08979cd2018-11-09 09:28:27 +0000669 auto ZExt = cast<ZExtInst>(V);
670 if (ZExt->getDestTy() != ExtTy)
671 continue;
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000672
Sam Parker08979cd2018-11-09 09:28:27 +0000673 Value *Src = ZExt->getOperand(0);
674 if (ZExt->getSrcTy() == ZExt->getDestTy()) {
675 LLVM_DEBUG(dbgs() << "ARM CGP: Removing unnecessary cast.\n");
676 ReplaceAllUsersOfWith(ZExt, Src);
677 InstsToRemove.push_back(ZExt);
678 continue;
679 }
680
681 // For any truncs that we insert to handle zexts, we can replace the
682 // result of the zext with the input to the trunc.
683 if (NewInsts.count(Src) && isa<TruncInst>(Src)) {
684 auto *Trunc = cast<TruncInst>(Src);
685 assert(Trunc->getOperand(0)->getType() == ExtTy &&
686 "expected inserted trunc to be operating on i32");
687 LLVM_DEBUG(dbgs() << "ARM CGP: Replacing zext with trunc operand: "
688 << *Trunc->getOperand(0));
689 ReplaceAllUsersOfWith(ZExt, Trunc->getOperand(0));
690 InstsToRemove.push_back(ZExt);
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000691 }
692 }
693
694 for (auto *I : InstsToRemove) {
695 LLVM_DEBUG(dbgs() << "ARM CGP: Removing " << *I << "\n");
696 I->dropAllReferences();
697 I->eraseFromParent();
698 }
699
700 InstsToRemove.clear();
701 NewInsts.clear();
702 TruncTysMap.clear();
703 Promoted.clear();
Sam Parker84a2f8b2018-11-01 15:23:42 +0000704}
705
706void IRPromoter::Mutate(Type *OrigTy,
707 SmallPtrSetImpl<Value*> &Visited,
708 SmallPtrSetImpl<Value*> &Sources,
709 SmallPtrSetImpl<Instruction*> &Sinks,
710 SmallPtrSetImpl<Instruction*> &SafeToPromote) {
711 LLVM_DEBUG(dbgs() << "ARM CGP: Promoting use-def chains to from "
712 << ARMCodeGenPrepare::TypeSize << " to 32-bits\n");
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000713
714 assert(isa<IntegerType>(OrigTy) && "expected integer type");
715 this->OrigTy = cast<IntegerType>(OrigTy);
716 assert(OrigTy->getPrimitiveSizeInBits() < ExtTy->getPrimitiveSizeInBits() &&
717 "original type not smaller than extended type");
Sam Parker84a2f8b2018-11-01 15:23:42 +0000718
719 // Cache original types.
720 for (auto *V : Visited)
721 TruncTysMap[V] = V->getType();
722
723 // Convert adds and subs using negative immediates to equivalent instructions
724 // that use positive constants.
725 PrepareConstants(Visited, SafeToPromote);
726
727 // Insert zext instructions between sources and their users.
728 ExtendSources(Sources);
729
730 // Promote visited instructions, mutating their types in place. Also insert
731 // DSP intrinsics, if enabled, for adds and subs which would be unsafe to
732 // promote.
733 PromoteTree(Visited, Sources, Sinks, SafeToPromote);
734
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000735 // Insert trunc instructions for use by calls, stores etc...
Sam Parker84a2f8b2018-11-01 15:23:42 +0000736 TruncateSinks(Sources, Sinks);
737
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000738 // Finally, remove unecessary zexts and truncs, delete old instructions and
739 // clear the data structures.
Sam Parker08979cd2018-11-09 09:28:27 +0000740 Cleanup(Visited);
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000741
Sam Parker08979cd2018-11-09 09:28:27 +0000742 LLVM_DEBUG(dbgs() << "ARM CGP: Mutation complete\n");
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 Parker08979cd2018-11-09 09:28:27 +0000750 if (auto *I = dyn_cast<ICmpInst>(V)) {
751 // Now that we allow small types than TypeSize, only allow icmp of
752 // TypeSize because they will require a trunc to be legalised.
753 // TODO: Allow icmp of smaller types, and calculate at the end
754 // whether the transform would be beneficial.
755 if (isa<PointerType>(I->getOperand(0)->getType()))
756 return true;
757 return EqualTypeSize(I->getOperand(0));
758 }
Sam Parker8c4b9642018-08-10 13:57:13 +0000759
Volodymyr Sapsai703ab842018-09-18 00:11:55 +0000760 // Memory instructions
761 if (isa<StoreInst>(V) || isa<GetElementPtrInst>(V))
762 return true;
763
764 // Branches and targets.
765 if( isa<BranchInst>(V) || isa<SwitchInst>(V) || isa<BasicBlock>(V))
766 return true;
767
768 // Non-instruction values that we can handle.
769 if ((isa<Constant>(V) && !isa<ConstantExpr>(V)) || isa<Argument>(V))
770 return isSupportedType(V);
771
772 if (isa<PHINode>(V) || isa<SelectInst>(V) || isa<ReturnInst>(V) ||
773 isa<LoadInst>(V))
774 return isSupportedType(V);
775
Sam Parker08979cd2018-11-09 09:28:27 +0000776 if (isa<SExtInst>(V))
777 return false;
Volodymyr Sapsai703ab842018-09-18 00:11:55 +0000778
Sam Parker08979cd2018-11-09 09:28:27 +0000779 if (auto *Cast = dyn_cast<CastInst>(V))
780 return isSupportedType(Cast) || isSupportedType(Cast->getOperand(0));
Sam Parker0e2f0bd2018-08-16 11:54:09 +0000781
Sam Parker8c4b9642018-08-10 13:57:13 +0000782 // Special cases for calls as we need to check for zeroext
783 // TODO We should accept calls even if they don't have zeroext, as they can
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000784 // still be sinks.
Sam Parker8c4b9642018-08-10 13:57:13 +0000785 if (auto *Call = dyn_cast<CallInst>(V))
786 return isSupportedType(Call) &&
787 Call->hasRetAttr(Attribute::AttrKind::ZExt);
788
Volodymyr Sapsai703ab842018-09-18 00:11:55 +0000789 if (!isa<BinaryOperator>(V))
790 return false;
791
792 if (!isSupportedType(V))
793 return false;
794
795 if (generateSignBits(V)) {
796 LLVM_DEBUG(dbgs() << "ARM CGP: No, instruction can generate sign bits.\n");
797 return false;
798 }
799 return true;
Sam Parker8c4b9642018-08-10 13:57:13 +0000800}
801
802/// Check that the type of V would be promoted and that the original type is
803/// smaller than the targeted promoted type. Check that we're not trying to
804/// promote something larger than our base 'TypeSize' type.
805bool ARMCodeGenPrepare::isLegalToPromote(Value *V) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000806
807 auto *I = dyn_cast<Instruction>(V);
808 if (!I)
Sam Parker84a2f8b2018-11-01 15:23:42 +0000809 return true;
810
811 if (SafeToPromote.count(I))
812 return true;
813
814 if (isPromotedResultSafe(V) || isSafeOverflow(I)) {
815 SafeToPromote.insert(I);
816 return true;
817 }
818
819 if (I->getOpcode() != Instruction::Add && I->getOpcode() != Instruction::Sub)
Sam Parker8c4b9642018-08-10 13:57:13 +0000820 return false;
821
822 // If promotion is not safe, can we use a DSP instruction to natively
823 // handle the narrow type?
Sam Parker3828c6f2018-07-23 12:27:47 +0000824 if (!ST->hasDSP() || !EnableDSP || !isSupportedType(I))
825 return false;
826
827 if (ST->isThumb() && !ST->hasThumb2())
828 return false;
829
Sam Parker3828c6f2018-07-23 12:27:47 +0000830 // TODO
831 // Would it be profitable? For Thumb code, these parallel DSP instructions
832 // are only Thumb-2, so we wouldn't be able to dual issue on Cortex-M33. For
833 // Cortex-A, specifically Cortex-A72, the latency is double and throughput is
834 // halved. They also do not take immediates as operands.
835 for (auto &Op : I->operands()) {
836 if (isa<Constant>(Op)) {
837 if (!EnableDSPWithImms)
838 return false;
839 }
840 }
Sam Parker84a2f8b2018-11-01 15:23:42 +0000841 LLVM_DEBUG(dbgs() << "ARM CGP: Will use an intrinsic for: " << *I << "\n");
Sam Parker3828c6f2018-07-23 12:27:47 +0000842 return true;
843}
844
Sam Parker3828c6f2018-07-23 12:27:47 +0000845bool ARMCodeGenPrepare::TryToPromote(Value *V) {
846 OrigTy = V->getType();
847 TypeSize = OrigTy->getPrimitiveSizeInBits();
Sam Parkerfabf7fe2018-08-15 13:29:50 +0000848 if (TypeSize > 16 || TypeSize < 8)
Sam Parker8c4b9642018-08-10 13:57:13 +0000849 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000850
Sam Parker84a2f8b2018-11-01 15:23:42 +0000851 SafeToPromote.clear();
852
Sam Parker3828c6f2018-07-23 12:27:47 +0000853 if (!isSupportedValue(V) || !shouldPromote(V) || !isLegalToPromote(V))
854 return false;
855
Sam Parker8c4b9642018-08-10 13:57:13 +0000856 LLVM_DEBUG(dbgs() << "ARM CGP: TryToPromote: " << *V << ", TypeSize = "
857 << TypeSize << "\n");
Sam Parker3828c6f2018-07-23 12:27:47 +0000858
859 SetVector<Value*> WorkList;
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000860 SmallPtrSet<Value*, 8> Sources;
861 SmallPtrSet<Instruction*, 4> Sinks;
Sam Parker3828c6f2018-07-23 12:27:47 +0000862 SmallPtrSet<Value*, 16> CurrentVisited;
Sam Parker84a2f8b2018-11-01 15:23:42 +0000863 WorkList.insert(V);
Sam Parker3828c6f2018-07-23 12:27:47 +0000864
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000865 // Return true if V was added to the worklist as a supported instruction,
866 // if it was already visited, or if we don't need to explore it (e.g.
867 // pointer values and GEPs), and false otherwise.
Sam Parker3828c6f2018-07-23 12:27:47 +0000868 auto AddLegalInst = [&](Value *V) {
869 if (CurrentVisited.count(V))
870 return true;
871
Sam Parker0d511972018-08-16 12:24:40 +0000872 // Ignore GEPs because they don't need promoting and the constant indices
873 // will prevent the transformation.
874 if (isa<GetElementPtrInst>(V))
875 return true;
876
Sam Parker3828c6f2018-07-23 12:27:47 +0000877 if (!isSupportedValue(V) || (shouldPromote(V) && !isLegalToPromote(V))) {
878 LLVM_DEBUG(dbgs() << "ARM CGP: Can't handle: " << *V << "\n");
879 return false;
880 }
881
882 WorkList.insert(V);
883 return true;
884 };
885
886 // Iterate through, and add to, a tree of operands and users in the use-def.
887 while (!WorkList.empty()) {
888 Value *V = WorkList.back();
889 WorkList.pop_back();
890 if (CurrentVisited.count(V))
891 continue;
892
Sam Parker7def86b2018-08-15 07:52:35 +0000893 // Ignore non-instructions, other than arguments.
Sam Parker3828c6f2018-07-23 12:27:47 +0000894 if (!isa<Instruction>(V) && !isSource(V))
895 continue;
896
897 // If we've already visited this value from somewhere, bail now because
898 // the tree has already been explored.
899 // TODO: This could limit the transform, ie if we try to promote something
900 // from an i8 and fail first, before trying an i16.
Sam Parkeraaec3c62018-09-13 15:14:12 +0000901 if (AllVisited.count(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000902 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000903
904 CurrentVisited.insert(V);
905 AllVisited.insert(V);
906
907 // Calls can be both sources and sinks.
908 if (isSink(V))
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000909 Sinks.insert(cast<Instruction>(V));
Sam Parker08979cd2018-11-09 09:28:27 +0000910
Sam Parker3828c6f2018-07-23 12:27:47 +0000911 if (isSource(V))
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000912 Sources.insert(V);
Sam Parker08979cd2018-11-09 09:28:27 +0000913
914 if (!isSink(V) && !isSource(V)) {
915 if (auto *I = dyn_cast<Instruction>(V)) {
916 // Visit operands of any instruction visited.
917 for (auto &U : I->operands()) {
918 if (!AddLegalInst(U))
919 return false;
920 }
Sam Parker3828c6f2018-07-23 12:27:47 +0000921 }
922 }
923
924 // Don't visit users of a node which isn't going to be mutated unless its a
925 // source.
926 if (isSource(V) || shouldPromote(V)) {
927 for (Use &U : V->uses()) {
928 if (!AddLegalInst(U.getUser()))
929 return false;
930 }
931 }
932 }
933
Sam Parker3828c6f2018-07-23 12:27:47 +0000934 LLVM_DEBUG(dbgs() << "ARM CGP: Visited nodes:\n";
935 for (auto *I : CurrentVisited)
936 I->dump();
937 );
Sam Parker7def86b2018-08-15 07:52:35 +0000938 unsigned ToPromote = 0;
939 for (auto *V : CurrentVisited) {
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000940 if (Sources.count(V))
Sam Parker7def86b2018-08-15 07:52:35 +0000941 continue;
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000942 if (Sinks.count(cast<Instruction>(V)))
Sam Parker7def86b2018-08-15 07:52:35 +0000943 continue;
944 ++ToPromote;
945 }
946
947 if (ToPromote < 2)
948 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000949
Sam Parker84a2f8b2018-11-01 15:23:42 +0000950 Promoter->Mutate(OrigTy, CurrentVisited, Sources, Sinks, SafeToPromote);
Sam Parker3828c6f2018-07-23 12:27:47 +0000951 return true;
952}
953
954bool ARMCodeGenPrepare::doInitialization(Module &M) {
955 Promoter = new IRPromoter(&M);
956 return false;
957}
958
959bool ARMCodeGenPrepare::runOnFunction(Function &F) {
960 if (skipFunction(F) || DisableCGP)
961 return false;
962
963 auto *TPC = &getAnalysis<TargetPassConfig>();
964 if (!TPC)
965 return false;
966
967 const TargetMachine &TM = TPC->getTM<TargetMachine>();
968 ST = &TM.getSubtarget<ARMSubtarget>(F);
969 bool MadeChange = false;
970 LLVM_DEBUG(dbgs() << "ARM CGP: Running on " << F.getName() << "\n");
971
972 // Search up from icmps to try to promote their operands.
973 for (BasicBlock &BB : F) {
974 auto &Insts = BB.getInstList();
975 for (auto &I : Insts) {
976 if (AllVisited.count(&I))
977 continue;
978
979 if (isa<ICmpInst>(I)) {
980 auto &CI = cast<ICmpInst>(I);
981
982 // Skip signed or pointer compares
983 if (CI.isSigned() || !isa<IntegerType>(CI.getOperand(0)->getType()))
984 continue;
985
Sam Parker08979cd2018-11-09 09:28:27 +0000986 LLVM_DEBUG(dbgs() << "ARM CGP: Searching from: " << CI << "\n");
987
Sam Parker3828c6f2018-07-23 12:27:47 +0000988 for (auto &Op : CI.operands()) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000989 if (auto *I = dyn_cast<Instruction>(Op))
990 MadeChange |= TryToPromote(I);
Sam Parker3828c6f2018-07-23 12:27:47 +0000991 }
992 }
993 }
Sam Parker3828c6f2018-07-23 12:27:47 +0000994 LLVM_DEBUG(if (verifyFunction(F, &dbgs())) {
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000995 dbgs() << F;
Sam Parker3828c6f2018-07-23 12:27:47 +0000996 report_fatal_error("Broken function after type promotion");
997 });
998 }
999 if (MadeChange)
1000 LLVM_DEBUG(dbgs() << "After ARMCodeGenPrepare: " << F << "\n");
1001
1002 return MadeChange;
1003}
1004
Matt Morehousea70685f2018-07-23 17:00:45 +00001005bool ARMCodeGenPrepare::doFinalization(Module &M) {
1006 delete Promoter;
1007 return false;
1008}
1009
Sam Parker3828c6f2018-07-23 12:27:47 +00001010INITIALIZE_PASS_BEGIN(ARMCodeGenPrepare, DEBUG_TYPE,
1011 "ARM IR optimizations", false, false)
1012INITIALIZE_PASS_END(ARMCodeGenPrepare, DEBUG_TYPE, "ARM IR optimizations",
1013 false, false)
1014
1015char ARMCodeGenPrepare::ID = 0;
Sam Parker8c4b9642018-08-10 13:57:13 +00001016unsigned ARMCodeGenPrepare::TypeSize = 0;
Sam Parker3828c6f2018-07-23 12:27:47 +00001017
1018FunctionPass *llvm::createARMCodeGenPreparePass() {
1019 return new ARMCodeGenPrepare();
1020}