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