1 //===----- TypePromotion.cpp ----------------------------------------------===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// This is an opcode based type promotion pass for small types that would
11 /// otherwise be promoted during legalisation. This works around the limitations
12 /// of selection dag for cyclic regions. The search begins from icmp
13 /// instructions operands where a tree, consisting of non-wrapping or safe
14 /// wrapping instructions, is built, checked and promoted if possible.
15 ///
16 //===----------------------------------------------------------------------===//
17 
18 #include "llvm/ADT/SetVector.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/CodeGen/Passes.h"
21 #include "llvm/CodeGen/TargetLowering.h"
22 #include "llvm/CodeGen/TargetPassConfig.h"
23 #include "llvm/CodeGen/TargetSubtargetInfo.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/DataLayout.h"
29 #include "llvm/IR/InstrTypes.h"
30 #include "llvm/IR/Instruction.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/Intrinsics.h"
34 #include "llvm/IR/Type.h"
35 #include "llvm/IR/Value.h"
36 #include "llvm/IR/Verifier.h"
37 #include "llvm/InitializePasses.h"
38 #include "llvm/Pass.h"
39 #include "llvm/Support/Casting.h"
40 #include "llvm/Support/CommandLine.h"
41 
42 #define DEBUG_TYPE "type-promotion"
43 #define PASS_NAME "Type Promotion"
44 
45 using namespace llvm;
46 
47 static cl::opt<bool>
48 DisablePromotion("disable-type-promotion", cl::Hidden, cl::init(true),
49                  cl::desc("Disable type promotion pass"));
50 
51 // The goal of this pass is to enable more efficient code generation for
52 // operations on narrow types (i.e. types with < 32-bits) and this is a
53 // motivating IR code example:
54 //
55 //   define hidden i32 @cmp(i8 zeroext) {
56 //     %2 = add i8 %0, -49
57 //     %3 = icmp ult i8 %2, 3
58 //     ..
59 //   }
60 //
61 // The issue here is that i8 is type-legalized to i32 because i8 is not a
62 // legal type. Thus, arithmetic is done in integer-precision, but then the
63 // byte value is masked out as follows:
64 //
65 //   t19: i32 = add t4, Constant:i32<-49>
66 //     t24: i32 = and t19, Constant:i32<255>
67 //
68 // Consequently, we generate code like this:
69 //
70 //   subs  r0, #49
71 //   uxtb  r1, r0
72 //   cmp r1, #3
73 //
74 // This shows that masking out the byte value results in generation of
75 // the UXTB instruction. This is not optimal as r0 already contains the byte
76 // value we need, and so instead we can just generate:
77 //
78 //   sub.w r1, r0, #49
79 //   cmp r1, #3
80 //
81 // We achieve this by type promoting the IR to i32 like so for this example:
82 //
83 //   define i32 @cmp(i8 zeroext %c) {
84 //     %0 = zext i8 %c to i32
85 //     %c.off = add i32 %0, -49
86 //     %1 = icmp ult i32 %c.off, 3
87 //     ..
88 //   }
89 //
90 // For this to be valid and legal, we need to prove that the i32 add is
91 // producing the same value as the i8 addition, and that e.g. no overflow
92 // happens.
93 //
94 // A brief sketch of the algorithm and some terminology.
95 // We pattern match interesting IR patterns:
96 // - which have "sources": instructions producing narrow values (i8, i16), and
97 // - they have "sinks": instructions consuming these narrow values.
98 //
99 // We collect all instruction connecting sources and sinks in a worklist, so
100 // that we can mutate these instruction and perform type promotion when it is
101 // legal to do so.
102 
103 namespace {
104 class IRPromoter {
105   SmallPtrSet<Value*, 8> NewInsts;
106   SmallPtrSet<Instruction*, 4> InstsToRemove;
107   DenseMap<Value*, SmallVector<Type*, 4>> TruncTysMap;
108   SmallPtrSet<Value*, 8> Promoted;
109   LLVMContext &Ctx;
110   // The type we promote to: always i32
111   IntegerType *ExtTy = nullptr;
112   // The type of the value that the search began from, either i8 or i16.
113   // This defines the max range of the values that we allow in the promoted
114   // tree.
115   IntegerType *OrigTy = nullptr;
116   SetVector<Value*> *Visited;
117   SmallPtrSetImpl<Value*> *Sources;
118   SmallPtrSetImpl<Instruction*> *Sinks;
119   SmallPtrSetImpl<Instruction*> *SafeToPromote;
120   SmallPtrSetImpl<Instruction*> *SafeWrap;
121 
122   void ReplaceAllUsersOfWith(Value *From, Value *To);
123   void PrepareWrappingAdds(void);
124   void ExtendSources(void);
125   void ConvertTruncs(void);
126   void PromoteTree(void);
127   void TruncateSinks(void);
128   void Cleanup(void);
129 
130 public:
131   IRPromoter(Module *M) : Ctx(M->getContext()) { }
132 
133 
134   void Mutate(Type *OrigTy, unsigned PromotedWidth,
135               SetVector<Value*> &Visited,
136               SmallPtrSetImpl<Value*> &Sources,
137               SmallPtrSetImpl<Instruction*> &Sinks,
138               SmallPtrSetImpl<Instruction*> &SafeToPromote,
139               SmallPtrSetImpl<Instruction*> &SafeWrap);
140 };
141 
142 class TypePromotion : public FunctionPass {
143   IRPromoter *Promoter = nullptr;
144   SmallPtrSet<Value*, 16> AllVisited;
145   SmallPtrSet<Instruction*, 8> SafeToPromote;
146   SmallPtrSet<Instruction*, 4> SafeWrap;
147 
148   bool isSafeWrap(Instruction *I);
149   bool isSupportedValue(Value *V);
150   bool isLegalToPromote(Value *V);
151   bool TryToPromote(Value *V, unsigned PromotedWidth);
152 
153 public:
154   static char ID;
155   static unsigned TypeSize;
156   Type *OrigTy = nullptr;
157 
158   TypePromotion() : FunctionPass(ID) {}
159 
160   void getAnalysisUsage(AnalysisUsage &AU) const override {
161     AU.addRequired<TargetPassConfig>();
162   }
163 
164   StringRef getPassName() const override { return PASS_NAME; }
165 
166   bool doInitialization(Module &M) override;
167   bool runOnFunction(Function &F) override;
168   bool doFinalization(Module &M) override;
169 };
170 
171 }
172 
173 static bool GenerateSignBits(Value *V) {
174   if (!isa<Instruction>(V))
175     return false;
176 
177   unsigned Opc = cast<Instruction>(V)->getOpcode();
178   return Opc == Instruction::AShr || Opc == Instruction::SDiv ||
179          Opc == Instruction::SRem || Opc == Instruction::SExt;
180 }
181 
182 static bool EqualTypeSize(Value *V) {
183   return V->getType()->getScalarSizeInBits() == TypePromotion::TypeSize;
184 }
185 
186 static bool LessOrEqualTypeSize(Value *V) {
187   return V->getType()->getScalarSizeInBits() <= TypePromotion::TypeSize;
188 }
189 
190 static bool GreaterThanTypeSize(Value *V) {
191   return V->getType()->getScalarSizeInBits() > TypePromotion::TypeSize;
192 }
193 
194 static bool LessThanTypeSize(Value *V) {
195   return V->getType()->getScalarSizeInBits() < TypePromotion::TypeSize;
196 }
197 
198 /// Some instructions can use 8- and 16-bit operands, and we don't need to
199 /// promote anything larger. We disallow booleans to make life easier when
200 /// dealing with icmps but allow any other integer that is <= 16 bits. Void
201 /// types are accepted so we can handle switches.
202 static bool isSupportedType(Value *V) {
203   Type *Ty = V->getType();
204 
205   // Allow voids and pointers, these won't be promoted.
206   if (Ty->isVoidTy() || Ty->isPointerTy())
207     return true;
208 
209   if (auto *Ld = dyn_cast<LoadInst>(V))
210     Ty = cast<PointerType>(Ld->getPointerOperandType())->getElementType();
211 
212   if (!isa<IntegerType>(Ty) ||
213       cast<IntegerType>(V->getType())->getBitWidth() == 1)
214     return false;
215 
216   return LessOrEqualTypeSize(V);
217 }
218 
219 /// Return true if the given value is a source in the use-def chain, producing
220 /// a narrow 'TypeSize' value. These values will be zext to start the promotion
221 /// of the tree to i32. We guarantee that these won't populate the upper bits
222 /// of the register. ZExt on the loads will be free, and the same for call
223 /// return values because we only accept ones that guarantee a zeroext ret val.
224 /// Many arguments will have the zeroext attribute too, so those would be free
225 /// too.
226 static bool isSource(Value *V) {
227   if (!isa<IntegerType>(V->getType()))
228     return false;
229 
230   // TODO Allow zext to be sources.
231   if (isa<Argument>(V))
232     return true;
233   else if (isa<LoadInst>(V))
234     return true;
235   else if (isa<BitCastInst>(V))
236     return true;
237   else if (auto *Call = dyn_cast<CallInst>(V))
238     return Call->hasRetAttr(Attribute::AttrKind::ZExt);
239   else if (auto *Trunc = dyn_cast<TruncInst>(V))
240     return EqualTypeSize(Trunc);
241   return false;
242 }
243 
244 /// Return true if V will require any promoted values to be truncated for the
245 /// the IR to remain valid. We can't mutate the value type of these
246 /// instructions.
247 static bool isSink(Value *V) {
248   // TODO The truncate also isn't actually necessary because we would already
249   // proved that the data value is kept within the range of the original data
250   // type.
251 
252   // Sinks are:
253   // - points where the value in the register is being observed, such as an
254   //   icmp, switch or store.
255   // - points where value types have to match, such as calls and returns.
256   // - zext are included to ease the transformation and are generally removed
257   //   later on.
258   if (auto *Store = dyn_cast<StoreInst>(V))
259     return LessOrEqualTypeSize(Store->getValueOperand());
260   if (auto *Return = dyn_cast<ReturnInst>(V))
261     return LessOrEqualTypeSize(Return->getReturnValue());
262   if (auto *ZExt = dyn_cast<ZExtInst>(V))
263     return GreaterThanTypeSize(ZExt);
264   if (auto *Switch = dyn_cast<SwitchInst>(V))
265     return LessThanTypeSize(Switch->getCondition());
266   if (auto *ICmp = dyn_cast<ICmpInst>(V))
267     return ICmp->isSigned() || LessThanTypeSize(ICmp->getOperand(0));
268 
269   return isa<CallInst>(V);
270 }
271 
272 /// Return whether this instruction can safely wrap.
273 bool TypePromotion::isSafeWrap(Instruction *I) {
274   // We can support a, potentially, wrapping instruction (I) if:
275   // - It is only used by an unsigned icmp.
276   // - The icmp uses a constant.
277   // - The wrapping value (I) is decreasing, i.e would underflow - wrapping
278   //   around zero to become a larger number than before.
279   // - The wrapping instruction (I) also uses a constant.
280   //
281   // We can then use the two constants to calculate whether the result would
282   // wrap in respect to itself in the original bitwidth. If it doesn't wrap,
283   // just underflows the range, the icmp would give the same result whether the
284   // result has been truncated or not. We calculate this by:
285   // - Zero extending both constants, if needed, to 32-bits.
286   // - Take the absolute value of I's constant, adding this to the icmp const.
287   // - Check that this value is not out of range for small type. If it is, it
288   //   means that it has underflowed enough to wrap around the icmp constant.
289   //
290   // For example:
291   //
292   // %sub = sub i8 %a, 2
293   // %cmp = icmp ule i8 %sub, 254
294   //
295   // If %a = 0, %sub = -2 == FE == 254
296   // But if this is evalulated as a i32
297   // %sub = -2 == FF FF FF FE == 4294967294
298   // So the unsigned compares (i8 and i32) would not yield the same result.
299   //
300   // Another way to look at it is:
301   // %a - 2 <= 254
302   // %a + 2 <= 254 + 2
303   // %a <= 256
304   // And we can't represent 256 in the i8 format, so we don't support it.
305   //
306   // Whereas:
307   //
308   // %sub i8 %a, 1
309   // %cmp = icmp ule i8 %sub, 254
310   //
311   // If %a = 0, %sub = -1 == FF == 255
312   // As i32:
313   // %sub = -1 == FF FF FF FF == 4294967295
314   //
315   // In this case, the unsigned compare results would be the same and this
316   // would also be true for ult, uge and ugt:
317   // - (255 < 254) == (0xFFFFFFFF < 254) == false
318   // - (255 <= 254) == (0xFFFFFFFF <= 254) == false
319   // - (255 > 254) == (0xFFFFFFFF > 254) == true
320   // - (255 >= 254) == (0xFFFFFFFF >= 254) == true
321   //
322   // To demonstrate why we can't handle increasing values:
323   //
324   // %add = add i8 %a, 2
325   // %cmp = icmp ult i8 %add, 127
326   //
327   // If %a = 254, %add = 256 == (i8 1)
328   // As i32:
329   // %add = 256
330   //
331   // (1 < 127) != (256 < 127)
332 
333   unsigned Opc = I->getOpcode();
334   if (Opc != Instruction::Add && Opc != Instruction::Sub)
335     return false;
336 
337   if (!I->hasOneUse() ||
338       !isa<ICmpInst>(*I->user_begin()) ||
339       !isa<ConstantInt>(I->getOperand(1)))
340     return false;
341 
342   ConstantInt *OverflowConst = cast<ConstantInt>(I->getOperand(1));
343   bool NegImm = OverflowConst->isNegative();
344   bool IsDecreasing = ((Opc == Instruction::Sub) && !NegImm) ||
345                        ((Opc == Instruction::Add) && NegImm);
346   if (!IsDecreasing)
347     return false;
348 
349   // Don't support an icmp that deals with sign bits.
350   auto *CI = cast<ICmpInst>(*I->user_begin());
351   if (CI->isSigned() || CI->isEquality())
352     return false;
353 
354   ConstantInt *ICmpConst = nullptr;
355   if (auto *Const = dyn_cast<ConstantInt>(CI->getOperand(0)))
356     ICmpConst = Const;
357   else if (auto *Const = dyn_cast<ConstantInt>(CI->getOperand(1)))
358     ICmpConst = Const;
359   else
360     return false;
361 
362   // Now check that the result can't wrap on itself.
363   APInt Total = ICmpConst->getValue().getBitWidth() < 32 ?
364     ICmpConst->getValue().zext(32) : ICmpConst->getValue();
365 
366   Total += OverflowConst->getValue().getBitWidth() < 32 ?
367     OverflowConst->getValue().abs().zext(32) : OverflowConst->getValue().abs();
368 
369   APInt Max = APInt::getAllOnesValue(TypePromotion::TypeSize);
370 
371   if (Total.getBitWidth() > Max.getBitWidth()) {
372     if (Total.ugt(Max.zext(Total.getBitWidth())))
373       return false;
374   } else if (Max.getBitWidth() > Total.getBitWidth()) {
375     if (Total.zext(Max.getBitWidth()).ugt(Max))
376       return false;
377   } else if (Total.ugt(Max))
378     return false;
379 
380   LLVM_DEBUG(dbgs() << "IR Promotion: Allowing safe overflow for " << *I << "\n");
381   SafeWrap.insert(I);
382   return true;
383 }
384 
385 static bool shouldPromote(Value *V) {
386   if (!isa<IntegerType>(V->getType()) || isSink(V))
387     return false;
388 
389   if (isSource(V))
390     return true;
391 
392   auto *I = dyn_cast<Instruction>(V);
393   if (!I)
394     return false;
395 
396   if (isa<ICmpInst>(I))
397     return false;
398 
399   return true;
400 }
401 
402 /// Return whether we can safely mutate V's type to ExtTy without having to be
403 /// concerned with zero extending or truncation.
404 static bool isPromotedResultSafe(Value *V) {
405   if (GenerateSignBits(V))
406     return false;
407 
408   if (!isa<Instruction>(V))
409     return true;
410 
411   if (!isa<OverflowingBinaryOperator>(V))
412     return true;
413 
414   return cast<Instruction>(V)->hasNoUnsignedWrap();
415 }
416 
417 void IRPromoter::ReplaceAllUsersOfWith(Value *From, Value *To) {
418   SmallVector<Instruction*, 4> Users;
419   Instruction *InstTo = dyn_cast<Instruction>(To);
420   bool ReplacedAll = true;
421 
422   LLVM_DEBUG(dbgs() << "IR Promotion: Replacing " << *From << " with " << *To
423              << "\n");
424 
425   for (Use &U : From->uses()) {
426     auto *User = cast<Instruction>(U.getUser());
427     if (InstTo && User->isIdenticalTo(InstTo)) {
428       ReplacedAll = false;
429       continue;
430     }
431     Users.push_back(User);
432   }
433 
434   for (auto *U : Users)
435     U->replaceUsesOfWith(From, To);
436 
437   if (ReplacedAll)
438     if (auto *I = dyn_cast<Instruction>(From))
439       InstsToRemove.insert(I);
440 }
441 
442 void IRPromoter::PrepareWrappingAdds() {
443   LLVM_DEBUG(dbgs() << "IR Promotion: Prepare wrapping adds.\n");
444   IRBuilder<> Builder{Ctx};
445 
446   // For adds that safely wrap and use a negative immediate as operand 1, we
447   // create an equivalent instruction using a positive immediate.
448   // That positive immediate can then be zext along with all the other
449   // immediates later.
450   for (auto *I : *SafeWrap) {
451     if (I->getOpcode() != Instruction::Add)
452       continue;
453 
454     LLVM_DEBUG(dbgs() << "IR Promotion: Adjusting " << *I << "\n");
455     assert((isa<ConstantInt>(I->getOperand(1)) &&
456             cast<ConstantInt>(I->getOperand(1))->isNegative()) &&
457            "Wrapping should have a negative immediate as the second operand");
458 
459     auto Const = cast<ConstantInt>(I->getOperand(1));
460     auto *NewConst = ConstantInt::get(Ctx, Const->getValue().abs());
461     Builder.SetInsertPoint(I);
462     Value *NewVal = Builder.CreateSub(I->getOperand(0), NewConst);
463     if (auto *NewInst = dyn_cast<Instruction>(NewVal)) {
464       NewInst->copyIRFlags(I);
465       NewInsts.insert(NewInst);
466     }
467     InstsToRemove.insert(I);
468     I->replaceAllUsesWith(NewVal);
469     LLVM_DEBUG(dbgs() << "IR Promotion: New equivalent: " << *NewVal << "\n");
470   }
471   for (auto *I : NewInsts)
472     Visited->insert(I);
473 }
474 
475 void IRPromoter::ExtendSources() {
476   IRBuilder<> Builder{Ctx};
477 
478   auto InsertZExt = [&](Value *V, Instruction *InsertPt) {
479     assert(V->getType() != ExtTy && "zext already extends to i32");
480     LLVM_DEBUG(dbgs() << "IR Promotion: Inserting ZExt for " << *V << "\n");
481     Builder.SetInsertPoint(InsertPt);
482     if (auto *I = dyn_cast<Instruction>(V))
483       Builder.SetCurrentDebugLocation(I->getDebugLoc());
484 
485     Value *ZExt = Builder.CreateZExt(V, ExtTy);
486     if (auto *I = dyn_cast<Instruction>(ZExt)) {
487       if (isa<Argument>(V))
488         I->moveBefore(InsertPt);
489       else
490         I->moveAfter(InsertPt);
491       NewInsts.insert(I);
492     }
493 
494     ReplaceAllUsersOfWith(V, ZExt);
495   };
496 
497   // Now, insert extending instructions between the sources and their users.
498   LLVM_DEBUG(dbgs() << "IR Promotion: Promoting sources:\n");
499   for (auto V : *Sources) {
500     LLVM_DEBUG(dbgs() << " - " << *V << "\n");
501     if (auto *I = dyn_cast<Instruction>(V))
502       InsertZExt(I, I);
503     else if (auto *Arg = dyn_cast<Argument>(V)) {
504       BasicBlock &BB = Arg->getParent()->front();
505       InsertZExt(Arg, &*BB.getFirstInsertionPt());
506     } else {
507       llvm_unreachable("unhandled source that needs extending");
508     }
509     Promoted.insert(V);
510   }
511 }
512 
513 void IRPromoter::PromoteTree() {
514   LLVM_DEBUG(dbgs() << "IR Promotion: Mutating the tree..\n");
515 
516   IRBuilder<> Builder{Ctx};
517 
518   // Mutate the types of the instructions within the tree. Here we handle
519   // constant operands.
520   for (auto *V : *Visited) {
521     if (Sources->count(V))
522       continue;
523 
524     auto *I = cast<Instruction>(V);
525     if (Sinks->count(I))
526       continue;
527 
528     for (unsigned i = 0, e = I->getNumOperands(); i < e; ++i) {
529       Value *Op = I->getOperand(i);
530       if ((Op->getType() == ExtTy) || !isa<IntegerType>(Op->getType()))
531         continue;
532 
533       if (auto *Const = dyn_cast<ConstantInt>(Op)) {
534         Constant *NewConst = ConstantExpr::getZExt(Const, ExtTy);
535         I->setOperand(i, NewConst);
536       } else if (isa<UndefValue>(Op))
537         I->setOperand(i, UndefValue::get(ExtTy));
538     }
539 
540     if (shouldPromote(I)) {
541       I->mutateType(ExtTy);
542       Promoted.insert(I);
543     }
544   }
545 }
546 
547 void IRPromoter::TruncateSinks() {
548   LLVM_DEBUG(dbgs() << "IR Promotion: Fixing up the sinks:\n");
549 
550   IRBuilder<> Builder{Ctx};
551 
552   auto InsertTrunc = [&](Value *V, Type *TruncTy) -> Instruction* {
553     if (!isa<Instruction>(V) || !isa<IntegerType>(V->getType()))
554       return nullptr;
555 
556     if ((!Promoted.count(V) && !NewInsts.count(V)) || Sources->count(V))
557       return nullptr;
558 
559     LLVM_DEBUG(dbgs() << "IR Promotion: Creating " << *TruncTy << " Trunc for "
560                << *V << "\n");
561     Builder.SetInsertPoint(cast<Instruction>(V));
562     auto *Trunc = dyn_cast<Instruction>(Builder.CreateTrunc(V, TruncTy));
563     if (Trunc)
564       NewInsts.insert(Trunc);
565     return Trunc;
566   };
567 
568   // Fix up any stores or returns that use the results of the promoted
569   // chain.
570   for (auto I : *Sinks) {
571     LLVM_DEBUG(dbgs() << "IR Promotion: For Sink: " << *I << "\n");
572 
573     // Handle calls separately as we need to iterate over arg operands.
574     if (auto *Call = dyn_cast<CallInst>(I)) {
575       for (unsigned i = 0; i < Call->getNumArgOperands(); ++i) {
576         Value *Arg = Call->getArgOperand(i);
577         Type *Ty = TruncTysMap[Call][i];
578         if (Instruction *Trunc = InsertTrunc(Arg, Ty)) {
579           Trunc->moveBefore(Call);
580           Call->setArgOperand(i, Trunc);
581         }
582       }
583       continue;
584     }
585 
586     // Special case switches because we need to truncate the condition.
587     if (auto *Switch = dyn_cast<SwitchInst>(I)) {
588       Type *Ty = TruncTysMap[Switch][0];
589       if (Instruction *Trunc = InsertTrunc(Switch->getCondition(), Ty)) {
590         Trunc->moveBefore(Switch);
591         Switch->setCondition(Trunc);
592       }
593       continue;
594     }
595 
596     // Now handle the others.
597     for (unsigned i = 0; i < I->getNumOperands(); ++i) {
598       Type *Ty = TruncTysMap[I][i];
599       if (Instruction *Trunc = InsertTrunc(I->getOperand(i), Ty)) {
600         Trunc->moveBefore(I);
601         I->setOperand(i, Trunc);
602       }
603     }
604   }
605 }
606 
607 void IRPromoter::Cleanup() {
608   LLVM_DEBUG(dbgs() << "IR Promotion: Cleanup..\n");
609   // Some zexts will now have become redundant, along with their trunc
610   // operands, so remove them
611   for (auto V : *Visited) {
612     if (!isa<ZExtInst>(V))
613       continue;
614 
615     auto ZExt = cast<ZExtInst>(V);
616     if (ZExt->getDestTy() != ExtTy)
617       continue;
618 
619     Value *Src = ZExt->getOperand(0);
620     if (ZExt->getSrcTy() == ZExt->getDestTy()) {
621       LLVM_DEBUG(dbgs() << "IR Promotion: Removing unnecessary cast: " << *ZExt
622                  << "\n");
623       ReplaceAllUsersOfWith(ZExt, Src);
624       continue;
625     }
626 
627     // Unless they produce a value that is narrower than ExtTy, we can
628     // replace the result of the zext with the input of a newly inserted
629     // trunc.
630     if (NewInsts.count(Src) && isa<TruncInst>(Src) &&
631         Src->getType() == OrigTy) {
632       auto *Trunc = cast<TruncInst>(Src);
633       assert(Trunc->getOperand(0)->getType() == ExtTy &&
634              "expected inserted trunc to be operating on i32");
635       ReplaceAllUsersOfWith(ZExt, Trunc->getOperand(0));
636     }
637   }
638 
639   for (auto *I : InstsToRemove) {
640     LLVM_DEBUG(dbgs() << "IR Promotion: Removing " << *I << "\n");
641     I->dropAllReferences();
642     I->eraseFromParent();
643   }
644 
645   InstsToRemove.clear();
646   NewInsts.clear();
647   TruncTysMap.clear();
648   Promoted.clear();
649   SafeToPromote->clear();
650   SafeWrap->clear();
651 }
652 
653 void IRPromoter::ConvertTruncs() {
654   LLVM_DEBUG(dbgs() << "IR Promotion: Converting truncs..\n");
655   IRBuilder<> Builder{Ctx};
656 
657   for (auto *V : *Visited) {
658     if (!isa<TruncInst>(V) || Sources->count(V))
659       continue;
660 
661     auto *Trunc = cast<TruncInst>(V);
662     Builder.SetInsertPoint(Trunc);
663     IntegerType *SrcTy = cast<IntegerType>(Trunc->getOperand(0)->getType());
664     IntegerType *DestTy = cast<IntegerType>(TruncTysMap[Trunc][0]);
665 
666     unsigned NumBits = DestTy->getScalarSizeInBits();
667     ConstantInt *Mask =
668       ConstantInt::get(SrcTy, APInt::getMaxValue(NumBits).getZExtValue());
669     Value *Masked = Builder.CreateAnd(Trunc->getOperand(0), Mask);
670 
671     if (auto *I = dyn_cast<Instruction>(Masked))
672       NewInsts.insert(I);
673 
674     ReplaceAllUsersOfWith(Trunc, Masked);
675   }
676 }
677 
678 void IRPromoter::Mutate(Type *OrigTy, unsigned PromotedWidth,
679                         SetVector<Value*> &Visited,
680                         SmallPtrSetImpl<Value*> &Sources,
681                         SmallPtrSetImpl<Instruction*> &Sinks,
682                         SmallPtrSetImpl<Instruction*> &SafeToPromote,
683                         SmallPtrSetImpl<Instruction*> &SafeWrap) {
684   LLVM_DEBUG(dbgs() << "IR Promotion: Promoting use-def chains to from "
685              << TypePromotion::TypeSize << " to 32-bits\n");
686 
687   assert(isa<IntegerType>(OrigTy) && "expected integer type");
688   this->OrigTy = cast<IntegerType>(OrigTy);
689   ExtTy = IntegerType::get(Ctx, PromotedWidth);
690   assert(OrigTy->getPrimitiveSizeInBits() < ExtTy->getPrimitiveSizeInBits() &&
691          "original type not smaller than extended type");
692 
693   this->Visited = &Visited;
694   this->Sources = &Sources;
695   this->Sinks = &Sinks;
696   this->SafeToPromote = &SafeToPromote;
697   this->SafeWrap = &SafeWrap;
698 
699   // Cache original types of the values that will likely need truncating
700   for (auto *I : Sinks) {
701     if (auto *Call = dyn_cast<CallInst>(I)) {
702       for (unsigned i = 0; i < Call->getNumArgOperands(); ++i) {
703         Value *Arg = Call->getArgOperand(i);
704         TruncTysMap[Call].push_back(Arg->getType());
705       }
706     } else if (auto *Switch = dyn_cast<SwitchInst>(I))
707       TruncTysMap[I].push_back(Switch->getCondition()->getType());
708     else {
709       for (unsigned i = 0; i < I->getNumOperands(); ++i)
710         TruncTysMap[I].push_back(I->getOperand(i)->getType());
711     }
712   }
713   for (auto *V : Visited) {
714     if (!isa<TruncInst>(V) || Sources.count(V))
715       continue;
716     auto *Trunc = cast<TruncInst>(V);
717     TruncTysMap[Trunc].push_back(Trunc->getDestTy());
718   }
719 
720   // Convert adds using negative immediates to equivalent instructions that use
721   // positive constants.
722   PrepareWrappingAdds();
723 
724   // Insert zext instructions between sources and their users.
725   ExtendSources();
726 
727   // Promote visited instructions, mutating their types in place.
728   PromoteTree();
729 
730   // Convert any truncs, that aren't sources, into AND masks.
731   ConvertTruncs();
732 
733   // Insert trunc instructions for use by calls, stores etc...
734   TruncateSinks();
735 
736   // Finally, remove unecessary zexts and truncs, delete old instructions and
737   // clear the data structures.
738   Cleanup();
739 
740   LLVM_DEBUG(dbgs() << "IR Promotion: Mutation complete\n");
741 }
742 
743 /// We accept most instructions, as well as Arguments and ConstantInsts. We
744 /// Disallow casts other than zext and truncs and only allow calls if their
745 /// return value is zeroext. We don't allow opcodes that can introduce sign
746 /// bits.
747 bool TypePromotion::isSupportedValue(Value *V) {
748   if (auto *I = dyn_cast<Instruction>(V)) {
749     switch (I->getOpcode()) {
750     default:
751       return isa<BinaryOperator>(I) && isSupportedType(I) &&
752              !GenerateSignBits(I);
753     case Instruction::GetElementPtr:
754     case Instruction::Store:
755     case Instruction::Br:
756     case Instruction::Switch:
757       return true;
758     case Instruction::PHI:
759     case Instruction::Select:
760     case Instruction::Ret:
761     case Instruction::Load:
762     case Instruction::Trunc:
763     case Instruction::BitCast:
764       return isSupportedType(I);
765     case Instruction::ZExt:
766       return isSupportedType(I->getOperand(0));
767     case Instruction::ICmp:
768       // Now that we allow small types than TypeSize, only allow icmp of
769       // TypeSize because they will require a trunc to be legalised.
770       // TODO: Allow icmp of smaller types, and calculate at the end
771       // whether the transform would be beneficial.
772       if (isa<PointerType>(I->getOperand(0)->getType()))
773         return true;
774       return EqualTypeSize(I->getOperand(0));
775     case Instruction::Call: {
776       // Special cases for calls as we need to check for zeroext
777       // TODO We should accept calls even if they don't have zeroext, as they
778       // can still be sinks.
779       auto *Call = cast<CallInst>(I);
780       return isSupportedType(Call) &&
781              Call->hasRetAttr(Attribute::AttrKind::ZExt);
782     }
783     }
784   } else if (isa<Constant>(V) && !isa<ConstantExpr>(V)) {
785     return isSupportedType(V);
786   } else if (isa<Argument>(V))
787     return isSupportedType(V);
788 
789   return isa<BasicBlock>(V);
790 }
791 
792 /// Check that the type of V would be promoted and that the original type is
793 /// smaller than the targeted promoted type. Check that we're not trying to
794 /// promote something larger than our base 'TypeSize' type.
795 bool TypePromotion::isLegalToPromote(Value *V) {
796 
797   auto *I = dyn_cast<Instruction>(V);
798   if (!I)
799     return true;
800 
801   if (SafeToPromote.count(I))
802    return true;
803 
804   if (isPromotedResultSafe(V) || isSafeWrap(I)) {
805     SafeToPromote.insert(I);
806     return true;
807   }
808   return false;
809 }
810 
811 bool TypePromotion::TryToPromote(Value *V, unsigned PromotedWidth) {
812   OrigTy = V->getType();
813   TypeSize = OrigTy->getPrimitiveSizeInBits();
814   SafeToPromote.clear();
815   SafeWrap.clear();
816 
817   if (!isSupportedValue(V) || !shouldPromote(V) || !isLegalToPromote(V))
818     return false;
819 
820   LLVM_DEBUG(dbgs() << "IR Promotion: TryToPromote: " << *V << ", from "
821              << TypeSize << " bits to " << PromotedWidth << "\n");
822 
823   SetVector<Value*> WorkList;
824   SmallPtrSet<Value*, 8> Sources;
825   SmallPtrSet<Instruction*, 4> Sinks;
826   SetVector<Value*> CurrentVisited;
827   WorkList.insert(V);
828 
829   // Return true if V was added to the worklist as a supported instruction,
830   // if it was already visited, or if we don't need to explore it (e.g.
831   // pointer values and GEPs), and false otherwise.
832   auto AddLegalInst = [&](Value *V) {
833     if (CurrentVisited.count(V))
834       return true;
835 
836     // Ignore GEPs because they don't need promoting and the constant indices
837     // will prevent the transformation.
838     if (isa<GetElementPtrInst>(V))
839       return true;
840 
841     if (!isSupportedValue(V) || (shouldPromote(V) && !isLegalToPromote(V))) {
842       LLVM_DEBUG(dbgs() << "IR Promotion: Can't handle: " << *V << "\n");
843       return false;
844     }
845 
846     WorkList.insert(V);
847     return true;
848   };
849 
850   // Iterate through, and add to, a tree of operands and users in the use-def.
851   while (!WorkList.empty()) {
852     Value *V = WorkList.back();
853     WorkList.pop_back();
854     if (CurrentVisited.count(V))
855       continue;
856 
857     // Ignore non-instructions, other than arguments.
858     if (!isa<Instruction>(V) && !isSource(V))
859       continue;
860 
861     // If we've already visited this value from somewhere, bail now because
862     // the tree has already been explored.
863     // TODO: This could limit the transform, ie if we try to promote something
864     // from an i8 and fail first, before trying an i16.
865     if (AllVisited.count(V))
866       return false;
867 
868     CurrentVisited.insert(V);
869     AllVisited.insert(V);
870 
871     // Calls can be both sources and sinks.
872     if (isSink(V))
873       Sinks.insert(cast<Instruction>(V));
874 
875     if (isSource(V))
876       Sources.insert(V);
877 
878     if (!isSink(V) && !isSource(V)) {
879       if (auto *I = dyn_cast<Instruction>(V)) {
880         // Visit operands of any instruction visited.
881         for (auto &U : I->operands()) {
882           if (!AddLegalInst(U))
883             return false;
884         }
885       }
886     }
887 
888     // Don't visit users of a node which isn't going to be mutated unless its a
889     // source.
890     if (isSource(V) || shouldPromote(V)) {
891       for (Use &U : V->uses()) {
892         if (!AddLegalInst(U.getUser()))
893           return false;
894       }
895     }
896   }
897 
898   LLVM_DEBUG(dbgs() << "IR Promotion: Visited nodes:\n";
899              for (auto *I : CurrentVisited)
900                I->dump();
901              );
902   unsigned ToPromote = 0;
903   for (auto *V : CurrentVisited) {
904     if (Sources.count(V))
905       continue;
906     if (Sinks.count(cast<Instruction>(V)))
907       continue;
908     ++ToPromote;
909   }
910 
911   if (ToPromote < 2)
912     return false;
913 
914   Promoter->Mutate(OrigTy, PromotedWidth, CurrentVisited, Sources, Sinks,
915                    SafeToPromote, SafeWrap);
916   return true;
917 }
918 
919 bool TypePromotion::doInitialization(Module &M) {
920   Promoter = new IRPromoter(&M);
921   return false;
922 }
923 
924 bool TypePromotion::runOnFunction(Function &F) {
925   if (skipFunction(F) || DisablePromotion)
926     return false;
927 
928   LLVM_DEBUG(dbgs() << "IR Promotion: Running on " << F.getName() << "\n");
929 
930   auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
931   if (!TPC)
932     return false;
933 
934   bool MadeChange = false;
935   const DataLayout &DL = F.getParent()->getDataLayout();
936   const TargetMachine &TM = TPC->getTM<TargetMachine>();
937   const TargetSubtargetInfo *SubtargetInfo = TM.getSubtargetImpl(F);
938   const TargetLowering *TLI = SubtargetInfo->getTargetLowering();
939 
940   // Search up from icmps to try to promote their operands.
941   for (BasicBlock &BB : F) {
942     auto &Insts = BB.getInstList();
943     for (auto &I : Insts) {
944       if (AllVisited.count(&I))
945         continue;
946 
947       if (!isa<ICmpInst>(&I))
948         continue;
949 
950       auto *ICmp = cast<ICmpInst>(&I);
951       // Skip signed or pointer compares
952       if (ICmp->isSigned() ||
953           !isa<IntegerType>(ICmp->getOperand(0)->getType()))
954         continue;
955 
956       LLVM_DEBUG(dbgs() << "IR Promotion: Searching from: " << *ICmp << "\n");
957 
958       for (auto &Op : ICmp->operands()) {
959         if (auto *I = dyn_cast<Instruction>(Op)) {
960           EVT SrcVT = TLI->getValueType(DL, I->getType());
961           if (SrcVT.isSimple() && TLI->isTypeLegal(SrcVT.getSimpleVT()))
962             break;
963 
964           if (TLI->getTypeAction(ICmp->getContext(), SrcVT) !=
965               TargetLowering::TypePromoteInteger)
966             break;
967 
968           EVT PromotedVT = TLI->getTypeToTransformTo(ICmp->getContext(), SrcVT);
969           MadeChange |= TryToPromote(I, PromotedVT.getSizeInBits());
970           break;
971         }
972       }
973     }
974     LLVM_DEBUG(if (verifyFunction(F, &dbgs())) {
975                 dbgs() << F;
976                 report_fatal_error("Broken function after type promotion");
977                });
978   }
979   if (MadeChange)
980     LLVM_DEBUG(dbgs() << "After TypePromotion: " << F << "\n");
981 
982   return MadeChange;
983 }
984 
985 bool TypePromotion::doFinalization(Module &M) {
986   delete Promoter;
987   return false;
988 }
989 
990 INITIALIZE_PASS_BEGIN(TypePromotion, DEBUG_TYPE, PASS_NAME, false, false)
991 INITIALIZE_PASS_END(TypePromotion, DEBUG_TYPE, PASS_NAME, false, false)
992 
993 char TypePromotion::ID = 0;
994 unsigned TypePromotion::TypeSize = 0;
995 
996 FunctionPass *llvm::createTypePromotionPass() {
997   return new TypePromotion();
998 }
999