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