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