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