1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions.  This pass does not modify the CFG.  This pass is where
12 // algebraic simplification happens.
13 //
14 // This pass combines things like:
15 //    %Y = add i32 %X, 1
16 //    %Z = add i32 %Y, 1
17 // into:
18 //    %Z = add i32 %X, 2
19 //
20 // This is a simple worklist driven algorithm.
21 //
22 // This pass guarantees that the following canonicalizations are performed on
23 // the program:
24 //    1. If a binary operator has a constant operand, it is moved to the RHS
25 //    2. Bitwise operators with constant operands are always grouped so that
26 //       shifts are performed first, then or's, then and's, then xor's.
27 //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All cmp instructions on boolean values are replaced with logical ops
29 //    5. add X, X is represented as (X*2) => (X << 1)
30 //    6. Multiplies with a power-of-two constant argument are transformed into
31 //       shifts.
32 //   ... etc.
33 //
34 //===----------------------------------------------------------------------===//
35 
36 #include "InstCombineInternal.h"
37 #include "llvm-c/Initialization.h"
38 #include "llvm/ADT/SmallPtrSet.h"
39 #include "llvm/ADT/Statistic.h"
40 #include "llvm/ADT/StringSwitch.h"
41 #include "llvm/Analysis/AliasAnalysis.h"
42 #include "llvm/Analysis/AssumptionCache.h"
43 #include "llvm/Analysis/BasicAliasAnalysis.h"
44 #include "llvm/Analysis/CFG.h"
45 #include "llvm/Analysis/ConstantFolding.h"
46 #include "llvm/Analysis/EHPersonalities.h"
47 #include "llvm/Analysis/GlobalsModRef.h"
48 #include "llvm/Analysis/InstructionSimplify.h"
49 #include "llvm/Analysis/LoopInfo.h"
50 #include "llvm/Analysis/MemoryBuiltins.h"
51 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
52 #include "llvm/Analysis/TargetLibraryInfo.h"
53 #include "llvm/Analysis/ValueTracking.h"
54 #include "llvm/IR/CFG.h"
55 #include "llvm/IR/DIBuilder.h"
56 #include "llvm/IR/DataLayout.h"
57 #include "llvm/IR/Dominators.h"
58 #include "llvm/IR/GetElementPtrTypeIterator.h"
59 #include "llvm/IR/IntrinsicInst.h"
60 #include "llvm/IR/PatternMatch.h"
61 #include "llvm/IR/ValueHandle.h"
62 #include "llvm/Support/CommandLine.h"
63 #include "llvm/Support/Debug.h"
64 #include "llvm/Support/DebugCounter.h"
65 #include "llvm/Support/KnownBits.h"
66 #include "llvm/Support/raw_ostream.h"
67 #include "llvm/Transforms/InstCombine/InstCombine.h"
68 #include "llvm/Transforms/Scalar.h"
69 #include "llvm/Transforms/Utils/Local.h"
70 #include <algorithm>
71 #include <climits>
72 using namespace llvm;
73 using namespace llvm::PatternMatch;
74 
75 #define DEBUG_TYPE "instcombine"
76 
77 STATISTIC(NumCombined , "Number of insts combined");
78 STATISTIC(NumConstProp, "Number of constant folds");
79 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
80 STATISTIC(NumSunkInst , "Number of instructions sunk");
81 STATISTIC(NumExpand,    "Number of expansions");
82 STATISTIC(NumFactor   , "Number of factorizations");
83 STATISTIC(NumReassoc  , "Number of reassociations");
84 DEBUG_COUNTER(VisitCounter, "instcombine-visit",
85               "Controls which instructions are visited");
86 
87 static cl::opt<bool>
88 EnableExpensiveCombines("expensive-combines",
89                         cl::desc("Enable expensive instruction combines"));
90 
91 static cl::opt<unsigned>
92 MaxArraySize("instcombine-maxarray-size", cl::init(1024),
93              cl::desc("Maximum array size considered when doing a combine"));
94 
95 // FIXME: Remove this flag when it is no longer necessary to convert
96 // llvm.dbg.declare to avoid inaccurate debug info. Setting this to false
97 // increases variable availability at the cost of accuracy. Variables that
98 // cannot be promoted by mem2reg or SROA will be described as living in memory
99 // for their entire lifetime. However, passes like DSE and instcombine can
100 // delete stores to the alloca, leading to misleading and inaccurate debug
101 // information. This flag can be removed when those passes are fixed.
102 static cl::opt<unsigned> ShouldLowerDbgDeclare("instcombine-lower-dbg-declare",
103                                                cl::Hidden, cl::init(true));
104 
105 Value *InstCombiner::EmitGEPOffset(User *GEP) {
106   return llvm::EmitGEPOffset(&Builder, DL, GEP);
107 }
108 
109 /// Return true if it is desirable to convert an integer computation from a
110 /// given bit width to a new bit width.
111 /// We don't want to convert from a legal to an illegal type or from a smaller
112 /// to a larger illegal type. A width of '1' is always treated as a legal type
113 /// because i1 is a fundamental type in IR, and there are many specialized
114 /// optimizations for i1 types.
115 bool InstCombiner::shouldChangeType(unsigned FromWidth,
116                                     unsigned ToWidth) const {
117   bool FromLegal = FromWidth == 1 || DL.isLegalInteger(FromWidth);
118   bool ToLegal = ToWidth == 1 || DL.isLegalInteger(ToWidth);
119 
120   // If this is a legal integer from type, and the result would be an illegal
121   // type, don't do the transformation.
122   if (FromLegal && !ToLegal)
123     return false;
124 
125   // Otherwise, if both are illegal, do not increase the size of the result. We
126   // do allow things like i160 -> i64, but not i64 -> i160.
127   if (!FromLegal && !ToLegal && ToWidth > FromWidth)
128     return false;
129 
130   return true;
131 }
132 
133 /// Return true if it is desirable to convert a computation from 'From' to 'To'.
134 /// We don't want to convert from a legal to an illegal type or from a smaller
135 /// to a larger illegal type. i1 is always treated as a legal type because it is
136 /// a fundamental type in IR, and there are many specialized optimizations for
137 /// i1 types.
138 bool InstCombiner::shouldChangeType(Type *From, Type *To) const {
139   assert(From->isIntegerTy() && To->isIntegerTy());
140 
141   unsigned FromWidth = From->getPrimitiveSizeInBits();
142   unsigned ToWidth = To->getPrimitiveSizeInBits();
143   return shouldChangeType(FromWidth, ToWidth);
144 }
145 
146 // Return true, if No Signed Wrap should be maintained for I.
147 // The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
148 // where both B and C should be ConstantInts, results in a constant that does
149 // not overflow. This function only handles the Add and Sub opcodes. For
150 // all other opcodes, the function conservatively returns false.
151 static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
152   OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
153   if (!OBO || !OBO->hasNoSignedWrap())
154     return false;
155 
156   // We reason about Add and Sub Only.
157   Instruction::BinaryOps Opcode = I.getOpcode();
158   if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
159     return false;
160 
161   const APInt *BVal, *CVal;
162   if (!match(B, m_APInt(BVal)) || !match(C, m_APInt(CVal)))
163     return false;
164 
165   bool Overflow = false;
166   if (Opcode == Instruction::Add)
167     (void)BVal->sadd_ov(*CVal, Overflow);
168   else
169     (void)BVal->ssub_ov(*CVal, Overflow);
170 
171   return !Overflow;
172 }
173 
174 /// Conservatively clears subclassOptionalData after a reassociation or
175 /// commutation. We preserve fast-math flags when applicable as they can be
176 /// preserved.
177 static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {
178   FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
179   if (!FPMO) {
180     I.clearSubclassOptionalData();
181     return;
182   }
183 
184   FastMathFlags FMF = I.getFastMathFlags();
185   I.clearSubclassOptionalData();
186   I.setFastMathFlags(FMF);
187 }
188 
189 /// Combine constant operands of associative operations either before or after a
190 /// cast to eliminate one of the associative operations:
191 /// (op (cast (op X, C2)), C1) --> (cast (op X, op (C1, C2)))
192 /// (op (cast (op X, C2)), C1) --> (op (cast X), op (C1, C2))
193 static bool simplifyAssocCastAssoc(BinaryOperator *BinOp1) {
194   auto *Cast = dyn_cast<CastInst>(BinOp1->getOperand(0));
195   if (!Cast || !Cast->hasOneUse())
196     return false;
197 
198   // TODO: Enhance logic for other casts and remove this check.
199   auto CastOpcode = Cast->getOpcode();
200   if (CastOpcode != Instruction::ZExt)
201     return false;
202 
203   // TODO: Enhance logic for other BinOps and remove this check.
204   if (!BinOp1->isBitwiseLogicOp())
205     return false;
206 
207   auto AssocOpcode = BinOp1->getOpcode();
208   auto *BinOp2 = dyn_cast<BinaryOperator>(Cast->getOperand(0));
209   if (!BinOp2 || !BinOp2->hasOneUse() || BinOp2->getOpcode() != AssocOpcode)
210     return false;
211 
212   Constant *C1, *C2;
213   if (!match(BinOp1->getOperand(1), m_Constant(C1)) ||
214       !match(BinOp2->getOperand(1), m_Constant(C2)))
215     return false;
216 
217   // TODO: This assumes a zext cast.
218   // Eg, if it was a trunc, we'd cast C1 to the source type because casting C2
219   // to the destination type might lose bits.
220 
221   // Fold the constants together in the destination type:
222   // (op (cast (op X, C2)), C1) --> (op (cast X), FoldedC)
223   Type *DestTy = C1->getType();
224   Constant *CastC2 = ConstantExpr::getCast(CastOpcode, C2, DestTy);
225   Constant *FoldedC = ConstantExpr::get(AssocOpcode, C1, CastC2);
226   Cast->setOperand(0, BinOp2->getOperand(0));
227   BinOp1->setOperand(1, FoldedC);
228   return true;
229 }
230 
231 /// This performs a few simplifications for operators that are associative or
232 /// commutative:
233 ///
234 ///  Commutative operators:
235 ///
236 ///  1. Order operands such that they are listed from right (least complex) to
237 ///     left (most complex).  This puts constants before unary operators before
238 ///     binary operators.
239 ///
240 ///  Associative operators:
241 ///
242 ///  2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
243 ///  3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
244 ///
245 ///  Associative and commutative operators:
246 ///
247 ///  4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
248 ///  5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
249 ///  6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
250 ///     if C1 and C2 are constants.
251 bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
252   Instruction::BinaryOps Opcode = I.getOpcode();
253   bool Changed = false;
254 
255   do {
256     // Order operands such that they are listed from right (least complex) to
257     // left (most complex).  This puts constants before unary operators before
258     // binary operators.
259     if (I.isCommutative() && getComplexity(I.getOperand(0)) <
260         getComplexity(I.getOperand(1)))
261       Changed = !I.swapOperands();
262 
263     BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
264     BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
265 
266     if (I.isAssociative()) {
267       // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
268       if (Op0 && Op0->getOpcode() == Opcode) {
269         Value *A = Op0->getOperand(0);
270         Value *B = Op0->getOperand(1);
271         Value *C = I.getOperand(1);
272 
273         // Does "B op C" simplify?
274         if (Value *V = SimplifyBinOp(Opcode, B, C, SQ.getWithInstruction(&I))) {
275           // It simplifies to V.  Form "A op V".
276           I.setOperand(0, A);
277           I.setOperand(1, V);
278           // Conservatively clear the optional flags, since they may not be
279           // preserved by the reassociation.
280           if (MaintainNoSignedWrap(I, B, C) &&
281               (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
282             // Note: this is only valid because SimplifyBinOp doesn't look at
283             // the operands to Op0.
284             I.clearSubclassOptionalData();
285             I.setHasNoSignedWrap(true);
286           } else {
287             ClearSubclassDataAfterReassociation(I);
288           }
289 
290           Changed = true;
291           ++NumReassoc;
292           continue;
293         }
294       }
295 
296       // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
297       if (Op1 && Op1->getOpcode() == Opcode) {
298         Value *A = I.getOperand(0);
299         Value *B = Op1->getOperand(0);
300         Value *C = Op1->getOperand(1);
301 
302         // Does "A op B" simplify?
303         if (Value *V = SimplifyBinOp(Opcode, A, B, SQ.getWithInstruction(&I))) {
304           // It simplifies to V.  Form "V op C".
305           I.setOperand(0, V);
306           I.setOperand(1, C);
307           // Conservatively clear the optional flags, since they may not be
308           // preserved by the reassociation.
309           ClearSubclassDataAfterReassociation(I);
310           Changed = true;
311           ++NumReassoc;
312           continue;
313         }
314       }
315     }
316 
317     if (I.isAssociative() && I.isCommutative()) {
318       if (simplifyAssocCastAssoc(&I)) {
319         Changed = true;
320         ++NumReassoc;
321         continue;
322       }
323 
324       // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
325       if (Op0 && Op0->getOpcode() == Opcode) {
326         Value *A = Op0->getOperand(0);
327         Value *B = Op0->getOperand(1);
328         Value *C = I.getOperand(1);
329 
330         // Does "C op A" simplify?
331         if (Value *V = SimplifyBinOp(Opcode, C, A, SQ.getWithInstruction(&I))) {
332           // It simplifies to V.  Form "V op B".
333           I.setOperand(0, V);
334           I.setOperand(1, B);
335           // Conservatively clear the optional flags, since they may not be
336           // preserved by the reassociation.
337           ClearSubclassDataAfterReassociation(I);
338           Changed = true;
339           ++NumReassoc;
340           continue;
341         }
342       }
343 
344       // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
345       if (Op1 && Op1->getOpcode() == Opcode) {
346         Value *A = I.getOperand(0);
347         Value *B = Op1->getOperand(0);
348         Value *C = Op1->getOperand(1);
349 
350         // Does "C op A" simplify?
351         if (Value *V = SimplifyBinOp(Opcode, C, A, SQ.getWithInstruction(&I))) {
352           // It simplifies to V.  Form "B op V".
353           I.setOperand(0, B);
354           I.setOperand(1, V);
355           // Conservatively clear the optional flags, since they may not be
356           // preserved by the reassociation.
357           ClearSubclassDataAfterReassociation(I);
358           Changed = true;
359           ++NumReassoc;
360           continue;
361         }
362       }
363 
364       // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
365       // if C1 and C2 are constants.
366       if (Op0 && Op1 &&
367           Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
368           isa<Constant>(Op0->getOperand(1)) &&
369           isa<Constant>(Op1->getOperand(1)) &&
370           Op0->hasOneUse() && Op1->hasOneUse()) {
371         Value *A = Op0->getOperand(0);
372         Constant *C1 = cast<Constant>(Op0->getOperand(1));
373         Value *B = Op1->getOperand(0);
374         Constant *C2 = cast<Constant>(Op1->getOperand(1));
375 
376         Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
377         BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
378         if (isa<FPMathOperator>(New)) {
379           FastMathFlags Flags = I.getFastMathFlags();
380           Flags &= Op0->getFastMathFlags();
381           Flags &= Op1->getFastMathFlags();
382           New->setFastMathFlags(Flags);
383         }
384         InsertNewInstWith(New, I);
385         New->takeName(Op1);
386         I.setOperand(0, New);
387         I.setOperand(1, Folded);
388         // Conservatively clear the optional flags, since they may not be
389         // preserved by the reassociation.
390         ClearSubclassDataAfterReassociation(I);
391 
392         Changed = true;
393         continue;
394       }
395     }
396 
397     // No further simplifications.
398     return Changed;
399   } while (1);
400 }
401 
402 /// Return whether "X LOp (Y ROp Z)" is always equal to
403 /// "(X LOp Y) ROp (X LOp Z)".
404 static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
405                                      Instruction::BinaryOps ROp) {
406   switch (LOp) {
407   default:
408     return false;
409 
410   case Instruction::And:
411     // And distributes over Or and Xor.
412     switch (ROp) {
413     default:
414       return false;
415     case Instruction::Or:
416     case Instruction::Xor:
417       return true;
418     }
419 
420   case Instruction::Mul:
421     // Multiplication distributes over addition and subtraction.
422     switch (ROp) {
423     default:
424       return false;
425     case Instruction::Add:
426     case Instruction::Sub:
427       return true;
428     }
429 
430   case Instruction::Or:
431     // Or distributes over And.
432     switch (ROp) {
433     default:
434       return false;
435     case Instruction::And:
436       return true;
437     }
438   }
439 }
440 
441 /// Return whether "(X LOp Y) ROp Z" is always equal to
442 /// "(X ROp Z) LOp (Y ROp Z)".
443 static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
444                                      Instruction::BinaryOps ROp) {
445   if (Instruction::isCommutative(ROp))
446     return LeftDistributesOverRight(ROp, LOp);
447 
448   switch (LOp) {
449   default:
450     return false;
451   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
452   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
453   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
454   case Instruction::And:
455   case Instruction::Or:
456   case Instruction::Xor:
457     switch (ROp) {
458     default:
459       return false;
460     case Instruction::Shl:
461     case Instruction::LShr:
462     case Instruction::AShr:
463       return true;
464     }
465   }
466   // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
467   // but this requires knowing that the addition does not overflow and other
468   // such subtleties.
469   return false;
470 }
471 
472 /// This function returns identity value for given opcode, which can be used to
473 /// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
474 static Value *getIdentityValue(Instruction::BinaryOps Opcode, Value *V) {
475   if (isa<Constant>(V))
476     return nullptr;
477 
478   return ConstantExpr::getBinOpIdentity(Opcode, V->getType());
479 }
480 
481 /// This function factors binary ops which can be combined using distributive
482 /// laws. This function tries to transform 'Op' based TopLevelOpcode to enable
483 /// factorization e.g for ADD(SHL(X , 2), MUL(X, 5)), When this function called
484 /// with TopLevelOpcode == Instruction::Add and Op = SHL(X, 2), transforms
485 /// SHL(X, 2) to MUL(X, 4) i.e. returns Instruction::Mul with LHS set to 'X' and
486 /// RHS to 4.
487 static Instruction::BinaryOps
488 getBinOpsForFactorization(Instruction::BinaryOps TopLevelOpcode,
489                           BinaryOperator *Op, Value *&LHS, Value *&RHS) {
490   assert(Op && "Expected a binary operator");
491 
492   LHS = Op->getOperand(0);
493   RHS = Op->getOperand(1);
494 
495   switch (TopLevelOpcode) {
496   default:
497     return Op->getOpcode();
498 
499   case Instruction::Add:
500   case Instruction::Sub:
501     if (Op->getOpcode() == Instruction::Shl) {
502       if (Constant *CST = dyn_cast<Constant>(Op->getOperand(1))) {
503         // The multiplier is really 1 << CST.
504         RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), CST);
505         return Instruction::Mul;
506       }
507     }
508     return Op->getOpcode();
509   }
510 
511   // TODO: We can add other conversions e.g. shr => div etc.
512 }
513 
514 /// This tries to simplify binary operations by factorizing out common terms
515 /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
516 Value *InstCombiner::tryFactorization(BinaryOperator &I,
517                                       Instruction::BinaryOps InnerOpcode,
518                                       Value *A, Value *B, Value *C, Value *D) {
519   assert(A && B && C && D && "All values must be provided");
520 
521   Value *V = nullptr;
522   Value *SimplifiedInst = nullptr;
523   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
524   Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
525 
526   // Does "X op' Y" always equal "Y op' X"?
527   bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
528 
529   // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
530   if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
531     // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
532     // commutative case, "(A op' B) op (C op' A)"?
533     if (A == C || (InnerCommutative && A == D)) {
534       if (A != C)
535         std::swap(C, D);
536       // Consider forming "A op' (B op D)".
537       // If "B op D" simplifies then it can be formed with no cost.
538       V = SimplifyBinOp(TopLevelOpcode, B, D, SQ.getWithInstruction(&I));
539       // If "B op D" doesn't simplify then only go on if both of the existing
540       // operations "A op' B" and "C op' D" will be zapped as no longer used.
541       if (!V && LHS->hasOneUse() && RHS->hasOneUse())
542         V = Builder.CreateBinOp(TopLevelOpcode, B, D, RHS->getName());
543       if (V) {
544         SimplifiedInst = Builder.CreateBinOp(InnerOpcode, A, V);
545       }
546     }
547 
548   // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
549   if (!SimplifiedInst && RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
550     // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
551     // commutative case, "(A op' B) op (B op' D)"?
552     if (B == D || (InnerCommutative && B == C)) {
553       if (B != D)
554         std::swap(C, D);
555       // Consider forming "(A op C) op' B".
556       // If "A op C" simplifies then it can be formed with no cost.
557       V = SimplifyBinOp(TopLevelOpcode, A, C, SQ.getWithInstruction(&I));
558 
559       // If "A op C" doesn't simplify then only go on if both of the existing
560       // operations "A op' B" and "C op' D" will be zapped as no longer used.
561       if (!V && LHS->hasOneUse() && RHS->hasOneUse())
562         V = Builder.CreateBinOp(TopLevelOpcode, A, C, LHS->getName());
563       if (V) {
564         SimplifiedInst = Builder.CreateBinOp(InnerOpcode, V, B);
565       }
566     }
567 
568   if (SimplifiedInst) {
569     ++NumFactor;
570     SimplifiedInst->takeName(&I);
571 
572     // Check if we can add NSW flag to SimplifiedInst. If so, set NSW flag.
573     // TODO: Check for NUW.
574     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) {
575       if (isa<OverflowingBinaryOperator>(SimplifiedInst)) {
576         bool HasNSW = false;
577         if (isa<OverflowingBinaryOperator>(&I))
578           HasNSW = I.hasNoSignedWrap();
579 
580         if (auto *LOBO = dyn_cast<OverflowingBinaryOperator>(LHS))
581           HasNSW &= LOBO->hasNoSignedWrap();
582 
583         if (auto *ROBO = dyn_cast<OverflowingBinaryOperator>(RHS))
584           HasNSW &= ROBO->hasNoSignedWrap();
585 
586         // We can propagate 'nsw' if we know that
587         //  %Y = mul nsw i16 %X, C
588         //  %Z = add nsw i16 %Y, %X
589         // =>
590         //  %Z = mul nsw i16 %X, C+1
591         //
592         // iff C+1 isn't INT_MIN
593         const APInt *CInt;
594         if (TopLevelOpcode == Instruction::Add &&
595             InnerOpcode == Instruction::Mul)
596           if (match(V, m_APInt(CInt)) && !CInt->isMinSignedValue())
597             BO->setHasNoSignedWrap(HasNSW);
598       }
599     }
600   }
601   return SimplifiedInst;
602 }
603 
604 /// This tries to simplify binary operations which some other binary operation
605 /// distributes over either by factorizing out common terms
606 /// (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this results in
607 /// simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is a win).
608 /// Returns the simplified value, or null if it didn't simplify.
609 Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
610   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
611   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
612   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
613   Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
614 
615   {
616     // Factorization.
617     Value *A, *B, *C, *D;
618     Instruction::BinaryOps LHSOpcode, RHSOpcode;
619     if (Op0)
620       LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B);
621     if (Op1)
622       RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D);
623 
624     // The instruction has the form "(A op' B) op (C op' D)".  Try to factorize
625     // a common term.
626     if (Op0 && Op1 && LHSOpcode == RHSOpcode)
627       if (Value *V = tryFactorization(I, LHSOpcode, A, B, C, D))
628         return V;
629 
630     // The instruction has the form "(A op' B) op (C)".  Try to factorize common
631     // term.
632     if (Op0)
633       if (Value *Ident = getIdentityValue(LHSOpcode, RHS))
634         if (Value *V =
635                 tryFactorization(I, LHSOpcode, A, B, RHS, Ident))
636           return V;
637 
638     // The instruction has the form "(B) op (C op' D)".  Try to factorize common
639     // term.
640     if (Op1)
641       if (Value *Ident = getIdentityValue(RHSOpcode, LHS))
642         if (Value *V =
643                 tryFactorization(I, RHSOpcode, LHS, Ident, C, D))
644           return V;
645   }
646 
647   // Expansion.
648   if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
649     // The instruction has the form "(A op' B) op C".  See if expanding it out
650     // to "(A op C) op' (B op C)" results in simplifications.
651     Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
652     Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
653 
654     Value *L = SimplifyBinOp(TopLevelOpcode, A, C, SQ.getWithInstruction(&I));
655     Value *R = SimplifyBinOp(TopLevelOpcode, B, C, SQ.getWithInstruction(&I));
656 
657     // Do "A op C" and "B op C" both simplify?
658     if (L && R) {
659       // They do! Return "L op' R".
660       ++NumExpand;
661       C = Builder.CreateBinOp(InnerOpcode, L, R);
662       C->takeName(&I);
663       return C;
664     }
665 
666     // Does "A op C" simplify to the identity value for the inner opcode?
667     if (L && L == ConstantExpr::getBinOpIdentity(InnerOpcode, L->getType())) {
668       // They do! Return "B op C".
669       ++NumExpand;
670       C = Builder.CreateBinOp(TopLevelOpcode, B, C);
671       C->takeName(&I);
672       return C;
673     }
674 
675     // Does "B op C" simplify to the identity value for the inner opcode?
676     if (R && R == ConstantExpr::getBinOpIdentity(InnerOpcode, R->getType())) {
677       // They do! Return "A op C".
678       ++NumExpand;
679       C = Builder.CreateBinOp(TopLevelOpcode, A, C);
680       C->takeName(&I);
681       return C;
682     }
683   }
684 
685   if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
686     // The instruction has the form "A op (B op' C)".  See if expanding it out
687     // to "(A op B) op' (A op C)" results in simplifications.
688     Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
689     Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
690 
691     Value *L = SimplifyBinOp(TopLevelOpcode, A, B, SQ.getWithInstruction(&I));
692     Value *R = SimplifyBinOp(TopLevelOpcode, A, C, SQ.getWithInstruction(&I));
693 
694     // Do "A op B" and "A op C" both simplify?
695     if (L && R) {
696       // They do! Return "L op' R".
697       ++NumExpand;
698       A = Builder.CreateBinOp(InnerOpcode, L, R);
699       A->takeName(&I);
700       return A;
701     }
702 
703     // Does "A op B" simplify to the identity value for the inner opcode?
704     if (L && L == ConstantExpr::getBinOpIdentity(InnerOpcode, L->getType())) {
705       // They do! Return "A op C".
706       ++NumExpand;
707       A = Builder.CreateBinOp(TopLevelOpcode, A, C);
708       A->takeName(&I);
709       return A;
710     }
711 
712     // Does "A op C" simplify to the identity value for the inner opcode?
713     if (R && R == ConstantExpr::getBinOpIdentity(InnerOpcode, R->getType())) {
714       // They do! Return "A op B".
715       ++NumExpand;
716       A = Builder.CreateBinOp(TopLevelOpcode, A, B);
717       A->takeName(&I);
718       return A;
719     }
720   }
721 
722   return SimplifySelectsFeedingBinaryOp(I, LHS, RHS);
723 }
724 
725 Value *InstCombiner::SimplifySelectsFeedingBinaryOp(BinaryOperator &I,
726                                                     Value *LHS, Value *RHS) {
727   Instruction::BinaryOps Opcode = I.getOpcode();
728   // (op (select (a, b, c)), (select (a, d, e))) -> (select (a, (op b, d), (op
729   // c, e)))
730   Value *A, *B, *C, *D, *E;
731   Value *SI = nullptr;
732   if (match(LHS, m_Select(m_Value(A), m_Value(B), m_Value(C))) &&
733       match(RHS, m_Select(m_Specific(A), m_Value(D), m_Value(E)))) {
734     bool SelectsHaveOneUse = LHS->hasOneUse() && RHS->hasOneUse();
735     BuilderTy::FastMathFlagGuard Guard(Builder);
736     if (isa<FPMathOperator>(&I))
737       Builder.setFastMathFlags(I.getFastMathFlags());
738 
739     Value *V1 = SimplifyBinOp(Opcode, C, E, SQ.getWithInstruction(&I));
740     Value *V2 = SimplifyBinOp(Opcode, B, D, SQ.getWithInstruction(&I));
741     if (V1 && V2)
742       SI = Builder.CreateSelect(A, V2, V1);
743     else if (V2 && SelectsHaveOneUse)
744       SI = Builder.CreateSelect(A, V2, Builder.CreateBinOp(Opcode, C, E));
745     else if (V1 && SelectsHaveOneUse)
746       SI = Builder.CreateSelect(A, Builder.CreateBinOp(Opcode, B, D), V1);
747 
748     if (SI)
749       SI->takeName(&I);
750   }
751 
752   return SI;
753 }
754 
755 /// Given a 'sub' instruction, return the RHS of the instruction if the LHS is a
756 /// constant zero (which is the 'negate' form).
757 Value *InstCombiner::dyn_castNegVal(Value *V) const {
758   if (BinaryOperator::isNeg(V))
759     return BinaryOperator::getNegArgument(V);
760 
761   // Constants can be considered to be negated values if they can be folded.
762   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
763     return ConstantExpr::getNeg(C);
764 
765   if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
766     if (C->getType()->getElementType()->isIntegerTy())
767       return ConstantExpr::getNeg(C);
768 
769   if (ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
770     for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
771       Constant *Elt = CV->getAggregateElement(i);
772       if (!Elt)
773         return nullptr;
774 
775       if (isa<UndefValue>(Elt))
776         continue;
777 
778       if (!isa<ConstantInt>(Elt))
779         return nullptr;
780     }
781     return ConstantExpr::getNeg(CV);
782   }
783 
784   return nullptr;
785 }
786 
787 /// Given a 'fsub' instruction, return the RHS of the instruction if the LHS is
788 /// a constant negative zero (which is the 'negate' form).
789 Value *InstCombiner::dyn_castFNegVal(Value *V, bool IgnoreZeroSign) const {
790   if (BinaryOperator::isFNeg(V, IgnoreZeroSign))
791     return BinaryOperator::getFNegArgument(V);
792 
793   // Constants can be considered to be negated values if they can be folded.
794   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
795     return ConstantExpr::getFNeg(C);
796 
797   if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
798     if (C->getType()->getElementType()->isFloatingPointTy())
799       return ConstantExpr::getFNeg(C);
800 
801   return nullptr;
802 }
803 
804 static Value *foldOperationIntoSelectOperand(Instruction &I, Value *SO,
805                                              InstCombiner::BuilderTy &Builder) {
806   if (auto *Cast = dyn_cast<CastInst>(&I))
807     return Builder.CreateCast(Cast->getOpcode(), SO, I.getType());
808 
809   assert(I.isBinaryOp() && "Unexpected opcode for select folding");
810 
811   // Figure out if the constant is the left or the right argument.
812   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
813   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
814 
815   if (auto *SOC = dyn_cast<Constant>(SO)) {
816     if (ConstIsRHS)
817       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
818     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
819   }
820 
821   Value *Op0 = SO, *Op1 = ConstOperand;
822   if (!ConstIsRHS)
823     std::swap(Op0, Op1);
824 
825   auto *BO = cast<BinaryOperator>(&I);
826   Value *RI = Builder.CreateBinOp(BO->getOpcode(), Op0, Op1,
827                                   SO->getName() + ".op");
828   auto *FPInst = dyn_cast<Instruction>(RI);
829   if (FPInst && isa<FPMathOperator>(FPInst))
830     FPInst->copyFastMathFlags(BO);
831   return RI;
832 }
833 
834 Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
835   // Don't modify shared select instructions.
836   if (!SI->hasOneUse())
837     return nullptr;
838 
839   Value *TV = SI->getTrueValue();
840   Value *FV = SI->getFalseValue();
841   if (!(isa<Constant>(TV) || isa<Constant>(FV)))
842     return nullptr;
843 
844   // Bool selects with constant operands can be folded to logical ops.
845   if (SI->getType()->isIntOrIntVectorTy(1))
846     return nullptr;
847 
848   // If it's a bitcast involving vectors, make sure it has the same number of
849   // elements on both sides.
850   if (auto *BC = dyn_cast<BitCastInst>(&Op)) {
851     VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
852     VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
853 
854     // Verify that either both or neither are vectors.
855     if ((SrcTy == nullptr) != (DestTy == nullptr))
856       return nullptr;
857 
858     // If vectors, verify that they have the same number of elements.
859     if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
860       return nullptr;
861   }
862 
863   // Test if a CmpInst instruction is used exclusively by a select as
864   // part of a minimum or maximum operation. If so, refrain from doing
865   // any other folding. This helps out other analyses which understand
866   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
867   // and CodeGen. And in this case, at least one of the comparison
868   // operands has at least one user besides the compare (the select),
869   // which would often largely negate the benefit of folding anyway.
870   if (auto *CI = dyn_cast<CmpInst>(SI->getCondition())) {
871     if (CI->hasOneUse()) {
872       Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
873       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
874           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
875         return nullptr;
876     }
877   }
878 
879   Value *NewTV = foldOperationIntoSelectOperand(Op, TV, Builder);
880   Value *NewFV = foldOperationIntoSelectOperand(Op, FV, Builder);
881   return SelectInst::Create(SI->getCondition(), NewTV, NewFV, "", nullptr, SI);
882 }
883 
884 static Value *foldOperationIntoPhiValue(BinaryOperator *I, Value *InV,
885                                         InstCombiner::BuilderTy &Builder) {
886   bool ConstIsRHS = isa<Constant>(I->getOperand(1));
887   Constant *C = cast<Constant>(I->getOperand(ConstIsRHS));
888 
889   if (auto *InC = dyn_cast<Constant>(InV)) {
890     if (ConstIsRHS)
891       return ConstantExpr::get(I->getOpcode(), InC, C);
892     return ConstantExpr::get(I->getOpcode(), C, InC);
893   }
894 
895   Value *Op0 = InV, *Op1 = C;
896   if (!ConstIsRHS)
897     std::swap(Op0, Op1);
898 
899   Value *RI = Builder.CreateBinOp(I->getOpcode(), Op0, Op1, "phitmp");
900   auto *FPInst = dyn_cast<Instruction>(RI);
901   if (FPInst && isa<FPMathOperator>(FPInst))
902     FPInst->copyFastMathFlags(I);
903   return RI;
904 }
905 
906 Instruction *InstCombiner::foldOpIntoPhi(Instruction &I, PHINode *PN) {
907   unsigned NumPHIValues = PN->getNumIncomingValues();
908   if (NumPHIValues == 0)
909     return nullptr;
910 
911   // We normally only transform phis with a single use.  However, if a PHI has
912   // multiple uses and they are all the same operation, we can fold *all* of the
913   // uses into the PHI.
914   if (!PN->hasOneUse()) {
915     // Walk the use list for the instruction, comparing them to I.
916     for (User *U : PN->users()) {
917       Instruction *UI = cast<Instruction>(U);
918       if (UI != &I && !I.isIdenticalTo(UI))
919         return nullptr;
920     }
921     // Otherwise, we can replace *all* users with the new PHI we form.
922   }
923 
924   // Check to see if all of the operands of the PHI are simple constants
925   // (constantint/constantfp/undef).  If there is one non-constant value,
926   // remember the BB it is in.  If there is more than one or if *it* is a PHI,
927   // bail out.  We don't do arbitrary constant expressions here because moving
928   // their computation can be expensive without a cost model.
929   BasicBlock *NonConstBB = nullptr;
930   for (unsigned i = 0; i != NumPHIValues; ++i) {
931     Value *InVal = PN->getIncomingValue(i);
932     if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
933       continue;
934 
935     if (isa<PHINode>(InVal)) return nullptr;  // Itself a phi.
936     if (NonConstBB) return nullptr;  // More than one non-const value.
937 
938     NonConstBB = PN->getIncomingBlock(i);
939 
940     // If the InVal is an invoke at the end of the pred block, then we can't
941     // insert a computation after it without breaking the edge.
942     if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
943       if (II->getParent() == NonConstBB)
944         return nullptr;
945 
946     // If the incoming non-constant value is in I's block, we will remove one
947     // instruction, but insert another equivalent one, leading to infinite
948     // instcombine.
949     if (isPotentiallyReachable(I.getParent(), NonConstBB, &DT, LI))
950       return nullptr;
951   }
952 
953   // If there is exactly one non-constant value, we can insert a copy of the
954   // operation in that block.  However, if this is a critical edge, we would be
955   // inserting the computation on some other paths (e.g. inside a loop).  Only
956   // do this if the pred block is unconditionally branching into the phi block.
957   if (NonConstBB != nullptr) {
958     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
959     if (!BI || !BI->isUnconditional()) return nullptr;
960   }
961 
962   // Okay, we can do the transformation: create the new PHI node.
963   PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
964   InsertNewInstBefore(NewPN, *PN);
965   NewPN->takeName(PN);
966 
967   // If we are going to have to insert a new computation, do so right before the
968   // predecessor's terminator.
969   if (NonConstBB)
970     Builder.SetInsertPoint(NonConstBB->getTerminator());
971 
972   // Next, add all of the operands to the PHI.
973   if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
974     // We only currently try to fold the condition of a select when it is a phi,
975     // not the true/false values.
976     Value *TrueV = SI->getTrueValue();
977     Value *FalseV = SI->getFalseValue();
978     BasicBlock *PhiTransBB = PN->getParent();
979     for (unsigned i = 0; i != NumPHIValues; ++i) {
980       BasicBlock *ThisBB = PN->getIncomingBlock(i);
981       Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
982       Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
983       Value *InV = nullptr;
984       // Beware of ConstantExpr:  it may eventually evaluate to getNullValue,
985       // even if currently isNullValue gives false.
986       Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i));
987       // For vector constants, we cannot use isNullValue to fold into
988       // FalseVInPred versus TrueVInPred. When we have individual nonzero
989       // elements in the vector, we will incorrectly fold InC to
990       // `TrueVInPred`.
991       if (InC && !isa<ConstantExpr>(InC) && isa<ConstantInt>(InC))
992         InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
993       else {
994         // Generate the select in the same block as PN's current incoming block.
995         // Note: ThisBB need not be the NonConstBB because vector constants
996         // which are constants by definition are handled here.
997         // FIXME: This can lead to an increase in IR generation because we might
998         // generate selects for vector constant phi operand, that could not be
999         // folded to TrueVInPred or FalseVInPred as done for ConstantInt. For
1000         // non-vector phis, this transformation was always profitable because
1001         // the select would be generated exactly once in the NonConstBB.
1002         Builder.SetInsertPoint(ThisBB->getTerminator());
1003         InV = Builder.CreateSelect(PN->getIncomingValue(i), TrueVInPred,
1004                                    FalseVInPred, "phitmp");
1005       }
1006       NewPN->addIncoming(InV, ThisBB);
1007     }
1008   } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
1009     Constant *C = cast<Constant>(I.getOperand(1));
1010     for (unsigned i = 0; i != NumPHIValues; ++i) {
1011       Value *InV = nullptr;
1012       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
1013         InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1014       else if (isa<ICmpInst>(CI))
1015         InV = Builder.CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
1016                                  C, "phitmp");
1017       else
1018         InV = Builder.CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
1019                                  C, "phitmp");
1020       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1021     }
1022   } else if (auto *BO = dyn_cast<BinaryOperator>(&I)) {
1023     for (unsigned i = 0; i != NumPHIValues; ++i) {
1024       Value *InV = foldOperationIntoPhiValue(BO, PN->getIncomingValue(i),
1025                                              Builder);
1026       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1027     }
1028   } else {
1029     CastInst *CI = cast<CastInst>(&I);
1030     Type *RetTy = CI->getType();
1031     for (unsigned i = 0; i != NumPHIValues; ++i) {
1032       Value *InV;
1033       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
1034         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1035       else
1036         InV = Builder.CreateCast(CI->getOpcode(), PN->getIncomingValue(i),
1037                                  I.getType(), "phitmp");
1038       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1039     }
1040   }
1041 
1042   for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
1043     Instruction *User = cast<Instruction>(*UI++);
1044     if (User == &I) continue;
1045     replaceInstUsesWith(*User, NewPN);
1046     eraseInstFromFunction(*User);
1047   }
1048   return replaceInstUsesWith(I, NewPN);
1049 }
1050 
1051 Instruction *InstCombiner::foldOpWithConstantIntoOperand(BinaryOperator &I) {
1052   assert(isa<Constant>(I.getOperand(1)) && "Unexpected operand type");
1053 
1054   if (auto *Sel = dyn_cast<SelectInst>(I.getOperand(0))) {
1055     if (Instruction *NewSel = FoldOpIntoSelect(I, Sel))
1056       return NewSel;
1057   } else if (auto *PN = dyn_cast<PHINode>(I.getOperand(0))) {
1058     if (Instruction *NewPhi = foldOpIntoPhi(I, PN))
1059       return NewPhi;
1060   }
1061   return nullptr;
1062 }
1063 
1064 /// Given a pointer type and a constant offset, determine whether or not there
1065 /// is a sequence of GEP indices into the pointed type that will land us at the
1066 /// specified offset. If so, fill them into NewIndices and return the resultant
1067 /// element type, otherwise return null.
1068 Type *InstCombiner::FindElementAtOffset(PointerType *PtrTy, int64_t Offset,
1069                                         SmallVectorImpl<Value *> &NewIndices) {
1070   Type *Ty = PtrTy->getElementType();
1071   if (!Ty->isSized())
1072     return nullptr;
1073 
1074   // Start with the index over the outer type.  Note that the type size
1075   // might be zero (even if the offset isn't zero) if the indexed type
1076   // is something like [0 x {int, int}]
1077   Type *IntPtrTy = DL.getIntPtrType(PtrTy);
1078   int64_t FirstIdx = 0;
1079   if (int64_t TySize = DL.getTypeAllocSize(Ty)) {
1080     FirstIdx = Offset/TySize;
1081     Offset -= FirstIdx*TySize;
1082 
1083     // Handle hosts where % returns negative instead of values [0..TySize).
1084     if (Offset < 0) {
1085       --FirstIdx;
1086       Offset += TySize;
1087       assert(Offset >= 0);
1088     }
1089     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
1090   }
1091 
1092   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
1093 
1094   // Index into the types.  If we fail, set OrigBase to null.
1095   while (Offset) {
1096     // Indexing into tail padding between struct/array elements.
1097     if (uint64_t(Offset * 8) >= DL.getTypeSizeInBits(Ty))
1098       return nullptr;
1099 
1100     if (StructType *STy = dyn_cast<StructType>(Ty)) {
1101       const StructLayout *SL = DL.getStructLayout(STy);
1102       assert(Offset < (int64_t)SL->getSizeInBytes() &&
1103              "Offset must stay within the indexed type");
1104 
1105       unsigned Elt = SL->getElementContainingOffset(Offset);
1106       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
1107                                             Elt));
1108 
1109       Offset -= SL->getElementOffset(Elt);
1110       Ty = STy->getElementType(Elt);
1111     } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
1112       uint64_t EltSize = DL.getTypeAllocSize(AT->getElementType());
1113       assert(EltSize && "Cannot index into a zero-sized array");
1114       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
1115       Offset %= EltSize;
1116       Ty = AT->getElementType();
1117     } else {
1118       // Otherwise, we can't index into the middle of this atomic type, bail.
1119       return nullptr;
1120     }
1121   }
1122 
1123   return Ty;
1124 }
1125 
1126 static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
1127   // If this GEP has only 0 indices, it is the same pointer as
1128   // Src. If Src is not a trivial GEP too, don't combine
1129   // the indices.
1130   if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
1131       !Src.hasOneUse())
1132     return false;
1133   return true;
1134 }
1135 
1136 /// Return a value X such that Val = X * Scale, or null if none.
1137 /// If the multiplication is known not to overflow, then NoSignedWrap is set.
1138 Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
1139   assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
1140   assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
1141          Scale.getBitWidth() && "Scale not compatible with value!");
1142 
1143   // If Val is zero or Scale is one then Val = Val * Scale.
1144   if (match(Val, m_Zero()) || Scale == 1) {
1145     NoSignedWrap = true;
1146     return Val;
1147   }
1148 
1149   // If Scale is zero then it does not divide Val.
1150   if (Scale.isMinValue())
1151     return nullptr;
1152 
1153   // Look through chains of multiplications, searching for a constant that is
1154   // divisible by Scale.  For example, descaling X*(Y*(Z*4)) by a factor of 4
1155   // will find the constant factor 4 and produce X*(Y*Z).  Descaling X*(Y*8) by
1156   // a factor of 4 will produce X*(Y*2).  The principle of operation is to bore
1157   // down from Val:
1158   //
1159   //     Val = M1 * X          ||   Analysis starts here and works down
1160   //      M1 = M2 * Y          ||   Doesn't descend into terms with more
1161   //      M2 =  Z * 4          \/   than one use
1162   //
1163   // Then to modify a term at the bottom:
1164   //
1165   //     Val = M1 * X
1166   //      M1 =  Z * Y          ||   Replaced M2 with Z
1167   //
1168   // Then to work back up correcting nsw flags.
1169 
1170   // Op - the term we are currently analyzing.  Starts at Val then drills down.
1171   // Replaced with its descaled value before exiting from the drill down loop.
1172   Value *Op = Val;
1173 
1174   // Parent - initially null, but after drilling down notes where Op came from.
1175   // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
1176   // 0'th operand of Val.
1177   std::pair<Instruction*, unsigned> Parent;
1178 
1179   // Set if the transform requires a descaling at deeper levels that doesn't
1180   // overflow.
1181   bool RequireNoSignedWrap = false;
1182 
1183   // Log base 2 of the scale. Negative if not a power of 2.
1184   int32_t logScale = Scale.exactLogBase2();
1185 
1186   for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
1187 
1188     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1189       // If Op is a constant divisible by Scale then descale to the quotient.
1190       APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
1191       APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
1192       if (!Remainder.isMinValue())
1193         // Not divisible by Scale.
1194         return nullptr;
1195       // Replace with the quotient in the parent.
1196       Op = ConstantInt::get(CI->getType(), Quotient);
1197       NoSignedWrap = true;
1198       break;
1199     }
1200 
1201     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
1202 
1203       if (BO->getOpcode() == Instruction::Mul) {
1204         // Multiplication.
1205         NoSignedWrap = BO->hasNoSignedWrap();
1206         if (RequireNoSignedWrap && !NoSignedWrap)
1207           return nullptr;
1208 
1209         // There are three cases for multiplication: multiplication by exactly
1210         // the scale, multiplication by a constant different to the scale, and
1211         // multiplication by something else.
1212         Value *LHS = BO->getOperand(0);
1213         Value *RHS = BO->getOperand(1);
1214 
1215         if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1216           // Multiplication by a constant.
1217           if (CI->getValue() == Scale) {
1218             // Multiplication by exactly the scale, replace the multiplication
1219             // by its left-hand side in the parent.
1220             Op = LHS;
1221             break;
1222           }
1223 
1224           // Otherwise drill down into the constant.
1225           if (!Op->hasOneUse())
1226             return nullptr;
1227 
1228           Parent = std::make_pair(BO, 1);
1229           continue;
1230         }
1231 
1232         // Multiplication by something else. Drill down into the left-hand side
1233         // since that's where the reassociate pass puts the good stuff.
1234         if (!Op->hasOneUse())
1235           return nullptr;
1236 
1237         Parent = std::make_pair(BO, 0);
1238         continue;
1239       }
1240 
1241       if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
1242           isa<ConstantInt>(BO->getOperand(1))) {
1243         // Multiplication by a power of 2.
1244         NoSignedWrap = BO->hasNoSignedWrap();
1245         if (RequireNoSignedWrap && !NoSignedWrap)
1246           return nullptr;
1247 
1248         Value *LHS = BO->getOperand(0);
1249         int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
1250           getLimitedValue(Scale.getBitWidth());
1251         // Op = LHS << Amt.
1252 
1253         if (Amt == logScale) {
1254           // Multiplication by exactly the scale, replace the multiplication
1255           // by its left-hand side in the parent.
1256           Op = LHS;
1257           break;
1258         }
1259         if (Amt < logScale || !Op->hasOneUse())
1260           return nullptr;
1261 
1262         // Multiplication by more than the scale.  Reduce the multiplying amount
1263         // by the scale in the parent.
1264         Parent = std::make_pair(BO, 1);
1265         Op = ConstantInt::get(BO->getType(), Amt - logScale);
1266         break;
1267       }
1268     }
1269 
1270     if (!Op->hasOneUse())
1271       return nullptr;
1272 
1273     if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
1274       if (Cast->getOpcode() == Instruction::SExt) {
1275         // Op is sign-extended from a smaller type, descale in the smaller type.
1276         unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1277         APInt SmallScale = Scale.trunc(SmallSize);
1278         // Suppose Op = sext X, and we descale X as Y * SmallScale.  We want to
1279         // descale Op as (sext Y) * Scale.  In order to have
1280         //   sext (Y * SmallScale) = (sext Y) * Scale
1281         // some conditions need to hold however: SmallScale must sign-extend to
1282         // Scale and the multiplication Y * SmallScale should not overflow.
1283         if (SmallScale.sext(Scale.getBitWidth()) != Scale)
1284           // SmallScale does not sign-extend to Scale.
1285           return nullptr;
1286         assert(SmallScale.exactLogBase2() == logScale);
1287         // Require that Y * SmallScale must not overflow.
1288         RequireNoSignedWrap = true;
1289 
1290         // Drill down through the cast.
1291         Parent = std::make_pair(Cast, 0);
1292         Scale = SmallScale;
1293         continue;
1294       }
1295 
1296       if (Cast->getOpcode() == Instruction::Trunc) {
1297         // Op is truncated from a larger type, descale in the larger type.
1298         // Suppose Op = trunc X, and we descale X as Y * sext Scale.  Then
1299         //   trunc (Y * sext Scale) = (trunc Y) * Scale
1300         // always holds.  However (trunc Y) * Scale may overflow even if
1301         // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
1302         // from this point up in the expression (see later).
1303         if (RequireNoSignedWrap)
1304           return nullptr;
1305 
1306         // Drill down through the cast.
1307         unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1308         Parent = std::make_pair(Cast, 0);
1309         Scale = Scale.sext(LargeSize);
1310         if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1311           logScale = -1;
1312         assert(Scale.exactLogBase2() == logScale);
1313         continue;
1314       }
1315     }
1316 
1317     // Unsupported expression, bail out.
1318     return nullptr;
1319   }
1320 
1321   // If Op is zero then Val = Op * Scale.
1322   if (match(Op, m_Zero())) {
1323     NoSignedWrap = true;
1324     return Op;
1325   }
1326 
1327   // We know that we can successfully descale, so from here on we can safely
1328   // modify the IR.  Op holds the descaled version of the deepest term in the
1329   // expression.  NoSignedWrap is 'true' if multiplying Op by Scale is known
1330   // not to overflow.
1331 
1332   if (!Parent.first)
1333     // The expression only had one term.
1334     return Op;
1335 
1336   // Rewrite the parent using the descaled version of its operand.
1337   assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
1338   assert(Op != Parent.first->getOperand(Parent.second) &&
1339          "Descaling was a no-op?");
1340   Parent.first->setOperand(Parent.second, Op);
1341   Worklist.Add(Parent.first);
1342 
1343   // Now work back up the expression correcting nsw flags.  The logic is based
1344   // on the following observation: if X * Y is known not to overflow as a signed
1345   // multiplication, and Y is replaced by a value Z with smaller absolute value,
1346   // then X * Z will not overflow as a signed multiplication either.  As we work
1347   // our way up, having NoSignedWrap 'true' means that the descaled value at the
1348   // current level has strictly smaller absolute value than the original.
1349   Instruction *Ancestor = Parent.first;
1350   do {
1351     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
1352       // If the multiplication wasn't nsw then we can't say anything about the
1353       // value of the descaled multiplication, and we have to clear nsw flags
1354       // from this point on up.
1355       bool OpNoSignedWrap = BO->hasNoSignedWrap();
1356       NoSignedWrap &= OpNoSignedWrap;
1357       if (NoSignedWrap != OpNoSignedWrap) {
1358         BO->setHasNoSignedWrap(NoSignedWrap);
1359         Worklist.Add(Ancestor);
1360       }
1361     } else if (Ancestor->getOpcode() == Instruction::Trunc) {
1362       // The fact that the descaled input to the trunc has smaller absolute
1363       // value than the original input doesn't tell us anything useful about
1364       // the absolute values of the truncations.
1365       NoSignedWrap = false;
1366     }
1367     assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
1368            "Failed to keep proper track of nsw flags while drilling down?");
1369 
1370     if (Ancestor == Val)
1371       // Got to the top, all done!
1372       return Val;
1373 
1374     // Move up one level in the expression.
1375     assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
1376     Ancestor = Ancestor->user_back();
1377   } while (1);
1378 }
1379 
1380 /// \brief Creates node of binary operation with the same attributes as the
1381 /// specified one but with other operands.
1382 static Value *CreateBinOpAsGiven(BinaryOperator &Inst, Value *LHS, Value *RHS,
1383                                  InstCombiner::BuilderTy &B) {
1384   Value *BO = B.CreateBinOp(Inst.getOpcode(), LHS, RHS);
1385   // If LHS and RHS are constant, BO won't be a binary operator.
1386   if (BinaryOperator *NewBO = dyn_cast<BinaryOperator>(BO))
1387     NewBO->copyIRFlags(&Inst);
1388   return BO;
1389 }
1390 
1391 /// \brief Makes transformation of binary operation specific for vector types.
1392 /// \param Inst Binary operator to transform.
1393 /// \return Pointer to node that must replace the original binary operator, or
1394 ///         null pointer if no transformation was made.
1395 Value *InstCombiner::SimplifyVectorOp(BinaryOperator &Inst) {
1396   if (!Inst.getType()->isVectorTy()) return nullptr;
1397 
1398   // It may not be safe to reorder shuffles and things like div, urem, etc.
1399   // because we may trap when executing those ops on unknown vector elements.
1400   // See PR20059.
1401   if (!isSafeToSpeculativelyExecute(&Inst))
1402     return nullptr;
1403 
1404   unsigned VWidth = cast<VectorType>(Inst.getType())->getNumElements();
1405   Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
1406   assert(cast<VectorType>(LHS->getType())->getNumElements() == VWidth);
1407   assert(cast<VectorType>(RHS->getType())->getNumElements() == VWidth);
1408 
1409   // If both arguments of the binary operation are shuffles that use the same
1410   // mask and shuffle within a single vector, move the shuffle after the binop:
1411   //   Op(shuffle(v1, m), shuffle(v2, m)) -> shuffle(Op(v1, v2), m)
1412   auto *LShuf = dyn_cast<ShuffleVectorInst>(LHS);
1413   auto *RShuf = dyn_cast<ShuffleVectorInst>(RHS);
1414   if (LShuf && RShuf && LShuf->getMask() == RShuf->getMask() &&
1415       isa<UndefValue>(LShuf->getOperand(1)) &&
1416       isa<UndefValue>(RShuf->getOperand(1)) &&
1417       LShuf->getOperand(0)->getType() == RShuf->getOperand(0)->getType()) {
1418     Value *NewBO = CreateBinOpAsGiven(Inst, LShuf->getOperand(0),
1419                                       RShuf->getOperand(0), Builder);
1420     return Builder.CreateShuffleVector(
1421         NewBO, UndefValue::get(NewBO->getType()), LShuf->getMask());
1422   }
1423 
1424   // If one argument is a shuffle within one vector, the other is a constant,
1425   // try moving the shuffle after the binary operation.
1426   ShuffleVectorInst *Shuffle = nullptr;
1427   Constant *C1 = nullptr;
1428   if (isa<ShuffleVectorInst>(LHS)) Shuffle = cast<ShuffleVectorInst>(LHS);
1429   if (isa<ShuffleVectorInst>(RHS)) Shuffle = cast<ShuffleVectorInst>(RHS);
1430   if (isa<Constant>(LHS)) C1 = cast<Constant>(LHS);
1431   if (isa<Constant>(RHS)) C1 = cast<Constant>(RHS);
1432   if (Shuffle && C1 &&
1433       (isa<ConstantVector>(C1) || isa<ConstantDataVector>(C1)) &&
1434       isa<UndefValue>(Shuffle->getOperand(1)) &&
1435       Shuffle->getType() == Shuffle->getOperand(0)->getType()) {
1436     SmallVector<int, 16> ShMask = Shuffle->getShuffleMask();
1437     // Find constant C2 that has property:
1438     //   shuffle(C2, ShMask) = C1
1439     // If such constant does not exist (example: ShMask=<0,0> and C1=<1,2>)
1440     // reorder is not possible.
1441     SmallVector<Constant*, 16> C2M(VWidth,
1442                                UndefValue::get(C1->getType()->getScalarType()));
1443     bool MayChange = true;
1444     for (unsigned I = 0; I < VWidth; ++I) {
1445       if (ShMask[I] >= 0) {
1446         assert(ShMask[I] < (int)VWidth);
1447         if (!isa<UndefValue>(C2M[ShMask[I]])) {
1448           MayChange = false;
1449           break;
1450         }
1451         C2M[ShMask[I]] = C1->getAggregateElement(I);
1452       }
1453     }
1454     if (MayChange) {
1455       Constant *C2 = ConstantVector::get(C2M);
1456       Value *NewLHS = isa<Constant>(LHS) ? C2 : Shuffle->getOperand(0);
1457       Value *NewRHS = isa<Constant>(LHS) ? Shuffle->getOperand(0) : C2;
1458       Value *NewBO = CreateBinOpAsGiven(Inst, NewLHS, NewRHS, Builder);
1459       return Builder.CreateShuffleVector(NewBO,
1460           UndefValue::get(Inst.getType()), Shuffle->getMask());
1461     }
1462   }
1463 
1464   return nullptr;
1465 }
1466 
1467 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1468   SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
1469 
1470   if (Value *V = SimplifyGEPInst(GEP.getSourceElementType(), Ops,
1471                                  SQ.getWithInstruction(&GEP)))
1472     return replaceInstUsesWith(GEP, V);
1473 
1474   Value *PtrOp = GEP.getOperand(0);
1475 
1476   // Eliminate unneeded casts for indices, and replace indices which displace
1477   // by multiples of a zero size type with zero.
1478   bool MadeChange = false;
1479   Type *IntPtrTy =
1480     DL.getIntPtrType(GEP.getPointerOperandType()->getScalarType());
1481 
1482   gep_type_iterator GTI = gep_type_begin(GEP);
1483   for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
1484        ++I, ++GTI) {
1485     // Skip indices into struct types.
1486     if (GTI.isStruct())
1487       continue;
1488 
1489     // Index type should have the same width as IntPtr
1490     Type *IndexTy = (*I)->getType();
1491     Type *NewIndexType = IndexTy->isVectorTy() ?
1492       VectorType::get(IntPtrTy, IndexTy->getVectorNumElements()) : IntPtrTy;
1493 
1494     // If the element type has zero size then any index over it is equivalent
1495     // to an index of zero, so replace it with zero if it is not zero already.
1496     Type *EltTy = GTI.getIndexedType();
1497     if (EltTy->isSized() && DL.getTypeAllocSize(EltTy) == 0)
1498       if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
1499         *I = Constant::getNullValue(NewIndexType);
1500         MadeChange = true;
1501       }
1502 
1503     if (IndexTy != NewIndexType) {
1504       // If we are using a wider index than needed for this platform, shrink
1505       // it to what we need.  If narrower, sign-extend it to what we need.
1506       // This explicit cast can make subsequent optimizations more obvious.
1507       *I = Builder.CreateIntCast(*I, NewIndexType, true);
1508       MadeChange = true;
1509     }
1510   }
1511   if (MadeChange)
1512     return &GEP;
1513 
1514   // Check to see if the inputs to the PHI node are getelementptr instructions.
1515   if (PHINode *PN = dyn_cast<PHINode>(PtrOp)) {
1516     GetElementPtrInst *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
1517     if (!Op1)
1518       return nullptr;
1519 
1520     // Don't fold a GEP into itself through a PHI node. This can only happen
1521     // through the back-edge of a loop. Folding a GEP into itself means that
1522     // the value of the previous iteration needs to be stored in the meantime,
1523     // thus requiring an additional register variable to be live, but not
1524     // actually achieving anything (the GEP still needs to be executed once per
1525     // loop iteration).
1526     if (Op1 == &GEP)
1527       return nullptr;
1528 
1529     int DI = -1;
1530 
1531     for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
1532       GetElementPtrInst *Op2 = dyn_cast<GetElementPtrInst>(*I);
1533       if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
1534         return nullptr;
1535 
1536       // As for Op1 above, don't try to fold a GEP into itself.
1537       if (Op2 == &GEP)
1538         return nullptr;
1539 
1540       // Keep track of the type as we walk the GEP.
1541       Type *CurTy = nullptr;
1542 
1543       for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
1544         if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
1545           return nullptr;
1546 
1547         if (Op1->getOperand(J) != Op2->getOperand(J)) {
1548           if (DI == -1) {
1549             // We have not seen any differences yet in the GEPs feeding the
1550             // PHI yet, so we record this one if it is allowed to be a
1551             // variable.
1552 
1553             // The first two arguments can vary for any GEP, the rest have to be
1554             // static for struct slots
1555             if (J > 1 && CurTy->isStructTy())
1556               return nullptr;
1557 
1558             DI = J;
1559           } else {
1560             // The GEP is different by more than one input. While this could be
1561             // extended to support GEPs that vary by more than one variable it
1562             // doesn't make sense since it greatly increases the complexity and
1563             // would result in an R+R+R addressing mode which no backend
1564             // directly supports and would need to be broken into several
1565             // simpler instructions anyway.
1566             return nullptr;
1567           }
1568         }
1569 
1570         // Sink down a layer of the type for the next iteration.
1571         if (J > 0) {
1572           if (J == 1) {
1573             CurTy = Op1->getSourceElementType();
1574           } else if (CompositeType *CT = dyn_cast<CompositeType>(CurTy)) {
1575             CurTy = CT->getTypeAtIndex(Op1->getOperand(J));
1576           } else {
1577             CurTy = nullptr;
1578           }
1579         }
1580       }
1581     }
1582 
1583     // If not all GEPs are identical we'll have to create a new PHI node.
1584     // Check that the old PHI node has only one use so that it will get
1585     // removed.
1586     if (DI != -1 && !PN->hasOneUse())
1587       return nullptr;
1588 
1589     GetElementPtrInst *NewGEP = cast<GetElementPtrInst>(Op1->clone());
1590     if (DI == -1) {
1591       // All the GEPs feeding the PHI are identical. Clone one down into our
1592       // BB so that it can be merged with the current GEP.
1593       GEP.getParent()->getInstList().insert(
1594           GEP.getParent()->getFirstInsertionPt(), NewGEP);
1595     } else {
1596       // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
1597       // into the current block so it can be merged, and create a new PHI to
1598       // set that index.
1599       PHINode *NewPN;
1600       {
1601         IRBuilderBase::InsertPointGuard Guard(Builder);
1602         Builder.SetInsertPoint(PN);
1603         NewPN = Builder.CreatePHI(Op1->getOperand(DI)->getType(),
1604                                   PN->getNumOperands());
1605       }
1606 
1607       for (auto &I : PN->operands())
1608         NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1609                            PN->getIncomingBlock(I));
1610 
1611       NewGEP->setOperand(DI, NewPN);
1612       GEP.getParent()->getInstList().insert(
1613           GEP.getParent()->getFirstInsertionPt(), NewGEP);
1614       NewGEP->setOperand(DI, NewPN);
1615     }
1616 
1617     GEP.setOperand(0, NewGEP);
1618     PtrOp = NewGEP;
1619   }
1620 
1621   // Combine Indices - If the source pointer to this getelementptr instruction
1622   // is a getelementptr instruction, combine the indices of the two
1623   // getelementptr instructions into a single instruction.
1624   //
1625   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
1626     if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
1627       return nullptr;
1628 
1629     // Note that if our source is a gep chain itself then we wait for that
1630     // chain to be resolved before we perform this transformation.  This
1631     // avoids us creating a TON of code in some cases.
1632     if (GEPOperator *SrcGEP =
1633           dyn_cast<GEPOperator>(Src->getOperand(0)))
1634       if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
1635         return nullptr;   // Wait until our source is folded to completion.
1636 
1637     SmallVector<Value*, 8> Indices;
1638 
1639     // Find out whether the last index in the source GEP is a sequential idx.
1640     bool EndsWithSequential = false;
1641     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
1642          I != E; ++I)
1643       EndsWithSequential = I.isSequential();
1644 
1645     // Can we combine the two pointer arithmetics offsets?
1646     if (EndsWithSequential) {
1647       // Replace: gep (gep %P, long B), long A, ...
1648       // With:    T = long A+B; gep %P, T, ...
1649       //
1650       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1651       Value *GO1 = GEP.getOperand(1);
1652 
1653       // If they aren't the same type, then the input hasn't been processed
1654       // by the loop above yet (which canonicalizes sequential index types to
1655       // intptr_t).  Just avoid transforming this until the input has been
1656       // normalized.
1657       if (SO1->getType() != GO1->getType())
1658         return nullptr;
1659 
1660       Value *Sum =
1661           SimplifyAddInst(GO1, SO1, false, false, SQ.getWithInstruction(&GEP));
1662       // Only do the combine when we are sure the cost after the
1663       // merge is never more than that before the merge.
1664       if (Sum == nullptr)
1665         return nullptr;
1666 
1667       // Update the GEP in place if possible.
1668       if (Src->getNumOperands() == 2) {
1669         GEP.setOperand(0, Src->getOperand(0));
1670         GEP.setOperand(1, Sum);
1671         return &GEP;
1672       }
1673       Indices.append(Src->op_begin()+1, Src->op_end()-1);
1674       Indices.push_back(Sum);
1675       Indices.append(GEP.op_begin()+2, GEP.op_end());
1676     } else if (isa<Constant>(*GEP.idx_begin()) &&
1677                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
1678                Src->getNumOperands() != 1) {
1679       // Otherwise we can do the fold if the first index of the GEP is a zero
1680       Indices.append(Src->op_begin()+1, Src->op_end());
1681       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
1682     }
1683 
1684     if (!Indices.empty())
1685       return GEP.isInBounds() && Src->isInBounds()
1686                  ? GetElementPtrInst::CreateInBounds(
1687                        Src->getSourceElementType(), Src->getOperand(0), Indices,
1688                        GEP.getName())
1689                  : GetElementPtrInst::Create(Src->getSourceElementType(),
1690                                              Src->getOperand(0), Indices,
1691                                              GEP.getName());
1692   }
1693 
1694   if (GEP.getNumIndices() == 1) {
1695     unsigned AS = GEP.getPointerAddressSpace();
1696     if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
1697         DL.getPointerSizeInBits(AS)) {
1698       Type *Ty = GEP.getSourceElementType();
1699       uint64_t TyAllocSize = DL.getTypeAllocSize(Ty);
1700 
1701       bool Matched = false;
1702       uint64_t C;
1703       Value *V = nullptr;
1704       if (TyAllocSize == 1) {
1705         V = GEP.getOperand(1);
1706         Matched = true;
1707       } else if (match(GEP.getOperand(1),
1708                        m_AShr(m_Value(V), m_ConstantInt(C)))) {
1709         if (TyAllocSize == 1ULL << C)
1710           Matched = true;
1711       } else if (match(GEP.getOperand(1),
1712                        m_SDiv(m_Value(V), m_ConstantInt(C)))) {
1713         if (TyAllocSize == C)
1714           Matched = true;
1715       }
1716 
1717       if (Matched) {
1718         // Canonicalize (gep i8* X, -(ptrtoint Y))
1719         // to (inttoptr (sub (ptrtoint X), (ptrtoint Y)))
1720         // The GEP pattern is emitted by the SCEV expander for certain kinds of
1721         // pointer arithmetic.
1722         if (match(V, m_Neg(m_PtrToInt(m_Value())))) {
1723           Operator *Index = cast<Operator>(V);
1724           Value *PtrToInt = Builder.CreatePtrToInt(PtrOp, Index->getType());
1725           Value *NewSub = Builder.CreateSub(PtrToInt, Index->getOperand(1));
1726           return CastInst::Create(Instruction::IntToPtr, NewSub, GEP.getType());
1727         }
1728         // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X))
1729         // to (bitcast Y)
1730         Value *Y;
1731         if (match(V, m_Sub(m_PtrToInt(m_Value(Y)),
1732                            m_PtrToInt(m_Specific(GEP.getOperand(0)))))) {
1733           return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y,
1734                                                                GEP.getType());
1735         }
1736       }
1737     }
1738   }
1739 
1740   // We do not handle pointer-vector geps here.
1741   if (GEP.getType()->isVectorTy())
1742     return nullptr;
1743 
1744   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
1745   Value *StrippedPtr = PtrOp->stripPointerCasts();
1746   PointerType *StrippedPtrTy = cast<PointerType>(StrippedPtr->getType());
1747 
1748   if (StrippedPtr != PtrOp) {
1749     bool HasZeroPointerIndex = false;
1750     if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
1751       HasZeroPointerIndex = C->isZero();
1752 
1753     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
1754     // into     : GEP [10 x i8]* X, i32 0, ...
1755     //
1756     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
1757     //           into     : GEP i8* X, ...
1758     //
1759     // This occurs when the program declares an array extern like "int X[];"
1760     if (HasZeroPointerIndex) {
1761       if (ArrayType *CATy =
1762           dyn_cast<ArrayType>(GEP.getSourceElementType())) {
1763         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
1764         if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
1765           // -> GEP i8* X, ...
1766           SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
1767           GetElementPtrInst *Res = GetElementPtrInst::Create(
1768               StrippedPtrTy->getElementType(), StrippedPtr, Idx, GEP.getName());
1769           Res->setIsInBounds(GEP.isInBounds());
1770           if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
1771             return Res;
1772           // Insert Res, and create an addrspacecast.
1773           // e.g.,
1774           // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
1775           // ->
1776           // %0 = GEP i8 addrspace(1)* X, ...
1777           // addrspacecast i8 addrspace(1)* %0 to i8*
1778           return new AddrSpaceCastInst(Builder.Insert(Res), GEP.getType());
1779         }
1780 
1781         if (ArrayType *XATy =
1782               dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
1783           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
1784           if (CATy->getElementType() == XATy->getElementType()) {
1785             // -> GEP [10 x i8]* X, i32 0, ...
1786             // At this point, we know that the cast source type is a pointer
1787             // to an array of the same type as the destination pointer
1788             // array.  Because the array type is never stepped over (there
1789             // is a leading zero) we can fold the cast into this GEP.
1790             if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
1791               GEP.setOperand(0, StrippedPtr);
1792               GEP.setSourceElementType(XATy);
1793               return &GEP;
1794             }
1795             // Cannot replace the base pointer directly because StrippedPtr's
1796             // address space is different. Instead, create a new GEP followed by
1797             // an addrspacecast.
1798             // e.g.,
1799             // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
1800             //   i32 0, ...
1801             // ->
1802             // %0 = GEP [10 x i8] addrspace(1)* X, ...
1803             // addrspacecast i8 addrspace(1)* %0 to i8*
1804             SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
1805             Value *NewGEP = GEP.isInBounds()
1806                                 ? Builder.CreateInBoundsGEP(
1807                                       nullptr, StrippedPtr, Idx, GEP.getName())
1808                                 : Builder.CreateGEP(nullptr, StrippedPtr, Idx,
1809                                                     GEP.getName());
1810             return new AddrSpaceCastInst(NewGEP, GEP.getType());
1811           }
1812         }
1813       }
1814     } else if (GEP.getNumOperands() == 2) {
1815       // Transform things like:
1816       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
1817       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
1818       Type *SrcElTy = StrippedPtrTy->getElementType();
1819       Type *ResElTy = GEP.getSourceElementType();
1820       if (SrcElTy->isArrayTy() &&
1821           DL.getTypeAllocSize(SrcElTy->getArrayElementType()) ==
1822               DL.getTypeAllocSize(ResElTy)) {
1823         Type *IdxType = DL.getIntPtrType(GEP.getType());
1824         Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
1825         Value *NewGEP =
1826             GEP.isInBounds()
1827                 ? Builder.CreateInBoundsGEP(nullptr, StrippedPtr, Idx,
1828                                             GEP.getName())
1829                 : Builder.CreateGEP(nullptr, StrippedPtr, Idx, GEP.getName());
1830 
1831         // V and GEP are both pointer types --> BitCast
1832         return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1833                                                              GEP.getType());
1834       }
1835 
1836       // Transform things like:
1837       // %V = mul i64 %N, 4
1838       // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
1839       // into:  %t1 = getelementptr i32* %arr, i32 %N; bitcast
1840       if (ResElTy->isSized() && SrcElTy->isSized()) {
1841         // Check that changing the type amounts to dividing the index by a scale
1842         // factor.
1843         uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1844         uint64_t SrcSize = DL.getTypeAllocSize(SrcElTy);
1845         if (ResSize && SrcSize % ResSize == 0) {
1846           Value *Idx = GEP.getOperand(1);
1847           unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1848           uint64_t Scale = SrcSize / ResSize;
1849 
1850           // Earlier transforms ensure that the index has type IntPtrType, which
1851           // considerably simplifies the logic by eliminating implicit casts.
1852           assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
1853                  "Index not cast to pointer width?");
1854 
1855           bool NSW;
1856           if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1857             // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1858             // If the multiplication NewIdx * Scale may overflow then the new
1859             // GEP may not be "inbounds".
1860             Value *NewGEP =
1861                 GEP.isInBounds() && NSW
1862                     ? Builder.CreateInBoundsGEP(nullptr, StrippedPtr, NewIdx,
1863                                                 GEP.getName())
1864                     : Builder.CreateGEP(nullptr, StrippedPtr, NewIdx,
1865                                         GEP.getName());
1866 
1867             // The NewGEP must be pointer typed, so must the old one -> BitCast
1868             return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1869                                                                  GEP.getType());
1870           }
1871         }
1872       }
1873 
1874       // Similarly, transform things like:
1875       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
1876       //   (where tmp = 8*tmp2) into:
1877       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
1878       if (ResElTy->isSized() && SrcElTy->isSized() && SrcElTy->isArrayTy()) {
1879         // Check that changing to the array element type amounts to dividing the
1880         // index by a scale factor.
1881         uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1882         uint64_t ArrayEltSize =
1883             DL.getTypeAllocSize(SrcElTy->getArrayElementType());
1884         if (ResSize && ArrayEltSize % ResSize == 0) {
1885           Value *Idx = GEP.getOperand(1);
1886           unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1887           uint64_t Scale = ArrayEltSize / ResSize;
1888 
1889           // Earlier transforms ensure that the index has type IntPtrType, which
1890           // considerably simplifies the logic by eliminating implicit casts.
1891           assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
1892                  "Index not cast to pointer width?");
1893 
1894           bool NSW;
1895           if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1896             // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1897             // If the multiplication NewIdx * Scale may overflow then the new
1898             // GEP may not be "inbounds".
1899             Value *Off[2] = {
1900                 Constant::getNullValue(DL.getIntPtrType(GEP.getType())),
1901                 NewIdx};
1902 
1903             Value *NewGEP = GEP.isInBounds() && NSW
1904                                 ? Builder.CreateInBoundsGEP(
1905                                       SrcElTy, StrippedPtr, Off, GEP.getName())
1906                                 : Builder.CreateGEP(SrcElTy, StrippedPtr, Off,
1907                                                     GEP.getName());
1908             // The NewGEP must be pointer typed, so must the old one -> BitCast
1909             return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1910                                                                  GEP.getType());
1911           }
1912         }
1913       }
1914     }
1915   }
1916 
1917   // addrspacecast between types is canonicalized as a bitcast, then an
1918   // addrspacecast. To take advantage of the below bitcast + struct GEP, look
1919   // through the addrspacecast.
1920   if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
1921     //   X = bitcast A addrspace(1)* to B addrspace(1)*
1922     //   Y = addrspacecast A addrspace(1)* to B addrspace(2)*
1923     //   Z = gep Y, <...constant indices...>
1924     // Into an addrspacecasted GEP of the struct.
1925     if (BitCastInst *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
1926       PtrOp = BC;
1927   }
1928 
1929   /// See if we can simplify:
1930   ///   X = bitcast A* to B*
1931   ///   Y = gep X, <...constant indices...>
1932   /// into a gep of the original struct.  This is important for SROA and alias
1933   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
1934   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
1935     Value *Operand = BCI->getOperand(0);
1936     PointerType *OpType = cast<PointerType>(Operand->getType());
1937     unsigned OffsetBits = DL.getPointerTypeSizeInBits(GEP.getType());
1938     APInt Offset(OffsetBits, 0);
1939     if (!isa<BitCastInst>(Operand) &&
1940         GEP.accumulateConstantOffset(DL, Offset)) {
1941 
1942       // If this GEP instruction doesn't move the pointer, just replace the GEP
1943       // with a bitcast of the real input to the dest type.
1944       if (!Offset) {
1945         // If the bitcast is of an allocation, and the allocation will be
1946         // converted to match the type of the cast, don't touch this.
1947         if (isa<AllocaInst>(Operand) || isAllocationFn(Operand, &TLI)) {
1948           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1949           if (Instruction *I = visitBitCast(*BCI)) {
1950             if (I != BCI) {
1951               I->takeName(BCI);
1952               BCI->getParent()->getInstList().insert(BCI->getIterator(), I);
1953               replaceInstUsesWith(*BCI, I);
1954             }
1955             return &GEP;
1956           }
1957         }
1958 
1959         if (Operand->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1960           return new AddrSpaceCastInst(Operand, GEP.getType());
1961         return new BitCastInst(Operand, GEP.getType());
1962       }
1963 
1964       // Otherwise, if the offset is non-zero, we need to find out if there is a
1965       // field at Offset in 'A's type.  If so, we can pull the cast through the
1966       // GEP.
1967       SmallVector<Value*, 8> NewIndices;
1968       if (FindElementAtOffset(OpType, Offset.getSExtValue(), NewIndices)) {
1969         Value *NGEP =
1970             GEP.isInBounds()
1971                 ? Builder.CreateInBoundsGEP(nullptr, Operand, NewIndices)
1972                 : Builder.CreateGEP(nullptr, Operand, NewIndices);
1973 
1974         if (NGEP->getType() == GEP.getType())
1975           return replaceInstUsesWith(GEP, NGEP);
1976         NGEP->takeName(&GEP);
1977 
1978         if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1979           return new AddrSpaceCastInst(NGEP, GEP.getType());
1980         return new BitCastInst(NGEP, GEP.getType());
1981       }
1982     }
1983   }
1984 
1985   if (!GEP.isInBounds()) {
1986     unsigned PtrWidth =
1987         DL.getPointerSizeInBits(PtrOp->getType()->getPointerAddressSpace());
1988     APInt BasePtrOffset(PtrWidth, 0);
1989     Value *UnderlyingPtrOp =
1990             PtrOp->stripAndAccumulateInBoundsConstantOffsets(DL,
1991                                                              BasePtrOffset);
1992     if (auto *AI = dyn_cast<AllocaInst>(UnderlyingPtrOp)) {
1993       if (GEP.accumulateConstantOffset(DL, BasePtrOffset) &&
1994           BasePtrOffset.isNonNegative()) {
1995         APInt AllocSize(PtrWidth, DL.getTypeAllocSize(AI->getAllocatedType()));
1996         if (BasePtrOffset.ule(AllocSize)) {
1997           return GetElementPtrInst::CreateInBounds(
1998               PtrOp, makeArrayRef(Ops).slice(1), GEP.getName());
1999         }
2000       }
2001     }
2002   }
2003 
2004   return nullptr;
2005 }
2006 
2007 static bool isNeverEqualToUnescapedAlloc(Value *V, const TargetLibraryInfo *TLI,
2008                                          Instruction *AI) {
2009   if (isa<ConstantPointerNull>(V))
2010     return true;
2011   if (auto *LI = dyn_cast<LoadInst>(V))
2012     return isa<GlobalVariable>(LI->getPointerOperand());
2013   // Two distinct allocations will never be equal.
2014   // We rely on LookThroughBitCast in isAllocLikeFn being false, since looking
2015   // through bitcasts of V can cause
2016   // the result statement below to be true, even when AI and V (ex:
2017   // i8* ->i32* ->i8* of AI) are the same allocations.
2018   return isAllocLikeFn(V, TLI) && V != AI;
2019 }
2020 
2021 static bool isAllocSiteRemovable(Instruction *AI,
2022                                  SmallVectorImpl<WeakTrackingVH> &Users,
2023                                  const TargetLibraryInfo *TLI) {
2024   SmallVector<Instruction*, 4> Worklist;
2025   Worklist.push_back(AI);
2026 
2027   do {
2028     Instruction *PI = Worklist.pop_back_val();
2029     for (User *U : PI->users()) {
2030       Instruction *I = cast<Instruction>(U);
2031       switch (I->getOpcode()) {
2032       default:
2033         // Give up the moment we see something we can't handle.
2034         return false;
2035 
2036       case Instruction::AddrSpaceCast:
2037       case Instruction::BitCast:
2038       case Instruction::GetElementPtr:
2039         Users.emplace_back(I);
2040         Worklist.push_back(I);
2041         continue;
2042 
2043       case Instruction::ICmp: {
2044         ICmpInst *ICI = cast<ICmpInst>(I);
2045         // We can fold eq/ne comparisons with null to false/true, respectively.
2046         // We also fold comparisons in some conditions provided the alloc has
2047         // not escaped (see isNeverEqualToUnescapedAlloc).
2048         if (!ICI->isEquality())
2049           return false;
2050         unsigned OtherIndex = (ICI->getOperand(0) == PI) ? 1 : 0;
2051         if (!isNeverEqualToUnescapedAlloc(ICI->getOperand(OtherIndex), TLI, AI))
2052           return false;
2053         Users.emplace_back(I);
2054         continue;
2055       }
2056 
2057       case Instruction::Call:
2058         // Ignore no-op and store intrinsics.
2059         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2060           switch (II->getIntrinsicID()) {
2061           default:
2062             return false;
2063 
2064           case Intrinsic::memmove:
2065           case Intrinsic::memcpy:
2066           case Intrinsic::memset: {
2067             MemIntrinsic *MI = cast<MemIntrinsic>(II);
2068             if (MI->isVolatile() || MI->getRawDest() != PI)
2069               return false;
2070             LLVM_FALLTHROUGH;
2071           }
2072           case Intrinsic::invariant_start:
2073           case Intrinsic::invariant_end:
2074           case Intrinsic::lifetime_start:
2075           case Intrinsic::lifetime_end:
2076           case Intrinsic::objectsize:
2077             Users.emplace_back(I);
2078             continue;
2079           }
2080         }
2081 
2082         if (isFreeCall(I, TLI)) {
2083           Users.emplace_back(I);
2084           continue;
2085         }
2086         return false;
2087 
2088       case Instruction::Store: {
2089         StoreInst *SI = cast<StoreInst>(I);
2090         if (SI->isVolatile() || SI->getPointerOperand() != PI)
2091           return false;
2092         Users.emplace_back(I);
2093         continue;
2094       }
2095       }
2096       llvm_unreachable("missing a return?");
2097     }
2098   } while (!Worklist.empty());
2099   return true;
2100 }
2101 
2102 Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
2103   // If we have a malloc call which is only used in any amount of comparisons
2104   // to null and free calls, delete the calls and replace the comparisons with
2105   // true or false as appropriate.
2106   SmallVector<WeakTrackingVH, 64> Users;
2107 
2108   // If we are removing an alloca with a dbg.declare, insert dbg.value calls
2109   // before each store.
2110   TinyPtrVector<DbgInfoIntrinsic *> DIIs;
2111   std::unique_ptr<DIBuilder> DIB;
2112   if (isa<AllocaInst>(MI)) {
2113     DIIs = FindDbgAddrUses(&MI);
2114     DIB.reset(new DIBuilder(*MI.getModule(), /*AllowUnresolved=*/false));
2115   }
2116 
2117   if (isAllocSiteRemovable(&MI, Users, &TLI)) {
2118     for (unsigned i = 0, e = Users.size(); i != e; ++i) {
2119       // Lowering all @llvm.objectsize calls first because they may
2120       // use a bitcast/GEP of the alloca we are removing.
2121       if (!Users[i])
2122        continue;
2123 
2124       Instruction *I = cast<Instruction>(&*Users[i]);
2125 
2126       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2127         if (II->getIntrinsicID() == Intrinsic::objectsize) {
2128           ConstantInt *Result = lowerObjectSizeCall(II, DL, &TLI,
2129                                                     /*MustSucceed=*/true);
2130           replaceInstUsesWith(*I, Result);
2131           eraseInstFromFunction(*I);
2132           Users[i] = nullptr; // Skip examining in the next loop.
2133         }
2134       }
2135     }
2136     for (unsigned i = 0, e = Users.size(); i != e; ++i) {
2137       if (!Users[i])
2138         continue;
2139 
2140       Instruction *I = cast<Instruction>(&*Users[i]);
2141 
2142       if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
2143         replaceInstUsesWith(*C,
2144                             ConstantInt::get(Type::getInt1Ty(C->getContext()),
2145                                              C->isFalseWhenEqual()));
2146       } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I) ||
2147                  isa<AddrSpaceCastInst>(I)) {
2148         replaceInstUsesWith(*I, UndefValue::get(I->getType()));
2149       } else if (auto *SI = dyn_cast<StoreInst>(I)) {
2150         for (auto *DII : DIIs)
2151           ConvertDebugDeclareToDebugValue(DII, SI, *DIB);
2152       }
2153       eraseInstFromFunction(*I);
2154     }
2155 
2156     if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
2157       // Replace invoke with a NOP intrinsic to maintain the original CFG
2158       Module *M = II->getModule();
2159       Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
2160       InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
2161                          None, "", II->getParent());
2162     }
2163 
2164     for (auto *DII : DIIs)
2165       eraseInstFromFunction(*DII);
2166 
2167     return eraseInstFromFunction(MI);
2168   }
2169   return nullptr;
2170 }
2171 
2172 /// \brief Move the call to free before a NULL test.
2173 ///
2174 /// Check if this free is accessed after its argument has been test
2175 /// against NULL (property 0).
2176 /// If yes, it is legal to move this call in its predecessor block.
2177 ///
2178 /// The move is performed only if the block containing the call to free
2179 /// will be removed, i.e.:
2180 /// 1. it has only one predecessor P, and P has two successors
2181 /// 2. it contains the call and an unconditional branch
2182 /// 3. its successor is the same as its predecessor's successor
2183 ///
2184 /// The profitability is out-of concern here and this function should
2185 /// be called only if the caller knows this transformation would be
2186 /// profitable (e.g., for code size).
2187 static Instruction *
2188 tryToMoveFreeBeforeNullTest(CallInst &FI) {
2189   Value *Op = FI.getArgOperand(0);
2190   BasicBlock *FreeInstrBB = FI.getParent();
2191   BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
2192 
2193   // Validate part of constraint #1: Only one predecessor
2194   // FIXME: We can extend the number of predecessor, but in that case, we
2195   //        would duplicate the call to free in each predecessor and it may
2196   //        not be profitable even for code size.
2197   if (!PredBB)
2198     return nullptr;
2199 
2200   // Validate constraint #2: Does this block contains only the call to
2201   //                         free and an unconditional branch?
2202   // FIXME: We could check if we can speculate everything in the
2203   //        predecessor block
2204   if (FreeInstrBB->size() != 2)
2205     return nullptr;
2206   BasicBlock *SuccBB;
2207   if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
2208     return nullptr;
2209 
2210   // Validate the rest of constraint #1 by matching on the pred branch.
2211   TerminatorInst *TI = PredBB->getTerminator();
2212   BasicBlock *TrueBB, *FalseBB;
2213   ICmpInst::Predicate Pred;
2214   if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
2215     return nullptr;
2216   if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2217     return nullptr;
2218 
2219   // Validate constraint #3: Ensure the null case just falls through.
2220   if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
2221     return nullptr;
2222   assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
2223          "Broken CFG: missing edge from predecessor to successor");
2224 
2225   FI.moveBefore(TI);
2226   return &FI;
2227 }
2228 
2229 
2230 Instruction *InstCombiner::visitFree(CallInst &FI) {
2231   Value *Op = FI.getArgOperand(0);
2232 
2233   // free undef -> unreachable.
2234   if (isa<UndefValue>(Op)) {
2235     // Insert a new store to null because we cannot modify the CFG here.
2236     Builder.CreateStore(ConstantInt::getTrue(FI.getContext()),
2237                         UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
2238     return eraseInstFromFunction(FI);
2239   }
2240 
2241   // If we have 'free null' delete the instruction.  This can happen in stl code
2242   // when lots of inlining happens.
2243   if (isa<ConstantPointerNull>(Op))
2244     return eraseInstFromFunction(FI);
2245 
2246   // If we optimize for code size, try to move the call to free before the null
2247   // test so that simplify cfg can remove the empty block and dead code
2248   // elimination the branch. I.e., helps to turn something like:
2249   // if (foo) free(foo);
2250   // into
2251   // free(foo);
2252   if (MinimizeSize)
2253     if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
2254       return I;
2255 
2256   return nullptr;
2257 }
2258 
2259 Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) {
2260   if (RI.getNumOperands() == 0) // ret void
2261     return nullptr;
2262 
2263   Value *ResultOp = RI.getOperand(0);
2264   Type *VTy = ResultOp->getType();
2265   if (!VTy->isIntegerTy())
2266     return nullptr;
2267 
2268   // There might be assume intrinsics dominating this return that completely
2269   // determine the value. If so, constant fold it.
2270   KnownBits Known = computeKnownBits(ResultOp, 0, &RI);
2271   if (Known.isConstant())
2272     RI.setOperand(0, Constant::getIntegerValue(VTy, Known.getConstant()));
2273 
2274   return nullptr;
2275 }
2276 
2277 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2278   // Change br (not X), label True, label False to: br X, label False, True
2279   Value *X = nullptr;
2280   BasicBlock *TrueDest;
2281   BasicBlock *FalseDest;
2282   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
2283       !isa<Constant>(X)) {
2284     // Swap Destinations and condition...
2285     BI.setCondition(X);
2286     BI.swapSuccessors();
2287     return &BI;
2288   }
2289 
2290   // If the condition is irrelevant, remove the use so that other
2291   // transforms on the condition become more effective.
2292   if (BI.isConditional() && !isa<ConstantInt>(BI.getCondition()) &&
2293       BI.getSuccessor(0) == BI.getSuccessor(1)) {
2294     BI.setCondition(ConstantInt::getFalse(BI.getCondition()->getType()));
2295     return &BI;
2296   }
2297 
2298   // Canonicalize, for example, icmp_ne -> icmp_eq or fcmp_one -> fcmp_oeq.
2299   CmpInst::Predicate Pred;
2300   if (match(&BI, m_Br(m_OneUse(m_Cmp(Pred, m_Value(), m_Value())), TrueDest,
2301                       FalseDest)) &&
2302       !isCanonicalPredicate(Pred)) {
2303     // Swap destinations and condition.
2304     CmpInst *Cond = cast<CmpInst>(BI.getCondition());
2305     Cond->setPredicate(CmpInst::getInversePredicate(Pred));
2306     BI.swapSuccessors();
2307     Worklist.Add(Cond);
2308     return &BI;
2309   }
2310 
2311   return nullptr;
2312 }
2313 
2314 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
2315   Value *Cond = SI.getCondition();
2316   Value *Op0;
2317   ConstantInt *AddRHS;
2318   if (match(Cond, m_Add(m_Value(Op0), m_ConstantInt(AddRHS)))) {
2319     // Change 'switch (X+4) case 1:' into 'switch (X) case -3'.
2320     for (auto Case : SI.cases()) {
2321       Constant *NewCase = ConstantExpr::getSub(Case.getCaseValue(), AddRHS);
2322       assert(isa<ConstantInt>(NewCase) &&
2323              "Result of expression should be constant");
2324       Case.setValue(cast<ConstantInt>(NewCase));
2325     }
2326     SI.setCondition(Op0);
2327     return &SI;
2328   }
2329 
2330   KnownBits Known = computeKnownBits(Cond, 0, &SI);
2331   unsigned LeadingKnownZeros = Known.countMinLeadingZeros();
2332   unsigned LeadingKnownOnes = Known.countMinLeadingOnes();
2333 
2334   // Compute the number of leading bits we can ignore.
2335   // TODO: A better way to determine this would use ComputeNumSignBits().
2336   for (auto &C : SI.cases()) {
2337     LeadingKnownZeros = std::min(
2338         LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
2339     LeadingKnownOnes = std::min(
2340         LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
2341   }
2342 
2343   unsigned NewWidth = Known.getBitWidth() - std::max(LeadingKnownZeros, LeadingKnownOnes);
2344 
2345   // Shrink the condition operand if the new type is smaller than the old type.
2346   // This may produce a non-standard type for the switch, but that's ok because
2347   // the backend should extend back to a legal type for the target.
2348   if (NewWidth > 0 && NewWidth < Known.getBitWidth()) {
2349     IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
2350     Builder.SetInsertPoint(&SI);
2351     Value *NewCond = Builder.CreateTrunc(Cond, Ty, "trunc");
2352     SI.setCondition(NewCond);
2353 
2354     for (auto Case : SI.cases()) {
2355       APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(NewWidth);
2356       Case.setValue(ConstantInt::get(SI.getContext(), TruncatedCase));
2357     }
2358     return &SI;
2359   }
2360 
2361   return nullptr;
2362 }
2363 
2364 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
2365   Value *Agg = EV.getAggregateOperand();
2366 
2367   if (!EV.hasIndices())
2368     return replaceInstUsesWith(EV, Agg);
2369 
2370   if (Value *V = SimplifyExtractValueInst(Agg, EV.getIndices(),
2371                                           SQ.getWithInstruction(&EV)))
2372     return replaceInstUsesWith(EV, V);
2373 
2374   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
2375     // We're extracting from an insertvalue instruction, compare the indices
2376     const unsigned *exti, *exte, *insi, *inse;
2377     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
2378          exte = EV.idx_end(), inse = IV->idx_end();
2379          exti != exte && insi != inse;
2380          ++exti, ++insi) {
2381       if (*insi != *exti)
2382         // The insert and extract both reference distinctly different elements.
2383         // This means the extract is not influenced by the insert, and we can
2384         // replace the aggregate operand of the extract with the aggregate
2385         // operand of the insert. i.e., replace
2386         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2387         // %E = extractvalue { i32, { i32 } } %I, 0
2388         // with
2389         // %E = extractvalue { i32, { i32 } } %A, 0
2390         return ExtractValueInst::Create(IV->getAggregateOperand(),
2391                                         EV.getIndices());
2392     }
2393     if (exti == exte && insi == inse)
2394       // Both iterators are at the end: Index lists are identical. Replace
2395       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2396       // %C = extractvalue { i32, { i32 } } %B, 1, 0
2397       // with "i32 42"
2398       return replaceInstUsesWith(EV, IV->getInsertedValueOperand());
2399     if (exti == exte) {
2400       // The extract list is a prefix of the insert list. i.e. replace
2401       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2402       // %E = extractvalue { i32, { i32 } } %I, 1
2403       // with
2404       // %X = extractvalue { i32, { i32 } } %A, 1
2405       // %E = insertvalue { i32 } %X, i32 42, 0
2406       // by switching the order of the insert and extract (though the
2407       // insertvalue should be left in, since it may have other uses).
2408       Value *NewEV = Builder.CreateExtractValue(IV->getAggregateOperand(),
2409                                                 EV.getIndices());
2410       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
2411                                      makeArrayRef(insi, inse));
2412     }
2413     if (insi == inse)
2414       // The insert list is a prefix of the extract list
2415       // We can simply remove the common indices from the extract and make it
2416       // operate on the inserted value instead of the insertvalue result.
2417       // i.e., replace
2418       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2419       // %E = extractvalue { i32, { i32 } } %I, 1, 0
2420       // with
2421       // %E extractvalue { i32 } { i32 42 }, 0
2422       return ExtractValueInst::Create(IV->getInsertedValueOperand(),
2423                                       makeArrayRef(exti, exte));
2424   }
2425   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
2426     // We're extracting from an intrinsic, see if we're the only user, which
2427     // allows us to simplify multiple result intrinsics to simpler things that
2428     // just get one value.
2429     if (II->hasOneUse()) {
2430       // Check if we're grabbing the overflow bit or the result of a 'with
2431       // overflow' intrinsic.  If it's the latter we can remove the intrinsic
2432       // and replace it with a traditional binary instruction.
2433       switch (II->getIntrinsicID()) {
2434       case Intrinsic::uadd_with_overflow:
2435       case Intrinsic::sadd_with_overflow:
2436         if (*EV.idx_begin() == 0) {  // Normal result.
2437           Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2438           replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2439           eraseInstFromFunction(*II);
2440           return BinaryOperator::CreateAdd(LHS, RHS);
2441         }
2442 
2443         // If the normal result of the add is dead, and the RHS is a constant,
2444         // we can transform this into a range comparison.
2445         // overflow = uadd a, -4  -->  overflow = icmp ugt a, 3
2446         if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2447           if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
2448             return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
2449                                 ConstantExpr::getNot(CI));
2450         break;
2451       case Intrinsic::usub_with_overflow:
2452       case Intrinsic::ssub_with_overflow:
2453         if (*EV.idx_begin() == 0) {  // Normal result.
2454           Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2455           replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2456           eraseInstFromFunction(*II);
2457           return BinaryOperator::CreateSub(LHS, RHS);
2458         }
2459         break;
2460       case Intrinsic::umul_with_overflow:
2461       case Intrinsic::smul_with_overflow:
2462         if (*EV.idx_begin() == 0) {  // Normal result.
2463           Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2464           replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2465           eraseInstFromFunction(*II);
2466           return BinaryOperator::CreateMul(LHS, RHS);
2467         }
2468         break;
2469       default:
2470         break;
2471       }
2472     }
2473   }
2474   if (LoadInst *L = dyn_cast<LoadInst>(Agg))
2475     // If the (non-volatile) load only has one use, we can rewrite this to a
2476     // load from a GEP. This reduces the size of the load. If a load is used
2477     // only by extractvalue instructions then this either must have been
2478     // optimized before, or it is a struct with padding, in which case we
2479     // don't want to do the transformation as it loses padding knowledge.
2480     if (L->isSimple() && L->hasOneUse()) {
2481       // extractvalue has integer indices, getelementptr has Value*s. Convert.
2482       SmallVector<Value*, 4> Indices;
2483       // Prefix an i32 0 since we need the first element.
2484       Indices.push_back(Builder.getInt32(0));
2485       for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
2486             I != E; ++I)
2487         Indices.push_back(Builder.getInt32(*I));
2488 
2489       // We need to insert these at the location of the old load, not at that of
2490       // the extractvalue.
2491       Builder.SetInsertPoint(L);
2492       Value *GEP = Builder.CreateInBoundsGEP(L->getType(),
2493                                              L->getPointerOperand(), Indices);
2494       Instruction *NL = Builder.CreateLoad(GEP);
2495       // Whatever aliasing information we had for the orignal load must also
2496       // hold for the smaller load, so propagate the annotations.
2497       AAMDNodes Nodes;
2498       L->getAAMetadata(Nodes);
2499       NL->setAAMetadata(Nodes);
2500       // Returning the load directly will cause the main loop to insert it in
2501       // the wrong spot, so use replaceInstUsesWith().
2502       return replaceInstUsesWith(EV, NL);
2503     }
2504   // We could simplify extracts from other values. Note that nested extracts may
2505   // already be simplified implicitly by the above: extract (extract (insert) )
2506   // will be translated into extract ( insert ( extract ) ) first and then just
2507   // the value inserted, if appropriate. Similarly for extracts from single-use
2508   // loads: extract (extract (load)) will be translated to extract (load (gep))
2509   // and if again single-use then via load (gep (gep)) to load (gep).
2510   // However, double extracts from e.g. function arguments or return values
2511   // aren't handled yet.
2512   return nullptr;
2513 }
2514 
2515 /// Return 'true' if the given typeinfo will match anything.
2516 static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
2517   switch (Personality) {
2518   case EHPersonality::GNU_C:
2519   case EHPersonality::GNU_C_SjLj:
2520   case EHPersonality::Rust:
2521     // The GCC C EH and Rust personality only exists to support cleanups, so
2522     // it's not clear what the semantics of catch clauses are.
2523     return false;
2524   case EHPersonality::Unknown:
2525     return false;
2526   case EHPersonality::GNU_Ada:
2527     // While __gnat_all_others_value will match any Ada exception, it doesn't
2528     // match foreign exceptions (or didn't, before gcc-4.7).
2529     return false;
2530   case EHPersonality::GNU_CXX:
2531   case EHPersonality::GNU_CXX_SjLj:
2532   case EHPersonality::GNU_ObjC:
2533   case EHPersonality::MSVC_X86SEH:
2534   case EHPersonality::MSVC_Win64SEH:
2535   case EHPersonality::MSVC_CXX:
2536   case EHPersonality::CoreCLR:
2537     return TypeInfo->isNullValue();
2538   }
2539   llvm_unreachable("invalid enum");
2540 }
2541 
2542 static bool shorter_filter(const Value *LHS, const Value *RHS) {
2543   return
2544     cast<ArrayType>(LHS->getType())->getNumElements()
2545   <
2546     cast<ArrayType>(RHS->getType())->getNumElements();
2547 }
2548 
2549 Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
2550   // The logic here should be correct for any real-world personality function.
2551   // However if that turns out not to be true, the offending logic can always
2552   // be conditioned on the personality function, like the catch-all logic is.
2553   EHPersonality Personality =
2554       classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn());
2555 
2556   // Simplify the list of clauses, eg by removing repeated catch clauses
2557   // (these are often created by inlining).
2558   bool MakeNewInstruction = false; // If true, recreate using the following:
2559   SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
2560   bool CleanupFlag = LI.isCleanup();   // - The new instruction is a cleanup.
2561 
2562   SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
2563   for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
2564     bool isLastClause = i + 1 == e;
2565     if (LI.isCatch(i)) {
2566       // A catch clause.
2567       Constant *CatchClause = LI.getClause(i);
2568       Constant *TypeInfo = CatchClause->stripPointerCasts();
2569 
2570       // If we already saw this clause, there is no point in having a second
2571       // copy of it.
2572       if (AlreadyCaught.insert(TypeInfo).second) {
2573         // This catch clause was not already seen.
2574         NewClauses.push_back(CatchClause);
2575       } else {
2576         // Repeated catch clause - drop the redundant copy.
2577         MakeNewInstruction = true;
2578       }
2579 
2580       // If this is a catch-all then there is no point in keeping any following
2581       // clauses or marking the landingpad as having a cleanup.
2582       if (isCatchAll(Personality, TypeInfo)) {
2583         if (!isLastClause)
2584           MakeNewInstruction = true;
2585         CleanupFlag = false;
2586         break;
2587       }
2588     } else {
2589       // A filter clause.  If any of the filter elements were already caught
2590       // then they can be dropped from the filter.  It is tempting to try to
2591       // exploit the filter further by saying that any typeinfo that does not
2592       // occur in the filter can't be caught later (and thus can be dropped).
2593       // However this would be wrong, since typeinfos can match without being
2594       // equal (for example if one represents a C++ class, and the other some
2595       // class derived from it).
2596       assert(LI.isFilter(i) && "Unsupported landingpad clause!");
2597       Constant *FilterClause = LI.getClause(i);
2598       ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
2599       unsigned NumTypeInfos = FilterType->getNumElements();
2600 
2601       // An empty filter catches everything, so there is no point in keeping any
2602       // following clauses or marking the landingpad as having a cleanup.  By
2603       // dealing with this case here the following code is made a bit simpler.
2604       if (!NumTypeInfos) {
2605         NewClauses.push_back(FilterClause);
2606         if (!isLastClause)
2607           MakeNewInstruction = true;
2608         CleanupFlag = false;
2609         break;
2610       }
2611 
2612       bool MakeNewFilter = false; // If true, make a new filter.
2613       SmallVector<Constant *, 16> NewFilterElts; // New elements.
2614       if (isa<ConstantAggregateZero>(FilterClause)) {
2615         // Not an empty filter - it contains at least one null typeinfo.
2616         assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
2617         Constant *TypeInfo =
2618           Constant::getNullValue(FilterType->getElementType());
2619         // If this typeinfo is a catch-all then the filter can never match.
2620         if (isCatchAll(Personality, TypeInfo)) {
2621           // Throw the filter away.
2622           MakeNewInstruction = true;
2623           continue;
2624         }
2625 
2626         // There is no point in having multiple copies of this typeinfo, so
2627         // discard all but the first copy if there is more than one.
2628         NewFilterElts.push_back(TypeInfo);
2629         if (NumTypeInfos > 1)
2630           MakeNewFilter = true;
2631       } else {
2632         ConstantArray *Filter = cast<ConstantArray>(FilterClause);
2633         SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
2634         NewFilterElts.reserve(NumTypeInfos);
2635 
2636         // Remove any filter elements that were already caught or that already
2637         // occurred in the filter.  While there, see if any of the elements are
2638         // catch-alls.  If so, the filter can be discarded.
2639         bool SawCatchAll = false;
2640         for (unsigned j = 0; j != NumTypeInfos; ++j) {
2641           Constant *Elt = Filter->getOperand(j);
2642           Constant *TypeInfo = Elt->stripPointerCasts();
2643           if (isCatchAll(Personality, TypeInfo)) {
2644             // This element is a catch-all.  Bail out, noting this fact.
2645             SawCatchAll = true;
2646             break;
2647           }
2648 
2649           // Even if we've seen a type in a catch clause, we don't want to
2650           // remove it from the filter.  An unexpected type handler may be
2651           // set up for a call site which throws an exception of the same
2652           // type caught.  In order for the exception thrown by the unexpected
2653           // handler to propagate correctly, the filter must be correctly
2654           // described for the call site.
2655           //
2656           // Example:
2657           //
2658           // void unexpected() { throw 1;}
2659           // void foo() throw (int) {
2660           //   std::set_unexpected(unexpected);
2661           //   try {
2662           //     throw 2.0;
2663           //   } catch (int i) {}
2664           // }
2665 
2666           // There is no point in having multiple copies of the same typeinfo in
2667           // a filter, so only add it if we didn't already.
2668           if (SeenInFilter.insert(TypeInfo).second)
2669             NewFilterElts.push_back(cast<Constant>(Elt));
2670         }
2671         // A filter containing a catch-all cannot match anything by definition.
2672         if (SawCatchAll) {
2673           // Throw the filter away.
2674           MakeNewInstruction = true;
2675           continue;
2676         }
2677 
2678         // If we dropped something from the filter, make a new one.
2679         if (NewFilterElts.size() < NumTypeInfos)
2680           MakeNewFilter = true;
2681       }
2682       if (MakeNewFilter) {
2683         FilterType = ArrayType::get(FilterType->getElementType(),
2684                                     NewFilterElts.size());
2685         FilterClause = ConstantArray::get(FilterType, NewFilterElts);
2686         MakeNewInstruction = true;
2687       }
2688 
2689       NewClauses.push_back(FilterClause);
2690 
2691       // If the new filter is empty then it will catch everything so there is
2692       // no point in keeping any following clauses or marking the landingpad
2693       // as having a cleanup.  The case of the original filter being empty was
2694       // already handled above.
2695       if (MakeNewFilter && !NewFilterElts.size()) {
2696         assert(MakeNewInstruction && "New filter but not a new instruction!");
2697         CleanupFlag = false;
2698         break;
2699       }
2700     }
2701   }
2702 
2703   // If several filters occur in a row then reorder them so that the shortest
2704   // filters come first (those with the smallest number of elements).  This is
2705   // advantageous because shorter filters are more likely to match, speeding up
2706   // unwinding, but mostly because it increases the effectiveness of the other
2707   // filter optimizations below.
2708   for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
2709     unsigned j;
2710     // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
2711     for (j = i; j != e; ++j)
2712       if (!isa<ArrayType>(NewClauses[j]->getType()))
2713         break;
2714 
2715     // Check whether the filters are already sorted by length.  We need to know
2716     // if sorting them is actually going to do anything so that we only make a
2717     // new landingpad instruction if it does.
2718     for (unsigned k = i; k + 1 < j; ++k)
2719       if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
2720         // Not sorted, so sort the filters now.  Doing an unstable sort would be
2721         // correct too but reordering filters pointlessly might confuse users.
2722         std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
2723                          shorter_filter);
2724         MakeNewInstruction = true;
2725         break;
2726       }
2727 
2728     // Look for the next batch of filters.
2729     i = j + 1;
2730   }
2731 
2732   // If typeinfos matched if and only if equal, then the elements of a filter L
2733   // that occurs later than a filter F could be replaced by the intersection of
2734   // the elements of F and L.  In reality two typeinfos can match without being
2735   // equal (for example if one represents a C++ class, and the other some class
2736   // derived from it) so it would be wrong to perform this transform in general.
2737   // However the transform is correct and useful if F is a subset of L.  In that
2738   // case L can be replaced by F, and thus removed altogether since repeating a
2739   // filter is pointless.  So here we look at all pairs of filters F and L where
2740   // L follows F in the list of clauses, and remove L if every element of F is
2741   // an element of L.  This can occur when inlining C++ functions with exception
2742   // specifications.
2743   for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
2744     // Examine each filter in turn.
2745     Value *Filter = NewClauses[i];
2746     ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
2747     if (!FTy)
2748       // Not a filter - skip it.
2749       continue;
2750     unsigned FElts = FTy->getNumElements();
2751     // Examine each filter following this one.  Doing this backwards means that
2752     // we don't have to worry about filters disappearing under us when removed.
2753     for (unsigned j = NewClauses.size() - 1; j != i; --j) {
2754       Value *LFilter = NewClauses[j];
2755       ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
2756       if (!LTy)
2757         // Not a filter - skip it.
2758         continue;
2759       // If Filter is a subset of LFilter, i.e. every element of Filter is also
2760       // an element of LFilter, then discard LFilter.
2761       SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
2762       // If Filter is empty then it is a subset of LFilter.
2763       if (!FElts) {
2764         // Discard LFilter.
2765         NewClauses.erase(J);
2766         MakeNewInstruction = true;
2767         // Move on to the next filter.
2768         continue;
2769       }
2770       unsigned LElts = LTy->getNumElements();
2771       // If Filter is longer than LFilter then it cannot be a subset of it.
2772       if (FElts > LElts)
2773         // Move on to the next filter.
2774         continue;
2775       // At this point we know that LFilter has at least one element.
2776       if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
2777         // Filter is a subset of LFilter iff Filter contains only zeros (as we
2778         // already know that Filter is not longer than LFilter).
2779         if (isa<ConstantAggregateZero>(Filter)) {
2780           assert(FElts <= LElts && "Should have handled this case earlier!");
2781           // Discard LFilter.
2782           NewClauses.erase(J);
2783           MakeNewInstruction = true;
2784         }
2785         // Move on to the next filter.
2786         continue;
2787       }
2788       ConstantArray *LArray = cast<ConstantArray>(LFilter);
2789       if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
2790         // Since Filter is non-empty and contains only zeros, it is a subset of
2791         // LFilter iff LFilter contains a zero.
2792         assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
2793         for (unsigned l = 0; l != LElts; ++l)
2794           if (LArray->getOperand(l)->isNullValue()) {
2795             // LFilter contains a zero - discard it.
2796             NewClauses.erase(J);
2797             MakeNewInstruction = true;
2798             break;
2799           }
2800         // Move on to the next filter.
2801         continue;
2802       }
2803       // At this point we know that both filters are ConstantArrays.  Loop over
2804       // operands to see whether every element of Filter is also an element of
2805       // LFilter.  Since filters tend to be short this is probably faster than
2806       // using a method that scales nicely.
2807       ConstantArray *FArray = cast<ConstantArray>(Filter);
2808       bool AllFound = true;
2809       for (unsigned f = 0; f != FElts; ++f) {
2810         Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
2811         AllFound = false;
2812         for (unsigned l = 0; l != LElts; ++l) {
2813           Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
2814           if (LTypeInfo == FTypeInfo) {
2815             AllFound = true;
2816             break;
2817           }
2818         }
2819         if (!AllFound)
2820           break;
2821       }
2822       if (AllFound) {
2823         // Discard LFilter.
2824         NewClauses.erase(J);
2825         MakeNewInstruction = true;
2826       }
2827       // Move on to the next filter.
2828     }
2829   }
2830 
2831   // If we changed any of the clauses, replace the old landingpad instruction
2832   // with a new one.
2833   if (MakeNewInstruction) {
2834     LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
2835                                                  NewClauses.size());
2836     for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
2837       NLI->addClause(NewClauses[i]);
2838     // A landing pad with no clauses must have the cleanup flag set.  It is
2839     // theoretically possible, though highly unlikely, that we eliminated all
2840     // clauses.  If so, force the cleanup flag to true.
2841     if (NewClauses.empty())
2842       CleanupFlag = true;
2843     NLI->setCleanup(CleanupFlag);
2844     return NLI;
2845   }
2846 
2847   // Even if none of the clauses changed, we may nonetheless have understood
2848   // that the cleanup flag is pointless.  Clear it if so.
2849   if (LI.isCleanup() != CleanupFlag) {
2850     assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
2851     LI.setCleanup(CleanupFlag);
2852     return &LI;
2853   }
2854 
2855   return nullptr;
2856 }
2857 
2858 /// Try to move the specified instruction from its current block into the
2859 /// beginning of DestBlock, which can only happen if it's safe to move the
2860 /// instruction past all of the instructions between it and the end of its
2861 /// block.
2862 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
2863   assert(I->hasOneUse() && "Invariants didn't hold!");
2864 
2865   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
2866   if (isa<PHINode>(I) || I->isEHPad() || I->mayHaveSideEffects() ||
2867       isa<TerminatorInst>(I))
2868     return false;
2869 
2870   // Do not sink alloca instructions out of the entry block.
2871   if (isa<AllocaInst>(I) && I->getParent() ==
2872         &DestBlock->getParent()->getEntryBlock())
2873     return false;
2874 
2875   // Do not sink into catchswitch blocks.
2876   if (isa<CatchSwitchInst>(DestBlock->getTerminator()))
2877     return false;
2878 
2879   // Do not sink convergent call instructions.
2880   if (auto *CI = dyn_cast<CallInst>(I)) {
2881     if (CI->isConvergent())
2882       return false;
2883   }
2884   // We can only sink load instructions if there is nothing between the load and
2885   // the end of block that could change the value.
2886   if (I->mayReadFromMemory()) {
2887     for (BasicBlock::iterator Scan = I->getIterator(),
2888                               E = I->getParent()->end();
2889          Scan != E; ++Scan)
2890       if (Scan->mayWriteToMemory())
2891         return false;
2892   }
2893 
2894   BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
2895   I->moveBefore(&*InsertPos);
2896   ++NumSunkInst;
2897   return true;
2898 }
2899 
2900 bool InstCombiner::run() {
2901   while (!Worklist.isEmpty()) {
2902     Instruction *I = Worklist.RemoveOne();
2903     if (I == nullptr) continue;  // skip null values.
2904 
2905     // Check to see if we can DCE the instruction.
2906     if (isInstructionTriviallyDead(I, &TLI)) {
2907       DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
2908       eraseInstFromFunction(*I);
2909       ++NumDeadInst;
2910       MadeIRChange = true;
2911       continue;
2912     }
2913 
2914     if (!DebugCounter::shouldExecute(VisitCounter))
2915       continue;
2916 
2917     // Instruction isn't dead, see if we can constant propagate it.
2918     if (!I->use_empty() &&
2919         (I->getNumOperands() == 0 || isa<Constant>(I->getOperand(0)))) {
2920       if (Constant *C = ConstantFoldInstruction(I, DL, &TLI)) {
2921         DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
2922 
2923         // Add operands to the worklist.
2924         replaceInstUsesWith(*I, C);
2925         ++NumConstProp;
2926         if (isInstructionTriviallyDead(I, &TLI))
2927           eraseInstFromFunction(*I);
2928         MadeIRChange = true;
2929         continue;
2930       }
2931     }
2932 
2933     // In general, it is possible for computeKnownBits to determine all bits in
2934     // a value even when the operands are not all constants.
2935     Type *Ty = I->getType();
2936     if (ExpensiveCombines && !I->use_empty() && Ty->isIntOrIntVectorTy()) {
2937       KnownBits Known = computeKnownBits(I, /*Depth*/0, I);
2938       if (Known.isConstant()) {
2939         Constant *C = ConstantInt::get(Ty, Known.getConstant());
2940         DEBUG(dbgs() << "IC: ConstFold (all bits known) to: " << *C <<
2941                         " from: " << *I << '\n');
2942 
2943         // Add operands to the worklist.
2944         replaceInstUsesWith(*I, C);
2945         ++NumConstProp;
2946         if (isInstructionTriviallyDead(I, &TLI))
2947           eraseInstFromFunction(*I);
2948         MadeIRChange = true;
2949         continue;
2950       }
2951     }
2952 
2953     // See if we can trivially sink this instruction to a successor basic block.
2954     if (I->hasOneUse()) {
2955       BasicBlock *BB = I->getParent();
2956       Instruction *UserInst = cast<Instruction>(*I->user_begin());
2957       BasicBlock *UserParent;
2958 
2959       // Get the block the use occurs in.
2960       if (PHINode *PN = dyn_cast<PHINode>(UserInst))
2961         UserParent = PN->getIncomingBlock(*I->use_begin());
2962       else
2963         UserParent = UserInst->getParent();
2964 
2965       if (UserParent != BB) {
2966         bool UserIsSuccessor = false;
2967         // See if the user is one of our successors.
2968         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
2969           if (*SI == UserParent) {
2970             UserIsSuccessor = true;
2971             break;
2972           }
2973 
2974         // If the user is one of our immediate successors, and if that successor
2975         // only has us as a predecessors (we'd have to split the critical edge
2976         // otherwise), we can keep going.
2977         if (UserIsSuccessor && UserParent->getUniquePredecessor()) {
2978           // Okay, the CFG is simple enough, try to sink this instruction.
2979           if (TryToSinkInstruction(I, UserParent)) {
2980             DEBUG(dbgs() << "IC: Sink: " << *I << '\n');
2981             MadeIRChange = true;
2982             // We'll add uses of the sunk instruction below, but since sinking
2983             // can expose opportunities for it's *operands* add them to the
2984             // worklist
2985             for (Use &U : I->operands())
2986               if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
2987                 Worklist.Add(OpI);
2988           }
2989         }
2990       }
2991     }
2992 
2993     // Now that we have an instruction, try combining it to simplify it.
2994     Builder.SetInsertPoint(I);
2995     Builder.SetCurrentDebugLocation(I->getDebugLoc());
2996 
2997 #ifndef NDEBUG
2998     std::string OrigI;
2999 #endif
3000     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
3001     DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
3002 
3003     if (Instruction *Result = visit(*I)) {
3004       ++NumCombined;
3005       // Should we replace the old instruction with a new one?
3006       if (Result != I) {
3007         DEBUG(dbgs() << "IC: Old = " << *I << '\n'
3008                      << "    New = " << *Result << '\n');
3009 
3010         if (I->getDebugLoc())
3011           Result->setDebugLoc(I->getDebugLoc());
3012         // Everything uses the new instruction now.
3013         I->replaceAllUsesWith(Result);
3014 
3015         // Move the name to the new instruction first.
3016         Result->takeName(I);
3017 
3018         // Push the new instruction and any users onto the worklist.
3019         Worklist.AddUsersToWorkList(*Result);
3020         Worklist.Add(Result);
3021 
3022         // Insert the new instruction into the basic block...
3023         BasicBlock *InstParent = I->getParent();
3024         BasicBlock::iterator InsertPos = I->getIterator();
3025 
3026         // If we replace a PHI with something that isn't a PHI, fix up the
3027         // insertion point.
3028         if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
3029           InsertPos = InstParent->getFirstInsertionPt();
3030 
3031         InstParent->getInstList().insert(InsertPos, Result);
3032 
3033         eraseInstFromFunction(*I);
3034       } else {
3035         DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
3036                      << "    New = " << *I << '\n');
3037 
3038         // If the instruction was modified, it's possible that it is now dead.
3039         // if so, remove it.
3040         if (isInstructionTriviallyDead(I, &TLI)) {
3041           eraseInstFromFunction(*I);
3042         } else {
3043           Worklist.AddUsersToWorkList(*I);
3044           Worklist.Add(I);
3045         }
3046       }
3047       MadeIRChange = true;
3048     }
3049   }
3050 
3051   Worklist.Zap();
3052   return MadeIRChange;
3053 }
3054 
3055 /// Walk the function in depth-first order, adding all reachable code to the
3056 /// worklist.
3057 ///
3058 /// This has a couple of tricks to make the code faster and more powerful.  In
3059 /// particular, we constant fold and DCE instructions as we go, to avoid adding
3060 /// them to the worklist (this significantly speeds up instcombine on code where
3061 /// many instructions are dead or constant).  Additionally, if we find a branch
3062 /// whose condition is a known constant, we only visit the reachable successors.
3063 ///
3064 static bool AddReachableCodeToWorklist(BasicBlock *BB, const DataLayout &DL,
3065                                        SmallPtrSetImpl<BasicBlock *> &Visited,
3066                                        InstCombineWorklist &ICWorklist,
3067                                        const TargetLibraryInfo *TLI) {
3068   bool MadeIRChange = false;
3069   SmallVector<BasicBlock*, 256> Worklist;
3070   Worklist.push_back(BB);
3071 
3072   SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
3073   DenseMap<Constant *, Constant *> FoldedConstants;
3074 
3075   do {
3076     BB = Worklist.pop_back_val();
3077 
3078     // We have now visited this block!  If we've already been here, ignore it.
3079     if (!Visited.insert(BB).second)
3080       continue;
3081 
3082     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
3083       Instruction *Inst = &*BBI++;
3084 
3085       // DCE instruction if trivially dead.
3086       if (isInstructionTriviallyDead(Inst, TLI)) {
3087         ++NumDeadInst;
3088         DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
3089         Inst->eraseFromParent();
3090         MadeIRChange = true;
3091         continue;
3092       }
3093 
3094       // ConstantProp instruction if trivially constant.
3095       if (!Inst->use_empty() &&
3096           (Inst->getNumOperands() == 0 || isa<Constant>(Inst->getOperand(0))))
3097         if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
3098           DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: "
3099                        << *Inst << '\n');
3100           Inst->replaceAllUsesWith(C);
3101           ++NumConstProp;
3102           if (isInstructionTriviallyDead(Inst, TLI))
3103             Inst->eraseFromParent();
3104           MadeIRChange = true;
3105           continue;
3106         }
3107 
3108       // See if we can constant fold its operands.
3109       for (Use &U : Inst->operands()) {
3110         if (!isa<ConstantVector>(U) && !isa<ConstantExpr>(U))
3111           continue;
3112 
3113         auto *C = cast<Constant>(U);
3114         Constant *&FoldRes = FoldedConstants[C];
3115         if (!FoldRes)
3116           FoldRes = ConstantFoldConstant(C, DL, TLI);
3117         if (!FoldRes)
3118           FoldRes = C;
3119 
3120         if (FoldRes != C) {
3121           DEBUG(dbgs() << "IC: ConstFold operand of: " << *Inst
3122                        << "\n    Old = " << *C
3123                        << "\n    New = " << *FoldRes << '\n');
3124           U = FoldRes;
3125           MadeIRChange = true;
3126         }
3127       }
3128 
3129       // Skip processing debug intrinsics in InstCombine. Processing these call instructions
3130       // consumes non-trivial amount of time and provides no value for the optimization.
3131       if (!isa<DbgInfoIntrinsic>(Inst))
3132         InstrsForInstCombineWorklist.push_back(Inst);
3133     }
3134 
3135     // Recursively visit successors.  If this is a branch or switch on a
3136     // constant, only visit the reachable successor.
3137     TerminatorInst *TI = BB->getTerminator();
3138     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3139       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
3140         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
3141         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
3142         Worklist.push_back(ReachableBB);
3143         continue;
3144       }
3145     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3146       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
3147         Worklist.push_back(SI->findCaseValue(Cond)->getCaseSuccessor());
3148         continue;
3149       }
3150     }
3151 
3152     for (BasicBlock *SuccBB : TI->successors())
3153       Worklist.push_back(SuccBB);
3154   } while (!Worklist.empty());
3155 
3156   // Once we've found all of the instructions to add to instcombine's worklist,
3157   // add them in reverse order.  This way instcombine will visit from the top
3158   // of the function down.  This jives well with the way that it adds all uses
3159   // of instructions to the worklist after doing a transformation, thus avoiding
3160   // some N^2 behavior in pathological cases.
3161   ICWorklist.AddInitialGroup(InstrsForInstCombineWorklist);
3162 
3163   return MadeIRChange;
3164 }
3165 
3166 /// \brief Populate the IC worklist from a function, and prune any dead basic
3167 /// blocks discovered in the process.
3168 ///
3169 /// This also does basic constant propagation and other forward fixing to make
3170 /// the combiner itself run much faster.
3171 static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL,
3172                                           TargetLibraryInfo *TLI,
3173                                           InstCombineWorklist &ICWorklist) {
3174   bool MadeIRChange = false;
3175 
3176   // Do a depth-first traversal of the function, populate the worklist with
3177   // the reachable instructions.  Ignore blocks that are not reachable.  Keep
3178   // track of which blocks we visit.
3179   SmallPtrSet<BasicBlock *, 32> Visited;
3180   MadeIRChange |=
3181       AddReachableCodeToWorklist(&F.front(), DL, Visited, ICWorklist, TLI);
3182 
3183   // Do a quick scan over the function.  If we find any blocks that are
3184   // unreachable, remove any instructions inside of them.  This prevents
3185   // the instcombine code from having to deal with some bad special cases.
3186   for (BasicBlock &BB : F) {
3187     if (Visited.count(&BB))
3188       continue;
3189 
3190     unsigned NumDeadInstInBB = removeAllNonTerminatorAndEHPadInstructions(&BB);
3191     MadeIRChange |= NumDeadInstInBB > 0;
3192     NumDeadInst += NumDeadInstInBB;
3193   }
3194 
3195   return MadeIRChange;
3196 }
3197 
3198 static bool combineInstructionsOverFunction(
3199     Function &F, InstCombineWorklist &Worklist, AliasAnalysis *AA,
3200     AssumptionCache &AC, TargetLibraryInfo &TLI, DominatorTree &DT,
3201     OptimizationRemarkEmitter &ORE, bool ExpensiveCombines = true,
3202     LoopInfo *LI = nullptr) {
3203   auto &DL = F.getParent()->getDataLayout();
3204   ExpensiveCombines |= EnableExpensiveCombines;
3205 
3206   /// Builder - This is an IRBuilder that automatically inserts new
3207   /// instructions into the worklist when they are created.
3208   IRBuilder<TargetFolder, IRBuilderCallbackInserter> Builder(
3209       F.getContext(), TargetFolder(DL),
3210       IRBuilderCallbackInserter([&Worklist, &AC](Instruction *I) {
3211         Worklist.Add(I);
3212 
3213         using namespace llvm::PatternMatch;
3214         if (match(I, m_Intrinsic<Intrinsic::assume>()))
3215           AC.registerAssumption(cast<CallInst>(I));
3216       }));
3217 
3218   // Lower dbg.declare intrinsics otherwise their value may be clobbered
3219   // by instcombiner.
3220   bool MadeIRChange = false;
3221   if (ShouldLowerDbgDeclare)
3222     MadeIRChange = LowerDbgDeclare(F);
3223 
3224   // Iterate while there is work to do.
3225   int Iteration = 0;
3226   for (;;) {
3227     ++Iteration;
3228     DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
3229                  << F.getName() << "\n");
3230 
3231     MadeIRChange |= prepareICWorklistFromFunction(F, DL, &TLI, Worklist);
3232 
3233     InstCombiner IC(Worklist, Builder, F.optForMinSize(), ExpensiveCombines, AA,
3234                     AC, TLI, DT, ORE, DL, LI);
3235     IC.MaxArraySizeForCombine = MaxArraySize;
3236 
3237     if (!IC.run())
3238       break;
3239   }
3240 
3241   return MadeIRChange || Iteration > 1;
3242 }
3243 
3244 PreservedAnalyses InstCombinePass::run(Function &F,
3245                                        FunctionAnalysisManager &AM) {
3246   auto &AC = AM.getResult<AssumptionAnalysis>(F);
3247   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
3248   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
3249   auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
3250 
3251   auto *LI = AM.getCachedResult<LoopAnalysis>(F);
3252 
3253   // FIXME: The AliasAnalysis is not yet supported in the new pass manager
3254   if (!combineInstructionsOverFunction(F, Worklist, nullptr, AC, TLI, DT, ORE,
3255                                        ExpensiveCombines, LI))
3256     // No changes, all analyses are preserved.
3257     return PreservedAnalyses::all();
3258 
3259   // Mark all the analyses that instcombine updates as preserved.
3260   PreservedAnalyses PA;
3261   PA.preserveSet<CFGAnalyses>();
3262   PA.preserve<AAManager>();
3263   PA.preserve<GlobalsAA>();
3264   return PA;
3265 }
3266 
3267 void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const {
3268   AU.setPreservesCFG();
3269   AU.addRequired<AAResultsWrapperPass>();
3270   AU.addRequired<AssumptionCacheTracker>();
3271   AU.addRequired<TargetLibraryInfoWrapperPass>();
3272   AU.addRequired<DominatorTreeWrapperPass>();
3273   AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
3274   AU.addPreserved<DominatorTreeWrapperPass>();
3275   AU.addPreserved<AAResultsWrapperPass>();
3276   AU.addPreserved<BasicAAWrapperPass>();
3277   AU.addPreserved<GlobalsAAWrapperPass>();
3278 }
3279 
3280 bool InstructionCombiningPass::runOnFunction(Function &F) {
3281   if (skipFunction(F))
3282     return false;
3283 
3284   // Required analyses.
3285   auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3286   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3287   auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
3288   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3289   auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
3290 
3291   // Optional analyses.
3292   auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
3293   auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
3294 
3295   return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT, ORE,
3296                                          ExpensiveCombines, LI);
3297 }
3298 
3299 char InstructionCombiningPass::ID = 0;
3300 INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine",
3301                       "Combine redundant instructions", false, false)
3302 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3303 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3304 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3305 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3306 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
3307 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
3308 INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine",
3309                     "Combine redundant instructions", false, false)
3310 
3311 // Initialization Routines
3312 void llvm::initializeInstCombine(PassRegistry &Registry) {
3313   initializeInstructionCombiningPassPass(Registry);
3314 }
3315 
3316 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
3317   initializeInstructionCombiningPassPass(*unwrap(R));
3318 }
3319 
3320 FunctionPass *llvm::createInstructionCombiningPass(bool ExpensiveCombines) {
3321   return new InstructionCombiningPass(ExpensiveCombines);
3322 }
3323