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