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> DisablePromotion("disable-type-promotion", cl::Hidden,
47                                       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 } // namespace
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 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) && i == 1)
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, ConstantInt::get(ExtTy, 0));
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     // Don't insert a trunc for a zext which can still legally promote.
553     if (auto ZExt = dyn_cast<ZExtInst>(I))
554       if (ZExt->getType()->getScalarSizeInBits() > PromotedWidth)
555         continue;
556 
557     // Now handle the others.
558     for (unsigned i = 0; i < I->getNumOperands(); ++i) {
559       Type *Ty = TruncTysMap[I][i];
560       if (Instruction *Trunc = InsertTrunc(I->getOperand(i), Ty)) {
561         Trunc->moveBefore(I);
562         I->setOperand(i, Trunc);
563       }
564     }
565   }
566 }
567 
568 void IRPromoter::Cleanup() {
569   LLVM_DEBUG(dbgs() << "IR Promotion: Cleanup..\n");
570   // Some zexts will now have become redundant, along with their trunc
571   // operands, so remove them
572   for (auto V : Visited) {
573     if (!isa<ZExtInst>(V))
574       continue;
575 
576     auto ZExt = cast<ZExtInst>(V);
577     if (ZExt->getDestTy() != ExtTy)
578       continue;
579 
580     Value *Src = ZExt->getOperand(0);
581     if (ZExt->getSrcTy() == ZExt->getDestTy()) {
582       LLVM_DEBUG(dbgs() << "IR Promotion: Removing unnecessary cast: " << *ZExt
583                         << "\n");
584       ReplaceAllUsersOfWith(ZExt, Src);
585       continue;
586     }
587 
588     // Unless they produce a value that is narrower than ExtTy, we can
589     // replace the result of the zext with the input of a newly inserted
590     // trunc.
591     if (NewInsts.count(Src) && isa<TruncInst>(Src) &&
592         Src->getType() == OrigTy) {
593       auto *Trunc = cast<TruncInst>(Src);
594       assert(Trunc->getOperand(0)->getType() == ExtTy &&
595              "expected inserted trunc to be operating on i32");
596       ReplaceAllUsersOfWith(ZExt, Trunc->getOperand(0));
597     }
598   }
599 
600   for (auto *I : InstsToRemove) {
601     LLVM_DEBUG(dbgs() << "IR Promotion: Removing " << *I << "\n");
602     I->dropAllReferences();
603     I->eraseFromParent();
604   }
605 }
606 
607 void IRPromoter::ConvertTruncs() {
608   LLVM_DEBUG(dbgs() << "IR Promotion: Converting truncs..\n");
609   IRBuilder<> Builder{Ctx};
610 
611   for (auto *V : Visited) {
612     if (!isa<TruncInst>(V) || Sources.count(V))
613       continue;
614 
615     auto *Trunc = cast<TruncInst>(V);
616     Builder.SetInsertPoint(Trunc);
617     IntegerType *SrcTy = cast<IntegerType>(Trunc->getOperand(0)->getType());
618     IntegerType *DestTy = cast<IntegerType>(TruncTysMap[Trunc][0]);
619 
620     unsigned NumBits = DestTy->getScalarSizeInBits();
621     ConstantInt *Mask =
622         ConstantInt::get(SrcTy, APInt::getMaxValue(NumBits).getZExtValue());
623     Value *Masked = Builder.CreateAnd(Trunc->getOperand(0), Mask);
624 
625     if (auto *I = dyn_cast<Instruction>(Masked))
626       NewInsts.insert(I);
627 
628     ReplaceAllUsersOfWith(Trunc, Masked);
629   }
630 }
631 
632 void IRPromoter::Mutate() {
633   LLVM_DEBUG(dbgs() << "IR Promotion: Promoting use-def chains from "
634                     << OrigTy->getBitWidth() << " to " << PromotedWidth
635                     << "-bits\n");
636 
637   // Cache original types of the values that will likely need truncating
638   for (auto *I : Sinks) {
639     if (auto *Call = dyn_cast<CallInst>(I)) {
640       for (Value *Arg : Call->args())
641         TruncTysMap[Call].push_back(Arg->getType());
642     } else if (auto *Switch = dyn_cast<SwitchInst>(I))
643       TruncTysMap[I].push_back(Switch->getCondition()->getType());
644     else {
645       for (unsigned i = 0; i < I->getNumOperands(); ++i)
646         TruncTysMap[I].push_back(I->getOperand(i)->getType());
647     }
648   }
649   for (auto *V : Visited) {
650     if (!isa<TruncInst>(V) || Sources.count(V))
651       continue;
652     auto *Trunc = cast<TruncInst>(V);
653     TruncTysMap[Trunc].push_back(Trunc->getDestTy());
654   }
655 
656   // Insert zext instructions between sources and their users.
657   ExtendSources();
658 
659   // Promote visited instructions, mutating their types in place.
660   PromoteTree();
661 
662   // Convert any truncs, that aren't sources, into AND masks.
663   ConvertTruncs();
664 
665   // Insert trunc instructions for use by calls, stores etc...
666   TruncateSinks();
667 
668   // Finally, remove unecessary zexts and truncs, delete old instructions and
669   // clear the data structures.
670   Cleanup();
671 
672   LLVM_DEBUG(dbgs() << "IR Promotion: Mutation complete\n");
673 }
674 
675 /// We disallow booleans to make life easier when dealing with icmps but allow
676 /// any other integer that fits in a scalar register. Void types are accepted
677 /// so we can handle switches.
678 bool TypePromotion::isSupportedType(Value *V) {
679   Type *Ty = V->getType();
680 
681   // Allow voids and pointers, these won't be promoted.
682   if (Ty->isVoidTy() || Ty->isPointerTy())
683     return true;
684 
685   if (!isa<IntegerType>(Ty) || cast<IntegerType>(Ty)->getBitWidth() == 1 ||
686       cast<IntegerType>(Ty)->getBitWidth() > RegisterBitWidth)
687     return false;
688 
689   return LessOrEqualTypeSize(V);
690 }
691 
692 /// We accept most instructions, as well as Arguments and ConstantInsts. We
693 /// Disallow casts other than zext and truncs and only allow calls if their
694 /// return value is zeroext. We don't allow opcodes that can introduce sign
695 /// bits.
696 bool TypePromotion::isSupportedValue(Value *V) {
697   if (auto *I = dyn_cast<Instruction>(V)) {
698     switch (I->getOpcode()) {
699     default:
700       return isa<BinaryOperator>(I) && isSupportedType(I) &&
701              !GenerateSignBits(I);
702     case Instruction::GetElementPtr:
703     case Instruction::Store:
704     case Instruction::Br:
705     case Instruction::Switch:
706       return true;
707     case Instruction::PHI:
708     case Instruction::Select:
709     case Instruction::Ret:
710     case Instruction::Load:
711     case Instruction::Trunc:
712     case Instruction::BitCast:
713       return isSupportedType(I);
714     case Instruction::ZExt:
715       return isSupportedType(I->getOperand(0));
716     case Instruction::ICmp:
717       // Now that we allow small types than TypeSize, only allow icmp of
718       // TypeSize because they will require a trunc to be legalised.
719       // TODO: Allow icmp of smaller types, and calculate at the end
720       // whether the transform would be beneficial.
721       if (isa<PointerType>(I->getOperand(0)->getType()))
722         return true;
723       return EqualTypeSize(I->getOperand(0));
724     case Instruction::Call: {
725       // Special cases for calls as we need to check for zeroext
726       // TODO We should accept calls even if they don't have zeroext, as they
727       // can still be sinks.
728       auto *Call = cast<CallInst>(I);
729       return isSupportedType(Call) &&
730              Call->hasRetAttr(Attribute::AttrKind::ZExt);
731     }
732     }
733   } else if (isa<Constant>(V) && !isa<ConstantExpr>(V)) {
734     return isSupportedType(V);
735   } else if (isa<Argument>(V))
736     return isSupportedType(V);
737 
738   return isa<BasicBlock>(V);
739 }
740 
741 /// Check that the type of V would be promoted and that the original type is
742 /// smaller than the targeted promoted type. Check that we're not trying to
743 /// promote something larger than our base 'TypeSize' type.
744 bool TypePromotion::isLegalToPromote(Value *V) {
745   auto *I = dyn_cast<Instruction>(V);
746   if (!I)
747     return true;
748 
749   if (SafeToPromote.count(I))
750     return true;
751 
752   if (isPromotedResultSafe(I) || isSafeWrap(I)) {
753     SafeToPromote.insert(I);
754     return true;
755   }
756   return false;
757 }
758 
759 bool TypePromotion::TryToPromote(Value *V, unsigned PromotedWidth) {
760   Type *OrigTy = V->getType();
761   TypeSize = OrigTy->getPrimitiveSizeInBits().getFixedSize();
762   SafeToPromote.clear();
763   SafeWrap.clear();
764 
765   if (!isSupportedValue(V) || !shouldPromote(V) || !isLegalToPromote(V))
766     return false;
767 
768   LLVM_DEBUG(dbgs() << "IR Promotion: TryToPromote: " << *V << ", from "
769                     << TypeSize << " bits to " << PromotedWidth << "\n");
770 
771   SetVector<Value *> WorkList;
772   SetVector<Value *> Sources;
773   SetVector<Instruction *> Sinks;
774   SetVector<Value *> CurrentVisited;
775   WorkList.insert(V);
776 
777   // Return true if V was added to the worklist as a supported instruction,
778   // if it was already visited, or if we don't need to explore it (e.g.
779   // pointer values and GEPs), and false otherwise.
780   auto AddLegalInst = [&](Value *V) {
781     if (CurrentVisited.count(V))
782       return true;
783 
784     // Ignore GEPs because they don't need promoting and the constant indices
785     // will prevent the transformation.
786     if (isa<GetElementPtrInst>(V))
787       return true;
788 
789     if (!isSupportedValue(V) || (shouldPromote(V) && !isLegalToPromote(V))) {
790       LLVM_DEBUG(dbgs() << "IR Promotion: Can't handle: " << *V << "\n");
791       return false;
792     }
793 
794     WorkList.insert(V);
795     return true;
796   };
797 
798   // Iterate through, and add to, a tree of operands and users in the use-def.
799   while (!WorkList.empty()) {
800     Value *V = WorkList.pop_back_val();
801     if (CurrentVisited.count(V))
802       continue;
803 
804     // Ignore non-instructions, other than arguments.
805     if (!isa<Instruction>(V) && !isSource(V))
806       continue;
807 
808     // If we've already visited this value from somewhere, bail now because
809     // the tree has already been explored.
810     // TODO: This could limit the transform, ie if we try to promote something
811     // from an i8 and fail first, before trying an i16.
812     if (AllVisited.count(V))
813       return false;
814 
815     CurrentVisited.insert(V);
816     AllVisited.insert(V);
817 
818     // Calls can be both sources and sinks.
819     if (isSink(V))
820       Sinks.insert(cast<Instruction>(V));
821 
822     if (isSource(V))
823       Sources.insert(V);
824 
825     if (!isSink(V) && !isSource(V)) {
826       if (auto *I = dyn_cast<Instruction>(V)) {
827         // Visit operands of any instruction visited.
828         for (auto &U : I->operands()) {
829           if (!AddLegalInst(U))
830             return false;
831         }
832       }
833     }
834 
835     // Don't visit users of a node which isn't going to be mutated unless its a
836     // source.
837     if (isSource(V) || shouldPromote(V)) {
838       for (Use &U : V->uses()) {
839         if (!AddLegalInst(U.getUser()))
840           return false;
841       }
842     }
843   }
844 
845   LLVM_DEBUG({
846     dbgs() << "IR Promotion: Visited nodes:\n";
847     for (auto *I : CurrentVisited)
848       I->dump();
849   });
850 
851   unsigned ToPromote = 0;
852   unsigned NonFreeArgs = 0;
853   SmallPtrSet<BasicBlock *, 4> Blocks;
854   for (auto *V : CurrentVisited) {
855     if (auto *I = dyn_cast<Instruction>(V))
856       Blocks.insert(I->getParent());
857 
858     if (Sources.count(V)) {
859       if (auto *Arg = dyn_cast<Argument>(V))
860         if (!Arg->hasZExtAttr() && !Arg->hasSExtAttr())
861           ++NonFreeArgs;
862       continue;
863     }
864 
865     if (Sinks.count(cast<Instruction>(V)))
866       continue;
867     ++ToPromote;
868   }
869 
870   // DAG optimizations should be able to handle these cases better, especially
871   // for function arguments.
872   if (ToPromote < 2 || (Blocks.size() == 1 && (NonFreeArgs > SafeWrap.size())))
873     return false;
874 
875   IRPromoter Promoter(*Ctx, cast<IntegerType>(OrigTy), PromotedWidth,
876                       CurrentVisited, Sources, Sinks, SafeWrap);
877   Promoter.Mutate();
878   return true;
879 }
880 
881 bool TypePromotion::runOnFunction(Function &F) {
882   if (skipFunction(F) || DisablePromotion)
883     return false;
884 
885   LLVM_DEBUG(dbgs() << "IR Promotion: Running on " << F.getName() << "\n");
886 
887   auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
888   if (!TPC)
889     return false;
890 
891   AllVisited.clear();
892   SafeToPromote.clear();
893   SafeWrap.clear();
894   bool MadeChange = false;
895   const DataLayout &DL = F.getParent()->getDataLayout();
896   const TargetMachine &TM = TPC->getTM<TargetMachine>();
897   const TargetSubtargetInfo *SubtargetInfo = TM.getSubtargetImpl(F);
898   const TargetLowering *TLI = SubtargetInfo->getTargetLowering();
899   const TargetTransformInfo &TII =
900       getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
901   RegisterBitWidth =
902       TII.getRegisterBitWidth(TargetTransformInfo::RGK_Scalar).getFixedSize();
903   Ctx = &F.getParent()->getContext();
904 
905   // Search up from icmps to try to promote their operands.
906   for (BasicBlock &BB : F) {
907     for (Instruction &I : BB) {
908       if (AllVisited.count(&I))
909         continue;
910 
911       if (!isa<ICmpInst>(&I))
912         continue;
913 
914       auto *ICmp = cast<ICmpInst>(&I);
915       // Skip signed or pointer compares
916       if (ICmp->isSigned() || !isa<IntegerType>(ICmp->getOperand(0)->getType()))
917         continue;
918 
919       LLVM_DEBUG(dbgs() << "IR Promotion: Searching from: " << *ICmp << "\n");
920 
921       for (auto &Op : ICmp->operands()) {
922         if (auto *I = dyn_cast<Instruction>(Op)) {
923           EVT SrcVT = TLI->getValueType(DL, I->getType());
924           if (SrcVT.isSimple() && TLI->isTypeLegal(SrcVT.getSimpleVT()))
925             break;
926 
927           if (TLI->getTypeAction(*Ctx, SrcVT) !=
928               TargetLowering::TypePromoteInteger)
929             break;
930           EVT PromotedVT = TLI->getTypeToTransformTo(*Ctx, SrcVT);
931           if (RegisterBitWidth < PromotedVT.getFixedSizeInBits()) {
932             LLVM_DEBUG(dbgs() << "IR Promotion: Couldn't find target register "
933                               << "for promoted type\n");
934             break;
935           }
936 
937           MadeChange |= TryToPromote(I, PromotedVT.getFixedSizeInBits());
938           break;
939         }
940       }
941     }
942   }
943 
944   AllVisited.clear();
945   SafeToPromote.clear();
946   SafeWrap.clear();
947 
948   return MadeChange;
949 }
950 
951 INITIALIZE_PASS_BEGIN(TypePromotion, DEBUG_TYPE, PASS_NAME, false, false)
952 INITIALIZE_PASS_END(TypePromotion, DEBUG_TYPE, PASS_NAME, false, false)
953 
954 char TypePromotion::ID = 0;
955 
956 FunctionPass *llvm::createTypePromotionPass() { return new TypePromotion(); }
957