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