blob: 2fc5f4aaab50f10e681db02c0ac8be981d75100a [file] [log] [blame]
Sam Parker3828c6f2018-07-23 12:27:47 +00001//===----- ARMCodeGenPrepare.cpp ------------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Sam Parker3828c6f2018-07-23 12:27:47 +00006//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// This pass inserts intrinsics to handle small types that would otherwise be
11/// promoted during legalization. Here we can manually promote types or insert
12/// intrinsics which can handle narrow types that aren't supported by the
13/// register classes.
14//
15//===----------------------------------------------------------------------===//
16
17#include "ARM.h"
18#include "ARMSubtarget.h"
19#include "ARMTargetMachine.h"
20#include "llvm/ADT/StringRef.h"
21#include "llvm/CodeGen/Passes.h"
22#include "llvm/CodeGen/TargetPassConfig.h"
23#include "llvm/IR/Attributes.h"
24#include "llvm/IR/BasicBlock.h"
25#include "llvm/IR/IRBuilder.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/InstrTypes.h"
28#include "llvm/IR/Instruction.h"
29#include "llvm/IR/Instructions.h"
30#include "llvm/IR/IntrinsicInst.h"
31#include "llvm/IR/Intrinsics.h"
32#include "llvm/IR/Type.h"
33#include "llvm/IR/Value.h"
34#include "llvm/IR/Verifier.h"
35#include "llvm/Pass.h"
36#include "llvm/Support/Casting.h"
37#include "llvm/Support/CommandLine.h"
38
39#define DEBUG_TYPE "arm-codegenprepare"
40
41using namespace llvm;
42
43static cl::opt<bool>
Hans Wennborg5555c002018-09-24 11:40:07 +000044DisableCGP("arm-disable-cgp", cl::Hidden, cl::init(true),
Sam Parker3828c6f2018-07-23 12:27:47 +000045 cl::desc("Disable ARM specific CodeGenPrepare pass"));
46
47static cl::opt<bool>
48EnableDSP("arm-enable-scalar-dsp", cl::Hidden, cl::init(false),
49 cl::desc("Use DSP instructions for scalar operations"));
50
51static cl::opt<bool>
52EnableDSPWithImms("arm-enable-scalar-dsp-imms", cl::Hidden, cl::init(false),
53 cl::desc("Use DSP instructions for scalar operations\
54 with immediate operands"));
55
Sjoerd Meijer31239a42018-08-17 07:34:01 +000056// The goal of this pass is to enable more efficient code generation for
57// operations on narrow types (i.e. types with < 32-bits) and this is a
58// motivating IR code example:
59//
60// define hidden i32 @cmp(i8 zeroext) {
61// %2 = add i8 %0, -49
62// %3 = icmp ult i8 %2, 3
63// ..
64// }
65//
66// The issue here is that i8 is type-legalized to i32 because i8 is not a
67// legal type. Thus, arithmetic is done in integer-precision, but then the
68// byte value is masked out as follows:
69//
70// t19: i32 = add t4, Constant:i32<-49>
71// t24: i32 = and t19, Constant:i32<255>
72//
73// Consequently, we generate code like this:
74//
75// subs r0, #49
76// uxtb r1, r0
77// cmp r1, #3
78//
79// This shows that masking out the byte value results in generation of
80// the UXTB instruction. This is not optimal as r0 already contains the byte
81// value we need, and so instead we can just generate:
82//
83// sub.w r1, r0, #49
84// cmp r1, #3
85//
86// We achieve this by type promoting the IR to i32 like so for this example:
87//
88// define i32 @cmp(i8 zeroext %c) {
89// %0 = zext i8 %c to i32
90// %c.off = add i32 %0, -49
91// %1 = icmp ult i32 %c.off, 3
92// ..
93// }
94//
95// For this to be valid and legal, we need to prove that the i32 add is
96// producing the same value as the i8 addition, and that e.g. no overflow
97// happens.
98//
99// A brief sketch of the algorithm and some terminology.
100// We pattern match interesting IR patterns:
101// - which have "sources": instructions producing narrow values (i8, i16), and
102// - they have "sinks": instructions consuming these narrow values.
103//
104// We collect all instruction connecting sources and sinks in a worklist, so
105// that we can mutate these instruction and perform type promotion when it is
106// legal to do so.
Sam Parker3828c6f2018-07-23 12:27:47 +0000107
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000108namespace {
Sam Parker3828c6f2018-07-23 12:27:47 +0000109class IRPromoter {
110 SmallPtrSet<Value*, 8> NewInsts;
Sam Parkere7c42dd2018-11-19 11:34:40 +0000111 SmallPtrSet<Instruction*, 4> InstsToRemove;
112 DenseMap<Value*, SmallVector<Type*, 4>> TruncTysMap;
Sam Parker84a2f8b2018-11-01 15:23:42 +0000113 SmallPtrSet<Value*, 8> Promoted;
Sam Parker3828c6f2018-07-23 12:27:47 +0000114 Module *M = nullptr;
115 LLVMContext &Ctx;
Sam Parker31bef632019-01-23 09:18:44 +0000116 // The type we promote to: always i32
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000117 IntegerType *ExtTy = nullptr;
Sam Parker31bef632019-01-23 09:18:44 +0000118 // The type of the value that the search began from, either i8 or i16.
119 // This defines the max range of the values that we allow in the promoted
120 // tree.
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000121 IntegerType *OrigTy = nullptr;
Sam Parker6ed47be2019-02-21 09:33:18 +0000122 SetVector<Value*> *Visited;
Sam Parkere7c42dd2018-11-19 11:34:40 +0000123 SmallPtrSetImpl<Value*> *Sources;
124 SmallPtrSetImpl<Instruction*> *Sinks;
125 SmallPtrSetImpl<Instruction*> *SafeToPromote;
Sam Parker3141bbd2019-05-21 07:56:47 +0000126 SmallPtrSetImpl<Instruction*> *SafeWrap;
Sam Parker84a2f8b2018-11-01 15:23:42 +0000127
Sam Parkere7c42dd2018-11-19 11:34:40 +0000128 void ReplaceAllUsersOfWith(Value *From, Value *To);
Sam Parker3141bbd2019-05-21 07:56:47 +0000129 void PrepareWrappingAdds(void);
Sam Parkere7c42dd2018-11-19 11:34:40 +0000130 void ExtendSources(void);
131 void ConvertTruncs(void);
132 void PromoteTree(void);
133 void TruncateSinks(void);
134 void Cleanup(void);
Sam Parker3828c6f2018-07-23 12:27:47 +0000135
136public:
Sam Parker84a2f8b2018-11-01 15:23:42 +0000137 IRPromoter(Module *M) : M(M), Ctx(M->getContext()),
138 ExtTy(Type::getInt32Ty(Ctx)) { }
Sam Parker3828c6f2018-07-23 12:27:47 +0000139
Sam Parker3828c6f2018-07-23 12:27:47 +0000140
141 void Mutate(Type *OrigTy,
Sam Parker6ed47be2019-02-21 09:33:18 +0000142 SetVector<Value*> &Visited,
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000143 SmallPtrSetImpl<Value*> &Sources,
Sam Parker84a2f8b2018-11-01 15:23:42 +0000144 SmallPtrSetImpl<Instruction*> &Sinks,
Sam Parker3141bbd2019-05-21 07:56:47 +0000145 SmallPtrSetImpl<Instruction*> &SafeToPromote,
146 SmallPtrSetImpl<Instruction*> &SafeWrap);
Sam Parker3828c6f2018-07-23 12:27:47 +0000147};
148
149class ARMCodeGenPrepare : public FunctionPass {
150 const ARMSubtarget *ST = nullptr;
151 IRPromoter *Promoter = nullptr;
152 std::set<Value*> AllVisited;
Sam Parker84a2f8b2018-11-01 15:23:42 +0000153 SmallPtrSet<Instruction*, 8> SafeToPromote;
Sam Parker3141bbd2019-05-21 07:56:47 +0000154 SmallPtrSet<Instruction*, 4> SafeWrap;
Sam Parker3828c6f2018-07-23 12:27:47 +0000155
Sam Parker3141bbd2019-05-21 07:56:47 +0000156 bool isSafeWrap(Instruction *I);
Sam Parker3828c6f2018-07-23 12:27:47 +0000157 bool isSupportedValue(Value *V);
158 bool isLegalToPromote(Value *V);
159 bool TryToPromote(Value *V);
160
161public:
162 static char ID;
Sam Parker8c4b9642018-08-10 13:57:13 +0000163 static unsigned TypeSize;
164 Type *OrigTy = nullptr;
Sam Parker3828c6f2018-07-23 12:27:47 +0000165
166 ARMCodeGenPrepare() : FunctionPass(ID) {}
167
Sam Parker3828c6f2018-07-23 12:27:47 +0000168 void getAnalysisUsage(AnalysisUsage &AU) const override {
169 AU.addRequired<TargetPassConfig>();
170 }
171
172 StringRef getPassName() const override { return "ARM IR optimizations"; }
173
174 bool doInitialization(Module &M) override;
175 bool runOnFunction(Function &F) override;
Matt Morehousea70685f2018-07-23 17:00:45 +0000176 bool doFinalization(Module &M) override;
Sam Parker3828c6f2018-07-23 12:27:47 +0000177};
178
179}
180
Sam Parkerd7b650c2019-05-09 11:56:16 +0000181static bool GenerateSignBits(Value *V) {
182 if (auto *Arg = dyn_cast<Argument>(V))
183 return Arg->hasSExtAttr();
184
Sam Parker3828c6f2018-07-23 12:27:47 +0000185 if (!isa<Instruction>(V))
186 return false;
187
188 unsigned Opc = cast<Instruction>(V)->getOpcode();
189 return Opc == Instruction::AShr || Opc == Instruction::SDiv ||
Sam Parkerd7b650c2019-05-09 11:56:16 +0000190 Opc == Instruction::SRem || Opc == Instruction::SExt ||
191 Opc == Instruction::SIToFP;
Sam Parker3828c6f2018-07-23 12:27:47 +0000192}
193
Sam Parker08979cd2018-11-09 09:28:27 +0000194static bool EqualTypeSize(Value *V) {
195 return V->getType()->getScalarSizeInBits() == ARMCodeGenPrepare::TypeSize;
196}
197
198static bool LessOrEqualTypeSize(Value *V) {
199 return V->getType()->getScalarSizeInBits() <= ARMCodeGenPrepare::TypeSize;
200}
201
202static bool GreaterThanTypeSize(Value *V) {
203 return V->getType()->getScalarSizeInBits() > ARMCodeGenPrepare::TypeSize;
204}
205
Sam Parkere7c42dd2018-11-19 11:34:40 +0000206static bool LessThanTypeSize(Value *V) {
207 return V->getType()->getScalarSizeInBits() < ARMCodeGenPrepare::TypeSize;
208}
209
Sam Parker3828c6f2018-07-23 12:27:47 +0000210/// Some instructions can use 8- and 16-bit operands, and we don't need to
211/// promote anything larger. We disallow booleans to make life easier when
212/// dealing with icmps but allow any other integer that is <= 16 bits. Void
213/// types are accepted so we can handle switches.
214static bool isSupportedType(Value *V) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000215 Type *Ty = V->getType();
Sam Parker7def86b2018-08-15 07:52:35 +0000216
217 // Allow voids and pointers, these won't be promoted.
218 if (Ty->isVoidTy() || Ty->isPointerTy())
Sam Parker3828c6f2018-07-23 12:27:47 +0000219 return true;
220
Sam Parker8c4b9642018-08-10 13:57:13 +0000221 if (auto *Ld = dyn_cast<LoadInst>(V))
222 Ty = cast<PointerType>(Ld->getPointerOperandType())->getElementType();
223
Sam Parker2804f322018-11-09 15:06:33 +0000224 if (!isa<IntegerType>(Ty) ||
225 cast<IntegerType>(V->getType())->getBitWidth() == 1)
Sam Parker3828c6f2018-07-23 12:27:47 +0000226 return false;
227
Sam Parker08979cd2018-11-09 09:28:27 +0000228 return LessOrEqualTypeSize(V);
Sam Parker8c4b9642018-08-10 13:57:13 +0000229}
Sam Parker3828c6f2018-07-23 12:27:47 +0000230
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000231/// Return true if the given value is a source in the use-def chain, producing
Sam Parkere7c42dd2018-11-19 11:34:40 +0000232/// a narrow 'TypeSize' value. These values will be zext to start the promotion
Sam Parker8c4b9642018-08-10 13:57:13 +0000233/// of the tree to i32. We guarantee that these won't populate the upper bits
234/// of the register. ZExt on the loads will be free, and the same for call
235/// return values because we only accept ones that guarantee a zeroext ret val.
236/// Many arguments will have the zeroext attribute too, so those would be free
237/// too.
238static bool isSource(Value *V) {
Sam Parker7def86b2018-08-15 07:52:35 +0000239 if (!isa<IntegerType>(V->getType()))
240 return false;
Sam Parker2804f322018-11-09 15:06:33 +0000241
Volodymyr Sapsai703ab842018-09-18 00:11:55 +0000242 // TODO Allow zext to be sources.
243 if (isa<Argument>(V))
Sam Parker8c4b9642018-08-10 13:57:13 +0000244 return true;
Volodymyr Sapsai703ab842018-09-18 00:11:55 +0000245 else if (isa<LoadInst>(V))
246 return true;
247 else if (isa<BitCastInst>(V))
248 return true;
249 else if (auto *Call = dyn_cast<CallInst>(V))
250 return Call->hasRetAttr(Attribute::AttrKind::ZExt);
251 else if (auto *Trunc = dyn_cast<TruncInst>(V))
Sam Parker08979cd2018-11-09 09:28:27 +0000252 return EqualTypeSize(Trunc);
Sam Parker8c4b9642018-08-10 13:57:13 +0000253 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000254}
255
256/// Return true if V will require any promoted values to be truncated for the
Sam Parker8c4b9642018-08-10 13:57:13 +0000257/// the IR to remain valid. We can't mutate the value type of these
258/// instructions.
Sam Parker3828c6f2018-07-23 12:27:47 +0000259static bool isSink(Value *V) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000260 // TODO The truncate also isn't actually necessary because we would already
261 // proved that the data value is kept within the range of the original data
262 // type.
Sam Parker3828c6f2018-07-23 12:27:47 +0000263
Sam Parkere7c42dd2018-11-19 11:34:40 +0000264 // Sinks are:
265 // - points where the value in the register is being observed, such as an
266 // icmp, switch or store.
267 // - points where value types have to match, such as calls and returns.
268 // - zext are included to ease the transformation and are generally removed
269 // later on.
Sam Parker3828c6f2018-07-23 12:27:47 +0000270 if (auto *Store = dyn_cast<StoreInst>(V))
Sam Parker08979cd2018-11-09 09:28:27 +0000271 return LessOrEqualTypeSize(Store->getValueOperand());
Sam Parker3828c6f2018-07-23 12:27:47 +0000272 if (auto *Return = dyn_cast<ReturnInst>(V))
Sam Parker08979cd2018-11-09 09:28:27 +0000273 return LessOrEqualTypeSize(Return->getReturnValue());
Sam Parker0e2f0bd2018-08-16 11:54:09 +0000274 if (auto *ZExt = dyn_cast<ZExtInst>(V))
Sam Parker08979cd2018-11-09 09:28:27 +0000275 return GreaterThanTypeSize(ZExt);
Sam Parkere7c42dd2018-11-19 11:34:40 +0000276 if (auto *Switch = dyn_cast<SwitchInst>(V))
277 return LessThanTypeSize(Switch->getCondition());
Sam Parker13567db2018-08-16 10:05:39 +0000278 if (auto *ICmp = dyn_cast<ICmpInst>(V))
Sam Parkere7c42dd2018-11-19 11:34:40 +0000279 return ICmp->isSigned() || LessThanTypeSize(ICmp->getOperand(0));
Sam Parker3828c6f2018-07-23 12:27:47 +0000280
281 return isa<CallInst>(V);
282}
283
Sam Parker3141bbd2019-05-21 07:56:47 +0000284/// Return whether this instruction can safely wrap.
285bool ARMCodeGenPrepare::isSafeWrap(Instruction *I) {
286 // We can support a, potentially, wrapping instruction (I) if:
Sam Parker75aca942018-09-26 10:56:00 +0000287 // - It is only used by an unsigned icmp.
288 // - The icmp uses a constant.
Sam Parker3141bbd2019-05-21 07:56:47 +0000289 // - The wrapping value (I) is decreasing, i.e would underflow - wrapping
Sam Parker75aca942018-09-26 10:56:00 +0000290 // around zero to become a larger number than before.
Sam Parker3141bbd2019-05-21 07:56:47 +0000291 // - The wrapping instruction (I) also uses a constant.
Sam Parker75aca942018-09-26 10:56:00 +0000292 //
293 // We can then use the two constants to calculate whether the result would
294 // wrap in respect to itself in the original bitwidth. If it doesn't wrap,
295 // just underflows the range, the icmp would give the same result whether the
296 // result has been truncated or not. We calculate this by:
297 // - Zero extending both constants, if needed, to 32-bits.
298 // - Take the absolute value of I's constant, adding this to the icmp const.
299 // - Check that this value is not out of range for small type. If it is, it
300 // means that it has underflowed enough to wrap around the icmp constant.
301 //
302 // For example:
303 //
304 // %sub = sub i8 %a, 2
305 // %cmp = icmp ule i8 %sub, 254
306 //
307 // If %a = 0, %sub = -2 == FE == 254
308 // But if this is evalulated as a i32
309 // %sub = -2 == FF FF FF FE == 4294967294
310 // So the unsigned compares (i8 and i32) would not yield the same result.
311 //
312 // Another way to look at it is:
313 // %a - 2 <= 254
314 // %a + 2 <= 254 + 2
315 // %a <= 256
316 // And we can't represent 256 in the i8 format, so we don't support it.
317 //
318 // Whereas:
319 //
320 // %sub i8 %a, 1
321 // %cmp = icmp ule i8 %sub, 254
322 //
323 // If %a = 0, %sub = -1 == FF == 255
324 // As i32:
325 // %sub = -1 == FF FF FF FF == 4294967295
326 //
327 // In this case, the unsigned compare results would be the same and this
328 // would also be true for ult, uge and ugt:
329 // - (255 < 254) == (0xFFFFFFFF < 254) == false
330 // - (255 <= 254) == (0xFFFFFFFF <= 254) == false
331 // - (255 > 254) == (0xFFFFFFFF > 254) == true
332 // - (255 >= 254) == (0xFFFFFFFF >= 254) == true
333 //
334 // To demonstrate why we can't handle increasing values:
Sam Parker31bef632019-01-23 09:18:44 +0000335 //
Sam Parker75aca942018-09-26 10:56:00 +0000336 // %add = add i8 %a, 2
337 // %cmp = icmp ult i8 %add, 127
338 //
339 // If %a = 254, %add = 256 == (i8 1)
340 // As i32:
341 // %add = 256
342 //
343 // (1 < 127) != (256 < 127)
344
Sam Parker3828c6f2018-07-23 12:27:47 +0000345 unsigned Opc = I->getOpcode();
Sam Parker75aca942018-09-26 10:56:00 +0000346 if (Opc != Instruction::Add && Opc != Instruction::Sub)
347 return false;
348
349 if (!I->hasOneUse() ||
350 !isa<ICmpInst>(*I->user_begin()) ||
351 !isa<ConstantInt>(I->getOperand(1)))
352 return false;
353
354 ConstantInt *OverflowConst = cast<ConstantInt>(I->getOperand(1));
355 bool NegImm = OverflowConst->isNegative();
356 bool IsDecreasing = ((Opc == Instruction::Sub) && !NegImm) ||
357 ((Opc == Instruction::Add) && NegImm);
358 if (!IsDecreasing)
359 return false;
360
361 // Don't support an icmp that deals with sign bits.
362 auto *CI = cast<ICmpInst>(*I->user_begin());
363 if (CI->isSigned() || CI->isEquality())
364 return false;
365
366 ConstantInt *ICmpConst = nullptr;
367 if (auto *Const = dyn_cast<ConstantInt>(CI->getOperand(0)))
368 ICmpConst = Const;
369 else if (auto *Const = dyn_cast<ConstantInt>(CI->getOperand(1)))
370 ICmpConst = Const;
371 else
372 return false;
373
374 // Now check that the result can't wrap on itself.
375 APInt Total = ICmpConst->getValue().getBitWidth() < 32 ?
376 ICmpConst->getValue().zext(32) : ICmpConst->getValue();
377
378 Total += OverflowConst->getValue().getBitWidth() < 32 ?
379 OverflowConst->getValue().abs().zext(32) : OverflowConst->getValue().abs();
380
381 APInt Max = APInt::getAllOnesValue(ARMCodeGenPrepare::TypeSize);
382
383 if (Total.getBitWidth() > Max.getBitWidth()) {
384 if (Total.ugt(Max.zext(Total.getBitWidth())))
Sam Parker3828c6f2018-07-23 12:27:47 +0000385 return false;
Sam Parker75aca942018-09-26 10:56:00 +0000386 } else if (Max.getBitWidth() > Total.getBitWidth()) {
387 if (Total.zext(Max.getBitWidth()).ugt(Max))
Sam Parker3828c6f2018-07-23 12:27:47 +0000388 return false;
Sam Parker75aca942018-09-26 10:56:00 +0000389 } else if (Total.ugt(Max))
390 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000391
Sam Parker75aca942018-09-26 10:56:00 +0000392 LLVM_DEBUG(dbgs() << "ARM CGP: Allowing safe overflow for " << *I << "\n");
Sam Parker3141bbd2019-05-21 07:56:47 +0000393 SafeWrap.insert(I);
Sam Parker75aca942018-09-26 10:56:00 +0000394 return true;
Sam Parker3828c6f2018-07-23 12:27:47 +0000395}
396
397static bool shouldPromote(Value *V) {
Sam Parkeraaec3c62018-09-13 15:14:12 +0000398 if (!isa<IntegerType>(V->getType()) || isSink(V))
Sam Parker8c4b9642018-08-10 13:57:13 +0000399 return false;
400
401 if (isSource(V))
402 return true;
403
Sam Parker3828c6f2018-07-23 12:27:47 +0000404 auto *I = dyn_cast<Instruction>(V);
405 if (!I)
406 return false;
407
Sam Parker8c4b9642018-08-10 13:57:13 +0000408 if (isa<ICmpInst>(I))
Sam Parker3828c6f2018-07-23 12:27:47 +0000409 return false;
410
Sam Parker3828c6f2018-07-23 12:27:47 +0000411 return true;
412}
413
414/// Return whether we can safely mutate V's type to ExtTy without having to be
415/// concerned with zero extending or truncation.
416static bool isPromotedResultSafe(Value *V) {
Sam Parkerd7b650c2019-05-09 11:56:16 +0000417 if (GenerateSignBits(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000418 return false;
419
Sam Parker3141bbd2019-05-21 07:56:47 +0000420 if (!isa<Instruction>(V))
421 return true;
422
423 if (!isa<OverflowingBinaryOperator>(V))
424 return true;
425
426 return cast<Instruction>(V)->hasNoUnsignedWrap();
Sam Parker3828c6f2018-07-23 12:27:47 +0000427}
428
429/// Return the intrinsic for the instruction that can perform the same
430/// operation but on a narrow type. This is using the parallel dsp intrinsics
431/// on scalar values.
Sam Parker8c4b9642018-08-10 13:57:13 +0000432static Intrinsic::ID getNarrowIntrinsic(Instruction *I) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000433 // Whether we use the signed or unsigned versions of these intrinsics
434 // doesn't matter because we're not using the GE bits that they set in
435 // the APSR.
436 switch(I->getOpcode()) {
437 default:
438 break;
439 case Instruction::Add:
Sam Parker8c4b9642018-08-10 13:57:13 +0000440 return ARMCodeGenPrepare::TypeSize == 16 ? Intrinsic::arm_uadd16 :
Sam Parker3828c6f2018-07-23 12:27:47 +0000441 Intrinsic::arm_uadd8;
442 case Instruction::Sub:
Sam Parker8c4b9642018-08-10 13:57:13 +0000443 return ARMCodeGenPrepare::TypeSize == 16 ? Intrinsic::arm_usub16 :
Sam Parker3828c6f2018-07-23 12:27:47 +0000444 Intrinsic::arm_usub8;
445 }
446 llvm_unreachable("unhandled opcode for narrow intrinsic");
447}
448
Sam Parkere7c42dd2018-11-19 11:34:40 +0000449void IRPromoter::ReplaceAllUsersOfWith(Value *From, Value *To) {
Sam Parker84a2f8b2018-11-01 15:23:42 +0000450 SmallVector<Instruction*, 4> Users;
451 Instruction *InstTo = dyn_cast<Instruction>(To);
Sam Parkere7c42dd2018-11-19 11:34:40 +0000452 bool ReplacedAll = true;
453
454 LLVM_DEBUG(dbgs() << "ARM CGP: Replacing " << *From << " with " << *To
455 << "\n");
456
Sam Parker84a2f8b2018-11-01 15:23:42 +0000457 for (Use &U : From->uses()) {
458 auto *User = cast<Instruction>(U.getUser());
Sam Parkere7c42dd2018-11-19 11:34:40 +0000459 if (InstTo && User->isIdenticalTo(InstTo)) {
460 ReplacedAll = false;
Sam Parker84a2f8b2018-11-01 15:23:42 +0000461 continue;
Sam Parkere7c42dd2018-11-19 11:34:40 +0000462 }
Sam Parker84a2f8b2018-11-01 15:23:42 +0000463 Users.push_back(User);
464 }
465
466 for (auto *U : Users)
467 U->replaceUsesOfWith(From, To);
Sam Parkere7c42dd2018-11-19 11:34:40 +0000468
469 if (ReplacedAll)
470 if (auto *I = dyn_cast<Instruction>(From))
471 InstsToRemove.insert(I);
Sam Parker84a2f8b2018-11-01 15:23:42 +0000472}
473
Sam Parker3141bbd2019-05-21 07:56:47 +0000474void IRPromoter::PrepareWrappingAdds() {
475 LLVM_DEBUG(dbgs() << "ARM CGP: Prepare underflowing adds.\n");
Sam Parker3828c6f2018-07-23 12:27:47 +0000476 IRBuilder<> Builder{Ctx};
Sam Parker3141bbd2019-05-21 07:56:47 +0000477
478 // For adds that safely wrap and use a negative immediate as operand 1, we
479 // create an equivalent instruction using a positive immediate.
480 // That positive immediate can then be zext along with all the other
481 // immediates later.
482 for (auto *I : *SafeWrap) {
483 if (I->getOpcode() != Instruction::Add)
Sam Parker84a2f8b2018-11-01 15:23:42 +0000484 continue;
Sam Parker3828c6f2018-07-23 12:27:47 +0000485
Sam Parker3141bbd2019-05-21 07:56:47 +0000486 LLVM_DEBUG(dbgs() << "ARM CGP: Adjusting " << *I << "\n");
487 assert((isa<ConstantInt>(I->getOperand(1)) &&
488 cast<ConstantInt>(I->getOperand(1))->isNegative()) &&
489 "Wrapping should have a negative immediate as the second operand");
Sam Parker13567db2018-08-16 10:05:39 +0000490
Sam Parker3141bbd2019-05-21 07:56:47 +0000491 auto Const = cast<ConstantInt>(I->getOperand(1));
492 auto *NewConst = ConstantInt::get(Ctx, Const->getValue().abs());
493 Builder.SetInsertPoint(I);
494 Value *NewVal = Builder.CreateSub(I->getOperand(0), NewConst);
495 if (auto *NewInst = dyn_cast<Instruction>(NewVal)) {
496 NewInst->copyIRFlags(I);
497 NewInsts.insert(NewInst);
Sam Parker3828c6f2018-07-23 12:27:47 +0000498 }
Sam Parker3141bbd2019-05-21 07:56:47 +0000499 InstsToRemove.insert(I);
500 I->replaceAllUsesWith(NewVal);
501 LLVM_DEBUG(dbgs() << "ARM CGP: New equivalent: " << *NewVal << "\n");
Sam Parker84a2f8b2018-11-01 15:23:42 +0000502 }
503 for (auto *I : NewInsts)
Sam Parkere7c42dd2018-11-19 11:34:40 +0000504 Visited->insert(I);
Sam Parker84a2f8b2018-11-01 15:23:42 +0000505}
Sam Parker3828c6f2018-07-23 12:27:47 +0000506
Sam Parkere7c42dd2018-11-19 11:34:40 +0000507void IRPromoter::ExtendSources() {
Sam Parker84a2f8b2018-11-01 15:23:42 +0000508 IRBuilder<> Builder{Ctx};
Sam Parker3828c6f2018-07-23 12:27:47 +0000509
510 auto InsertZExt = [&](Value *V, Instruction *InsertPt) {
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000511 assert(V->getType() != ExtTy && "zext already extends to i32");
Sam Parker3828c6f2018-07-23 12:27:47 +0000512 LLVM_DEBUG(dbgs() << "ARM CGP: Inserting ZExt for " << *V << "\n");
513 Builder.SetInsertPoint(InsertPt);
514 if (auto *I = dyn_cast<Instruction>(V))
515 Builder.SetCurrentDebugLocation(I->getDebugLoc());
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000516
517 Value *ZExt = Builder.CreateZExt(V, ExtTy);
518 if (auto *I = dyn_cast<Instruction>(ZExt)) {
519 if (isa<Argument>(V))
520 I->moveBefore(InsertPt);
521 else
522 I->moveAfter(InsertPt);
523 NewInsts.insert(I);
524 }
Sam Parkere7c42dd2018-11-19 11:34:40 +0000525
Sam Parker3828c6f2018-07-23 12:27:47 +0000526 ReplaceAllUsersOfWith(V, ZExt);
Sam Parker3828c6f2018-07-23 12:27:47 +0000527 };
528
Sam Parker84a2f8b2018-11-01 15:23:42 +0000529 // Now, insert extending instructions between the sources and their users.
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000530 LLVM_DEBUG(dbgs() << "ARM CGP: Promoting sources:\n");
Sam Parkere7c42dd2018-11-19 11:34:40 +0000531 for (auto V : *Sources) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000532 LLVM_DEBUG(dbgs() << " - " << *V << "\n");
Sam Parker8c4b9642018-08-10 13:57:13 +0000533 if (auto *I = dyn_cast<Instruction>(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000534 InsertZExt(I, I);
535 else if (auto *Arg = dyn_cast<Argument>(V)) {
536 BasicBlock &BB = Arg->getParent()->front();
537 InsertZExt(Arg, &*BB.getFirstInsertionPt());
538 } else {
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000539 llvm_unreachable("unhandled source that needs extending");
Sam Parker3828c6f2018-07-23 12:27:47 +0000540 }
541 Promoted.insert(V);
542 }
Sam Parker84a2f8b2018-11-01 15:23:42 +0000543}
Sam Parker3828c6f2018-07-23 12:27:47 +0000544
Sam Parkere7c42dd2018-11-19 11:34:40 +0000545void IRPromoter::PromoteTree() {
Sam Parker3828c6f2018-07-23 12:27:47 +0000546 LLVM_DEBUG(dbgs() << "ARM CGP: Mutating the tree..\n");
Sam Parker84a2f8b2018-11-01 15:23:42 +0000547
548 IRBuilder<> Builder{Ctx};
549
550 // Mutate the types of the instructions within the tree. Here we handle
Sam Parker3828c6f2018-07-23 12:27:47 +0000551 // constant operands.
Sam Parkere7c42dd2018-11-19 11:34:40 +0000552 for (auto *V : *Visited) {
553 if (Sources->count(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000554 continue;
555
Sam Parker3828c6f2018-07-23 12:27:47 +0000556 auto *I = cast<Instruction>(V);
Sam Parkere7c42dd2018-11-19 11:34:40 +0000557 if (Sinks->count(I))
Sam Parker3828c6f2018-07-23 12:27:47 +0000558 continue;
559
Sam Parker7def86b2018-08-15 07:52:35 +0000560 for (unsigned i = 0, e = I->getNumOperands(); i < e; ++i) {
561 Value *Op = I->getOperand(i);
562 if ((Op->getType() == ExtTy) || !isa<IntegerType>(Op->getType()))
Sam Parker3828c6f2018-07-23 12:27:47 +0000563 continue;
564
Sam Parker84a2f8b2018-11-01 15:23:42 +0000565 if (auto *Const = dyn_cast<ConstantInt>(Op)) {
566 Constant *NewConst = ConstantExpr::getZExt(Const, ExtTy);
567 I->setOperand(i, NewConst);
568 } else if (isa<UndefValue>(Op))
Sam Parker7def86b2018-08-15 07:52:35 +0000569 I->setOperand(i, UndefValue::get(ExtTy));
Sam Parker3828c6f2018-07-23 12:27:47 +0000570 }
571
572 if (shouldPromote(I)) {
573 I->mutateType(ExtTy);
574 Promoted.insert(I);
575 }
576 }
577
Sam Parker84a2f8b2018-11-01 15:23:42 +0000578 // Finally, any instructions that should be promoted but haven't yet been,
579 // need to be handled using intrinsics.
Sam Parkere7c42dd2018-11-19 11:34:40 +0000580 for (auto *V : *Visited) {
Sam Parker84a2f8b2018-11-01 15:23:42 +0000581 auto *I = dyn_cast<Instruction>(V);
582 if (!I)
Sam Parker3828c6f2018-07-23 12:27:47 +0000583 continue;
Sam Parker8c4b9642018-08-10 13:57:13 +0000584
Sam Parkere7c42dd2018-11-19 11:34:40 +0000585 if (Sources->count(I) || Sinks->count(I))
Sam Parker3828c6f2018-07-23 12:27:47 +0000586 continue;
587
Sam Parkere7c42dd2018-11-19 11:34:40 +0000588 if (!shouldPromote(I) || SafeToPromote->count(I) || NewInsts.count(I))
Sam Parker84a2f8b2018-11-01 15:23:42 +0000589 continue;
Sam Parker31bef632019-01-23 09:18:44 +0000590
Sam Parker75aca942018-09-26 10:56:00 +0000591 assert(EnableDSP && "DSP intrinisc insertion not enabled!");
592
Sam Parker3828c6f2018-07-23 12:27:47 +0000593 // Replace unsafe instructions with appropriate intrinsic calls.
Sam Parker84a2f8b2018-11-01 15:23:42 +0000594 LLVM_DEBUG(dbgs() << "ARM CGP: Inserting DSP intrinsic for "
595 << *I << "\n");
596 Function *DSPInst =
597 Intrinsic::getDeclaration(M, getNarrowIntrinsic(I));
598 Builder.SetInsertPoint(I);
599 Builder.SetCurrentDebugLocation(I->getDebugLoc());
600 Value *Args[] = { I->getOperand(0), I->getOperand(1) };
601 CallInst *Call = Builder.CreateCall(DSPInst, Args);
Sam Parker84a2f8b2018-11-01 15:23:42 +0000602 NewInsts.insert(Call);
Sam Parkere7c42dd2018-11-19 11:34:40 +0000603 ReplaceAllUsersOfWith(I, Call);
Sam Parker3828c6f2018-07-23 12:27:47 +0000604 }
Sam Parker84a2f8b2018-11-01 15:23:42 +0000605}
606
Sam Parkere7c42dd2018-11-19 11:34:40 +0000607void IRPromoter::TruncateSinks() {
Sam Parker84a2f8b2018-11-01 15:23:42 +0000608 LLVM_DEBUG(dbgs() << "ARM CGP: Fixing up the sinks:\n");
609
610 IRBuilder<> Builder{Ctx};
Sam Parker3828c6f2018-07-23 12:27:47 +0000611
Sam Parkere7c42dd2018-11-19 11:34:40 +0000612 auto InsertTrunc = [&](Value *V, Type *TruncTy) -> Instruction* {
Sam Parker13567db2018-08-16 10:05:39 +0000613 if (!isa<Instruction>(V) || !isa<IntegerType>(V->getType()))
614 return nullptr;
615
Sam Parkere7c42dd2018-11-19 11:34:40 +0000616 if ((!Promoted.count(V) && !NewInsts.count(V)) || Sources->count(V))
Sam Parker13567db2018-08-16 10:05:39 +0000617 return nullptr;
618
619 LLVM_DEBUG(dbgs() << "ARM CGP: Creating " << *TruncTy << " Trunc for "
620 << *V << "\n");
621 Builder.SetInsertPoint(cast<Instruction>(V));
Sam Parker48fbf752018-11-01 16:44:45 +0000622 auto *Trunc = dyn_cast<Instruction>(Builder.CreateTrunc(V, TruncTy));
623 if (Trunc)
624 NewInsts.insert(Trunc);
Sam Parker13567db2018-08-16 10:05:39 +0000625 return Trunc;
626 };
627
Sam Parker3828c6f2018-07-23 12:27:47 +0000628 // Fix up any stores or returns that use the results of the promoted
629 // chain.
Sam Parkere7c42dd2018-11-19 11:34:40 +0000630 for (auto I : *Sinks) {
631 LLVM_DEBUG(dbgs() << "ARM CGP: For Sink: " << *I << "\n");
Sam Parker13567db2018-08-16 10:05:39 +0000632
633 // Handle calls separately as we need to iterate over arg operands.
634 if (auto *Call = dyn_cast<CallInst>(I)) {
635 for (unsigned i = 0; i < Call->getNumArgOperands(); ++i) {
636 Value *Arg = Call->getArgOperand(i);
Sam Parkere7c42dd2018-11-19 11:34:40 +0000637 Type *Ty = TruncTysMap[Call][i];
638 if (Instruction *Trunc = InsertTrunc(Arg, Ty)) {
Sam Parker13567db2018-08-16 10:05:39 +0000639 Trunc->moveBefore(Call);
640 Call->setArgOperand(i, Trunc);
641 }
642 }
643 continue;
Sam Parker3828c6f2018-07-23 12:27:47 +0000644 }
645
Sam Parkere7c42dd2018-11-19 11:34:40 +0000646 // Special case switches because we need to truncate the condition.
647 if (auto *Switch = dyn_cast<SwitchInst>(I)) {
648 Type *Ty = TruncTysMap[Switch][0];
649 if (Instruction *Trunc = InsertTrunc(Switch->getCondition(), Ty)) {
650 Trunc->moveBefore(Switch);
651 Switch->setCondition(Trunc);
652 }
653 continue;
654 }
655
Sam Parker13567db2018-08-16 10:05:39 +0000656 // Now handle the others.
Sam Parker3828c6f2018-07-23 12:27:47 +0000657 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
Sam Parkere7c42dd2018-11-19 11:34:40 +0000658 Type *Ty = TruncTysMap[I][i];
659 if (Instruction *Trunc = InsertTrunc(I->getOperand(i), Ty)) {
Sam Parker13567db2018-08-16 10:05:39 +0000660 Trunc->moveBefore(I);
661 I->setOperand(i, Trunc);
Sam Parker3828c6f2018-07-23 12:27:47 +0000662 }
663 }
664 }
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000665}
666
Sam Parkere7c42dd2018-11-19 11:34:40 +0000667void IRPromoter::Cleanup() {
Sam Parker3c17cb72019-02-15 09:04:39 +0000668 LLVM_DEBUG(dbgs() << "ARM CGP: Cleanup..\n");
Sam Parker08979cd2018-11-09 09:28:27 +0000669 // Some zexts will now have become redundant, along with their trunc
670 // operands, so remove them
Sam Parkere7c42dd2018-11-19 11:34:40 +0000671 for (auto V : *Visited) {
Sam Parker31bef632019-01-23 09:18:44 +0000672 if (!isa<ZExtInst>(V))
Sam Parker08979cd2018-11-09 09:28:27 +0000673 continue;
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000674
Sam Parker31bef632019-01-23 09:18:44 +0000675 auto ZExt = cast<ZExtInst>(V);
Sam Parker08979cd2018-11-09 09:28:27 +0000676 if (ZExt->getDestTy() != ExtTy)
677 continue;
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000678
Sam Parker08979cd2018-11-09 09:28:27 +0000679 Value *Src = ZExt->getOperand(0);
680 if (ZExt->getSrcTy() == ZExt->getDestTy()) {
Sam Parkere7c42dd2018-11-19 11:34:40 +0000681 LLVM_DEBUG(dbgs() << "ARM CGP: Removing unnecessary cast: " << *ZExt
682 << "\n");
Sam Parker08979cd2018-11-09 09:28:27 +0000683 ReplaceAllUsersOfWith(ZExt, Src);
Sam Parker08979cd2018-11-09 09:28:27 +0000684 continue;
685 }
686
Sam Parker31bef632019-01-23 09:18:44 +0000687 // Unless they produce a value that is narrower than ExtTy, we can
688 // replace the result of the zext with the input of a newly inserted
689 // trunc.
690 if (NewInsts.count(Src) && isa<TruncInst>(Src) &&
691 Src->getType() == OrigTy) {
Sam Parker08979cd2018-11-09 09:28:27 +0000692 auto *Trunc = cast<TruncInst>(Src);
693 assert(Trunc->getOperand(0)->getType() == ExtTy &&
694 "expected inserted trunc to be operating on i32");
Sam Parker08979cd2018-11-09 09:28:27 +0000695 ReplaceAllUsersOfWith(ZExt, Trunc->getOperand(0));
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000696 }
697 }
698
699 for (auto *I : InstsToRemove) {
700 LLVM_DEBUG(dbgs() << "ARM CGP: Removing " << *I << "\n");
701 I->dropAllReferences();
702 I->eraseFromParent();
703 }
704
705 InstsToRemove.clear();
706 NewInsts.clear();
707 TruncTysMap.clear();
708 Promoted.clear();
Sam Parker3141bbd2019-05-21 07:56:47 +0000709 SafeToPromote->clear();
710 SafeWrap->clear();
Sam Parker84a2f8b2018-11-01 15:23:42 +0000711}
712
Sam Parkere7c42dd2018-11-19 11:34:40 +0000713void IRPromoter::ConvertTruncs() {
Sam Parker3c17cb72019-02-15 09:04:39 +0000714 LLVM_DEBUG(dbgs() << "ARM CGP: Converting truncs..\n");
Sam Parkere7c42dd2018-11-19 11:34:40 +0000715 IRBuilder<> Builder{Ctx};
716
717 for (auto *V : *Visited) {
718 if (!isa<TruncInst>(V) || Sources->count(V))
719 continue;
720
721 auto *Trunc = cast<TruncInst>(V);
Sam Parkere7c42dd2018-11-19 11:34:40 +0000722 Builder.SetInsertPoint(Trunc);
Sam Parker3c17cb72019-02-15 09:04:39 +0000723 IntegerType *SrcTy = cast<IntegerType>(Trunc->getOperand(0)->getType());
724 IntegerType *DestTy = cast<IntegerType>(TruncTysMap[Trunc][0]);
725
726 unsigned NumBits = DestTy->getScalarSizeInBits();
727 ConstantInt *Mask =
728 ConstantInt::get(SrcTy, APInt::getMaxValue(NumBits).getZExtValue());
Sam Parkere7c42dd2018-11-19 11:34:40 +0000729 Value *Masked = Builder.CreateAnd(Trunc->getOperand(0), Mask);
730
731 if (auto *I = dyn_cast<Instruction>(Masked))
732 NewInsts.insert(I);
733
734 ReplaceAllUsersOfWith(Trunc, Masked);
735 }
736}
737
Sam Parker84a2f8b2018-11-01 15:23:42 +0000738void IRPromoter::Mutate(Type *OrigTy,
Sam Parker6ed47be2019-02-21 09:33:18 +0000739 SetVector<Value*> &Visited,
Sam Parker84a2f8b2018-11-01 15:23:42 +0000740 SmallPtrSetImpl<Value*> &Sources,
741 SmallPtrSetImpl<Instruction*> &Sinks,
Sam Parker3141bbd2019-05-21 07:56:47 +0000742 SmallPtrSetImpl<Instruction*> &SafeToPromote,
743 SmallPtrSetImpl<Instruction*> &SafeWrap) {
Sam Parker84a2f8b2018-11-01 15:23:42 +0000744 LLVM_DEBUG(dbgs() << "ARM CGP: Promoting use-def chains to from "
745 << ARMCodeGenPrepare::TypeSize << " to 32-bits\n");
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000746
747 assert(isa<IntegerType>(OrigTy) && "expected integer type");
748 this->OrigTy = cast<IntegerType>(OrigTy);
749 assert(OrigTy->getPrimitiveSizeInBits() < ExtTy->getPrimitiveSizeInBits() &&
750 "original type not smaller than extended type");
Sam Parker84a2f8b2018-11-01 15:23:42 +0000751
Sam Parkere7c42dd2018-11-19 11:34:40 +0000752 this->Visited = &Visited;
753 this->Sources = &Sources;
754 this->Sinks = &Sinks;
755 this->SafeToPromote = &SafeToPromote;
Sam Parker3141bbd2019-05-21 07:56:47 +0000756 this->SafeWrap = &SafeWrap;
Sam Parkere7c42dd2018-11-19 11:34:40 +0000757
758 // Cache original types of the values that will likely need truncating
759 for (auto *I : Sinks) {
760 if (auto *Call = dyn_cast<CallInst>(I)) {
761 for (unsigned i = 0; i < Call->getNumArgOperands(); ++i) {
762 Value *Arg = Call->getArgOperand(i);
763 TruncTysMap[Call].push_back(Arg->getType());
764 }
765 } else if (auto *Switch = dyn_cast<SwitchInst>(I))
766 TruncTysMap[I].push_back(Switch->getCondition()->getType());
767 else {
768 for (unsigned i = 0; i < I->getNumOperands(); ++i)
769 TruncTysMap[I].push_back(I->getOperand(i)->getType());
770 }
771 }
Sam Parker3c17cb72019-02-15 09:04:39 +0000772 for (auto *V : Visited) {
773 if (!isa<TruncInst>(V) || Sources.count(V))
774 continue;
775 auto *Trunc = cast<TruncInst>(V);
776 TruncTysMap[Trunc].push_back(Trunc->getDestTy());
777 }
Sam Parker84a2f8b2018-11-01 15:23:42 +0000778
Sam Parker3141bbd2019-05-21 07:56:47 +0000779 // Convert adds using negative immediates to equivalent instructions that use
780 // positive constants.
781 PrepareWrappingAdds();
Sam Parker84a2f8b2018-11-01 15:23:42 +0000782
783 // Insert zext instructions between sources and their users.
Sam Parkere7c42dd2018-11-19 11:34:40 +0000784 ExtendSources();
785
Sam Parker84a2f8b2018-11-01 15:23:42 +0000786 // Promote visited instructions, mutating their types in place. Also insert
787 // DSP intrinsics, if enabled, for adds and subs which would be unsafe to
788 // promote.
Sam Parkere7c42dd2018-11-19 11:34:40 +0000789 PromoteTree();
Sam Parker84a2f8b2018-11-01 15:23:42 +0000790
Sam Parker3c17cb72019-02-15 09:04:39 +0000791 // Convert any truncs, that aren't sources, into AND masks.
792 ConvertTruncs();
793
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000794 // Insert trunc instructions for use by calls, stores etc...
Sam Parkere7c42dd2018-11-19 11:34:40 +0000795 TruncateSinks();
Sam Parker84a2f8b2018-11-01 15:23:42 +0000796
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000797 // Finally, remove unecessary zexts and truncs, delete old instructions and
798 // clear the data structures.
Sam Parkere7c42dd2018-11-19 11:34:40 +0000799 Cleanup();
Sam Parkerfcd8ada2018-11-05 10:58:37 +0000800
Sam Parker08979cd2018-11-09 09:28:27 +0000801 LLVM_DEBUG(dbgs() << "ARM CGP: Mutation complete\n");
Sam Parker3828c6f2018-07-23 12:27:47 +0000802}
803
Sam Parker8c4b9642018-08-10 13:57:13 +0000804/// We accept most instructions, as well as Arguments and ConstantInsts. We
805/// Disallow casts other than zext and truncs and only allow calls if their
806/// return value is zeroext. We don't allow opcodes that can introduce sign
807/// bits.
808bool ARMCodeGenPrepare::isSupportedValue(Value *V) {
Sam Parker08979cd2018-11-09 09:28:27 +0000809 if (auto *I = dyn_cast<ICmpInst>(V)) {
810 // Now that we allow small types than TypeSize, only allow icmp of
811 // TypeSize because they will require a trunc to be legalised.
812 // TODO: Allow icmp of smaller types, and calculate at the end
813 // whether the transform would be beneficial.
814 if (isa<PointerType>(I->getOperand(0)->getType()))
815 return true;
816 return EqualTypeSize(I->getOperand(0));
817 }
Sam Parker8c4b9642018-08-10 13:57:13 +0000818
Sam Parkerd7b650c2019-05-09 11:56:16 +0000819 if (GenerateSignBits(V)) {
820 LLVM_DEBUG(dbgs() << "ARM CGP: No, instruction can generate sign bits.\n");
821 return false;
822 }
823
Volodymyr Sapsai703ab842018-09-18 00:11:55 +0000824 // Memory instructions
825 if (isa<StoreInst>(V) || isa<GetElementPtrInst>(V))
826 return true;
827
828 // Branches and targets.
829 if( isa<BranchInst>(V) || isa<SwitchInst>(V) || isa<BasicBlock>(V))
830 return true;
831
832 // Non-instruction values that we can handle.
833 if ((isa<Constant>(V) && !isa<ConstantExpr>(V)) || isa<Argument>(V))
834 return isSupportedType(V);
835
836 if (isa<PHINode>(V) || isa<SelectInst>(V) || isa<ReturnInst>(V) ||
837 isa<LoadInst>(V))
838 return isSupportedType(V);
839
Sam Parker08979cd2018-11-09 09:28:27 +0000840 if (auto *Cast = dyn_cast<CastInst>(V))
841 return isSupportedType(Cast) || isSupportedType(Cast->getOperand(0));
Sam Parker0e2f0bd2018-08-16 11:54:09 +0000842
Sam Parker8c4b9642018-08-10 13:57:13 +0000843 // Special cases for calls as we need to check for zeroext
844 // TODO We should accept calls even if they don't have zeroext, as they can
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000845 // still be sinks.
Sam Parker8c4b9642018-08-10 13:57:13 +0000846 if (auto *Call = dyn_cast<CallInst>(V))
847 return isSupportedType(Call) &&
848 Call->hasRetAttr(Attribute::AttrKind::ZExt);
849
Volodymyr Sapsai703ab842018-09-18 00:11:55 +0000850 if (!isa<BinaryOperator>(V))
851 return false;
852
853 if (!isSupportedType(V))
854 return false;
855
Volodymyr Sapsai703ab842018-09-18 00:11:55 +0000856 return true;
Sam Parker8c4b9642018-08-10 13:57:13 +0000857}
858
859/// Check that the type of V would be promoted and that the original type is
860/// smaller than the targeted promoted type. Check that we're not trying to
861/// promote something larger than our base 'TypeSize' type.
862bool ARMCodeGenPrepare::isLegalToPromote(Value *V) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000863
864 auto *I = dyn_cast<Instruction>(V);
865 if (!I)
Sam Parker84a2f8b2018-11-01 15:23:42 +0000866 return true;
867
868 if (SafeToPromote.count(I))
869 return true;
870
Sam Parker3141bbd2019-05-21 07:56:47 +0000871 if (isPromotedResultSafe(V) || isSafeWrap(I)) {
Sam Parker84a2f8b2018-11-01 15:23:42 +0000872 SafeToPromote.insert(I);
873 return true;
874 }
875
876 if (I->getOpcode() != Instruction::Add && I->getOpcode() != Instruction::Sub)
Sam Parker8c4b9642018-08-10 13:57:13 +0000877 return false;
878
879 // If promotion is not safe, can we use a DSP instruction to natively
880 // handle the narrow type?
Sam Parker3828c6f2018-07-23 12:27:47 +0000881 if (!ST->hasDSP() || !EnableDSP || !isSupportedType(I))
882 return false;
883
884 if (ST->isThumb() && !ST->hasThumb2())
885 return false;
886
Sam Parker3828c6f2018-07-23 12:27:47 +0000887 // TODO
888 // Would it be profitable? For Thumb code, these parallel DSP instructions
889 // are only Thumb-2, so we wouldn't be able to dual issue on Cortex-M33. For
890 // Cortex-A, specifically Cortex-A72, the latency is double and throughput is
891 // halved. They also do not take immediates as operands.
892 for (auto &Op : I->operands()) {
893 if (isa<Constant>(Op)) {
894 if (!EnableDSPWithImms)
895 return false;
896 }
897 }
Sam Parker84a2f8b2018-11-01 15:23:42 +0000898 LLVM_DEBUG(dbgs() << "ARM CGP: Will use an intrinsic for: " << *I << "\n");
Sam Parker3828c6f2018-07-23 12:27:47 +0000899 return true;
900}
901
Sam Parker3828c6f2018-07-23 12:27:47 +0000902bool ARMCodeGenPrepare::TryToPromote(Value *V) {
903 OrigTy = V->getType();
904 TypeSize = OrigTy->getPrimitiveSizeInBits();
Sam Parkerfabf7fe2018-08-15 13:29:50 +0000905 if (TypeSize > 16 || TypeSize < 8)
Sam Parker8c4b9642018-08-10 13:57:13 +0000906 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000907
Sam Parker84a2f8b2018-11-01 15:23:42 +0000908 SafeToPromote.clear();
Sam Parker617cdc52019-05-23 07:46:39 +0000909 SafeWrap.clear();
Sam Parker84a2f8b2018-11-01 15:23:42 +0000910
Sam Parker3828c6f2018-07-23 12:27:47 +0000911 if (!isSupportedValue(V) || !shouldPromote(V) || !isLegalToPromote(V))
912 return false;
913
Sam Parker8c4b9642018-08-10 13:57:13 +0000914 LLVM_DEBUG(dbgs() << "ARM CGP: TryToPromote: " << *V << ", TypeSize = "
915 << TypeSize << "\n");
Sam Parker3828c6f2018-07-23 12:27:47 +0000916
917 SetVector<Value*> WorkList;
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000918 SmallPtrSet<Value*, 8> Sources;
919 SmallPtrSet<Instruction*, 4> Sinks;
Sam Parker6ed47be2019-02-21 09:33:18 +0000920 SetVector<Value*> CurrentVisited;
Sam Parker84a2f8b2018-11-01 15:23:42 +0000921 WorkList.insert(V);
Sam Parker3828c6f2018-07-23 12:27:47 +0000922
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000923 // Return true if V was added to the worklist as a supported instruction,
924 // if it was already visited, or if we don't need to explore it (e.g.
925 // pointer values and GEPs), and false otherwise.
Sam Parker3828c6f2018-07-23 12:27:47 +0000926 auto AddLegalInst = [&](Value *V) {
927 if (CurrentVisited.count(V))
928 return true;
929
Sam Parker0d511972018-08-16 12:24:40 +0000930 // Ignore GEPs because they don't need promoting and the constant indices
931 // will prevent the transformation.
932 if (isa<GetElementPtrInst>(V))
933 return true;
934
Sam Parker3828c6f2018-07-23 12:27:47 +0000935 if (!isSupportedValue(V) || (shouldPromote(V) && !isLegalToPromote(V))) {
936 LLVM_DEBUG(dbgs() << "ARM CGP: Can't handle: " << *V << "\n");
937 return false;
938 }
939
940 WorkList.insert(V);
941 return true;
942 };
943
944 // Iterate through, and add to, a tree of operands and users in the use-def.
945 while (!WorkList.empty()) {
946 Value *V = WorkList.back();
947 WorkList.pop_back();
948 if (CurrentVisited.count(V))
949 continue;
950
Sam Parker7def86b2018-08-15 07:52:35 +0000951 // Ignore non-instructions, other than arguments.
Sam Parker3828c6f2018-07-23 12:27:47 +0000952 if (!isa<Instruction>(V) && !isSource(V))
953 continue;
954
955 // If we've already visited this value from somewhere, bail now because
956 // the tree has already been explored.
957 // TODO: This could limit the transform, ie if we try to promote something
958 // from an i8 and fail first, before trying an i16.
Sam Parkeraaec3c62018-09-13 15:14:12 +0000959 if (AllVisited.count(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000960 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000961
962 CurrentVisited.insert(V);
963 AllVisited.insert(V);
964
965 // Calls can be both sources and sinks.
966 if (isSink(V))
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000967 Sinks.insert(cast<Instruction>(V));
Sam Parker08979cd2018-11-09 09:28:27 +0000968
Sam Parker3828c6f2018-07-23 12:27:47 +0000969 if (isSource(V))
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000970 Sources.insert(V);
Sam Parker08979cd2018-11-09 09:28:27 +0000971
972 if (!isSink(V) && !isSource(V)) {
973 if (auto *I = dyn_cast<Instruction>(V)) {
974 // Visit operands of any instruction visited.
975 for (auto &U : I->operands()) {
976 if (!AddLegalInst(U))
977 return false;
978 }
Sam Parker3828c6f2018-07-23 12:27:47 +0000979 }
980 }
981
982 // Don't visit users of a node which isn't going to be mutated unless its a
983 // source.
984 if (isSource(V) || shouldPromote(V)) {
985 for (Use &U : V->uses()) {
986 if (!AddLegalInst(U.getUser()))
987 return false;
988 }
989 }
990 }
991
Sam Parker3828c6f2018-07-23 12:27:47 +0000992 LLVM_DEBUG(dbgs() << "ARM CGP: Visited nodes:\n";
993 for (auto *I : CurrentVisited)
994 I->dump();
995 );
Sam Parker7def86b2018-08-15 07:52:35 +0000996 unsigned ToPromote = 0;
997 for (auto *V : CurrentVisited) {
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000998 if (Sources.count(V))
Sam Parker7def86b2018-08-15 07:52:35 +0000999 continue;
Sjoerd Meijer31239a42018-08-17 07:34:01 +00001000 if (Sinks.count(cast<Instruction>(V)))
Sam Parker7def86b2018-08-15 07:52:35 +00001001 continue;
1002 ++ToPromote;
1003 }
1004
1005 if (ToPromote < 2)
1006 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +00001007
Sam Parker3141bbd2019-05-21 07:56:47 +00001008 Promoter->Mutate(OrigTy, CurrentVisited, Sources, Sinks, SafeToPromote,
1009 SafeWrap);
Sam Parker3828c6f2018-07-23 12:27:47 +00001010 return true;
1011}
1012
1013bool ARMCodeGenPrepare::doInitialization(Module &M) {
1014 Promoter = new IRPromoter(&M);
1015 return false;
1016}
1017
1018bool ARMCodeGenPrepare::runOnFunction(Function &F) {
1019 if (skipFunction(F) || DisableCGP)
1020 return false;
1021
1022 auto *TPC = &getAnalysis<TargetPassConfig>();
1023 if (!TPC)
1024 return false;
1025
1026 const TargetMachine &TM = TPC->getTM<TargetMachine>();
1027 ST = &TM.getSubtarget<ARMSubtarget>(F);
1028 bool MadeChange = false;
1029 LLVM_DEBUG(dbgs() << "ARM CGP: Running on " << F.getName() << "\n");
1030
1031 // Search up from icmps to try to promote their operands.
1032 for (BasicBlock &BB : F) {
1033 auto &Insts = BB.getInstList();
1034 for (auto &I : Insts) {
1035 if (AllVisited.count(&I))
1036 continue;
1037
1038 if (isa<ICmpInst>(I)) {
1039 auto &CI = cast<ICmpInst>(I);
1040
1041 // Skip signed or pointer compares
1042 if (CI.isSigned() || !isa<IntegerType>(CI.getOperand(0)->getType()))
1043 continue;
1044
Sam Parker08979cd2018-11-09 09:28:27 +00001045 LLVM_DEBUG(dbgs() << "ARM CGP: Searching from: " << CI << "\n");
1046
Sam Parker3828c6f2018-07-23 12:27:47 +00001047 for (auto &Op : CI.operands()) {
Sam Parker8c4b9642018-08-10 13:57:13 +00001048 if (auto *I = dyn_cast<Instruction>(Op))
1049 MadeChange |= TryToPromote(I);
Sam Parker3828c6f2018-07-23 12:27:47 +00001050 }
1051 }
1052 }
Sam Parker3828c6f2018-07-23 12:27:47 +00001053 LLVM_DEBUG(if (verifyFunction(F, &dbgs())) {
Sam Parkerfcd8ada2018-11-05 10:58:37 +00001054 dbgs() << F;
Sam Parker3828c6f2018-07-23 12:27:47 +00001055 report_fatal_error("Broken function after type promotion");
1056 });
1057 }
1058 if (MadeChange)
1059 LLVM_DEBUG(dbgs() << "After ARMCodeGenPrepare: " << F << "\n");
1060
1061 return MadeChange;
1062}
1063
Matt Morehousea70685f2018-07-23 17:00:45 +00001064bool ARMCodeGenPrepare::doFinalization(Module &M) {
1065 delete Promoter;
1066 return false;
1067}
1068
Sam Parker3828c6f2018-07-23 12:27:47 +00001069INITIALIZE_PASS_BEGIN(ARMCodeGenPrepare, DEBUG_TYPE,
1070 "ARM IR optimizations", false, false)
1071INITIALIZE_PASS_END(ARMCodeGenPrepare, DEBUG_TYPE, "ARM IR optimizations",
1072 false, false)
1073
1074char ARMCodeGenPrepare::ID = 0;
Sam Parker8c4b9642018-08-10 13:57:13 +00001075unsigned ARMCodeGenPrepare::TypeSize = 0;
Sam Parker3828c6f2018-07-23 12:27:47 +00001076
1077FunctionPass *llvm::createARMCodeGenPreparePass() {
1078 return new ARMCodeGenPrepare();
1079}