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