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