rename SimplifyCompare -> SimplifyCmpInst and split it into
[oota-llvm.git] / lib / Transforms / Scalar / 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 "llvm/IntrinsicInst.h"
39 #include "llvm/LLVMContext.h"
40 #include "llvm/Pass.h"
41 #include "llvm/DerivedTypes.h"
42 #include "llvm/GlobalVariable.h"
43 #include "llvm/Operator.h"
44 #include "llvm/Analysis/ConstantFolding.h"
45 #include "llvm/Analysis/InstructionSimplify.h"
46 #include "llvm/Analysis/MemoryBuiltins.h"
47 #include "llvm/Analysis/ValueTracking.h"
48 #include "llvm/Target/TargetData.h"
49 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
50 #include "llvm/Transforms/Utils/Local.h"
51 #include "llvm/Support/CallSite.h"
52 #include "llvm/Support/ConstantRange.h"
53 #include "llvm/Support/Debug.h"
54 #include "llvm/Support/ErrorHandling.h"
55 #include "llvm/Support/GetElementPtrTypeIterator.h"
56 #include "llvm/Support/InstVisitor.h"
57 #include "llvm/Support/IRBuilder.h"
58 #include "llvm/Support/MathExtras.h"
59 #include "llvm/Support/PatternMatch.h"
60 #include "llvm/Support/TargetFolder.h"
61 #include "llvm/Support/raw_ostream.h"
62 #include "llvm/ADT/DenseMap.h"
63 #include "llvm/ADT/SmallVector.h"
64 #include "llvm/ADT/SmallPtrSet.h"
65 #include "llvm/ADT/Statistic.h"
66 #include "llvm/ADT/STLExtras.h"
67 #include <algorithm>
68 #include <climits>
69 using namespace llvm;
70 using namespace llvm::PatternMatch;
71
72 STATISTIC(NumCombined , "Number of insts combined");
73 STATISTIC(NumConstProp, "Number of constant folds");
74 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
75 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
76 STATISTIC(NumSunkInst , "Number of instructions sunk");
77
78 namespace {
79   /// InstCombineWorklist - This is the worklist management logic for
80   /// InstCombine.
81   class InstCombineWorklist {
82     SmallVector<Instruction*, 256> Worklist;
83     DenseMap<Instruction*, unsigned> WorklistMap;
84     
85     void operator=(const InstCombineWorklist&RHS);   // DO NOT IMPLEMENT
86     InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
87   public:
88     InstCombineWorklist() {}
89     
90     bool isEmpty() const { return Worklist.empty(); }
91     
92     /// Add - Add the specified instruction to the worklist if it isn't already
93     /// in it.
94     void Add(Instruction *I) {
95       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {
96         DEBUG(errs() << "IC: ADD: " << *I << '\n');
97         Worklist.push_back(I);
98       }
99     }
100     
101     void AddValue(Value *V) {
102       if (Instruction *I = dyn_cast<Instruction>(V))
103         Add(I);
104     }
105     
106     /// AddInitialGroup - Add the specified batch of stuff in reverse order.
107     /// which should only be done when the worklist is empty and when the group
108     /// has no duplicates.
109     void AddInitialGroup(Instruction *const *List, unsigned NumEntries) {
110       assert(Worklist.empty() && "Worklist must be empty to add initial group");
111       Worklist.reserve(NumEntries+16);
112       DEBUG(errs() << "IC: ADDING: " << NumEntries << " instrs to worklist\n");
113       for (; NumEntries; --NumEntries) {
114         Instruction *I = List[NumEntries-1];
115         WorklistMap.insert(std::make_pair(I, Worklist.size()));
116         Worklist.push_back(I);
117       }
118     }
119     
120     // Remove - remove I from the worklist if it exists.
121     void Remove(Instruction *I) {
122       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
123       if (It == WorklistMap.end()) return; // Not in worklist.
124       
125       // Don't bother moving everything down, just null out the slot.
126       Worklist[It->second] = 0;
127       
128       WorklistMap.erase(It);
129     }
130     
131     Instruction *RemoveOne() {
132       Instruction *I = Worklist.back();
133       Worklist.pop_back();
134       WorklistMap.erase(I);
135       return I;
136     }
137
138     /// AddUsersToWorkList - When an instruction is simplified, add all users of
139     /// the instruction to the work lists because they might get more simplified
140     /// now.
141     ///
142     void AddUsersToWorkList(Instruction &I) {
143       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
144            UI != UE; ++UI)
145         Add(cast<Instruction>(*UI));
146     }
147     
148     
149     /// Zap - check that the worklist is empty and nuke the backing store for
150     /// the map if it is large.
151     void Zap() {
152       assert(WorklistMap.empty() && "Worklist empty, but map not?");
153       
154       // Do an explicit clear, this shrinks the map if needed.
155       WorklistMap.clear();
156     }
157   };
158 } // end anonymous namespace.
159
160
161 namespace {
162   /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
163   /// just like the normal insertion helper, but also adds any new instructions
164   /// to the instcombine worklist.
165   class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
166     InstCombineWorklist &Worklist;
167   public:
168     InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
169     
170     void InsertHelper(Instruction *I, const Twine &Name,
171                       BasicBlock *BB, BasicBlock::iterator InsertPt) const {
172       IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
173       Worklist.Add(I);
174     }
175   };
176 } // end anonymous namespace
177
178
179 namespace {
180   class InstCombiner : public FunctionPass,
181                        public InstVisitor<InstCombiner, Instruction*> {
182     TargetData *TD;
183     bool MustPreserveLCSSA;
184     bool MadeIRChange;
185   public:
186     /// Worklist - All of the instructions that need to be simplified.
187     InstCombineWorklist Worklist;
188
189     /// Builder - This is an IRBuilder that automatically inserts new
190     /// instructions into the worklist when they are created.
191     typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
192     BuilderTy *Builder;
193         
194     static char ID; // Pass identification, replacement for typeid
195     InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
196
197     LLVMContext *Context;
198     LLVMContext *getContext() const { return Context; }
199
200   public:
201     virtual bool runOnFunction(Function &F);
202     
203     bool DoOneIteration(Function &F, unsigned ItNum);
204
205     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
206       AU.addPreservedID(LCSSAID);
207       AU.setPreservesCFG();
208     }
209
210     TargetData *getTargetData() const { return TD; }
211
212     // Visitation implementation - Implement instruction combining for different
213     // instruction types.  The semantics are as follows:
214     // Return Value:
215     //    null        - No change was made
216     //     I          - Change was made, I is still valid, I may be dead though
217     //   otherwise    - Change was made, replace I with returned instruction
218     //
219     Instruction *visitAdd(BinaryOperator &I);
220     Instruction *visitFAdd(BinaryOperator &I);
221     Value *OptimizePointerDifference(Value *LHS, Value *RHS, const Type *Ty);
222     Instruction *visitSub(BinaryOperator &I);
223     Instruction *visitFSub(BinaryOperator &I);
224     Instruction *visitMul(BinaryOperator &I);
225     Instruction *visitFMul(BinaryOperator &I);
226     Instruction *visitURem(BinaryOperator &I);
227     Instruction *visitSRem(BinaryOperator &I);
228     Instruction *visitFRem(BinaryOperator &I);
229     bool SimplifyDivRemOfSelect(BinaryOperator &I);
230     Instruction *commonRemTransforms(BinaryOperator &I);
231     Instruction *commonIRemTransforms(BinaryOperator &I);
232     Instruction *commonDivTransforms(BinaryOperator &I);
233     Instruction *commonIDivTransforms(BinaryOperator &I);
234     Instruction *visitUDiv(BinaryOperator &I);
235     Instruction *visitSDiv(BinaryOperator &I);
236     Instruction *visitFDiv(BinaryOperator &I);
237     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
238     Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
239     Instruction *visitAnd(BinaryOperator &I);
240     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
241     Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
242     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
243                                      Value *A, Value *B, Value *C);
244     Instruction *visitOr (BinaryOperator &I);
245     Instruction *visitXor(BinaryOperator &I);
246     Instruction *visitShl(BinaryOperator &I);
247     Instruction *visitAShr(BinaryOperator &I);
248     Instruction *visitLShr(BinaryOperator &I);
249     Instruction *commonShiftTransforms(BinaryOperator &I);
250     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
251                                       Constant *RHSC);
252     Instruction *visitFCmpInst(FCmpInst &I);
253     Instruction *visitICmpInst(ICmpInst &I);
254     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
255     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
256                                                 Instruction *LHS,
257                                                 ConstantInt *RHS);
258     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
259                                 ConstantInt *DivRHS);
260
261     Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
262                              ICmpInst::Predicate Cond, Instruction &I);
263     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
264                                      BinaryOperator &I);
265     Instruction *commonCastTransforms(CastInst &CI);
266     Instruction *commonIntCastTransforms(CastInst &CI);
267     Instruction *commonPointerCastTransforms(CastInst &CI);
268     Instruction *visitTrunc(TruncInst &CI);
269     Instruction *visitZExt(ZExtInst &CI);
270     Instruction *visitSExt(SExtInst &CI);
271     Instruction *visitFPTrunc(FPTruncInst &CI);
272     Instruction *visitFPExt(CastInst &CI);
273     Instruction *visitFPToUI(FPToUIInst &FI);
274     Instruction *visitFPToSI(FPToSIInst &FI);
275     Instruction *visitUIToFP(CastInst &CI);
276     Instruction *visitSIToFP(CastInst &CI);
277     Instruction *visitPtrToInt(PtrToIntInst &CI);
278     Instruction *visitIntToPtr(IntToPtrInst &CI);
279     Instruction *visitBitCast(BitCastInst &CI);
280     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
281                                 Instruction *FI);
282     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
283     Instruction *visitSelectInst(SelectInst &SI);
284     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
285     Instruction *visitCallInst(CallInst &CI);
286     Instruction *visitInvokeInst(InvokeInst &II);
287
288     Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
289     Instruction *visitPHINode(PHINode &PN);
290     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
291     Instruction *visitAllocaInst(AllocaInst &AI);
292     Instruction *visitFree(Instruction &FI);
293     Instruction *visitLoadInst(LoadInst &LI);
294     Instruction *visitStoreInst(StoreInst &SI);
295     Instruction *visitBranchInst(BranchInst &BI);
296     Instruction *visitSwitchInst(SwitchInst &SI);
297     Instruction *visitInsertElementInst(InsertElementInst &IE);
298     Instruction *visitExtractElementInst(ExtractElementInst &EI);
299     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
300     Instruction *visitExtractValueInst(ExtractValueInst &EV);
301
302     // visitInstruction - Specify what to return for unhandled instructions...
303     Instruction *visitInstruction(Instruction &I) { return 0; }
304
305   private:
306     Instruction *visitCallSite(CallSite CS);
307     bool transformConstExprCastCall(CallSite CS);
308     Instruction *transformCallThroughTrampoline(CallSite CS);
309     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
310                                    bool DoXform = true);
311     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
312     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
313
314
315   public:
316     // InsertNewInstBefore - insert an instruction New before instruction Old
317     // in the program.  Add the new instruction to the worklist.
318     //
319     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
320       assert(New && New->getParent() == 0 &&
321              "New instruction already inserted into a basic block!");
322       BasicBlock *BB = Old.getParent();
323       BB->getInstList().insert(&Old, New);  // Insert inst
324       Worklist.Add(New);
325       return New;
326     }
327         
328     // ReplaceInstUsesWith - This method is to be used when an instruction is
329     // found to be dead, replacable with another preexisting expression.  Here
330     // we add all uses of I to the worklist, replace all uses of I with the new
331     // value, then return I, so that the inst combiner will know that I was
332     // modified.
333     //
334     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
335       Worklist.AddUsersToWorkList(I);   // Add all modified instrs to worklist.
336       
337       // If we are replacing the instruction with itself, this must be in a
338       // segment of unreachable code, so just clobber the instruction.
339       if (&I == V) 
340         V = UndefValue::get(I.getType());
341         
342       I.replaceAllUsesWith(V);
343       return &I;
344     }
345
346     // EraseInstFromFunction - When dealing with an instruction that has side
347     // effects or produces a void value, we can't rely on DCE to delete the
348     // instruction.  Instead, visit methods should return the value returned by
349     // this function.
350     Instruction *EraseInstFromFunction(Instruction &I) {
351       DEBUG(errs() << "IC: ERASE " << I << '\n');
352
353       assert(I.use_empty() && "Cannot erase instruction that is used!");
354       // Make sure that we reprocess all operands now that we reduced their
355       // use counts.
356       if (I.getNumOperands() < 8) {
357         for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
358           if (Instruction *Op = dyn_cast<Instruction>(*i))
359             Worklist.Add(Op);
360       }
361       Worklist.Remove(&I);
362       I.eraseFromParent();
363       MadeIRChange = true;
364       return 0;  // Don't do anything with FI
365     }
366         
367     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
368                            APInt &KnownOne, unsigned Depth = 0) const {
369       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
370     }
371     
372     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
373                            unsigned Depth = 0) const {
374       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
375     }
376     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
377       return llvm::ComputeNumSignBits(Op, TD, Depth);
378     }
379
380   private:
381
382     /// SimplifyCommutative - This performs a few simplifications for 
383     /// commutative operators.
384     bool SimplifyCommutative(BinaryOperator &I);
385
386     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
387     /// most-complex to least-complex order.
388     bool SimplifyCompare(CmpInst &I);
389
390     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
391     /// based on the demanded bits.
392     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
393                                    APInt& KnownZero, APInt& KnownOne,
394                                    unsigned Depth);
395     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
396                               APInt& KnownZero, APInt& KnownOne,
397                               unsigned Depth=0);
398         
399     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
400     /// SimplifyDemandedBits knows about.  See if the instruction has any
401     /// properties that allow us to simplify its operands.
402     bool SimplifyDemandedInstructionBits(Instruction &Inst);
403         
404     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
405                                       APInt& UndefElts, unsigned Depth = 0);
406       
407     // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
408     // which has a PHI node as operand #0, see if we can fold the instruction
409     // into the PHI (which is only possible if all operands to the PHI are
410     // constants).
411     //
412     // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
413     // that would normally be unprofitable because they strongly encourage jump
414     // threading.
415     Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
416
417     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
418     // operator and they all are only used by the PHI, PHI together their
419     // inputs, and do the operation once, to the result of the PHI.
420     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
421     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
422     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
423     Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
424
425     
426     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
427                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
428     
429     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
430                               bool isSub, Instruction &I);
431     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
432                                  bool isSigned, bool Inside, Instruction &IB);
433     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
434     Instruction *MatchBSwap(BinaryOperator &I);
435     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
436     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
437     Instruction *SimplifyMemSet(MemSetInst *MI);
438
439
440     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
441
442     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
443                                     unsigned CastOpc, int &NumCastsRemoved);
444     unsigned GetOrEnforceKnownAlignment(Value *V,
445                                         unsigned PrefAlign = 0);
446
447   };
448 } // end anonymous namespace
449
450 char InstCombiner::ID = 0;
451 static RegisterPass<InstCombiner>
452 X("instcombine", "Combine redundant instructions");
453
454 // getComplexity:  Assign a complexity or rank value to LLVM Values...
455 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
456 static unsigned getComplexity(Value *V) {
457   if (isa<Instruction>(V)) {
458     if (BinaryOperator::isNeg(V) ||
459         BinaryOperator::isFNeg(V) ||
460         BinaryOperator::isNot(V))
461       return 3;
462     return 4;
463   }
464   if (isa<Argument>(V)) return 3;
465   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
466 }
467
468 // isOnlyUse - Return true if this instruction will be deleted if we stop using
469 // it.
470 static bool isOnlyUse(Value *V) {
471   return V->hasOneUse() || isa<Constant>(V);
472 }
473
474 // getPromotedType - Return the specified type promoted as it would be to pass
475 // though a va_arg area...
476 static const Type *getPromotedType(const Type *Ty) {
477   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
478     if (ITy->getBitWidth() < 32)
479       return Type::getInt32Ty(Ty->getContext());
480   }
481   return Ty;
482 }
483
484 /// getBitCastOperand - If the specified operand is a CastInst, a constant
485 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
486 /// operand value, otherwise return null.
487 static Value *getBitCastOperand(Value *V) {
488   if (Operator *O = dyn_cast<Operator>(V)) {
489     if (O->getOpcode() == Instruction::BitCast)
490       return O->getOperand(0);
491     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
492       if (GEP->hasAllZeroIndices())
493         return GEP->getPointerOperand();
494   }
495   return 0;
496 }
497
498 /// This function is a wrapper around CastInst::isEliminableCastPair. It
499 /// simply extracts arguments and returns what that function returns.
500 static Instruction::CastOps 
501 isEliminableCastPair(
502   const CastInst *CI, ///< The first cast instruction
503   unsigned opcode,       ///< The opcode of the second cast instruction
504   const Type *DstTy,     ///< The target type for the second cast instruction
505   TargetData *TD         ///< The target data for pointer size
506 ) {
507
508   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
509   const Type *MidTy = CI->getType();                  // B from above
510
511   // Get the opcodes of the two Cast instructions
512   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
513   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
514
515   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
516                                                 DstTy,
517                                   TD ? TD->getIntPtrType(CI->getContext()) : 0);
518   
519   // We don't want to form an inttoptr or ptrtoint that converts to an integer
520   // type that differs from the pointer size.
521   if ((Res == Instruction::IntToPtr &&
522           (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
523       (Res == Instruction::PtrToInt &&
524           (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
525     Res = 0;
526   
527   return Instruction::CastOps(Res);
528 }
529
530 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
531 /// in any code being generated.  It does not require codegen if V is simple
532 /// enough or if the cast can be folded into other casts.
533 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
534                               const Type *Ty, TargetData *TD) {
535   if (V->getType() == Ty || isa<Constant>(V)) return false;
536   
537   // If this is another cast that can be eliminated, it isn't codegen either.
538   if (const CastInst *CI = dyn_cast<CastInst>(V))
539     if (isEliminableCastPair(CI, opcode, Ty, TD))
540       return false;
541   return true;
542 }
543
544 // SimplifyCommutative - This performs a few simplifications for commutative
545 // operators:
546 //
547 //  1. Order operands such that they are listed from right (least complex) to
548 //     left (most complex).  This puts constants before unary operators before
549 //     binary operators.
550 //
551 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
552 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
553 //
554 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
555   bool Changed = false;
556   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
557     Changed = !I.swapOperands();
558
559   if (!I.isAssociative()) return Changed;
560   Instruction::BinaryOps Opcode = I.getOpcode();
561   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
562     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
563       if (isa<Constant>(I.getOperand(1))) {
564         Constant *Folded = ConstantExpr::get(I.getOpcode(),
565                                              cast<Constant>(I.getOperand(1)),
566                                              cast<Constant>(Op->getOperand(1)));
567         I.setOperand(0, Op->getOperand(0));
568         I.setOperand(1, Folded);
569         return true;
570       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
571         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
572             isOnlyUse(Op) && isOnlyUse(Op1)) {
573           Constant *C1 = cast<Constant>(Op->getOperand(1));
574           Constant *C2 = cast<Constant>(Op1->getOperand(1));
575
576           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
577           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
578           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
579                                                     Op1->getOperand(0),
580                                                     Op1->getName(), &I);
581           Worklist.Add(New);
582           I.setOperand(0, New);
583           I.setOperand(1, Folded);
584           return true;
585         }
586     }
587   return Changed;
588 }
589
590 /// SimplifyCompare - For a CmpInst this function just orders the operands
591 /// so that theyare listed from right (least complex) to left (most complex).
592 /// This puts constants before unary operators before binary operators.
593 bool InstCombiner::SimplifyCompare(CmpInst &I) {
594   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
595     return false;
596   I.swapOperands();
597   // Compare instructions are not associative so there's nothing else we can do.
598   return true;
599 }
600
601 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
602 // if the LHS is a constant zero (which is the 'negate' form).
603 //
604 static inline Value *dyn_castNegVal(Value *V) {
605   if (BinaryOperator::isNeg(V))
606     return BinaryOperator::getNegArgument(V);
607
608   // Constants can be considered to be negated values if they can be folded.
609   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
610     return ConstantExpr::getNeg(C);
611
612   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
613     if (C->getType()->getElementType()->isInteger())
614       return ConstantExpr::getNeg(C);
615
616   return 0;
617 }
618
619 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
620 // instruction if the LHS is a constant negative zero (which is the 'negate'
621 // form).
622 //
623 static inline Value *dyn_castFNegVal(Value *V) {
624   if (BinaryOperator::isFNeg(V))
625     return BinaryOperator::getFNegArgument(V);
626
627   // Constants can be considered to be negated values if they can be folded.
628   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
629     return ConstantExpr::getFNeg(C);
630
631   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
632     if (C->getType()->getElementType()->isFloatingPoint())
633       return ConstantExpr::getFNeg(C);
634
635   return 0;
636 }
637
638 /// isFreeToInvert - Return true if the specified value is free to invert (apply
639 /// ~ to).  This happens in cases where the ~ can be eliminated.
640 static inline bool isFreeToInvert(Value *V) {
641   // ~(~(X)) -> X.
642   if (BinaryOperator::isNot(V))
643     return true;
644   
645   // Constants can be considered to be not'ed values.
646   if (isa<ConstantInt>(V))
647     return true;
648   
649   // Compares can be inverted if they have a single use.
650   if (CmpInst *CI = dyn_cast<CmpInst>(V))
651     return CI->hasOneUse();
652   
653   return false;
654 }
655
656 static inline Value *dyn_castNotVal(Value *V) {
657   // If this is not(not(x)) don't return that this is a not: we want the two
658   // not's to be folded first.
659   if (BinaryOperator::isNot(V)) {
660     Value *Operand = BinaryOperator::getNotArgument(V);
661     if (!isFreeToInvert(Operand))
662       return Operand;
663   }
664
665   // Constants can be considered to be not'ed values...
666   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
667     return ConstantInt::get(C->getType(), ~C->getValue());
668   return 0;
669 }
670
671
672
673 // dyn_castFoldableMul - If this value is a multiply that can be folded into
674 // other computations (because it has a constant operand), return the
675 // non-constant operand of the multiply, and set CST to point to the multiplier.
676 // Otherwise, return null.
677 //
678 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
679   if (V->hasOneUse() && V->getType()->isInteger())
680     if (Instruction *I = dyn_cast<Instruction>(V)) {
681       if (I->getOpcode() == Instruction::Mul)
682         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
683           return I->getOperand(0);
684       if (I->getOpcode() == Instruction::Shl)
685         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
686           // The multiplier is really 1 << CST.
687           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
688           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
689           CST = ConstantInt::get(V->getType()->getContext(),
690                                  APInt(BitWidth, 1).shl(CSTVal));
691           return I->getOperand(0);
692         }
693     }
694   return 0;
695 }
696
697 /// AddOne - Add one to a ConstantInt
698 static Constant *AddOne(Constant *C) {
699   return ConstantExpr::getAdd(C, 
700     ConstantInt::get(C->getType(), 1));
701 }
702 /// SubOne - Subtract one from a ConstantInt
703 static Constant *SubOne(ConstantInt *C) {
704   return ConstantExpr::getSub(C, 
705     ConstantInt::get(C->getType(), 1));
706 }
707 /// MultiplyOverflows - True if the multiply can not be expressed in an int
708 /// this size.
709 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
710   uint32_t W = C1->getBitWidth();
711   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
712   if (sign) {
713     LHSExt.sext(W * 2);
714     RHSExt.sext(W * 2);
715   } else {
716     LHSExt.zext(W * 2);
717     RHSExt.zext(W * 2);
718   }
719
720   APInt MulExt = LHSExt * RHSExt;
721
722   if (sign) {
723     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
724     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
725     return MulExt.slt(Min) || MulExt.sgt(Max);
726   } else 
727     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
728 }
729
730
731 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
732 /// specified instruction is a constant integer.  If so, check to see if there
733 /// are any bits set in the constant that are not demanded.  If so, shrink the
734 /// constant and return true.
735 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
736                                    APInt Demanded) {
737   assert(I && "No instruction?");
738   assert(OpNo < I->getNumOperands() && "Operand index too large");
739
740   // If the operand is not a constant integer, nothing to do.
741   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
742   if (!OpC) return false;
743
744   // If there are no bits set that aren't demanded, nothing to do.
745   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
746   if ((~Demanded & OpC->getValue()) == 0)
747     return false;
748
749   // This instruction is producing bits that are not demanded. Shrink the RHS.
750   Demanded &= OpC->getValue();
751   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
752   return true;
753 }
754
755 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
756 // set of known zero and one bits, compute the maximum and minimum values that
757 // could have the specified known zero and known one bits, returning them in
758 // min/max.
759 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
760                                                    const APInt& KnownOne,
761                                                    APInt& Min, APInt& Max) {
762   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
763          KnownZero.getBitWidth() == Min.getBitWidth() &&
764          KnownZero.getBitWidth() == Max.getBitWidth() &&
765          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
766   APInt UnknownBits = ~(KnownZero|KnownOne);
767
768   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
769   // bit if it is unknown.
770   Min = KnownOne;
771   Max = KnownOne|UnknownBits;
772   
773   if (UnknownBits.isNegative()) { // Sign bit is unknown
774     Min.set(Min.getBitWidth()-1);
775     Max.clear(Max.getBitWidth()-1);
776   }
777 }
778
779 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
780 // a set of known zero and one bits, compute the maximum and minimum values that
781 // could have the specified known zero and known one bits, returning them in
782 // min/max.
783 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
784                                                      const APInt &KnownOne,
785                                                      APInt &Min, APInt &Max) {
786   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
787          KnownZero.getBitWidth() == Min.getBitWidth() &&
788          KnownZero.getBitWidth() == Max.getBitWidth() &&
789          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
790   APInt UnknownBits = ~(KnownZero|KnownOne);
791   
792   // The minimum value is when the unknown bits are all zeros.
793   Min = KnownOne;
794   // The maximum value is when the unknown bits are all ones.
795   Max = KnownOne|UnknownBits;
796 }
797
798 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
799 /// SimplifyDemandedBits knows about.  See if the instruction has any
800 /// properties that allow us to simplify its operands.
801 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
802   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
803   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
804   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
805   
806   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
807                                      KnownZero, KnownOne, 0);
808   if (V == 0) return false;
809   if (V == &Inst) return true;
810   ReplaceInstUsesWith(Inst, V);
811   return true;
812 }
813
814 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
815 /// specified instruction operand if possible, updating it in place.  It returns
816 /// true if it made any change and false otherwise.
817 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
818                                         APInt &KnownZero, APInt &KnownOne,
819                                         unsigned Depth) {
820   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
821                                           KnownZero, KnownOne, Depth);
822   if (NewVal == 0) return false;
823   U = NewVal;
824   return true;
825 }
826
827
828 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
829 /// value based on the demanded bits.  When this function is called, it is known
830 /// that only the bits set in DemandedMask of the result of V are ever used
831 /// downstream. Consequently, depending on the mask and V, it may be possible
832 /// to replace V with a constant or one of its operands. In such cases, this
833 /// function does the replacement and returns true. In all other cases, it
834 /// returns false after analyzing the expression and setting KnownOne and known
835 /// to be one in the expression.  KnownZero contains all the bits that are known
836 /// to be zero in the expression. These are provided to potentially allow the
837 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
838 /// the expression. KnownOne and KnownZero always follow the invariant that 
839 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
840 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
841 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
842 /// and KnownOne must all be the same.
843 ///
844 /// This returns null if it did not change anything and it permits no
845 /// simplification.  This returns V itself if it did some simplification of V's
846 /// operands based on the information about what bits are demanded. This returns
847 /// some other non-null value if it found out that V is equal to another value
848 /// in the context where the specified bits are demanded, but not for all users.
849 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
850                                              APInt &KnownZero, APInt &KnownOne,
851                                              unsigned Depth) {
852   assert(V != 0 && "Null pointer of Value???");
853   assert(Depth <= 6 && "Limit Search Depth");
854   uint32_t BitWidth = DemandedMask.getBitWidth();
855   const Type *VTy = V->getType();
856   assert((TD || !isa<PointerType>(VTy)) &&
857          "SimplifyDemandedBits needs to know bit widths!");
858   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
859          (!VTy->isIntOrIntVector() ||
860           VTy->getScalarSizeInBits() == BitWidth) &&
861          KnownZero.getBitWidth() == BitWidth &&
862          KnownOne.getBitWidth() == BitWidth &&
863          "Value *V, DemandedMask, KnownZero and KnownOne "
864          "must have same BitWidth");
865   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
866     // We know all of the bits for a constant!
867     KnownOne = CI->getValue() & DemandedMask;
868     KnownZero = ~KnownOne & DemandedMask;
869     return 0;
870   }
871   if (isa<ConstantPointerNull>(V)) {
872     // We know all of the bits for a constant!
873     KnownOne.clear();
874     KnownZero = DemandedMask;
875     return 0;
876   }
877
878   KnownZero.clear();
879   KnownOne.clear();
880   if (DemandedMask == 0) {   // Not demanding any bits from V.
881     if (isa<UndefValue>(V))
882       return 0;
883     return UndefValue::get(VTy);
884   }
885   
886   if (Depth == 6)        // Limit search depth.
887     return 0;
888   
889   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
890   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
891
892   Instruction *I = dyn_cast<Instruction>(V);
893   if (!I) {
894     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
895     return 0;        // Only analyze instructions.
896   }
897
898   // If there are multiple uses of this value and we aren't at the root, then
899   // we can't do any simplifications of the operands, because DemandedMask
900   // only reflects the bits demanded by *one* of the users.
901   if (Depth != 0 && !I->hasOneUse()) {
902     // Despite the fact that we can't simplify this instruction in all User's
903     // context, we can at least compute the knownzero/knownone bits, and we can
904     // do simplifications that apply to *just* the one user if we know that
905     // this instruction has a simpler value in that context.
906     if (I->getOpcode() == Instruction::And) {
907       // If either the LHS or the RHS are Zero, the result is zero.
908       ComputeMaskedBits(I->getOperand(1), DemandedMask,
909                         RHSKnownZero, RHSKnownOne, Depth+1);
910       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
911                         LHSKnownZero, LHSKnownOne, Depth+1);
912       
913       // If all of the demanded bits are known 1 on one side, return the other.
914       // These bits cannot contribute to the result of the 'and' in this
915       // context.
916       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
917           (DemandedMask & ~LHSKnownZero))
918         return I->getOperand(0);
919       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
920           (DemandedMask & ~RHSKnownZero))
921         return I->getOperand(1);
922       
923       // If all of the demanded bits in the inputs are known zeros, return zero.
924       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
925         return Constant::getNullValue(VTy);
926       
927     } else if (I->getOpcode() == Instruction::Or) {
928       // We can simplify (X|Y) -> X or Y in the user's context if we know that
929       // only bits from X or Y are demanded.
930       
931       // If either the LHS or the RHS are One, the result is One.
932       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
933                         RHSKnownZero, RHSKnownOne, Depth+1);
934       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
935                         LHSKnownZero, LHSKnownOne, Depth+1);
936       
937       // If all of the demanded bits are known zero on one side, return the
938       // other.  These bits cannot contribute to the result of the 'or' in this
939       // context.
940       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
941           (DemandedMask & ~LHSKnownOne))
942         return I->getOperand(0);
943       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
944           (DemandedMask & ~RHSKnownOne))
945         return I->getOperand(1);
946       
947       // If all of the potentially set bits on one side are known to be set on
948       // the other side, just use the 'other' side.
949       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
950           (DemandedMask & (~RHSKnownZero)))
951         return I->getOperand(0);
952       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
953           (DemandedMask & (~LHSKnownZero)))
954         return I->getOperand(1);
955     }
956     
957     // Compute the KnownZero/KnownOne bits to simplify things downstream.
958     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
959     return 0;
960   }
961   
962   // If this is the root being simplified, allow it to have multiple uses,
963   // just set the DemandedMask to all bits so that we can try to simplify the
964   // operands.  This allows visitTruncInst (for example) to simplify the
965   // operand of a trunc without duplicating all the logic below.
966   if (Depth == 0 && !V->hasOneUse())
967     DemandedMask = APInt::getAllOnesValue(BitWidth);
968   
969   switch (I->getOpcode()) {
970   default:
971     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
972     break;
973   case Instruction::And:
974     // If either the LHS or the RHS are Zero, the result is zero.
975     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
976                              RHSKnownZero, RHSKnownOne, Depth+1) ||
977         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
978                              LHSKnownZero, LHSKnownOne, Depth+1))
979       return I;
980     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
981     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
982
983     // If all of the demanded bits are known 1 on one side, return the other.
984     // These bits cannot contribute to the result of the 'and'.
985     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
986         (DemandedMask & ~LHSKnownZero))
987       return I->getOperand(0);
988     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
989         (DemandedMask & ~RHSKnownZero))
990       return I->getOperand(1);
991     
992     // If all of the demanded bits in the inputs are known zeros, return zero.
993     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
994       return Constant::getNullValue(VTy);
995       
996     // If the RHS is a constant, see if we can simplify it.
997     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
998       return I;
999       
1000     // Output known-1 bits are only known if set in both the LHS & RHS.
1001     RHSKnownOne &= LHSKnownOne;
1002     // Output known-0 are known to be clear if zero in either the LHS | RHS.
1003     RHSKnownZero |= LHSKnownZero;
1004     break;
1005   case Instruction::Or:
1006     // If either the LHS or the RHS are One, the result is One.
1007     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1008                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1009         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
1010                              LHSKnownZero, LHSKnownOne, Depth+1))
1011       return I;
1012     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1013     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1014     
1015     // If all of the demanded bits are known zero on one side, return the other.
1016     // These bits cannot contribute to the result of the 'or'.
1017     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
1018         (DemandedMask & ~LHSKnownOne))
1019       return I->getOperand(0);
1020     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
1021         (DemandedMask & ~RHSKnownOne))
1022       return I->getOperand(1);
1023
1024     // If all of the potentially set bits on one side are known to be set on
1025     // the other side, just use the 'other' side.
1026     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
1027         (DemandedMask & (~RHSKnownZero)))
1028       return I->getOperand(0);
1029     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1030         (DemandedMask & (~LHSKnownZero)))
1031       return I->getOperand(1);
1032         
1033     // If the RHS is a constant, see if we can simplify it.
1034     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1035       return I;
1036           
1037     // Output known-0 bits are only known if clear in both the LHS & RHS.
1038     RHSKnownZero &= LHSKnownZero;
1039     // Output known-1 are known to be set if set in either the LHS | RHS.
1040     RHSKnownOne |= LHSKnownOne;
1041     break;
1042   case Instruction::Xor: {
1043     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1044                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1045         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1046                              LHSKnownZero, LHSKnownOne, Depth+1))
1047       return I;
1048     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1049     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1050     
1051     // If all of the demanded bits are known zero on one side, return the other.
1052     // These bits cannot contribute to the result of the 'xor'.
1053     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1054       return I->getOperand(0);
1055     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1056       return I->getOperand(1);
1057     
1058     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1059     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1060                          (RHSKnownOne & LHSKnownOne);
1061     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1062     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1063                         (RHSKnownOne & LHSKnownZero);
1064     
1065     // If all of the demanded bits are known to be zero on one side or the
1066     // other, turn this into an *inclusive* or.
1067     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1068     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1069       Instruction *Or = 
1070         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1071                                  I->getName());
1072       return InsertNewInstBefore(Or, *I);
1073     }
1074     
1075     // If all of the demanded bits on one side are known, and all of the set
1076     // bits on that side are also known to be set on the other side, turn this
1077     // into an AND, as we know the bits will be cleared.
1078     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1079     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1080       // all known
1081       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1082         Constant *AndC = Constant::getIntegerValue(VTy,
1083                                                    ~RHSKnownOne & DemandedMask);
1084         Instruction *And = 
1085           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1086         return InsertNewInstBefore(And, *I);
1087       }
1088     }
1089     
1090     // If the RHS is a constant, see if we can simplify it.
1091     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1092     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1093       return I;
1094     
1095     // If our LHS is an 'and' and if it has one use, and if any of the bits we
1096     // are flipping are known to be set, then the xor is just resetting those
1097     // bits to zero.  We can just knock out bits from the 'and' and the 'xor',
1098     // simplifying both of them.
1099     if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1100       if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1101           isa<ConstantInt>(I->getOperand(1)) &&
1102           isa<ConstantInt>(LHSInst->getOperand(1)) &&
1103           (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1104         ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1105         ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1106         APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1107         
1108         Constant *AndC =
1109           ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1110         Instruction *NewAnd = 
1111           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1112         InsertNewInstBefore(NewAnd, *I);
1113         
1114         Constant *XorC =
1115           ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1116         Instruction *NewXor =
1117           BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1118         return InsertNewInstBefore(NewXor, *I);
1119       }
1120           
1121           
1122     RHSKnownZero = KnownZeroOut;
1123     RHSKnownOne  = KnownOneOut;
1124     break;
1125   }
1126   case Instruction::Select:
1127     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1128                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1129         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1130                              LHSKnownZero, LHSKnownOne, Depth+1))
1131       return I;
1132     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1133     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1134     
1135     // If the operands are constants, see if we can simplify them.
1136     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1137         ShrinkDemandedConstant(I, 2, DemandedMask))
1138       return I;
1139     
1140     // Only known if known in both the LHS and RHS.
1141     RHSKnownOne &= LHSKnownOne;
1142     RHSKnownZero &= LHSKnownZero;
1143     break;
1144   case Instruction::Trunc: {
1145     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1146     DemandedMask.zext(truncBf);
1147     RHSKnownZero.zext(truncBf);
1148     RHSKnownOne.zext(truncBf);
1149     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1150                              RHSKnownZero, RHSKnownOne, Depth+1))
1151       return I;
1152     DemandedMask.trunc(BitWidth);
1153     RHSKnownZero.trunc(BitWidth);
1154     RHSKnownOne.trunc(BitWidth);
1155     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1156     break;
1157   }
1158   case Instruction::BitCast:
1159     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1160       return false;  // vector->int or fp->int?
1161
1162     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1163       if (const VectorType *SrcVTy =
1164             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1165         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1166           // Don't touch a bitcast between vectors of different element counts.
1167           return false;
1168       } else
1169         // Don't touch a scalar-to-vector bitcast.
1170         return false;
1171     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1172       // Don't touch a vector-to-scalar bitcast.
1173       return false;
1174
1175     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1176                              RHSKnownZero, RHSKnownOne, Depth+1))
1177       return I;
1178     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1179     break;
1180   case Instruction::ZExt: {
1181     // Compute the bits in the result that are not present in the input.
1182     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1183     
1184     DemandedMask.trunc(SrcBitWidth);
1185     RHSKnownZero.trunc(SrcBitWidth);
1186     RHSKnownOne.trunc(SrcBitWidth);
1187     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1188                              RHSKnownZero, RHSKnownOne, Depth+1))
1189       return I;
1190     DemandedMask.zext(BitWidth);
1191     RHSKnownZero.zext(BitWidth);
1192     RHSKnownOne.zext(BitWidth);
1193     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1194     // The top bits are known to be zero.
1195     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1196     break;
1197   }
1198   case Instruction::SExt: {
1199     // Compute the bits in the result that are not present in the input.
1200     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1201     
1202     APInt InputDemandedBits = DemandedMask & 
1203                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1204
1205     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1206     // If any of the sign extended bits are demanded, we know that the sign
1207     // bit is demanded.
1208     if ((NewBits & DemandedMask) != 0)
1209       InputDemandedBits.set(SrcBitWidth-1);
1210       
1211     InputDemandedBits.trunc(SrcBitWidth);
1212     RHSKnownZero.trunc(SrcBitWidth);
1213     RHSKnownOne.trunc(SrcBitWidth);
1214     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1215                              RHSKnownZero, RHSKnownOne, Depth+1))
1216       return I;
1217     InputDemandedBits.zext(BitWidth);
1218     RHSKnownZero.zext(BitWidth);
1219     RHSKnownOne.zext(BitWidth);
1220     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1221       
1222     // If the sign bit of the input is known set or clear, then we know the
1223     // top bits of the result.
1224
1225     // If the input sign bit is known zero, or if the NewBits are not demanded
1226     // convert this into a zero extension.
1227     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1228       // Convert to ZExt cast
1229       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1230       return InsertNewInstBefore(NewCast, *I);
1231     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1232       RHSKnownOne |= NewBits;
1233     }
1234     break;
1235   }
1236   case Instruction::Add: {
1237     // Figure out what the input bits are.  If the top bits of the and result
1238     // are not demanded, then the add doesn't demand them from its input
1239     // either.
1240     unsigned NLZ = DemandedMask.countLeadingZeros();
1241       
1242     // If there is a constant on the RHS, there are a variety of xformations
1243     // we can do.
1244     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1245       // If null, this should be simplified elsewhere.  Some of the xforms here
1246       // won't work if the RHS is zero.
1247       if (RHS->isZero())
1248         break;
1249       
1250       // If the top bit of the output is demanded, demand everything from the
1251       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1252       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1253
1254       // Find information about known zero/one bits in the input.
1255       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1256                                LHSKnownZero, LHSKnownOne, Depth+1))
1257         return I;
1258
1259       // If the RHS of the add has bits set that can't affect the input, reduce
1260       // the constant.
1261       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1262         return I;
1263       
1264       // Avoid excess work.
1265       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1266         break;
1267       
1268       // Turn it into OR if input bits are zero.
1269       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1270         Instruction *Or =
1271           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1272                                    I->getName());
1273         return InsertNewInstBefore(Or, *I);
1274       }
1275       
1276       // We can say something about the output known-zero and known-one bits,
1277       // depending on potential carries from the input constant and the
1278       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1279       // bits set and the RHS constant is 0x01001, then we know we have a known
1280       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1281       
1282       // To compute this, we first compute the potential carry bits.  These are
1283       // the bits which may be modified.  I'm not aware of a better way to do
1284       // this scan.
1285       const APInt &RHSVal = RHS->getValue();
1286       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1287       
1288       // Now that we know which bits have carries, compute the known-1/0 sets.
1289       
1290       // Bits are known one if they are known zero in one operand and one in the
1291       // other, and there is no input carry.
1292       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1293                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1294       
1295       // Bits are known zero if they are known zero in both operands and there
1296       // is no input carry.
1297       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1298     } else {
1299       // If the high-bits of this ADD are not demanded, then it does not demand
1300       // the high bits of its LHS or RHS.
1301       if (DemandedMask[BitWidth-1] == 0) {
1302         // Right fill the mask of bits for this ADD to demand the most
1303         // significant bit and all those below it.
1304         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1305         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1306                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1307             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1308                                  LHSKnownZero, LHSKnownOne, Depth+1))
1309           return I;
1310       }
1311     }
1312     break;
1313   }
1314   case Instruction::Sub:
1315     // If the high-bits of this SUB are not demanded, then it does not demand
1316     // the high bits of its LHS or RHS.
1317     if (DemandedMask[BitWidth-1] == 0) {
1318       // Right fill the mask of bits for this SUB to demand the most
1319       // significant bit and all those below it.
1320       uint32_t NLZ = DemandedMask.countLeadingZeros();
1321       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1322       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1323                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1324           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1325                                LHSKnownZero, LHSKnownOne, Depth+1))
1326         return I;
1327     }
1328     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1329     // the known zeros and ones.
1330     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1331     break;
1332   case Instruction::Shl:
1333     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1334       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1335       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1336       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1337                                RHSKnownZero, RHSKnownOne, Depth+1))
1338         return I;
1339       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1340       RHSKnownZero <<= ShiftAmt;
1341       RHSKnownOne  <<= ShiftAmt;
1342       // low bits known zero.
1343       if (ShiftAmt)
1344         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1345     }
1346     break;
1347   case Instruction::LShr:
1348     // For a logical shift right
1349     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1350       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1351       
1352       // Unsigned shift right.
1353       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1354       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1355                                RHSKnownZero, RHSKnownOne, Depth+1))
1356         return I;
1357       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1358       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1359       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1360       if (ShiftAmt) {
1361         // Compute the new bits that are at the top now.
1362         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1363         RHSKnownZero |= HighBits;  // high bits known zero.
1364       }
1365     }
1366     break;
1367   case Instruction::AShr:
1368     // If this is an arithmetic shift right and only the low-bit is set, we can
1369     // always convert this into a logical shr, even if the shift amount is
1370     // variable.  The low bit of the shift cannot be an input sign bit unless
1371     // the shift amount is >= the size of the datatype, which is undefined.
1372     if (DemandedMask == 1) {
1373       // Perform the logical shift right.
1374       Instruction *NewVal = BinaryOperator::CreateLShr(
1375                         I->getOperand(0), I->getOperand(1), I->getName());
1376       return InsertNewInstBefore(NewVal, *I);
1377     }    
1378
1379     // If the sign bit is the only bit demanded by this ashr, then there is no
1380     // need to do it, the shift doesn't change the high bit.
1381     if (DemandedMask.isSignBit())
1382       return I->getOperand(0);
1383     
1384     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1385       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1386       
1387       // Signed shift right.
1388       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1389       // If any of the "high bits" are demanded, we should set the sign bit as
1390       // demanded.
1391       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1392         DemandedMaskIn.set(BitWidth-1);
1393       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1394                                RHSKnownZero, RHSKnownOne, Depth+1))
1395         return I;
1396       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1397       // Compute the new bits that are at the top now.
1398       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1399       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1400       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1401         
1402       // Handle the sign bits.
1403       APInt SignBit(APInt::getSignBit(BitWidth));
1404       // Adjust to where it is now in the mask.
1405       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1406         
1407       // If the input sign bit is known to be zero, or if none of the top bits
1408       // are demanded, turn this into an unsigned shift right.
1409       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1410           (HighBits & ~DemandedMask) == HighBits) {
1411         // Perform the logical shift right.
1412         Instruction *NewVal = BinaryOperator::CreateLShr(
1413                           I->getOperand(0), SA, I->getName());
1414         return InsertNewInstBefore(NewVal, *I);
1415       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1416         RHSKnownOne |= HighBits;
1417       }
1418     }
1419     break;
1420   case Instruction::SRem:
1421     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1422       APInt RA = Rem->getValue().abs();
1423       if (RA.isPowerOf2()) {
1424         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1425           return I->getOperand(0);
1426
1427         APInt LowBits = RA - 1;
1428         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1429         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1430                                  LHSKnownZero, LHSKnownOne, Depth+1))
1431           return I;
1432
1433         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1434           LHSKnownZero |= ~LowBits;
1435
1436         KnownZero |= LHSKnownZero & DemandedMask;
1437
1438         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1439       }
1440     }
1441     break;
1442   case Instruction::URem: {
1443     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1444     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1445     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1446                              KnownZero2, KnownOne2, Depth+1) ||
1447         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1448                              KnownZero2, KnownOne2, Depth+1))
1449       return I;
1450
1451     unsigned Leaders = KnownZero2.countLeadingOnes();
1452     Leaders = std::max(Leaders,
1453                        KnownZero2.countLeadingOnes());
1454     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1455     break;
1456   }
1457   case Instruction::Call:
1458     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1459       switch (II->getIntrinsicID()) {
1460       default: break;
1461       case Intrinsic::bswap: {
1462         // If the only bits demanded come from one byte of the bswap result,
1463         // just shift the input byte into position to eliminate the bswap.
1464         unsigned NLZ = DemandedMask.countLeadingZeros();
1465         unsigned NTZ = DemandedMask.countTrailingZeros();
1466           
1467         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1468         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1469         // have 14 leading zeros, round to 8.
1470         NLZ &= ~7;
1471         NTZ &= ~7;
1472         // If we need exactly one byte, we can do this transformation.
1473         if (BitWidth-NLZ-NTZ == 8) {
1474           unsigned ResultBit = NTZ;
1475           unsigned InputBit = BitWidth-NTZ-8;
1476           
1477           // Replace this with either a left or right shift to get the byte into
1478           // the right place.
1479           Instruction *NewVal;
1480           if (InputBit > ResultBit)
1481             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1482                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1483           else
1484             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1485                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1486           NewVal->takeName(I);
1487           return InsertNewInstBefore(NewVal, *I);
1488         }
1489           
1490         // TODO: Could compute known zero/one bits based on the input.
1491         break;
1492       }
1493       }
1494     }
1495     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1496     break;
1497   }
1498   
1499   // If the client is only demanding bits that we know, return the known
1500   // constant.
1501   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1502     return Constant::getIntegerValue(VTy, RHSKnownOne);
1503   return false;
1504 }
1505
1506
1507 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1508 /// any number of elements. DemandedElts contains the set of elements that are
1509 /// actually used by the caller.  This method analyzes which elements of the
1510 /// operand are undef and returns that information in UndefElts.
1511 ///
1512 /// If the information about demanded elements can be used to simplify the
1513 /// operation, the operation is simplified, then the resultant value is
1514 /// returned.  This returns null if no change was made.
1515 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1516                                                 APInt& UndefElts,
1517                                                 unsigned Depth) {
1518   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1519   APInt EltMask(APInt::getAllOnesValue(VWidth));
1520   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1521
1522   if (isa<UndefValue>(V)) {
1523     // If the entire vector is undefined, just return this info.
1524     UndefElts = EltMask;
1525     return 0;
1526   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1527     UndefElts = EltMask;
1528     return UndefValue::get(V->getType());
1529   }
1530
1531   UndefElts = 0;
1532   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1533     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1534     Constant *Undef = UndefValue::get(EltTy);
1535
1536     std::vector<Constant*> Elts;
1537     for (unsigned i = 0; i != VWidth; ++i)
1538       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1539         Elts.push_back(Undef);
1540         UndefElts.set(i);
1541       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1542         Elts.push_back(Undef);
1543         UndefElts.set(i);
1544       } else {                               // Otherwise, defined.
1545         Elts.push_back(CP->getOperand(i));
1546       }
1547
1548     // If we changed the constant, return it.
1549     Constant *NewCP = ConstantVector::get(Elts);
1550     return NewCP != CP ? NewCP : 0;
1551   } else if (isa<ConstantAggregateZero>(V)) {
1552     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1553     // set to undef.
1554     
1555     // Check if this is identity. If so, return 0 since we are not simplifying
1556     // anything.
1557     if (DemandedElts == ((1ULL << VWidth) -1))
1558       return 0;
1559     
1560     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1561     Constant *Zero = Constant::getNullValue(EltTy);
1562     Constant *Undef = UndefValue::get(EltTy);
1563     std::vector<Constant*> Elts;
1564     for (unsigned i = 0; i != VWidth; ++i) {
1565       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1566       Elts.push_back(Elt);
1567     }
1568     UndefElts = DemandedElts ^ EltMask;
1569     return ConstantVector::get(Elts);
1570   }
1571   
1572   // Limit search depth.
1573   if (Depth == 10)
1574     return 0;
1575
1576   // If multiple users are using the root value, procede with
1577   // simplification conservatively assuming that all elements
1578   // are needed.
1579   if (!V->hasOneUse()) {
1580     // Quit if we find multiple users of a non-root value though.
1581     // They'll be handled when it's their turn to be visited by
1582     // the main instcombine process.
1583     if (Depth != 0)
1584       // TODO: Just compute the UndefElts information recursively.
1585       return 0;
1586
1587     // Conservatively assume that all elements are needed.
1588     DemandedElts = EltMask;
1589   }
1590   
1591   Instruction *I = dyn_cast<Instruction>(V);
1592   if (!I) return 0;        // Only analyze instructions.
1593   
1594   bool MadeChange = false;
1595   APInt UndefElts2(VWidth, 0);
1596   Value *TmpV;
1597   switch (I->getOpcode()) {
1598   default: break;
1599     
1600   case Instruction::InsertElement: {
1601     // If this is a variable index, we don't know which element it overwrites.
1602     // demand exactly the same input as we produce.
1603     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1604     if (Idx == 0) {
1605       // Note that we can't propagate undef elt info, because we don't know
1606       // which elt is getting updated.
1607       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1608                                         UndefElts2, Depth+1);
1609       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1610       break;
1611     }
1612     
1613     // If this is inserting an element that isn't demanded, remove this
1614     // insertelement.
1615     unsigned IdxNo = Idx->getZExtValue();
1616     if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1617       Worklist.Add(I);
1618       return I->getOperand(0);
1619     }
1620     
1621     // Otherwise, the element inserted overwrites whatever was there, so the
1622     // input demanded set is simpler than the output set.
1623     APInt DemandedElts2 = DemandedElts;
1624     DemandedElts2.clear(IdxNo);
1625     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1626                                       UndefElts, Depth+1);
1627     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1628
1629     // The inserted element is defined.
1630     UndefElts.clear(IdxNo);
1631     break;
1632   }
1633   case Instruction::ShuffleVector: {
1634     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1635     uint64_t LHSVWidth =
1636       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1637     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1638     for (unsigned i = 0; i < VWidth; i++) {
1639       if (DemandedElts[i]) {
1640         unsigned MaskVal = Shuffle->getMaskValue(i);
1641         if (MaskVal != -1u) {
1642           assert(MaskVal < LHSVWidth * 2 &&
1643                  "shufflevector mask index out of range!");
1644           if (MaskVal < LHSVWidth)
1645             LeftDemanded.set(MaskVal);
1646           else
1647             RightDemanded.set(MaskVal - LHSVWidth);
1648         }
1649       }
1650     }
1651
1652     APInt UndefElts4(LHSVWidth, 0);
1653     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1654                                       UndefElts4, Depth+1);
1655     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1656
1657     APInt UndefElts3(LHSVWidth, 0);
1658     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1659                                       UndefElts3, Depth+1);
1660     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1661
1662     bool NewUndefElts = false;
1663     for (unsigned i = 0; i < VWidth; i++) {
1664       unsigned MaskVal = Shuffle->getMaskValue(i);
1665       if (MaskVal == -1u) {
1666         UndefElts.set(i);
1667       } else if (MaskVal < LHSVWidth) {
1668         if (UndefElts4[MaskVal]) {
1669           NewUndefElts = true;
1670           UndefElts.set(i);
1671         }
1672       } else {
1673         if (UndefElts3[MaskVal - LHSVWidth]) {
1674           NewUndefElts = true;
1675           UndefElts.set(i);
1676         }
1677       }
1678     }
1679
1680     if (NewUndefElts) {
1681       // Add additional discovered undefs.
1682       std::vector<Constant*> Elts;
1683       for (unsigned i = 0; i < VWidth; ++i) {
1684         if (UndefElts[i])
1685           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
1686         else
1687           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
1688                                           Shuffle->getMaskValue(i)));
1689       }
1690       I->setOperand(2, ConstantVector::get(Elts));
1691       MadeChange = true;
1692     }
1693     break;
1694   }
1695   case Instruction::BitCast: {
1696     // Vector->vector casts only.
1697     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1698     if (!VTy) break;
1699     unsigned InVWidth = VTy->getNumElements();
1700     APInt InputDemandedElts(InVWidth, 0);
1701     unsigned Ratio;
1702
1703     if (VWidth == InVWidth) {
1704       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1705       // elements as are demanded of us.
1706       Ratio = 1;
1707       InputDemandedElts = DemandedElts;
1708     } else if (VWidth > InVWidth) {
1709       // Untested so far.
1710       break;
1711       
1712       // If there are more elements in the result than there are in the source,
1713       // then an input element is live if any of the corresponding output
1714       // elements are live.
1715       Ratio = VWidth/InVWidth;
1716       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1717         if (DemandedElts[OutIdx])
1718           InputDemandedElts.set(OutIdx/Ratio);
1719       }
1720     } else {
1721       // Untested so far.
1722       break;
1723       
1724       // If there are more elements in the source than there are in the result,
1725       // then an input element is live if the corresponding output element is
1726       // live.
1727       Ratio = InVWidth/VWidth;
1728       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1729         if (DemandedElts[InIdx/Ratio])
1730           InputDemandedElts.set(InIdx);
1731     }
1732     
1733     // div/rem demand all inputs, because they don't want divide by zero.
1734     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1735                                       UndefElts2, Depth+1);
1736     if (TmpV) {
1737       I->setOperand(0, TmpV);
1738       MadeChange = true;
1739     }
1740     
1741     UndefElts = UndefElts2;
1742     if (VWidth > InVWidth) {
1743       llvm_unreachable("Unimp");
1744       // If there are more elements in the result than there are in the source,
1745       // then an output element is undef if the corresponding input element is
1746       // undef.
1747       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1748         if (UndefElts2[OutIdx/Ratio])
1749           UndefElts.set(OutIdx);
1750     } else if (VWidth < InVWidth) {
1751       llvm_unreachable("Unimp");
1752       // If there are more elements in the source than there are in the result,
1753       // then a result element is undef if all of the corresponding input
1754       // elements are undef.
1755       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1756       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1757         if (!UndefElts2[InIdx])            // Not undef?
1758           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1759     }
1760     break;
1761   }
1762   case Instruction::And:
1763   case Instruction::Or:
1764   case Instruction::Xor:
1765   case Instruction::Add:
1766   case Instruction::Sub:
1767   case Instruction::Mul:
1768     // div/rem demand all inputs, because they don't want divide by zero.
1769     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1770                                       UndefElts, Depth+1);
1771     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1772     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1773                                       UndefElts2, Depth+1);
1774     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1775       
1776     // Output elements are undefined if both are undefined.  Consider things
1777     // like undef&0.  The result is known zero, not undef.
1778     UndefElts &= UndefElts2;
1779     break;
1780     
1781   case Instruction::Call: {
1782     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1783     if (!II) break;
1784     switch (II->getIntrinsicID()) {
1785     default: break;
1786       
1787     // Binary vector operations that work column-wise.  A dest element is a
1788     // function of the corresponding input elements from the two inputs.
1789     case Intrinsic::x86_sse_sub_ss:
1790     case Intrinsic::x86_sse_mul_ss:
1791     case Intrinsic::x86_sse_min_ss:
1792     case Intrinsic::x86_sse_max_ss:
1793     case Intrinsic::x86_sse2_sub_sd:
1794     case Intrinsic::x86_sse2_mul_sd:
1795     case Intrinsic::x86_sse2_min_sd:
1796     case Intrinsic::x86_sse2_max_sd:
1797       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1798                                         UndefElts, Depth+1);
1799       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1800       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1801                                         UndefElts2, Depth+1);
1802       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1803
1804       // If only the low elt is demanded and this is a scalarizable intrinsic,
1805       // scalarize it now.
1806       if (DemandedElts == 1) {
1807         switch (II->getIntrinsicID()) {
1808         default: break;
1809         case Intrinsic::x86_sse_sub_ss:
1810         case Intrinsic::x86_sse_mul_ss:
1811         case Intrinsic::x86_sse2_sub_sd:
1812         case Intrinsic::x86_sse2_mul_sd:
1813           // TODO: Lower MIN/MAX/ABS/etc
1814           Value *LHS = II->getOperand(1);
1815           Value *RHS = II->getOperand(2);
1816           // Extract the element as scalars.
1817           LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS, 
1818             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1819           RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1820             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1821           
1822           switch (II->getIntrinsicID()) {
1823           default: llvm_unreachable("Case stmts out of sync!");
1824           case Intrinsic::x86_sse_sub_ss:
1825           case Intrinsic::x86_sse2_sub_sd:
1826             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1827                                                         II->getName()), *II);
1828             break;
1829           case Intrinsic::x86_sse_mul_ss:
1830           case Intrinsic::x86_sse2_mul_sd:
1831             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1832                                                          II->getName()), *II);
1833             break;
1834           }
1835           
1836           Instruction *New =
1837             InsertElementInst::Create(
1838               UndefValue::get(II->getType()), TmpV,
1839               ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
1840           InsertNewInstBefore(New, *II);
1841           return New;
1842         }            
1843       }
1844         
1845       // Output elements are undefined if both are undefined.  Consider things
1846       // like undef&0.  The result is known zero, not undef.
1847       UndefElts &= UndefElts2;
1848       break;
1849     }
1850     break;
1851   }
1852   }
1853   return MadeChange ? I : 0;
1854 }
1855
1856
1857 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1858 /// function is designed to check a chain of associative operators for a
1859 /// potential to apply a certain optimization.  Since the optimization may be
1860 /// applicable if the expression was reassociated, this checks the chain, then
1861 /// reassociates the expression as necessary to expose the optimization
1862 /// opportunity.  This makes use of a special Functor, which must define
1863 /// 'shouldApply' and 'apply' methods.
1864 ///
1865 template<typename Functor>
1866 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1867   unsigned Opcode = Root.getOpcode();
1868   Value *LHS = Root.getOperand(0);
1869
1870   // Quick check, see if the immediate LHS matches...
1871   if (F.shouldApply(LHS))
1872     return F.apply(Root);
1873
1874   // Otherwise, if the LHS is not of the same opcode as the root, return.
1875   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1876   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1877     // Should we apply this transform to the RHS?
1878     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1879
1880     // If not to the RHS, check to see if we should apply to the LHS...
1881     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1882       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1883       ShouldApply = true;
1884     }
1885
1886     // If the functor wants to apply the optimization to the RHS of LHSI,
1887     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1888     if (ShouldApply) {
1889       // Now all of the instructions are in the current basic block, go ahead
1890       // and perform the reassociation.
1891       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1892
1893       // First move the selected RHS to the LHS of the root...
1894       Root.setOperand(0, LHSI->getOperand(1));
1895
1896       // Make what used to be the LHS of the root be the user of the root...
1897       Value *ExtraOperand = TmpLHSI->getOperand(1);
1898       if (&Root == TmpLHSI) {
1899         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1900         return 0;
1901       }
1902       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1903       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1904       BasicBlock::iterator ARI = &Root; ++ARI;
1905       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1906       ARI = Root;
1907
1908       // Now propagate the ExtraOperand down the chain of instructions until we
1909       // get to LHSI.
1910       while (TmpLHSI != LHSI) {
1911         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1912         // Move the instruction to immediately before the chain we are
1913         // constructing to avoid breaking dominance properties.
1914         NextLHSI->moveBefore(ARI);
1915         ARI = NextLHSI;
1916
1917         Value *NextOp = NextLHSI->getOperand(1);
1918         NextLHSI->setOperand(1, ExtraOperand);
1919         TmpLHSI = NextLHSI;
1920         ExtraOperand = NextOp;
1921       }
1922
1923       // Now that the instructions are reassociated, have the functor perform
1924       // the transformation...
1925       return F.apply(Root);
1926     }
1927
1928     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1929   }
1930   return 0;
1931 }
1932
1933 namespace {
1934
1935 // AddRHS - Implements: X + X --> X << 1
1936 struct AddRHS {
1937   Value *RHS;
1938   explicit AddRHS(Value *rhs) : RHS(rhs) {}
1939   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1940   Instruction *apply(BinaryOperator &Add) const {
1941     return BinaryOperator::CreateShl(Add.getOperand(0),
1942                                      ConstantInt::get(Add.getType(), 1));
1943   }
1944 };
1945
1946 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1947 //                 iff C1&C2 == 0
1948 struct AddMaskingAnd {
1949   Constant *C2;
1950   explicit AddMaskingAnd(Constant *c) : C2(c) {}
1951   bool shouldApply(Value *LHS) const {
1952     ConstantInt *C1;
1953     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1954            ConstantExpr::getAnd(C1, C2)->isNullValue();
1955   }
1956   Instruction *apply(BinaryOperator &Add) const {
1957     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1958   }
1959 };
1960
1961 }
1962
1963 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1964                                              InstCombiner *IC) {
1965   if (CastInst *CI = dyn_cast<CastInst>(&I))
1966     return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
1967
1968   // Figure out if the constant is the left or the right argument.
1969   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1970   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1971
1972   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1973     if (ConstIsRHS)
1974       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1975     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1976   }
1977
1978   Value *Op0 = SO, *Op1 = ConstOperand;
1979   if (!ConstIsRHS)
1980     std::swap(Op0, Op1);
1981   
1982   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1983     return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1984                                     SO->getName()+".op");
1985   if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1986     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1987                                    SO->getName()+".cmp");
1988   if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1989     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1990                                    SO->getName()+".cmp");
1991   llvm_unreachable("Unknown binary instruction type!");
1992 }
1993
1994 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1995 // constant as the other operand, try to fold the binary operator into the
1996 // select arguments.  This also works for Cast instructions, which obviously do
1997 // not have a second operand.
1998 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1999                                      InstCombiner *IC) {
2000   // Don't modify shared select instructions
2001   if (!SI->hasOneUse()) return 0;
2002   Value *TV = SI->getOperand(1);
2003   Value *FV = SI->getOperand(2);
2004
2005   if (isa<Constant>(TV) || isa<Constant>(FV)) {
2006     // Bool selects with constant operands can be folded to logical ops.
2007     if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
2008
2009     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2010     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2011
2012     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2013                               SelectFalseVal);
2014   }
2015   return 0;
2016 }
2017
2018
2019 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2020 /// has a PHI node as operand #0, see if we can fold the instruction into the
2021 /// PHI (which is only possible if all operands to the PHI are constants).
2022 ///
2023 /// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2024 /// that would normally be unprofitable because they strongly encourage jump
2025 /// threading.
2026 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2027                                          bool AllowAggressive) {
2028   AllowAggressive = false;
2029   PHINode *PN = cast<PHINode>(I.getOperand(0));
2030   unsigned NumPHIValues = PN->getNumIncomingValues();
2031   if (NumPHIValues == 0 ||
2032       // We normally only transform phis with a single use, unless we're trying
2033       // hard to make jump threading happen.
2034       (!PN->hasOneUse() && !AllowAggressive))
2035     return 0;
2036   
2037   
2038   // Check to see if all of the operands of the PHI are simple constants
2039   // (constantint/constantfp/undef).  If there is one non-constant value,
2040   // remember the BB it is in.  If there is more than one or if *it* is a PHI,
2041   // bail out.  We don't do arbitrary constant expressions here because moving
2042   // their computation can be expensive without a cost model.
2043   BasicBlock *NonConstBB = 0;
2044   for (unsigned i = 0; i != NumPHIValues; ++i)
2045     if (!isa<Constant>(PN->getIncomingValue(i)) ||
2046         isa<ConstantExpr>(PN->getIncomingValue(i))) {
2047       if (NonConstBB) return 0;  // More than one non-const value.
2048       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
2049       NonConstBB = PN->getIncomingBlock(i);
2050       
2051       // If the incoming non-constant value is in I's block, we have an infinite
2052       // loop.
2053       if (NonConstBB == I.getParent())
2054         return 0;
2055     }
2056   
2057   // If there is exactly one non-constant value, we can insert a copy of the
2058   // operation in that block.  However, if this is a critical edge, we would be
2059   // inserting the computation one some other paths (e.g. inside a loop).  Only
2060   // do this if the pred block is unconditionally branching into the phi block.
2061   if (NonConstBB != 0 && !AllowAggressive) {
2062     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2063     if (!BI || !BI->isUnconditional()) return 0;
2064   }
2065
2066   // Okay, we can do the transformation: create the new PHI node.
2067   PHINode *NewPN = PHINode::Create(I.getType(), "");
2068   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2069   InsertNewInstBefore(NewPN, *PN);
2070   NewPN->takeName(PN);
2071
2072   // Next, add all of the operands to the PHI.
2073   if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2074     // We only currently try to fold the condition of a select when it is a phi,
2075     // not the true/false values.
2076     Value *TrueV = SI->getTrueValue();
2077     Value *FalseV = SI->getFalseValue();
2078     BasicBlock *PhiTransBB = PN->getParent();
2079     for (unsigned i = 0; i != NumPHIValues; ++i) {
2080       BasicBlock *ThisBB = PN->getIncomingBlock(i);
2081       Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2082       Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
2083       Value *InV = 0;
2084       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2085         InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
2086       } else {
2087         assert(PN->getIncomingBlock(i) == NonConstBB);
2088         InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2089                                  FalseVInPred,
2090                                  "phitmp", NonConstBB->getTerminator());
2091         Worklist.Add(cast<Instruction>(InV));
2092       }
2093       NewPN->addIncoming(InV, ThisBB);
2094     }
2095   } else if (I.getNumOperands() == 2) {
2096     Constant *C = cast<Constant>(I.getOperand(1));
2097     for (unsigned i = 0; i != NumPHIValues; ++i) {
2098       Value *InV = 0;
2099       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2100         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2101           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2102         else
2103           InV = ConstantExpr::get(I.getOpcode(), InC, C);
2104       } else {
2105         assert(PN->getIncomingBlock(i) == NonConstBB);
2106         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2107           InV = BinaryOperator::Create(BO->getOpcode(),
2108                                        PN->getIncomingValue(i), C, "phitmp",
2109                                        NonConstBB->getTerminator());
2110         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2111           InV = CmpInst::Create(CI->getOpcode(),
2112                                 CI->getPredicate(),
2113                                 PN->getIncomingValue(i), C, "phitmp",
2114                                 NonConstBB->getTerminator());
2115         else
2116           llvm_unreachable("Unknown binop!");
2117         
2118         Worklist.Add(cast<Instruction>(InV));
2119       }
2120       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2121     }
2122   } else { 
2123     CastInst *CI = cast<CastInst>(&I);
2124     const Type *RetTy = CI->getType();
2125     for (unsigned i = 0; i != NumPHIValues; ++i) {
2126       Value *InV;
2127       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2128         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2129       } else {
2130         assert(PN->getIncomingBlock(i) == NonConstBB);
2131         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2132                                I.getType(), "phitmp", 
2133                                NonConstBB->getTerminator());
2134         Worklist.Add(cast<Instruction>(InV));
2135       }
2136       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2137     }
2138   }
2139   return ReplaceInstUsesWith(I, NewPN);
2140 }
2141
2142
2143 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2144 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2145 /// This basically requires proving that the add in the original type would not
2146 /// overflow to change the sign bit or have a carry out.
2147 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2148   // There are different heuristics we can use for this.  Here are some simple
2149   // ones.
2150   
2151   // Add has the property that adding any two 2's complement numbers can only 
2152   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2153   // have at least two sign bits, we know that the addition of the two values will
2154   // sign extend fine.
2155   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2156     return true;
2157   
2158   
2159   // If one of the operands only has one non-zero bit, and if the other operand
2160   // has a known-zero bit in a more significant place than it (not including the
2161   // sign bit) the ripple may go up to and fill the zero, but won't change the
2162   // sign.  For example, (X & ~4) + 1.
2163   
2164   // TODO: Implement.
2165   
2166   return false;
2167 }
2168
2169
2170 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2171   bool Changed = SimplifyCommutative(I);
2172   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2173
2174   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2175     // X + undef -> undef
2176     if (isa<UndefValue>(RHS))
2177       return ReplaceInstUsesWith(I, RHS);
2178
2179     // X + 0 --> X
2180     if (RHSC->isNullValue())
2181       return ReplaceInstUsesWith(I, LHS);
2182
2183     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2184       // X + (signbit) --> X ^ signbit
2185       const APInt& Val = CI->getValue();
2186       uint32_t BitWidth = Val.getBitWidth();
2187       if (Val == APInt::getSignBit(BitWidth))
2188         return BinaryOperator::CreateXor(LHS, RHS);
2189       
2190       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2191       // (X & 254)+1 -> (X&254)|1
2192       if (SimplifyDemandedInstructionBits(I))
2193         return &I;
2194
2195       // zext(bool) + C -> bool ? C + 1 : C
2196       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2197         if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2198           return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2199     }
2200
2201     if (isa<PHINode>(LHS))
2202       if (Instruction *NV = FoldOpIntoPhi(I))
2203         return NV;
2204     
2205     ConstantInt *XorRHS = 0;
2206     Value *XorLHS = 0;
2207     if (isa<ConstantInt>(RHSC) &&
2208         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2209       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2210       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2211       
2212       uint32_t Size = TySizeBits / 2;
2213       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2214       APInt CFF80Val(-C0080Val);
2215       do {
2216         if (TySizeBits > Size) {
2217           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2218           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2219           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2220               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2221             // This is a sign extend if the top bits are known zero.
2222             if (!MaskedValueIsZero(XorLHS, 
2223                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2224               Size = 0;  // Not a sign ext, but can't be any others either.
2225             break;
2226           }
2227         }
2228         Size >>= 1;
2229         C0080Val = APIntOps::lshr(C0080Val, Size);
2230         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2231       } while (Size >= 1);
2232       
2233       // FIXME: This shouldn't be necessary. When the backends can handle types
2234       // with funny bit widths then this switch statement should be removed. It
2235       // is just here to get the size of the "middle" type back up to something
2236       // that the back ends can handle.
2237       const Type *MiddleType = 0;
2238       switch (Size) {
2239         default: break;
2240         case 32: MiddleType = Type::getInt32Ty(*Context); break;
2241         case 16: MiddleType = Type::getInt16Ty(*Context); break;
2242         case  8: MiddleType = Type::getInt8Ty(*Context); break;
2243       }
2244       if (MiddleType) {
2245         Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
2246         return new SExtInst(NewTrunc, I.getType(), I.getName());
2247       }
2248     }
2249   }
2250
2251   if (I.getType() == Type::getInt1Ty(*Context))
2252     return BinaryOperator::CreateXor(LHS, RHS);
2253
2254   // X + X --> X << 1
2255   if (I.getType()->isInteger()) {
2256     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2257       return Result;
2258
2259     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2260       if (RHSI->getOpcode() == Instruction::Sub)
2261         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2262           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2263     }
2264     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2265       if (LHSI->getOpcode() == Instruction::Sub)
2266         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2267           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2268     }
2269   }
2270
2271   // -A + B  -->  B - A
2272   // -A + -B  -->  -(A + B)
2273   if (Value *LHSV = dyn_castNegVal(LHS)) {
2274     if (LHS->getType()->isIntOrIntVector()) {
2275       if (Value *RHSV = dyn_castNegVal(RHS)) {
2276         Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
2277         return BinaryOperator::CreateNeg(NewAdd);
2278       }
2279     }
2280     
2281     return BinaryOperator::CreateSub(RHS, LHSV);
2282   }
2283
2284   // A + -B  -->  A - B
2285   if (!isa<Constant>(RHS))
2286     if (Value *V = dyn_castNegVal(RHS))
2287       return BinaryOperator::CreateSub(LHS, V);
2288
2289
2290   ConstantInt *C2;
2291   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2292     if (X == RHS)   // X*C + X --> X * (C+1)
2293       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2294
2295     // X*C1 + X*C2 --> X * (C1+C2)
2296     ConstantInt *C1;
2297     if (X == dyn_castFoldableMul(RHS, C1))
2298       return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2299   }
2300
2301   // X + X*C --> X * (C+1)
2302   if (dyn_castFoldableMul(RHS, C2) == LHS)
2303     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2304
2305   // X + ~X --> -1   since   ~X = -X-1
2306   if (dyn_castNotVal(LHS) == RHS ||
2307       dyn_castNotVal(RHS) == LHS)
2308     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2309   
2310
2311   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2312   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2313     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2314       return R;
2315   
2316   // A+B --> A|B iff A and B have no bits set in common.
2317   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2318     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2319     APInt LHSKnownOne(IT->getBitWidth(), 0);
2320     APInt LHSKnownZero(IT->getBitWidth(), 0);
2321     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2322     if (LHSKnownZero != 0) {
2323       APInt RHSKnownOne(IT->getBitWidth(), 0);
2324       APInt RHSKnownZero(IT->getBitWidth(), 0);
2325       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2326       
2327       // No bits in common -> bitwise or.
2328       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2329         return BinaryOperator::CreateOr(LHS, RHS);
2330     }
2331   }
2332
2333   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2334   if (I.getType()->isIntOrIntVector()) {
2335     Value *W, *X, *Y, *Z;
2336     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2337         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2338       if (W != Y) {
2339         if (W == Z) {
2340           std::swap(Y, Z);
2341         } else if (Y == X) {
2342           std::swap(W, X);
2343         } else if (X == Z) {
2344           std::swap(Y, Z);
2345           std::swap(W, X);
2346         }
2347       }
2348
2349       if (W == Y) {
2350         Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
2351         return BinaryOperator::CreateMul(W, NewAdd);
2352       }
2353     }
2354   }
2355
2356   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2357     Value *X = 0;
2358     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2359       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2360
2361     // (X & FF00) + xx00  -> (X+xx00) & FF00
2362     if (LHS->hasOneUse() &&
2363         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2364       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2365       if (Anded == CRHS) {
2366         // See if all bits from the first bit set in the Add RHS up are included
2367         // in the mask.  First, get the rightmost bit.
2368         const APInt& AddRHSV = CRHS->getValue();
2369
2370         // Form a mask of all bits from the lowest bit added through the top.
2371         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2372
2373         // See if the and mask includes all of these bits.
2374         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2375
2376         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2377           // Okay, the xform is safe.  Insert the new add pronto.
2378           Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
2379           return BinaryOperator::CreateAnd(NewAdd, C2);
2380         }
2381       }
2382     }
2383
2384     // Try to fold constant add into select arguments.
2385     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2386       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2387         return R;
2388   }
2389
2390   // add (select X 0 (sub n A)) A  -->  select X A n
2391   {
2392     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2393     Value *A = RHS;
2394     if (!SI) {
2395       SI = dyn_cast<SelectInst>(RHS);
2396       A = LHS;
2397     }
2398     if (SI && SI->hasOneUse()) {
2399       Value *TV = SI->getTrueValue();
2400       Value *FV = SI->getFalseValue();
2401       Value *N;
2402
2403       // Can we fold the add into the argument of the select?
2404       // We check both true and false select arguments for a matching subtract.
2405       if (match(FV, m_Zero()) &&
2406           match(TV, m_Sub(m_Value(N), m_Specific(A))))
2407         // Fold the add into the true select value.
2408         return SelectInst::Create(SI->getCondition(), N, A);
2409       if (match(TV, m_Zero()) &&
2410           match(FV, m_Sub(m_Value(N), m_Specific(A))))
2411         // Fold the add into the false select value.
2412         return SelectInst::Create(SI->getCondition(), A, N);
2413     }
2414   }
2415
2416   // Check for (add (sext x), y), see if we can merge this into an
2417   // integer add followed by a sext.
2418   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2419     // (add (sext x), cst) --> (sext (add x, cst'))
2420     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2421       Constant *CI = 
2422         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2423       if (LHSConv->hasOneUse() &&
2424           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2425           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2426         // Insert the new, smaller add.
2427         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0), 
2428                                               CI, "addconv");
2429         return new SExtInst(NewAdd, I.getType());
2430       }
2431     }
2432     
2433     // (add (sext x), (sext y)) --> (sext (add int x, y))
2434     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2435       // Only do this if x/y have the same type, if at last one of them has a
2436       // single use (so we don't increase the number of sexts), and if the
2437       // integer add will not overflow.
2438       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2439           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2440           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2441                                    RHSConv->getOperand(0))) {
2442         // Insert the new integer add.
2443         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0), 
2444                                               RHSConv->getOperand(0), "addconv");
2445         return new SExtInst(NewAdd, I.getType());
2446       }
2447     }
2448   }
2449
2450   return Changed ? &I : 0;
2451 }
2452
2453 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2454   bool Changed = SimplifyCommutative(I);
2455   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2456
2457   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2458     // X + 0 --> X
2459     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2460       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2461                               (I.getType())->getValueAPF()))
2462         return ReplaceInstUsesWith(I, LHS);
2463     }
2464
2465     if (isa<PHINode>(LHS))
2466       if (Instruction *NV = FoldOpIntoPhi(I))
2467         return NV;
2468   }
2469
2470   // -A + B  -->  B - A
2471   // -A + -B  -->  -(A + B)
2472   if (Value *LHSV = dyn_castFNegVal(LHS))
2473     return BinaryOperator::CreateFSub(RHS, LHSV);
2474
2475   // A + -B  -->  A - B
2476   if (!isa<Constant>(RHS))
2477     if (Value *V = dyn_castFNegVal(RHS))
2478       return BinaryOperator::CreateFSub(LHS, V);
2479
2480   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2481   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2482     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2483       return ReplaceInstUsesWith(I, LHS);
2484
2485   // Check for (add double (sitofp x), y), see if we can merge this into an
2486   // integer add followed by a promotion.
2487   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2488     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2489     // ... if the constant fits in the integer value.  This is useful for things
2490     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2491     // requires a constant pool load, and generally allows the add to be better
2492     // instcombined.
2493     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2494       Constant *CI = 
2495       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2496       if (LHSConv->hasOneUse() &&
2497           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2498           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2499         // Insert the new integer add.
2500         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2501                                               CI, "addconv");
2502         return new SIToFPInst(NewAdd, I.getType());
2503       }
2504     }
2505     
2506     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2507     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2508       // Only do this if x/y have the same type, if at last one of them has a
2509       // single use (so we don't increase the number of int->fp conversions),
2510       // and if the integer add will not overflow.
2511       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2512           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2513           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2514                                    RHSConv->getOperand(0))) {
2515         // Insert the new integer add.
2516         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0), 
2517                                               RHSConv->getOperand(0),"addconv");
2518         return new SIToFPInst(NewAdd, I.getType());
2519       }
2520     }
2521   }
2522   
2523   return Changed ? &I : 0;
2524 }
2525
2526
2527 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2528 /// code necessary to compute the offset from the base pointer (without adding
2529 /// in the base pointer).  Return the result as a signed integer of intptr size.
2530 static Value *EmitGEPOffset(User *GEP, InstCombiner &IC) {
2531   TargetData &TD = *IC.getTargetData();
2532   gep_type_iterator GTI = gep_type_begin(GEP);
2533   const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
2534   Value *Result = Constant::getNullValue(IntPtrTy);
2535
2536   // Build a mask for high order bits.
2537   unsigned IntPtrWidth = TD.getPointerSizeInBits();
2538   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2539
2540   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
2541        ++i, ++GTI) {
2542     Value *Op = *i;
2543     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
2544     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
2545       if (OpC->isZero()) continue;
2546       
2547       // Handle a struct index, which adds its field offset to the pointer.
2548       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2549         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
2550         
2551         Result = IC.Builder->CreateAdd(Result,
2552                                        ConstantInt::get(IntPtrTy, Size),
2553                                        GEP->getName()+".offs");
2554         continue;
2555       }
2556       
2557       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2558       Constant *OC =
2559               ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
2560       Scale = ConstantExpr::getMul(OC, Scale);
2561       // Emit an add instruction.
2562       Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
2563       continue;
2564     }
2565     // Convert to correct type.
2566     if (Op->getType() != IntPtrTy)
2567       Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
2568     if (Size != 1) {
2569       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2570       // We'll let instcombine(mul) convert this to a shl if possible.
2571       Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
2572     }
2573
2574     // Emit an add instruction.
2575     Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
2576   }
2577   return Result;
2578 }
2579
2580
2581 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
2582 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
2583 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
2584 /// be complex, and scales are involved.  The above expression would also be
2585 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
2586 /// This later form is less amenable to optimization though, and we are allowed
2587 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
2588 ///
2589 /// If we can't emit an optimized form for this expression, this returns null.
2590 /// 
2591 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
2592                                           InstCombiner &IC) {
2593   TargetData &TD = *IC.getTargetData();
2594   gep_type_iterator GTI = gep_type_begin(GEP);
2595
2596   // Check to see if this gep only has a single variable index.  If so, and if
2597   // any constant indices are a multiple of its scale, then we can compute this
2598   // in terms of the scale of the variable index.  For example, if the GEP
2599   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
2600   // because the expression will cross zero at the same point.
2601   unsigned i, e = GEP->getNumOperands();
2602   int64_t Offset = 0;
2603   for (i = 1; i != e; ++i, ++GTI) {
2604     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2605       // Compute the aggregate offset of constant indices.
2606       if (CI->isZero()) continue;
2607
2608       // Handle a struct index, which adds its field offset to the pointer.
2609       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2610         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2611       } else {
2612         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2613         Offset += Size*CI->getSExtValue();
2614       }
2615     } else {
2616       // Found our variable index.
2617       break;
2618     }
2619   }
2620   
2621   // If there are no variable indices, we must have a constant offset, just
2622   // evaluate it the general way.
2623   if (i == e) return 0;
2624   
2625   Value *VariableIdx = GEP->getOperand(i);
2626   // Determine the scale factor of the variable element.  For example, this is
2627   // 4 if the variable index is into an array of i32.
2628   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
2629   
2630   // Verify that there are no other variable indices.  If so, emit the hard way.
2631   for (++i, ++GTI; i != e; ++i, ++GTI) {
2632     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
2633     if (!CI) return 0;
2634    
2635     // Compute the aggregate offset of constant indices.
2636     if (CI->isZero()) continue;
2637     
2638     // Handle a struct index, which adds its field offset to the pointer.
2639     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2640       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2641     } else {
2642       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2643       Offset += Size*CI->getSExtValue();
2644     }
2645   }
2646   
2647   // Okay, we know we have a single variable index, which must be a
2648   // pointer/array/vector index.  If there is no offset, life is simple, return
2649   // the index.
2650   unsigned IntPtrWidth = TD.getPointerSizeInBits();
2651   if (Offset == 0) {
2652     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
2653     // we don't need to bother extending: the extension won't affect where the
2654     // computation crosses zero.
2655     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
2656       VariableIdx = new TruncInst(VariableIdx, 
2657                                   TD.getIntPtrType(VariableIdx->getContext()),
2658                                   VariableIdx->getName(), &I);
2659     return VariableIdx;
2660   }
2661   
2662   // Otherwise, there is an index.  The computation we will do will be modulo
2663   // the pointer size, so get it.
2664   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2665   
2666   Offset &= PtrSizeMask;
2667   VariableScale &= PtrSizeMask;
2668
2669   // To do this transformation, any constant index must be a multiple of the
2670   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
2671   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
2672   // multiple of the variable scale.
2673   int64_t NewOffs = Offset / (int64_t)VariableScale;
2674   if (Offset != NewOffs*(int64_t)VariableScale)
2675     return 0;
2676
2677   // Okay, we can do this evaluation.  Start by converting the index to intptr.
2678   const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
2679   if (VariableIdx->getType() != IntPtrTy)
2680     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
2681                                               true /*SExt*/, 
2682                                               VariableIdx->getName(), &I);
2683   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
2684   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
2685 }
2686
2687
2688 /// Optimize pointer differences into the same array into a size.  Consider:
2689 ///  &A[10] - &A[0]: we should compile this to "10".  LHS/RHS are the pointer
2690 /// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2691 ///
2692 Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
2693                                                const Type *Ty) {
2694   assert(TD && "Must have target data info for this");
2695   
2696   // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
2697   // this.
2698   bool Swapped;
2699   GetElementPtrInst *GEP;
2700   
2701   if ((GEP = dyn_cast<GetElementPtrInst>(LHS)) &&
2702       GEP->getOperand(0) == RHS)
2703     Swapped = false;
2704   else if ((GEP = dyn_cast<GetElementPtrInst>(RHS)) &&
2705            GEP->getOperand(0) == LHS)
2706     Swapped = true;
2707   else
2708     return 0;
2709   
2710   // TODO: Could also optimize &A[i] - &A[j] -> "i-j".
2711   
2712   // Emit the offset of the GEP and an intptr_t.
2713   Value *Result = EmitGEPOffset(GEP, *this);
2714
2715   // If we have p - gep(p, ...)  then we have to negate the result.
2716   if (Swapped)
2717     Result = Builder->CreateNeg(Result, "diff.neg");
2718
2719   return Builder->CreateIntCast(Result, Ty, true);
2720 }
2721
2722
2723 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2724   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2725
2726   if (Op0 == Op1)                        // sub X, X  -> 0
2727     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2728
2729   // If this is a 'B = x-(-A)', change to B = x+A.
2730   if (Value *V = dyn_castNegVal(Op1))
2731     return BinaryOperator::CreateAdd(Op0, V);
2732
2733   if (isa<UndefValue>(Op0))
2734     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2735   if (isa<UndefValue>(Op1))
2736     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2737   if (I.getType() == Type::getInt1Ty(*Context))
2738     return BinaryOperator::CreateXor(Op0, Op1);
2739   
2740   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2741     // Replace (-1 - A) with (~A).
2742     if (C->isAllOnesValue())
2743       return BinaryOperator::CreateNot(Op1);
2744
2745     // C - ~X == X + (1+C)
2746     Value *X = 0;
2747     if (match(Op1, m_Not(m_Value(X))))
2748       return BinaryOperator::CreateAdd(X, AddOne(C));
2749
2750     // -(X >>u 31) -> (X >>s 31)
2751     // -(X >>s 31) -> (X >>u 31)
2752     if (C->isZero()) {
2753       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2754         if (SI->getOpcode() == Instruction::LShr) {
2755           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2756             // Check to see if we are shifting out everything but the sign bit.
2757             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2758                 SI->getType()->getPrimitiveSizeInBits()-1) {
2759               // Ok, the transformation is safe.  Insert AShr.
2760               return BinaryOperator::Create(Instruction::AShr, 
2761                                           SI->getOperand(0), CU, SI->getName());
2762             }
2763           }
2764         } else if (SI->getOpcode() == Instruction::AShr) {
2765           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2766             // Check to see if we are shifting out everything but the sign bit.
2767             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2768                 SI->getType()->getPrimitiveSizeInBits()-1) {
2769               // Ok, the transformation is safe.  Insert LShr. 
2770               return BinaryOperator::CreateLShr(
2771                                           SI->getOperand(0), CU, SI->getName());
2772             }
2773           }
2774         }
2775       }
2776     }
2777
2778     // Try to fold constant sub into select arguments.
2779     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2780       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2781         return R;
2782
2783     // C - zext(bool) -> bool ? C - 1 : C
2784     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2785       if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2786         return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2787   }
2788
2789   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2790     if (Op1I->getOpcode() == Instruction::Add) {
2791       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2792         return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2793                                          I.getName());
2794       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2795         return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2796                                          I.getName());
2797       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2798         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2799           // C1-(X+C2) --> (C1-C2)-X
2800           return BinaryOperator::CreateSub(
2801             ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2802       }
2803     }
2804
2805     if (Op1I->hasOneUse()) {
2806       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2807       // is not used by anyone else...
2808       //
2809       if (Op1I->getOpcode() == Instruction::Sub) {
2810         // Swap the two operands of the subexpr...
2811         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2812         Op1I->setOperand(0, IIOp1);
2813         Op1I->setOperand(1, IIOp0);
2814
2815         // Create the new top level add instruction...
2816         return BinaryOperator::CreateAdd(Op0, Op1);
2817       }
2818
2819       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2820       //
2821       if (Op1I->getOpcode() == Instruction::And &&
2822           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2823         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2824
2825         Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
2826         return BinaryOperator::CreateAnd(Op0, NewNot);
2827       }
2828
2829       // 0 - (X sdiv C)  -> (X sdiv -C)
2830       if (Op1I->getOpcode() == Instruction::SDiv)
2831         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2832           if (CSI->isZero())
2833             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2834               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2835                                           ConstantExpr::getNeg(DivRHS));
2836
2837       // X - X*C --> X * (1-C)
2838       ConstantInt *C2 = 0;
2839       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2840         Constant *CP1 = 
2841           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2842                                              C2);
2843         return BinaryOperator::CreateMul(Op0, CP1);
2844       }
2845     }
2846   }
2847
2848   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2849     if (Op0I->getOpcode() == Instruction::Add) {
2850       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2851         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2852       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2853         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2854     } else if (Op0I->getOpcode() == Instruction::Sub) {
2855       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2856         return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2857                                          I.getName());
2858     }
2859   }
2860
2861   ConstantInt *C1;
2862   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2863     if (X == Op1)  // X*C - X --> X * (C-1)
2864       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2865
2866     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2867     if (X == dyn_castFoldableMul(Op1, C2))
2868       return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2869   }
2870   
2871   // Optimize pointer differences into the same array into a size.  Consider:
2872   //  &A[10] - &A[0]: we should compile this to "10".
2873   if (TD) {
2874     if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(Op0))
2875       if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(Op1))
2876         if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2877                                                    RHS->getOperand(0),
2878                                                    I.getType()))
2879           return ReplaceInstUsesWith(I, Res);
2880     
2881     // trunc(p)-trunc(q) -> trunc(p-q)
2882     if (TruncInst *LHST = dyn_cast<TruncInst>(Op0))
2883       if (TruncInst *RHST = dyn_cast<TruncInst>(Op1))
2884         if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(LHST->getOperand(0)))
2885           if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(RHST->getOperand(0)))
2886             if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2887                                                        RHS->getOperand(0),
2888                                                        I.getType()))
2889               return ReplaceInstUsesWith(I, Res);
2890   }
2891   
2892   return 0;
2893 }
2894
2895 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2896   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2897
2898   // If this is a 'B = x-(-A)', change to B = x+A...
2899   if (Value *V = dyn_castFNegVal(Op1))
2900     return BinaryOperator::CreateFAdd(Op0, V);
2901
2902   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2903     if (Op1I->getOpcode() == Instruction::FAdd) {
2904       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2905         return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
2906                                           I.getName());
2907       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2908         return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
2909                                           I.getName());
2910     }
2911   }
2912
2913   return 0;
2914 }
2915
2916 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2917 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2918 /// TrueIfSigned if the result of the comparison is true when the input value is
2919 /// signed.
2920 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2921                            bool &TrueIfSigned) {
2922   switch (pred) {
2923   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2924     TrueIfSigned = true;
2925     return RHS->isZero();
2926   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2927     TrueIfSigned = true;
2928     return RHS->isAllOnesValue();
2929   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2930     TrueIfSigned = false;
2931     return RHS->isAllOnesValue();
2932   case ICmpInst::ICMP_UGT:
2933     // True if LHS u> RHS and RHS == high-bit-mask - 1
2934     TrueIfSigned = true;
2935     return RHS->getValue() ==
2936       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2937   case ICmpInst::ICMP_UGE: 
2938     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2939     TrueIfSigned = true;
2940     return RHS->getValue().isSignBit();
2941   default:
2942     return false;
2943   }
2944 }
2945
2946 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2947   bool Changed = SimplifyCommutative(I);
2948   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2949
2950   if (isa<UndefValue>(Op1))              // undef * X -> 0
2951     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2952
2953   // Simplify mul instructions with a constant RHS.
2954   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2955     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
2956
2957       // ((X << C1)*C2) == (X * (C2 << C1))
2958       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2959         if (SI->getOpcode() == Instruction::Shl)
2960           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2961             return BinaryOperator::CreateMul(SI->getOperand(0),
2962                                         ConstantExpr::getShl(CI, ShOp));
2963
2964       if (CI->isZero())
2965         return ReplaceInstUsesWith(I, Op1C);  // X * 0  == 0
2966       if (CI->equalsInt(1))                  // X * 1  == X
2967         return ReplaceInstUsesWith(I, Op0);
2968       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2969         return BinaryOperator::CreateNeg(Op0, I.getName());
2970
2971       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2972       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2973         return BinaryOperator::CreateShl(Op0,
2974                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2975       }
2976     } else if (isa<VectorType>(Op1C->getType())) {
2977       if (Op1C->isNullValue())
2978         return ReplaceInstUsesWith(I, Op1C);
2979
2980       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
2981         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2982           return BinaryOperator::CreateNeg(Op0, I.getName());
2983
2984         // As above, vector X*splat(1.0) -> X in all defined cases.
2985         if (Constant *Splat = Op1V->getSplatValue()) {
2986           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2987             if (CI->equalsInt(1))
2988               return ReplaceInstUsesWith(I, Op0);
2989         }
2990       }
2991     }
2992     
2993     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2994       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2995           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
2996         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2997         Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
2998         Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
2999         return BinaryOperator::CreateAdd(Add, C1C2);
3000         
3001       }
3002
3003     // Try to fold constant mul into select arguments.
3004     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3005       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3006         return R;
3007
3008     if (isa<PHINode>(Op0))
3009       if (Instruction *NV = FoldOpIntoPhi(I))
3010         return NV;
3011   }
3012
3013   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
3014     if (Value *Op1v = dyn_castNegVal(Op1))
3015       return BinaryOperator::CreateMul(Op0v, Op1v);
3016
3017   // (X / Y) *  Y = X - (X % Y)
3018   // (X / Y) * -Y = (X % Y) - X
3019   {
3020     Value *Op1C = Op1;
3021     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
3022     if (!BO ||
3023         (BO->getOpcode() != Instruction::UDiv && 
3024          BO->getOpcode() != Instruction::SDiv)) {
3025       Op1C = Op0;
3026       BO = dyn_cast<BinaryOperator>(Op1);
3027     }
3028     Value *Neg = dyn_castNegVal(Op1C);
3029     if (BO && BO->hasOneUse() &&
3030         (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
3031         (BO->getOpcode() == Instruction::UDiv ||
3032          BO->getOpcode() == Instruction::SDiv)) {
3033       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
3034
3035       // If the division is exact, X % Y is zero.
3036       if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
3037         if (SDiv->isExact()) {
3038           if (Op1BO == Op1C)
3039             return ReplaceInstUsesWith(I, Op0BO);
3040           return BinaryOperator::CreateNeg(Op0BO);
3041         }
3042
3043       Value *Rem;
3044       if (BO->getOpcode() == Instruction::UDiv)
3045         Rem = Builder->CreateURem(Op0BO, Op1BO);
3046       else
3047         Rem = Builder->CreateSRem(Op0BO, Op1BO);
3048       Rem->takeName(BO);
3049
3050       if (Op1BO == Op1C)
3051         return BinaryOperator::CreateSub(Op0BO, Rem);
3052       return BinaryOperator::CreateSub(Rem, Op0BO);
3053     }
3054   }
3055
3056   /// i1 mul -> i1 and.
3057   if (I.getType() == Type::getInt1Ty(*Context))
3058     return BinaryOperator::CreateAnd(Op0, Op1);
3059
3060   // X*(1 << Y) --> X << Y
3061   // (1 << Y)*X --> X << Y
3062   {
3063     Value *Y;
3064     if (match(Op0, m_Shl(m_One(), m_Value(Y))))
3065       return BinaryOperator::CreateShl(Op1, Y);
3066     if (match(Op1, m_Shl(m_One(), m_Value(Y))))
3067       return BinaryOperator::CreateShl(Op0, Y);
3068   }
3069   
3070   // If one of the operands of the multiply is a cast from a boolean value, then
3071   // we know the bool is either zero or one, so this is a 'masking' multiply.
3072   //   X * Y (where Y is 0 or 1) -> X & (0-Y)
3073   if (!isa<VectorType>(I.getType())) {
3074     // -2 is "-1 << 1" so it is all bits set except the low one.
3075     APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
3076     
3077     Value *BoolCast = 0, *OtherOp = 0;
3078     if (MaskedValueIsZero(Op0, Negative2))
3079       BoolCast = Op0, OtherOp = Op1;
3080     else if (MaskedValueIsZero(Op1, Negative2))
3081       BoolCast = Op1, OtherOp = Op0;
3082
3083     if (BoolCast) {
3084       Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
3085                                     BoolCast, "tmp");
3086       return BinaryOperator::CreateAnd(V, OtherOp);
3087     }
3088   }
3089
3090   return Changed ? &I : 0;
3091 }
3092
3093 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
3094   bool Changed = SimplifyCommutative(I);
3095   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3096
3097   // Simplify mul instructions with a constant RHS...
3098   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3099     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
3100       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
3101       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3102       if (Op1F->isExactlyValue(1.0))
3103         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
3104     } else if (isa<VectorType>(Op1C->getType())) {
3105       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
3106         // As above, vector X*splat(1.0) -> X in all defined cases.
3107         if (Constant *Splat = Op1V->getSplatValue()) {
3108           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
3109             if (F->isExactlyValue(1.0))
3110               return ReplaceInstUsesWith(I, Op0);
3111         }
3112       }
3113     }
3114
3115     // Try to fold constant mul into select arguments.
3116     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3117       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3118         return R;
3119
3120     if (isa<PHINode>(Op0))
3121       if (Instruction *NV = FoldOpIntoPhi(I))
3122         return NV;
3123   }
3124
3125   if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
3126     if (Value *Op1v = dyn_castFNegVal(Op1))
3127       return BinaryOperator::CreateFMul(Op0v, Op1v);
3128
3129   return Changed ? &I : 0;
3130 }
3131
3132 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
3133 /// instruction.
3134 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
3135   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
3136   
3137   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
3138   int NonNullOperand = -1;
3139   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3140     if (ST->isNullValue())
3141       NonNullOperand = 2;
3142   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
3143   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3144     if (ST->isNullValue())
3145       NonNullOperand = 1;
3146   
3147   if (NonNullOperand == -1)
3148     return false;
3149   
3150   Value *SelectCond = SI->getOperand(0);
3151   
3152   // Change the div/rem to use 'Y' instead of the select.
3153   I.setOperand(1, SI->getOperand(NonNullOperand));
3154   
3155   // Okay, we know we replace the operand of the div/rem with 'Y' with no
3156   // problem.  However, the select, or the condition of the select may have
3157   // multiple uses.  Based on our knowledge that the operand must be non-zero,
3158   // propagate the known value for the select into other uses of it, and
3159   // propagate a known value of the condition into its other users.
3160   
3161   // If the select and condition only have a single use, don't bother with this,
3162   // early exit.
3163   if (SI->use_empty() && SelectCond->hasOneUse())
3164     return true;
3165   
3166   // Scan the current block backward, looking for other uses of SI.
3167   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
3168   
3169   while (BBI != BBFront) {
3170     --BBI;
3171     // If we found a call to a function, we can't assume it will return, so
3172     // information from below it cannot be propagated above it.
3173     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
3174       break;
3175     
3176     // Replace uses of the select or its condition with the known values.
3177     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
3178          I != E; ++I) {
3179       if (*I == SI) {
3180         *I = SI->getOperand(NonNullOperand);
3181         Worklist.Add(BBI);
3182       } else if (*I == SelectCond) {
3183         *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
3184                                    ConstantInt::getFalse(*Context);
3185         Worklist.Add(BBI);
3186       }
3187     }
3188     
3189     // If we past the instruction, quit looking for it.
3190     if (&*BBI == SI)
3191       SI = 0;
3192     if (&*BBI == SelectCond)
3193       SelectCond = 0;
3194     
3195     // If we ran out of things to eliminate, break out of the loop.
3196     if (SelectCond == 0 && SI == 0)
3197       break;
3198     
3199   }
3200   return true;
3201 }
3202
3203
3204 /// This function implements the transforms on div instructions that work
3205 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3206 /// used by the visitors to those instructions.
3207 /// @brief Transforms common to all three div instructions
3208 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
3209   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3210
3211   // undef / X -> 0        for integer.
3212   // undef / X -> undef    for FP (the undef could be a snan).
3213   if (isa<UndefValue>(Op0)) {
3214     if (Op0->getType()->isFPOrFPVector())
3215       return ReplaceInstUsesWith(I, Op0);
3216     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3217   }
3218
3219   // X / undef -> undef
3220   if (isa<UndefValue>(Op1))
3221     return ReplaceInstUsesWith(I, Op1);
3222
3223   return 0;
3224 }
3225
3226 /// This function implements the transforms common to both integer division
3227 /// instructions (udiv and sdiv). It is called by the visitors to those integer
3228 /// division instructions.
3229 /// @brief Common integer divide transforms
3230 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3231   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3232
3233   // (sdiv X, X) --> 1     (udiv X, X) --> 1
3234   if (Op0 == Op1) {
3235     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
3236       Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
3237       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
3238       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
3239     }
3240
3241     Constant *CI = ConstantInt::get(I.getType(), 1);
3242     return ReplaceInstUsesWith(I, CI);
3243   }
3244   
3245   if (Instruction *Common = commonDivTransforms(I))
3246     return Common;
3247   
3248   // Handle cases involving: [su]div X, (select Cond, Y, Z)
3249   // This does not apply for fdiv.
3250   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3251     return &I;
3252
3253   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3254     // div X, 1 == X
3255     if (RHS->equalsInt(1))
3256       return ReplaceInstUsesWith(I, Op0);
3257
3258     // (X / C1) / C2  -> X / (C1*C2)
3259     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3260       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3261         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3262           if (MultiplyOverflows(RHS, LHSRHS,
3263                                 I.getOpcode()==Instruction::SDiv))
3264             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3265           else 
3266             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
3267                                       ConstantExpr::getMul(RHS, LHSRHS));
3268         }
3269
3270     if (!RHS->isZero()) { // avoid X udiv 0
3271       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3272         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3273           return R;
3274       if (isa<PHINode>(Op0))
3275         if (Instruction *NV = FoldOpIntoPhi(I))
3276           return NV;
3277     }
3278   }
3279
3280   // 0 / X == 0, we don't need to preserve faults!
3281   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3282     if (LHS->equalsInt(0))
3283       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3284
3285   // It can't be division by zero, hence it must be division by one.
3286   if (I.getType() == Type::getInt1Ty(*Context))
3287     return ReplaceInstUsesWith(I, Op0);
3288
3289   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3290     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3291       // div X, 1 == X
3292       if (X->isOne())
3293         return ReplaceInstUsesWith(I, Op0);
3294   }
3295
3296   return 0;
3297 }
3298
3299 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3300   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3301
3302   // Handle the integer div common cases
3303   if (Instruction *Common = commonIDivTransforms(I))
3304     return Common;
3305
3306   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3307     // X udiv C^2 -> X >> C
3308     // Check to see if this is an unsigned division with an exact power of 2,
3309     // if so, convert to a right shift.
3310     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3311       return BinaryOperator::CreateLShr(Op0, 
3312             ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3313
3314     // X udiv C, where C >= signbit
3315     if (C->getValue().isNegative()) {
3316       Value *IC = Builder->CreateICmpULT( Op0, C);
3317       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3318                                 ConstantInt::get(I.getType(), 1));
3319     }
3320   }
3321
3322   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3323   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3324     if (RHSI->getOpcode() == Instruction::Shl &&
3325         isa<ConstantInt>(RHSI->getOperand(0))) {
3326       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3327       if (C1.isPowerOf2()) {
3328         Value *N = RHSI->getOperand(1);
3329         const Type *NTy = N->getType();
3330         if (uint32_t C2 = C1.logBase2())
3331           N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
3332         return BinaryOperator::CreateLShr(Op0, N);
3333       }
3334     }
3335   }
3336   
3337   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3338   // where C1&C2 are powers of two.
3339   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3340     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3341       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3342         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3343         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3344           // Compute the shift amounts
3345           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3346           // Construct the "on true" case of the select
3347           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3348           Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
3349   
3350           // Construct the "on false" case of the select
3351           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3352           Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
3353
3354           // construct the select instruction and return it.
3355           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3356         }
3357       }
3358   return 0;
3359 }
3360
3361 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3362   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3363
3364   // Handle the integer div common cases
3365   if (Instruction *Common = commonIDivTransforms(I))
3366     return Common;
3367
3368   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3369     // sdiv X, -1 == -X
3370     if (RHS->isAllOnesValue())
3371       return BinaryOperator::CreateNeg(Op0);
3372
3373     // sdiv X, C  -->  ashr X, log2(C)
3374     if (cast<SDivOperator>(&I)->isExact() &&
3375         RHS->getValue().isNonNegative() &&
3376         RHS->getValue().isPowerOf2()) {
3377       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3378                                             RHS->getValue().exactLogBase2());
3379       return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3380     }
3381
3382     // -X/C  -->  X/-C  provided the negation doesn't overflow.
3383     if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3384       if (isa<Constant>(Sub->getOperand(0)) &&
3385           cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3386           Sub->hasNoSignedWrap())
3387         return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3388                                           ConstantExpr::getNeg(RHS));
3389   }
3390
3391   // If the sign bits of both operands are zero (i.e. we can prove they are
3392   // unsigned inputs), turn this into a udiv.
3393   if (I.getType()->isInteger()) {
3394     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3395     if (MaskedValueIsZero(Op0, Mask)) {
3396       if (MaskedValueIsZero(Op1, Mask)) {
3397         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3398         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3399       }
3400       ConstantInt *ShiftedInt;
3401       if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3402           ShiftedInt->getValue().isPowerOf2()) {
3403         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3404         // Safe because the only negative value (1 << Y) can take on is
3405         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3406         // the sign bit set.
3407         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3408       }
3409     }
3410   }
3411   
3412   return 0;
3413 }
3414
3415 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3416   return commonDivTransforms(I);
3417 }
3418
3419 /// This function implements the transforms on rem instructions that work
3420 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3421 /// is used by the visitors to those instructions.
3422 /// @brief Transforms common to all three rem instructions
3423 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3424   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3425
3426   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3427     if (I.getType()->isFPOrFPVector())
3428       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3429     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3430   }
3431   if (isa<UndefValue>(Op1))
3432     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3433
3434   // Handle cases involving: rem X, (select Cond, Y, Z)
3435   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3436     return &I;
3437
3438   return 0;
3439 }
3440
3441 /// This function implements the transforms common to both integer remainder
3442 /// instructions (urem and srem). It is called by the visitors to those integer
3443 /// remainder instructions.
3444 /// @brief Common integer remainder transforms
3445 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3446   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3447
3448   if (Instruction *common = commonRemTransforms(I))
3449     return common;
3450
3451   // 0 % X == 0 for integer, we don't need to preserve faults!
3452   if (Constant *LHS = dyn_cast<Constant>(Op0))
3453     if (LHS->isNullValue())
3454       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3455
3456   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3457     // X % 0 == undef, we don't need to preserve faults!
3458     if (RHS->equalsInt(0))
3459       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3460     
3461     if (RHS->equalsInt(1))  // X % 1 == 0
3462       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3463
3464     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3465       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3466         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3467           return R;
3468       } else if (isa<PHINode>(Op0I)) {
3469         if (Instruction *NV = FoldOpIntoPhi(I))
3470           return NV;
3471       }
3472
3473       // See if we can fold away this rem instruction.
3474       if (SimplifyDemandedInstructionBits(I))
3475         return &I;
3476     }
3477   }
3478
3479   return 0;
3480 }
3481
3482 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3483   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3484
3485   if (Instruction *common = commonIRemTransforms(I))
3486     return common;
3487   
3488   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3489     // X urem C^2 -> X and C
3490     // Check to see if this is an unsigned remainder with an exact power of 2,
3491     // if so, convert to a bitwise and.
3492     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3493       if (C->getValue().isPowerOf2())
3494         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3495   }
3496
3497   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3498     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3499     if (RHSI->getOpcode() == Instruction::Shl &&
3500         isa<ConstantInt>(RHSI->getOperand(0))) {
3501       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3502         Constant *N1 = Constant::getAllOnesValue(I.getType());
3503         Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
3504         return BinaryOperator::CreateAnd(Op0, Add);
3505       }
3506     }
3507   }
3508
3509   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3510   // where C1&C2 are powers of two.
3511   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3512     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3513       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3514         // STO == 0 and SFO == 0 handled above.
3515         if ((STO->getValue().isPowerOf2()) && 
3516             (SFO->getValue().isPowerOf2())) {
3517           Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3518                                               SI->getName()+".t");
3519           Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3520                                                SI->getName()+".f");
3521           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3522         }
3523       }
3524   }
3525   
3526   return 0;
3527 }
3528
3529 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3530   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3531
3532   // Handle the integer rem common cases
3533   if (Instruction *Common = commonIRemTransforms(I))
3534     return Common;
3535   
3536   if (Value *RHSNeg = dyn_castNegVal(Op1))
3537     if (!isa<Constant>(RHSNeg) ||
3538         (isa<ConstantInt>(RHSNeg) &&
3539          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3540       // X % -Y -> X % Y
3541       Worklist.AddValue(I.getOperand(1));
3542       I.setOperand(1, RHSNeg);
3543       return &I;
3544     }
3545
3546   // If the sign bits of both operands are zero (i.e. we can prove they are
3547   // unsigned inputs), turn this into a urem.
3548   if (I.getType()->isInteger()) {
3549     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3550     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3551       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3552       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3553     }
3554   }
3555
3556   // If it's a constant vector, flip any negative values positive.
3557   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3558     unsigned VWidth = RHSV->getNumOperands();
3559
3560     bool hasNegative = false;
3561     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3562       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3563         if (RHS->getValue().isNegative())
3564           hasNegative = true;
3565
3566     if (hasNegative) {
3567       std::vector<Constant *> Elts(VWidth);
3568       for (unsigned i = 0; i != VWidth; ++i) {
3569         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3570           if (RHS->getValue().isNegative())
3571             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3572           else
3573             Elts[i] = RHS;
3574         }
3575       }
3576
3577       Constant *NewRHSV = ConstantVector::get(Elts);
3578       if (NewRHSV != RHSV) {
3579         Worklist.AddValue(I.getOperand(1));
3580         I.setOperand(1, NewRHSV);
3581         return &I;
3582       }
3583     }
3584   }
3585
3586   return 0;
3587 }
3588
3589 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3590   return commonRemTransforms(I);
3591 }
3592
3593 // isOneBitSet - Return true if there is exactly one bit set in the specified
3594 // constant.
3595 static bool isOneBitSet(const ConstantInt *CI) {
3596   return CI->getValue().isPowerOf2();
3597 }
3598
3599 // isHighOnes - Return true if the constant is of the form 1+0+.
3600 // This is the same as lowones(~X).
3601 static bool isHighOnes(const ConstantInt *CI) {
3602   return (~CI->getValue() + 1).isPowerOf2();
3603 }
3604
3605 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3606 /// are carefully arranged to allow folding of expressions such as:
3607 ///
3608 ///      (A < B) | (A > B) --> (A != B)
3609 ///
3610 /// Note that this is only valid if the first and second predicates have the
3611 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3612 ///
3613 /// Three bits are used to represent the condition, as follows:
3614 ///   0  A > B
3615 ///   1  A == B
3616 ///   2  A < B
3617 ///
3618 /// <=>  Value  Definition
3619 /// 000     0   Always false
3620 /// 001     1   A >  B
3621 /// 010     2   A == B
3622 /// 011     3   A >= B
3623 /// 100     4   A <  B
3624 /// 101     5   A != B
3625 /// 110     6   A <= B
3626 /// 111     7   Always true
3627 ///  
3628 static unsigned getICmpCode(const ICmpInst *ICI) {
3629   switch (ICI->getPredicate()) {
3630     // False -> 0
3631   case ICmpInst::ICMP_UGT: return 1;  // 001
3632   case ICmpInst::ICMP_SGT: return 1;  // 001
3633   case ICmpInst::ICMP_EQ:  return 2;  // 010
3634   case ICmpInst::ICMP_UGE: return 3;  // 011
3635   case ICmpInst::ICMP_SGE: return 3;  // 011
3636   case ICmpInst::ICMP_ULT: return 4;  // 100
3637   case ICmpInst::ICMP_SLT: return 4;  // 100
3638   case ICmpInst::ICMP_NE:  return 5;  // 101
3639   case ICmpInst::ICMP_ULE: return 6;  // 110
3640   case ICmpInst::ICMP_SLE: return 6;  // 110
3641     // True -> 7
3642   default:
3643     llvm_unreachable("Invalid ICmp predicate!");
3644     return 0;
3645   }
3646 }
3647
3648 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3649 /// predicate into a three bit mask. It also returns whether it is an ordered
3650 /// predicate by reference.
3651 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3652   isOrdered = false;
3653   switch (CC) {
3654   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3655   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3656   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3657   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3658   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3659   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3660   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3661   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3662   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3663   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3664   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3665   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3666   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3667   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3668     // True -> 7
3669   default:
3670     // Not expecting FCMP_FALSE and FCMP_TRUE;
3671     llvm_unreachable("Unexpected FCmp predicate!");
3672     return 0;
3673   }
3674 }
3675
3676 /// getICmpValue - This is the complement of getICmpCode, which turns an
3677 /// opcode and two operands into either a constant true or false, or a brand 
3678 /// new ICmp instruction. The sign is passed in to determine which kind
3679 /// of predicate to use in the new icmp instruction.
3680 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3681                            LLVMContext *Context) {
3682   switch (code) {
3683   default: llvm_unreachable("Illegal ICmp code!");
3684   case  0: return ConstantInt::getFalse(*Context);
3685   case  1: 
3686     if (sign)
3687       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3688     else
3689       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3690   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3691   case  3: 
3692     if (sign)
3693       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3694     else
3695       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3696   case  4: 
3697     if (sign)
3698       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3699     else
3700       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3701   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3702   case  6: 
3703     if (sign)
3704       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3705     else
3706       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3707   case  7: return ConstantInt::getTrue(*Context);
3708   }
3709 }
3710
3711 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3712 /// opcode and two operands into either a FCmp instruction. isordered is passed
3713 /// in to determine which kind of predicate to use in the new fcmp instruction.
3714 static Value *getFCmpValue(bool isordered, unsigned code,
3715                            Value *LHS, Value *RHS, LLVMContext *Context) {
3716   switch (code) {
3717   default: llvm_unreachable("Illegal FCmp code!");
3718   case  0:
3719     if (isordered)
3720       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3721     else
3722       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3723   case  1: 
3724     if (isordered)
3725       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3726     else
3727       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3728   case  2: 
3729     if (isordered)
3730       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3731     else
3732       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3733   case  3: 
3734     if (isordered)
3735       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3736     else
3737       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3738   case  4: 
3739     if (isordered)
3740       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3741     else
3742       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3743   case  5: 
3744     if (isordered)
3745       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3746     else
3747       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3748   case  6: 
3749     if (isordered)
3750       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3751     else
3752       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3753   case  7: return ConstantInt::getTrue(*Context);
3754   }
3755 }
3756
3757 /// PredicatesFoldable - Return true if both predicates match sign or if at
3758 /// least one of them is an equality comparison (which is signless).
3759 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3760   return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3761          (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3762          (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
3763 }
3764
3765 namespace { 
3766 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3767 struct FoldICmpLogical {
3768   InstCombiner &IC;
3769   Value *LHS, *RHS;
3770   ICmpInst::Predicate pred;
3771   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3772     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3773       pred(ICI->getPredicate()) {}
3774   bool shouldApply(Value *V) const {
3775     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3776       if (PredicatesFoldable(pred, ICI->getPredicate()))
3777         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3778                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3779     return false;
3780   }
3781   Instruction *apply(Instruction &Log) const {
3782     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3783     if (ICI->getOperand(0) != LHS) {
3784       assert(ICI->getOperand(1) == LHS);
3785       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3786     }
3787
3788     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3789     unsigned LHSCode = getICmpCode(ICI);
3790     unsigned RHSCode = getICmpCode(RHSICI);
3791     unsigned Code;
3792     switch (Log.getOpcode()) {
3793     case Instruction::And: Code = LHSCode & RHSCode; break;
3794     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3795     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3796     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3797     }
3798
3799     bool isSigned = RHSICI->isSigned() || ICI->isSigned();
3800     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3801     if (Instruction *I = dyn_cast<Instruction>(RV))
3802       return I;
3803     // Otherwise, it's a constant boolean value...
3804     return IC.ReplaceInstUsesWith(Log, RV);
3805   }
3806 };
3807 } // end anonymous namespace
3808
3809 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3810 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3811 // guaranteed to be a binary operator.
3812 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3813                                     ConstantInt *OpRHS,
3814                                     ConstantInt *AndRHS,
3815                                     BinaryOperator &TheAnd) {
3816   Value *X = Op->getOperand(0);
3817   Constant *Together = 0;
3818   if (!Op->isShift())
3819     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3820
3821   switch (Op->getOpcode()) {
3822   case Instruction::Xor:
3823     if (Op->hasOneUse()) {
3824       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3825       Value *And = Builder->CreateAnd(X, AndRHS);
3826       And->takeName(Op);
3827       return BinaryOperator::CreateXor(And, Together);
3828     }
3829     break;
3830   case Instruction::Or:
3831     if (Together == AndRHS) // (X | C) & C --> C
3832       return ReplaceInstUsesWith(TheAnd, AndRHS);
3833
3834     if (Op->hasOneUse() && Together != OpRHS) {
3835       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3836       Value *Or = Builder->CreateOr(X, Together);
3837       Or->takeName(Op);
3838       return BinaryOperator::CreateAnd(Or, AndRHS);
3839     }
3840     break;
3841   case Instruction::Add:
3842     if (Op->hasOneUse()) {
3843       // Adding a one to a single bit bit-field should be turned into an XOR
3844       // of the bit.  First thing to check is to see if this AND is with a
3845       // single bit constant.
3846       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3847
3848       // If there is only one bit set...
3849       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3850         // Ok, at this point, we know that we are masking the result of the
3851         // ADD down to exactly one bit.  If the constant we are adding has
3852         // no bits set below this bit, then we can eliminate the ADD.
3853         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3854
3855         // Check to see if any bits below the one bit set in AndRHSV are set.
3856         if ((AddRHS & (AndRHSV-1)) == 0) {
3857           // If not, the only thing that can effect the output of the AND is
3858           // the bit specified by AndRHSV.  If that bit is set, the effect of
3859           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3860           // no effect.
3861           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3862             TheAnd.setOperand(0, X);
3863             return &TheAnd;
3864           } else {
3865             // Pull the XOR out of the AND.
3866             Value *NewAnd = Builder->CreateAnd(X, AndRHS);
3867             NewAnd->takeName(Op);
3868             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3869           }
3870         }
3871       }
3872     }
3873     break;
3874
3875   case Instruction::Shl: {
3876     // We know that the AND will not produce any of the bits shifted in, so if
3877     // the anded constant includes them, clear them now!
3878     //
3879     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3880     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3881     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3882     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3883
3884     if (CI->getValue() == ShlMask) { 
3885     // Masking out bits that the shift already masks
3886       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3887     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3888       TheAnd.setOperand(1, CI);
3889       return &TheAnd;
3890     }
3891     break;
3892   }
3893   case Instruction::LShr:
3894   {
3895     // We know that the AND will not produce any of the bits shifted in, so if
3896     // the anded constant includes them, clear them now!  This only applies to
3897     // unsigned shifts, because a signed shr may bring in set bits!
3898     //
3899     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3900     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3901     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3902     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3903
3904     if (CI->getValue() == ShrMask) {   
3905     // Masking out bits that the shift already masks.
3906       return ReplaceInstUsesWith(TheAnd, Op);
3907     } else if (CI != AndRHS) {
3908       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3909       return &TheAnd;
3910     }
3911     break;
3912   }
3913   case Instruction::AShr:
3914     // Signed shr.
3915     // See if this is shifting in some sign extension, then masking it out
3916     // with an and.
3917     if (Op->hasOneUse()) {
3918       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3919       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3920       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3921       Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3922       if (C == AndRHS) {          // Masking out bits shifted in.
3923         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3924         // Make the argument unsigned.
3925         Value *ShVal = Op->getOperand(0);
3926         ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
3927         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3928       }
3929     }
3930     break;
3931   }
3932   return 0;
3933 }
3934
3935
3936 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3937 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3938 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3939 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3940 /// insert new instructions.
3941 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3942                                            bool isSigned, bool Inside, 
3943                                            Instruction &IB) {
3944   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3945             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3946          "Lo is not <= Hi in range emission code!");
3947     
3948   if (Inside) {
3949     if (Lo == Hi)  // Trivially false.
3950       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3951
3952     // V >= Min && V < Hi --> V < Hi
3953     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3954       ICmpInst::Predicate pred = (isSigned ? 
3955         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3956       return new ICmpInst(pred, V, Hi);
3957     }
3958
3959     // Emit V-Lo <u Hi-Lo
3960     Constant *NegLo = ConstantExpr::getNeg(Lo);
3961     Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3962     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3963     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3964   }
3965
3966   if (Lo == Hi)  // Trivially true.
3967     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3968
3969   // V < Min || V >= Hi -> V > Hi-1
3970   Hi = SubOne(cast<ConstantInt>(Hi));
3971   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3972     ICmpInst::Predicate pred = (isSigned ? 
3973         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3974     return new ICmpInst(pred, V, Hi);
3975   }
3976
3977   // Emit V-Lo >u Hi-1-Lo
3978   // Note that Hi has already had one subtracted from it, above.
3979   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3980   Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3981   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3982   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3983 }
3984
3985 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3986 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3987 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3988 // not, since all 1s are not contiguous.
3989 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3990   const APInt& V = Val->getValue();
3991   uint32_t BitWidth = Val->getType()->getBitWidth();
3992   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3993
3994   // look for the first zero bit after the run of ones
3995   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3996   // look for the first non-zero bit
3997   ME = V.getActiveBits(); 
3998   return true;
3999 }
4000
4001 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
4002 /// where isSub determines whether the operator is a sub.  If we can fold one of
4003 /// the following xforms:
4004 /// 
4005 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
4006 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4007 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4008 ///
4009 /// return (A +/- B).
4010 ///
4011 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
4012                                         ConstantInt *Mask, bool isSub,
4013                                         Instruction &I) {
4014   Instruction *LHSI = dyn_cast<Instruction>(LHS);
4015   if (!LHSI || LHSI->getNumOperands() != 2 ||
4016       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
4017
4018   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
4019
4020   switch (LHSI->getOpcode()) {
4021   default: return 0;
4022   case Instruction::And:
4023     if (ConstantExpr::getAnd(N, Mask) == Mask) {
4024       // If the AndRHS is a power of two minus one (0+1+), this is simple.
4025       if ((Mask->getValue().countLeadingZeros() + 
4026            Mask->getValue().countPopulation()) == 
4027           Mask->getValue().getBitWidth())
4028         break;
4029
4030       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4031       // part, we don't need any explicit masks to take them out of A.  If that
4032       // is all N is, ignore it.
4033       uint32_t MB = 0, ME = 0;
4034       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
4035         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
4036         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
4037         if (MaskedValueIsZero(RHS, Mask))
4038           break;
4039       }
4040     }
4041     return 0;
4042   case Instruction::Or:
4043   case Instruction::Xor:
4044     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
4045     if ((Mask->getValue().countLeadingZeros() + 
4046          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
4047         && ConstantExpr::getAnd(N, Mask)->isNullValue())
4048       break;
4049     return 0;
4050   }
4051   
4052   if (isSub)
4053     return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
4054   return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
4055 }
4056
4057 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
4058 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
4059                                           ICmpInst *LHS, ICmpInst *RHS) {
4060   Value *Val, *Val2;
4061   ConstantInt *LHSCst, *RHSCst;
4062   ICmpInst::Predicate LHSCC, RHSCC;
4063   
4064   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
4065   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4066                          m_ConstantInt(LHSCst))) ||
4067       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4068                          m_ConstantInt(RHSCst))))
4069     return 0;
4070   
4071   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
4072   // where C is a power of 2
4073   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
4074       LHSCst->getValue().isPowerOf2()) {
4075     Value *NewOr = Builder->CreateOr(Val, Val2);
4076     return new ICmpInst(LHSCC, NewOr, LHSCst);
4077   }
4078   
4079   // From here on, we only handle:
4080   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
4081   if (Val != Val2) return 0;
4082   
4083   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4084   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4085       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4086       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4087       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4088     return 0;
4089   
4090   // We can't fold (ugt x, C) & (sgt x, C2).
4091   if (!PredicatesFoldable(LHSCC, RHSCC))
4092     return 0;
4093     
4094   // Ensure that the larger constant is on the RHS.
4095   bool ShouldSwap;
4096   if (CmpInst::isSigned(LHSCC) ||
4097       (ICmpInst::isEquality(LHSCC) && 
4098        CmpInst::isSigned(RHSCC)))
4099     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4100   else
4101     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4102     
4103   if (ShouldSwap) {
4104     std::swap(LHS, RHS);
4105     std::swap(LHSCst, RHSCst);
4106     std::swap(LHSCC, RHSCC);
4107   }
4108
4109   // At this point, we know we have have two icmp instructions
4110   // comparing a value against two constants and and'ing the result
4111   // together.  Because of the above check, we know that we only have
4112   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
4113   // (from the FoldICmpLogical check above), that the two constants 
4114   // are not equal and that the larger constant is on the RHS
4115   assert(LHSCst != RHSCst && "Compares not folded above?");
4116
4117   switch (LHSCC) {
4118   default: llvm_unreachable("Unknown integer condition code!");
4119   case ICmpInst::ICMP_EQ:
4120     switch (RHSCC) {
4121     default: llvm_unreachable("Unknown integer condition code!");
4122     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
4123     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
4124     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
4125       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4126     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
4127     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
4128     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
4129       return ReplaceInstUsesWith(I, LHS);
4130     }
4131   case ICmpInst::ICMP_NE:
4132     switch (RHSCC) {
4133     default: llvm_unreachable("Unknown integer condition code!");
4134     case ICmpInst::ICMP_ULT:
4135       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4136         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
4137       break;                        // (X != 13 & X u< 15) -> no change
4138     case ICmpInst::ICMP_SLT:
4139       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4140         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
4141       break;                        // (X != 13 & X s< 15) -> no change
4142     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
4143     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
4144     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
4145       return ReplaceInstUsesWith(I, RHS);
4146     case ICmpInst::ICMP_NE:
4147       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
4148         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4149         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4150         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4151                             ConstantInt::get(Add->getType(), 1));
4152       }
4153       break;                        // (X != 13 & X != 15) -> no change
4154     }
4155     break;
4156   case ICmpInst::ICMP_ULT:
4157     switch (RHSCC) {
4158     default: llvm_unreachable("Unknown integer condition code!");
4159     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
4160     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
4161       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4162     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
4163       break;
4164     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
4165     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
4166       return ReplaceInstUsesWith(I, LHS);
4167     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
4168       break;
4169     }
4170     break;
4171   case ICmpInst::ICMP_SLT:
4172     switch (RHSCC) {
4173     default: llvm_unreachable("Unknown integer condition code!");
4174     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
4175     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
4176       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4177     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
4178       break;
4179     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
4180     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
4181       return ReplaceInstUsesWith(I, LHS);
4182     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
4183       break;
4184     }
4185     break;
4186   case ICmpInst::ICMP_UGT:
4187     switch (RHSCC) {
4188     default: llvm_unreachable("Unknown integer condition code!");
4189     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
4190     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
4191       return ReplaceInstUsesWith(I, RHS);
4192     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
4193       break;
4194     case ICmpInst::ICMP_NE:
4195       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4196         return new ICmpInst(LHSCC, Val, RHSCst);
4197       break;                        // (X u> 13 & X != 15) -> no change
4198     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
4199       return InsertRangeTest(Val, AddOne(LHSCst),
4200                              RHSCst, false, true, I);
4201     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
4202       break;
4203     }
4204     break;
4205   case ICmpInst::ICMP_SGT:
4206     switch (RHSCC) {
4207     default: llvm_unreachable("Unknown integer condition code!");
4208     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
4209     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
4210       return ReplaceInstUsesWith(I, RHS);
4211     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
4212       break;
4213     case ICmpInst::ICMP_NE:
4214       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4215         return new ICmpInst(LHSCC, Val, RHSCst);
4216       break;                        // (X s> 13 & X != 15) -> no change
4217     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
4218       return InsertRangeTest(Val, AddOne(LHSCst),
4219                              RHSCst, true, true, I);
4220     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
4221       break;
4222     }
4223     break;
4224   }
4225  
4226   return 0;
4227 }
4228
4229 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4230                                           FCmpInst *RHS) {
4231   
4232   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4233       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4234     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4235     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4236       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4237         // If either of the constants are nans, then the whole thing returns
4238         // false.
4239         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4240           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4241         return new FCmpInst(FCmpInst::FCMP_ORD,
4242                             LHS->getOperand(0), RHS->getOperand(0));
4243       }
4244     
4245     // Handle vector zeros.  This occurs because the canonical form of
4246     // "fcmp ord x,x" is "fcmp ord x, 0".
4247     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4248         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4249       return new FCmpInst(FCmpInst::FCMP_ORD,
4250                           LHS->getOperand(0), RHS->getOperand(0));
4251     return 0;
4252   }
4253   
4254   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4255   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4256   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4257   
4258   
4259   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4260     // Swap RHS operands to match LHS.
4261     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4262     std::swap(Op1LHS, Op1RHS);
4263   }
4264   
4265   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4266     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4267     if (Op0CC == Op1CC)
4268       return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4269     
4270     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
4271       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4272     if (Op0CC == FCmpInst::FCMP_TRUE)
4273       return ReplaceInstUsesWith(I, RHS);
4274     if (Op1CC == FCmpInst::FCMP_TRUE)
4275       return ReplaceInstUsesWith(I, LHS);
4276     
4277     bool Op0Ordered;
4278     bool Op1Ordered;
4279     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4280     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4281     if (Op1Pred == 0) {
4282       std::swap(LHS, RHS);
4283       std::swap(Op0Pred, Op1Pred);
4284       std::swap(Op0Ordered, Op1Ordered);
4285     }
4286     if (Op0Pred == 0) {
4287       // uno && ueq -> uno && (uno || eq) -> ueq
4288       // ord && olt -> ord && (ord && lt) -> olt
4289       if (Op0Ordered == Op1Ordered)
4290         return ReplaceInstUsesWith(I, RHS);
4291       
4292       // uno && oeq -> uno && (ord && eq) -> false
4293       // uno && ord -> false
4294       if (!Op0Ordered)
4295         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4296       // ord && ueq -> ord && (uno || eq) -> oeq
4297       return cast<Instruction>(getFCmpValue(true, Op1Pred,
4298                                             Op0LHS, Op0RHS, Context));
4299     }
4300   }
4301
4302   return 0;
4303 }
4304
4305
4306 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4307   bool Changed = SimplifyCommutative(I);
4308   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4309
4310   if (isa<UndefValue>(Op1))                         // X & undef -> 0
4311     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4312
4313   // and X, X = X
4314   if (Op0 == Op1)
4315     return ReplaceInstUsesWith(I, Op1);
4316
4317   // See if we can simplify any instructions used by the instruction whose sole 
4318   // purpose is to compute bits we don't care about.
4319   if (SimplifyDemandedInstructionBits(I))
4320     return &I;
4321   if (isa<VectorType>(I.getType())) {
4322     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4323       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
4324         return ReplaceInstUsesWith(I, I.getOperand(0));
4325     } else if (isa<ConstantAggregateZero>(Op1)) {
4326       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
4327     }
4328   }
4329
4330   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4331     const APInt &AndRHSMask = AndRHS->getValue();
4332     APInt NotAndRHS(~AndRHSMask);
4333
4334     // Optimize a variety of ((val OP C1) & C2) combinations...
4335     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4336       Value *Op0LHS = Op0I->getOperand(0);
4337       Value *Op0RHS = Op0I->getOperand(1);
4338       switch (Op0I->getOpcode()) {
4339       default: break;
4340       case Instruction::Xor:
4341       case Instruction::Or:
4342         // If the mask is only needed on one incoming arm, push it up.
4343         if (!Op0I->hasOneUse()) break;
4344           
4345         if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4346           // Not masking anything out for the LHS, move to RHS.
4347           Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4348                                              Op0RHS->getName()+".masked");
4349           return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4350         }
4351         if (!isa<Constant>(Op0RHS) &&
4352             MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4353           // Not masking anything out for the RHS, move to LHS.
4354           Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4355                                              Op0LHS->getName()+".masked");
4356           return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
4357         }
4358
4359         break;
4360       case Instruction::Add:
4361         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4362         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4363         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4364         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4365           return BinaryOperator::CreateAnd(V, AndRHS);
4366         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4367           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4368         break;
4369
4370       case Instruction::Sub:
4371         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4372         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4373         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4374         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4375           return BinaryOperator::CreateAnd(V, AndRHS);
4376
4377         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4378         // has 1's for all bits that the subtraction with A might affect.
4379         if (Op0I->hasOneUse()) {
4380           uint32_t BitWidth = AndRHSMask.getBitWidth();
4381           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4382           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4383
4384           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4385           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4386               MaskedValueIsZero(Op0LHS, Mask)) {
4387             Value *NewNeg = Builder->CreateNeg(Op0RHS);
4388             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4389           }
4390         }
4391         break;
4392
4393       case Instruction::Shl:
4394       case Instruction::LShr:
4395         // (1 << x) & 1 --> zext(x == 0)
4396         // (1 >> x) & 1 --> zext(x == 0)
4397         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4398           Value *NewICmp =
4399             Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
4400           return new ZExtInst(NewICmp, I.getType());
4401         }
4402         break;
4403       }
4404
4405       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4406         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4407           return Res;
4408     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4409       // If this is an integer truncation or change from signed-to-unsigned, and
4410       // if the source is an and/or with immediate, transform it.  This
4411       // frequently occurs for bitfield accesses.
4412       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4413         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4414             CastOp->getNumOperands() == 2)
4415           if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
4416             if (CastOp->getOpcode() == Instruction::And) {
4417               // Change: and (cast (and X, C1) to T), C2
4418               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4419               // This will fold the two constants together, which may allow 
4420               // other simplifications.
4421               Value *NewCast = Builder->CreateTruncOrBitCast(
4422                 CastOp->getOperand(0), I.getType(), 
4423                 CastOp->getName()+".shrunk");
4424               // trunc_or_bitcast(C1)&C2
4425               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4426               C3 = ConstantExpr::getAnd(C3, AndRHS);
4427               return BinaryOperator::CreateAnd(NewCast, C3);
4428             } else if (CastOp->getOpcode() == Instruction::Or) {
4429               // Change: and (cast (or X, C1) to T), C2
4430               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4431               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4432               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4433                 // trunc(C1)&C2
4434                 return ReplaceInstUsesWith(I, AndRHS);
4435             }
4436           }
4437       }
4438     }
4439
4440     // Try to fold constant and into select arguments.
4441     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4442       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4443         return R;
4444     if (isa<PHINode>(Op0))
4445       if (Instruction *NV = FoldOpIntoPhi(I))
4446         return NV;
4447   }
4448
4449   Value *Op0NotVal = dyn_castNotVal(Op0);
4450   Value *Op1NotVal = dyn_castNotVal(Op1);
4451
4452   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4453     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4454
4455   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4456   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4457     Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4458                                   I.getName()+".demorgan");
4459     return BinaryOperator::CreateNot(Or);
4460   }
4461   
4462   {
4463     Value *A = 0, *B = 0, *C = 0, *D = 0;
4464     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4465       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4466         return ReplaceInstUsesWith(I, Op1);
4467     
4468       // (A|B) & ~(A&B) -> A^B
4469       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4470         if ((A == C && B == D) || (A == D && B == C))
4471           return BinaryOperator::CreateXor(A, B);
4472       }
4473     }
4474     
4475     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4476       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4477         return ReplaceInstUsesWith(I, Op0);
4478
4479       // ~(A&B) & (A|B) -> A^B
4480       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4481         if ((A == C && B == D) || (A == D && B == C))
4482           return BinaryOperator::CreateXor(A, B);
4483       }
4484     }
4485     
4486     if (Op0->hasOneUse() &&
4487         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4488       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4489         I.swapOperands();     // Simplify below
4490         std::swap(Op0, Op1);
4491       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4492         cast<BinaryOperator>(Op0)->swapOperands();
4493         I.swapOperands();     // Simplify below
4494         std::swap(Op0, Op1);
4495       }
4496     }
4497
4498     if (Op1->hasOneUse() &&
4499         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4500       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4501         cast<BinaryOperator>(Op1)->swapOperands();
4502         std::swap(A, B);
4503       }
4504       if (A == Op0)                                // A&(A^B) -> A & ~B
4505         return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
4506     }
4507
4508     // (A&((~A)|B)) -> A&B
4509     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4510         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4511       return BinaryOperator::CreateAnd(A, Op1);
4512     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4513         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4514       return BinaryOperator::CreateAnd(A, Op0);
4515   }
4516   
4517   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4518     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4519     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4520       return R;
4521
4522     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4523       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4524         return Res;
4525   }
4526
4527   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4528   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4529     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4530       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4531         const Type *SrcTy = Op0C->getOperand(0)->getType();
4532         if (SrcTy == Op1C->getOperand(0)->getType() &&
4533             SrcTy->isIntOrIntVector() &&
4534             // Only do this if the casts both really cause code to be generated.
4535             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4536                               I.getType(), TD) &&
4537             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4538                               I.getType(), TD)) {
4539           Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4540                                             Op1C->getOperand(0), I.getName());
4541           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4542         }
4543       }
4544     
4545   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4546   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4547     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4548       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4549           SI0->getOperand(1) == SI1->getOperand(1) &&
4550           (SI0->hasOneUse() || SI1->hasOneUse())) {
4551         Value *NewOp =
4552           Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4553                              SI0->getName());
4554         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4555                                       SI1->getOperand(1));
4556       }
4557   }
4558
4559   // If and'ing two fcmp, try combine them into one.
4560   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4561     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4562       if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4563         return Res;
4564   }
4565
4566   return Changed ? &I : 0;
4567 }
4568
4569 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4570 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4571 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4572 /// the expression came from the corresponding "byte swapped" byte in some other
4573 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4574 /// we know that the expression deposits the low byte of %X into the high byte
4575 /// of the bswap result and that all other bytes are zero.  This expression is
4576 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4577 /// match.
4578 ///
4579 /// This function returns true if the match was unsuccessful and false if so.
4580 /// On entry to the function the "OverallLeftShift" is a signed integer value
4581 /// indicating the number of bytes that the subexpression is later shifted.  For
4582 /// example, if the expression is later right shifted by 16 bits, the
4583 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4584 /// byte of ByteValues is actually being set.
4585 ///
4586 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4587 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4588 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4589 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4590 /// always in the local (OverallLeftShift) coordinate space.
4591 ///
4592 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4593                               SmallVector<Value*, 8> &ByteValues) {
4594   if (Instruction *I = dyn_cast<Instruction>(V)) {
4595     // If this is an or instruction, it may be an inner node of the bswap.
4596     if (I->getOpcode() == Instruction::Or) {
4597       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4598                                ByteValues) ||
4599              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4600                                ByteValues);
4601     }
4602   
4603     // If this is a logical shift by a constant multiple of 8, recurse with
4604     // OverallLeftShift and ByteMask adjusted.
4605     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4606       unsigned ShAmt = 
4607         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4608       // Ensure the shift amount is defined and of a byte value.
4609       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4610         return true;
4611
4612       unsigned ByteShift = ShAmt >> 3;
4613       if (I->getOpcode() == Instruction::Shl) {
4614         // X << 2 -> collect(X, +2)
4615         OverallLeftShift += ByteShift;
4616         ByteMask >>= ByteShift;
4617       } else {
4618         // X >>u 2 -> collect(X, -2)
4619         OverallLeftShift -= ByteShift;
4620         ByteMask <<= ByteShift;
4621         ByteMask &= (~0U >> (32-ByteValues.size()));
4622       }
4623
4624       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4625       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4626
4627       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4628                                ByteValues);
4629     }
4630
4631     // If this is a logical 'and' with a mask that clears bytes, clear the
4632     // corresponding bytes in ByteMask.
4633     if (I->getOpcode() == Instruction::And &&
4634         isa<ConstantInt>(I->getOperand(1))) {
4635       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4636       unsigned NumBytes = ByteValues.size();
4637       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4638       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4639       
4640       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4641         // If this byte is masked out by a later operation, we don't care what
4642         // the and mask is.
4643         if ((ByteMask & (1 << i)) == 0)
4644           continue;
4645         
4646         // If the AndMask is all zeros for this byte, clear the bit.
4647         APInt MaskB = AndMask & Byte;
4648         if (MaskB == 0) {
4649           ByteMask &= ~(1U << i);
4650           continue;
4651         }
4652         
4653         // If the AndMask is not all ones for this byte, it's not a bytezap.
4654         if (MaskB != Byte)
4655           return true;
4656
4657         // Otherwise, this byte is kept.
4658       }
4659
4660       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4661                                ByteValues);
4662     }
4663   }
4664   
4665   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4666   // the input value to the bswap.  Some observations: 1) if more than one byte
4667   // is demanded from this input, then it could not be successfully assembled
4668   // into a byteswap.  At least one of the two bytes would not be aligned with
4669   // their ultimate destination.
4670   if (!isPowerOf2_32(ByteMask)) return true;
4671   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4672   
4673   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4674   // is demanded, it needs to go into byte 0 of the result.  This means that the
4675   // byte needs to be shifted until it lands in the right byte bucket.  The
4676   // shift amount depends on the position: if the byte is coming from the high
4677   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4678   // low part, it must be shifted left.
4679   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4680   if (InputByteNo < ByteValues.size()/2) {
4681     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4682       return true;
4683   } else {
4684     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4685       return true;
4686   }
4687   
4688   // If the destination byte value is already defined, the values are or'd
4689   // together, which isn't a bswap (unless it's an or of the same bits).
4690   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4691     return true;
4692   ByteValues[DestByteNo] = V;
4693   return false;
4694 }
4695
4696 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4697 /// If so, insert the new bswap intrinsic and return it.
4698 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4699   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4700   if (!ITy || ITy->getBitWidth() % 16 || 
4701       // ByteMask only allows up to 32-byte values.
4702       ITy->getBitWidth() > 32*8) 
4703     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4704   
4705   /// ByteValues - For each byte of the result, we keep track of which value
4706   /// defines each byte.
4707   SmallVector<Value*, 8> ByteValues;
4708   ByteValues.resize(ITy->getBitWidth()/8);
4709     
4710   // Try to find all the pieces corresponding to the bswap.
4711   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4712   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4713     return 0;
4714   
4715   // Check to see if all of the bytes come from the same value.
4716   Value *V = ByteValues[0];
4717   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4718   
4719   // Check to make sure that all of the bytes come from the same value.
4720   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4721     if (ByteValues[i] != V)
4722       return 0;
4723   const Type *Tys[] = { ITy };
4724   Module *M = I.getParent()->getParent()->getParent();
4725   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4726   return CallInst::Create(F, V);
4727 }
4728
4729 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4730 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4731 /// we can simplify this expression to "cond ? C : D or B".
4732 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4733                                          Value *C, Value *D,
4734                                          LLVMContext *Context) {
4735   // If A is not a select of -1/0, this cannot match.
4736   Value *Cond = 0;
4737   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4738     return 0;
4739
4740   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4741   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4742     return SelectInst::Create(Cond, C, B);
4743   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4744     return SelectInst::Create(Cond, C, B);
4745   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4746   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4747     return SelectInst::Create(Cond, C, D);
4748   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4749     return SelectInst::Create(Cond, C, D);
4750   return 0;
4751 }
4752
4753 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4754 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4755                                          ICmpInst *LHS, ICmpInst *RHS) {
4756   Value *Val, *Val2;
4757   ConstantInt *LHSCst, *RHSCst;
4758   ICmpInst::Predicate LHSCC, RHSCC;
4759   
4760   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4761   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4762              m_ConstantInt(LHSCst))) ||
4763       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4764              m_ConstantInt(RHSCst))))
4765     return 0;
4766   
4767   // From here on, we only handle:
4768   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4769   if (Val != Val2) return 0;
4770   
4771   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4772   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4773       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4774       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4775       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4776     return 0;
4777   
4778   // We can't fold (ugt x, C) | (sgt x, C2).
4779   if (!PredicatesFoldable(LHSCC, RHSCC))
4780     return 0;
4781   
4782   // Ensure that the larger constant is on the RHS.
4783   bool ShouldSwap;
4784   if (CmpInst::isSigned(LHSCC) ||
4785       (ICmpInst::isEquality(LHSCC) && 
4786        CmpInst::isSigned(RHSCC)))
4787     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4788   else
4789     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4790   
4791   if (ShouldSwap) {
4792     std::swap(LHS, RHS);
4793     std::swap(LHSCst, RHSCst);
4794     std::swap(LHSCC, RHSCC);
4795   }
4796   
4797   // At this point, we know we have have two icmp instructions
4798   // comparing a value against two constants and or'ing the result
4799   // together.  Because of the above check, we know that we only have
4800   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4801   // FoldICmpLogical check above), that the two constants are not
4802   // equal.
4803   assert(LHSCst != RHSCst && "Compares not folded above?");
4804
4805   switch (LHSCC) {
4806   default: llvm_unreachable("Unknown integer condition code!");
4807   case ICmpInst::ICMP_EQ:
4808     switch (RHSCC) {
4809     default: llvm_unreachable("Unknown integer condition code!");
4810     case ICmpInst::ICMP_EQ:
4811       if (LHSCst == SubOne(RHSCst)) {
4812         // (X == 13 | X == 14) -> X-13 <u 2
4813         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4814         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4815         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4816         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4817       }
4818       break;                         // (X == 13 | X == 15) -> no change
4819     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4820     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4821       break;
4822     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4823     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4824     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4825       return ReplaceInstUsesWith(I, RHS);
4826     }
4827     break;
4828   case ICmpInst::ICMP_NE:
4829     switch (RHSCC) {
4830     default: llvm_unreachable("Unknown integer condition code!");
4831     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4832     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4833     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4834       return ReplaceInstUsesWith(I, LHS);
4835     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4836     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4837     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4838       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4839     }
4840     break;
4841   case ICmpInst::ICMP_ULT:
4842     switch (RHSCC) {
4843     default: llvm_unreachable("Unknown integer condition code!");
4844     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4845       break;
4846     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4847       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4848       // this can cause overflow.
4849       if (RHSCst->isMaxValue(false))
4850         return ReplaceInstUsesWith(I, LHS);
4851       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4852                              false, false, I);
4853     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4854       break;
4855     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4856     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4857       return ReplaceInstUsesWith(I, RHS);
4858     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4859       break;
4860     }
4861     break;
4862   case ICmpInst::ICMP_SLT:
4863     switch (RHSCC) {
4864     default: llvm_unreachable("Unknown integer condition code!");
4865     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4866       break;
4867     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4868       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4869       // this can cause overflow.
4870       if (RHSCst->isMaxValue(true))
4871         return ReplaceInstUsesWith(I, LHS);
4872       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4873                              true, false, I);
4874     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4875       break;
4876     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4877     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4878       return ReplaceInstUsesWith(I, RHS);
4879     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4880       break;
4881     }
4882     break;
4883   case ICmpInst::ICMP_UGT:
4884     switch (RHSCC) {
4885     default: llvm_unreachable("Unknown integer condition code!");
4886     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4887     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4888       return ReplaceInstUsesWith(I, LHS);
4889     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4890       break;
4891     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4892     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4893       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4894     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4895       break;
4896     }
4897     break;
4898   case ICmpInst::ICMP_SGT:
4899     switch (RHSCC) {
4900     default: llvm_unreachable("Unknown integer condition code!");
4901     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4902     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4903       return ReplaceInstUsesWith(I, LHS);
4904     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4905       break;
4906     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4907     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4908       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4909     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4910       break;
4911     }
4912     break;
4913   }
4914   return 0;
4915 }
4916
4917 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4918                                          FCmpInst *RHS) {
4919   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4920       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4921       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4922     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4923       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4924         // If either of the constants are nans, then the whole thing returns
4925         // true.
4926         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4927           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4928         
4929         // Otherwise, no need to compare the two constants, compare the
4930         // rest.
4931         return new FCmpInst(FCmpInst::FCMP_UNO,
4932                             LHS->getOperand(0), RHS->getOperand(0));
4933       }
4934     
4935     // Handle vector zeros.  This occurs because the canonical form of
4936     // "fcmp uno x,x" is "fcmp uno x, 0".
4937     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4938         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4939       return new FCmpInst(FCmpInst::FCMP_UNO,
4940                           LHS->getOperand(0), RHS->getOperand(0));
4941     
4942     return 0;
4943   }
4944   
4945   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4946   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4947   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4948   
4949   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4950     // Swap RHS operands to match LHS.
4951     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4952     std::swap(Op1LHS, Op1RHS);
4953   }
4954   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4955     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4956     if (Op0CC == Op1CC)
4957       return new FCmpInst((FCmpInst::Predicate)Op0CC,
4958                           Op0LHS, Op0RHS);
4959     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4960       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4961     if (Op0CC == FCmpInst::FCMP_FALSE)
4962       return ReplaceInstUsesWith(I, RHS);
4963     if (Op1CC == FCmpInst::FCMP_FALSE)
4964       return ReplaceInstUsesWith(I, LHS);
4965     bool Op0Ordered;
4966     bool Op1Ordered;
4967     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4968     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4969     if (Op0Ordered == Op1Ordered) {
4970       // If both are ordered or unordered, return a new fcmp with
4971       // or'ed predicates.
4972       Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4973                                Op0LHS, Op0RHS, Context);
4974       if (Instruction *I = dyn_cast<Instruction>(RV))
4975         return I;
4976       // Otherwise, it's a constant boolean value...
4977       return ReplaceInstUsesWith(I, RV);
4978     }
4979   }
4980   return 0;
4981 }
4982
4983 /// FoldOrWithConstants - This helper function folds:
4984 ///
4985 ///     ((A | B) & C1) | (B & C2)
4986 ///
4987 /// into:
4988 /// 
4989 ///     (A & C1) | B
4990 ///
4991 /// when the XOR of the two constants is "all ones" (-1).
4992 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4993                                                Value *A, Value *B, Value *C) {
4994   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4995   if (!CI1) return 0;
4996
4997   Value *V1 = 0;
4998   ConstantInt *CI2 = 0;
4999   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
5000
5001   APInt Xor = CI1->getValue() ^ CI2->getValue();
5002   if (!Xor.isAllOnesValue()) return 0;
5003
5004   if (V1 == A || V1 == B) {
5005     Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
5006     return BinaryOperator::CreateOr(NewOp, V1);
5007   }
5008
5009   return 0;
5010 }
5011
5012 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
5013   bool Changed = SimplifyCommutative(I);
5014   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5015
5016   if (isa<UndefValue>(Op1))                       // X | undef -> -1
5017     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5018
5019   // or X, X = X
5020   if (Op0 == Op1)
5021     return ReplaceInstUsesWith(I, Op0);
5022
5023   // See if we can simplify any instructions used by the instruction whose sole 
5024   // purpose is to compute bits we don't care about.
5025   if (SimplifyDemandedInstructionBits(I))
5026     return &I;
5027   if (isa<VectorType>(I.getType())) {
5028     if (isa<ConstantAggregateZero>(Op1)) {
5029       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
5030     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
5031       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
5032         return ReplaceInstUsesWith(I, I.getOperand(1));
5033     }
5034   }
5035
5036   // or X, -1 == -1
5037   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5038     ConstantInt *C1 = 0; Value *X = 0;
5039     // (X & C1) | C2 --> (X | C2) & (C1|C2)
5040     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
5041         isOnlyUse(Op0)) {
5042       Value *Or = Builder->CreateOr(X, RHS);
5043       Or->takeName(Op0);
5044       return BinaryOperator::CreateAnd(Or, 
5045                ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
5046     }
5047
5048     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
5049     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
5050         isOnlyUse(Op0)) {
5051       Value *Or = Builder->CreateOr(X, RHS);
5052       Or->takeName(Op0);
5053       return BinaryOperator::CreateXor(Or,
5054                  ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
5055     }
5056
5057     // Try to fold constant and into select arguments.
5058     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5059       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5060         return R;
5061     if (isa<PHINode>(Op0))
5062       if (Instruction *NV = FoldOpIntoPhi(I))
5063         return NV;
5064   }
5065
5066   Value *A = 0, *B = 0;
5067   ConstantInt *C1 = 0, *C2 = 0;
5068
5069   if (match(Op0, m_And(m_Value(A), m_Value(B))))
5070     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
5071       return ReplaceInstUsesWith(I, Op1);
5072   if (match(Op1, m_And(m_Value(A), m_Value(B))))
5073     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
5074       return ReplaceInstUsesWith(I, Op0);
5075
5076   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
5077   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
5078   if (match(Op0, m_Or(m_Value(), m_Value())) ||
5079       match(Op1, m_Or(m_Value(), m_Value())) ||
5080       (match(Op0, m_Shift(m_Value(), m_Value())) &&
5081        match(Op1, m_Shift(m_Value(), m_Value())))) {
5082     if (Instruction *BSwap = MatchBSwap(I))
5083       return BSwap;
5084   }
5085   
5086   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
5087   if (Op0->hasOneUse() &&
5088       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
5089       MaskedValueIsZero(Op1, C1->getValue())) {
5090     Value *NOr = Builder->CreateOr(A, Op1);
5091     NOr->takeName(Op0);
5092     return BinaryOperator::CreateXor(NOr, C1);
5093   }
5094
5095   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
5096   if (Op1->hasOneUse() &&
5097       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
5098       MaskedValueIsZero(Op0, C1->getValue())) {
5099     Value *NOr = Builder->CreateOr(A, Op0);
5100     NOr->takeName(Op0);
5101     return BinaryOperator::CreateXor(NOr, C1);
5102   }
5103
5104   // (A & C)|(B & D)
5105   Value *C = 0, *D = 0;
5106   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
5107       match(Op1, m_And(m_Value(B), m_Value(D)))) {
5108     Value *V1 = 0, *V2 = 0, *V3 = 0;
5109     C1 = dyn_cast<ConstantInt>(C);
5110     C2 = dyn_cast<ConstantInt>(D);
5111     if (C1 && C2) {  // (A & C1)|(B & C2)
5112       // If we have: ((V + N) & C1) | (V & C2)
5113       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
5114       // replace with V+N.
5115       if (C1->getValue() == ~C2->getValue()) {
5116         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
5117             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
5118           // Add commutes, try both ways.
5119           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
5120             return ReplaceInstUsesWith(I, A);
5121           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
5122             return ReplaceInstUsesWith(I, A);
5123         }
5124         // Or commutes, try both ways.
5125         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
5126             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
5127           // Add commutes, try both ways.
5128           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
5129             return ReplaceInstUsesWith(I, B);
5130           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
5131             return ReplaceInstUsesWith(I, B);
5132         }
5133       }
5134       V1 = 0; V2 = 0; V3 = 0;
5135     }
5136     
5137     // Check to see if we have any common things being and'ed.  If so, find the
5138     // terms for V1 & (V2|V3).
5139     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
5140       if (A == B)      // (A & C)|(A & D) == A & (C|D)
5141         V1 = A, V2 = C, V3 = D;
5142       else if (A == D) // (A & C)|(B & A) == A & (B|C)
5143         V1 = A, V2 = B, V3 = C;
5144       else if (C == B) // (A & C)|(C & D) == C & (A|D)
5145         V1 = C, V2 = A, V3 = D;
5146       else if (C == D) // (A & C)|(B & C) == C & (A|B)
5147         V1 = C, V2 = A, V3 = B;
5148       
5149       if (V1) {
5150         Value *Or = Builder->CreateOr(V2, V3, "tmp");
5151         return BinaryOperator::CreateAnd(V1, Or);
5152       }
5153     }
5154
5155     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
5156     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
5157       return Match;
5158     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
5159       return Match;
5160     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
5161       return Match;
5162     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
5163       return Match;
5164
5165     // ((A&~B)|(~A&B)) -> A^B
5166     if ((match(C, m_Not(m_Specific(D))) &&
5167          match(B, m_Not(m_Specific(A)))))
5168       return BinaryOperator::CreateXor(A, D);
5169     // ((~B&A)|(~A&B)) -> A^B
5170     if ((match(A, m_Not(m_Specific(D))) &&
5171          match(B, m_Not(m_Specific(C)))))
5172       return BinaryOperator::CreateXor(C, D);
5173     // ((A&~B)|(B&~A)) -> A^B
5174     if ((match(C, m_Not(m_Specific(B))) &&
5175          match(D, m_Not(m_Specific(A)))))
5176       return BinaryOperator::CreateXor(A, B);
5177     // ((~B&A)|(B&~A)) -> A^B
5178     if ((match(A, m_Not(m_Specific(B))) &&
5179          match(D, m_Not(m_Specific(C)))))
5180       return BinaryOperator::CreateXor(C, B);
5181   }
5182   
5183   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
5184   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
5185     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
5186       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
5187           SI0->getOperand(1) == SI1->getOperand(1) &&
5188           (SI0->hasOneUse() || SI1->hasOneUse())) {
5189         Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
5190                                          SI0->getName());
5191         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
5192                                       SI1->getOperand(1));
5193       }
5194   }
5195
5196   // ((A|B)&1)|(B&-2) -> (A&1) | B
5197   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5198       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
5199     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
5200     if (Ret) return Ret;
5201   }
5202   // (B&-2)|((A|B)&1) -> (A&1) | B
5203   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5204       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
5205     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
5206     if (Ret) return Ret;
5207   }
5208
5209   if ((A = dyn_castNotVal(Op0))) {   // ~A | Op1
5210     if (A == Op1)   // ~A | A == -1
5211       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5212   } else {
5213     A = 0;
5214   }
5215   // Note, A is still live here!
5216   if ((B = dyn_castNotVal(Op1))) {   // Op0 | ~B
5217     if (Op0 == B)
5218       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5219
5220     // (~A | ~B) == (~(A & B)) - De Morgan's Law
5221     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
5222       Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
5223       return BinaryOperator::CreateNot(And);
5224     }
5225   }
5226
5227   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5228   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
5229     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5230       return R;
5231
5232     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5233       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5234         return Res;
5235   }
5236     
5237   // fold (or (cast A), (cast B)) -> (cast (or A, B))
5238   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5239     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5240       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
5241         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5242             !isa<ICmpInst>(Op1C->getOperand(0))) {
5243           const Type *SrcTy = Op0C->getOperand(0)->getType();
5244           if (SrcTy == Op1C->getOperand(0)->getType() &&
5245               SrcTy->isIntOrIntVector() &&
5246               // Only do this if the casts both really cause code to be
5247               // generated.
5248               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5249                                 I.getType(), TD) &&
5250               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5251                                 I.getType(), TD)) {
5252             Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5253                                              Op1C->getOperand(0), I.getName());
5254             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5255           }
5256         }
5257       }
5258   }
5259   
5260     
5261   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
5262   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
5263     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5264       if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5265         return Res;
5266   }
5267
5268   return Changed ? &I : 0;
5269 }
5270
5271 namespace {
5272
5273 // XorSelf - Implements: X ^ X --> 0
5274 struct XorSelf {
5275   Value *RHS;
5276   XorSelf(Value *rhs) : RHS(rhs) {}
5277   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5278   Instruction *apply(BinaryOperator &Xor) const {
5279     return &Xor;
5280   }
5281 };
5282
5283 }
5284
5285 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5286   bool Changed = SimplifyCommutative(I);
5287   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5288
5289   if (isa<UndefValue>(Op1)) {
5290     if (isa<UndefValue>(Op0))
5291       // Handle undef ^ undef -> 0 special case. This is a common
5292       // idiom (misuse).
5293       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5294     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5295   }
5296
5297   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5298   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
5299     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5300     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5301   }
5302   
5303   // See if we can simplify any instructions used by the instruction whose sole 
5304   // purpose is to compute bits we don't care about.
5305   if (SimplifyDemandedInstructionBits(I))
5306     return &I;
5307   if (isa<VectorType>(I.getType()))
5308     if (isa<ConstantAggregateZero>(Op1))
5309       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5310
5311   // Is this a ~ operation?
5312   if (Value *NotOp = dyn_castNotVal(&I)) {
5313     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5314       if (Op0I->getOpcode() == Instruction::And || 
5315           Op0I->getOpcode() == Instruction::Or) {
5316         // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5317         // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5318         if (dyn_castNotVal(Op0I->getOperand(1)))
5319           Op0I->swapOperands();
5320         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5321           Value *NotY =
5322             Builder->CreateNot(Op0I->getOperand(1),
5323                                Op0I->getOperand(1)->getName()+".not");
5324           if (Op0I->getOpcode() == Instruction::And)
5325             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5326           return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5327         }
5328         
5329         // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5330         // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5331         if (isFreeToInvert(Op0I->getOperand(0)) && 
5332             isFreeToInvert(Op0I->getOperand(1))) {
5333           Value *NotX =
5334             Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5335           Value *NotY =
5336             Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5337           if (Op0I->getOpcode() == Instruction::And)
5338             return BinaryOperator::CreateOr(NotX, NotY);
5339           return BinaryOperator::CreateAnd(NotX, NotY);
5340         }
5341       }
5342     }
5343   }
5344   
5345   
5346   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5347     if (RHS->isOne() && Op0->hasOneUse()) {
5348       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5349       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5350         return new ICmpInst(ICI->getInversePredicate(),
5351                             ICI->getOperand(0), ICI->getOperand(1));
5352
5353       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5354         return new FCmpInst(FCI->getInversePredicate(),
5355                             FCI->getOperand(0), FCI->getOperand(1));
5356     }
5357
5358     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5359     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5360       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5361         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5362           Instruction::CastOps Opcode = Op0C->getOpcode();
5363           if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5364               (RHS == ConstantExpr::getCast(Opcode, 
5365                                             ConstantInt::getTrue(*Context),
5366                                             Op0C->getDestTy()))) {
5367             CI->setPredicate(CI->getInversePredicate());
5368             return CastInst::Create(Opcode, CI, Op0C->getType());
5369           }
5370         }
5371       }
5372     }
5373
5374     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5375       // ~(c-X) == X-c-1 == X+(-c-1)
5376       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5377         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5378           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5379           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5380                                       ConstantInt::get(I.getType(), 1));
5381           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5382         }
5383           
5384       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5385         if (Op0I->getOpcode() == Instruction::Add) {
5386           // ~(X-c) --> (-c-1)-X
5387           if (RHS->isAllOnesValue()) {
5388             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5389             return BinaryOperator::CreateSub(
5390                            ConstantExpr::getSub(NegOp0CI,
5391                                       ConstantInt::get(I.getType(), 1)),
5392                                       Op0I->getOperand(0));
5393           } else if (RHS->getValue().isSignBit()) {
5394             // (X + C) ^ signbit -> (X + C + signbit)
5395             Constant *C = ConstantInt::get(*Context,
5396                                            RHS->getValue() + Op0CI->getValue());
5397             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5398
5399           }
5400         } else if (Op0I->getOpcode() == Instruction::Or) {
5401           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5402           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5403             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5404             // Anything in both C1 and C2 is known to be zero, remove it from
5405             // NewRHS.
5406             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5407             NewRHS = ConstantExpr::getAnd(NewRHS, 
5408                                        ConstantExpr::getNot(CommonBits));
5409             Worklist.Add(Op0I);
5410             I.setOperand(0, Op0I->getOperand(0));
5411             I.setOperand(1, NewRHS);
5412             return &I;
5413           }
5414         }
5415       }
5416     }
5417
5418     // Try to fold constant and into select arguments.
5419     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5420       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5421         return R;
5422     if (isa<PHINode>(Op0))
5423       if (Instruction *NV = FoldOpIntoPhi(I))
5424         return NV;
5425   }
5426
5427   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5428     if (X == Op1)
5429       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5430
5431   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5432     if (X == Op0)
5433       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5434
5435   
5436   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5437   if (Op1I) {
5438     Value *A, *B;
5439     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5440       if (A == Op0) {              // B^(B|A) == (A|B)^B
5441         Op1I->swapOperands();
5442         I.swapOperands();
5443         std::swap(Op0, Op1);
5444       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5445         I.swapOperands();     // Simplified below.
5446         std::swap(Op0, Op1);
5447       }
5448     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5449       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5450     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5451       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5452     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && 
5453                Op1I->hasOneUse()){
5454       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5455         Op1I->swapOperands();
5456         std::swap(A, B);
5457       }
5458       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5459         I.swapOperands();     // Simplified below.
5460         std::swap(Op0, Op1);
5461       }
5462     }
5463   }
5464   
5465   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5466   if (Op0I) {
5467     Value *A, *B;
5468     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5469         Op0I->hasOneUse()) {
5470       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5471         std::swap(A, B);
5472       if (B == Op1)                                  // (A|B)^B == A & ~B
5473         return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
5474     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5475       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5476     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5477       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5478     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && 
5479                Op0I->hasOneUse()){
5480       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5481         std::swap(A, B);
5482       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5483           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5484         return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
5485       }
5486     }
5487   }
5488   
5489   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5490   if (Op0I && Op1I && Op0I->isShift() && 
5491       Op0I->getOpcode() == Op1I->getOpcode() && 
5492       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5493       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5494     Value *NewOp =
5495       Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5496                          Op0I->getName());
5497     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5498                                   Op1I->getOperand(1));
5499   }
5500     
5501   if (Op0I && Op1I) {
5502     Value *A, *B, *C, *D;
5503     // (A & B)^(A | B) -> A ^ B
5504     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5505         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5506       if ((A == C && B == D) || (A == D && B == C)) 
5507         return BinaryOperator::CreateXor(A, B);
5508     }
5509     // (A | B)^(A & B) -> A ^ B
5510     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5511         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5512       if ((A == C && B == D) || (A == D && B == C)) 
5513         return BinaryOperator::CreateXor(A, B);
5514     }
5515     
5516     // (A & B)^(C & D)
5517     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5518         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5519         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5520       // (X & Y)^(X & Y) -> (Y^Z) & X
5521       Value *X = 0, *Y = 0, *Z = 0;
5522       if (A == C)
5523         X = A, Y = B, Z = D;
5524       else if (A == D)
5525         X = A, Y = B, Z = C;
5526       else if (B == C)
5527         X = B, Y = A, Z = D;
5528       else if (B == D)
5529         X = B, Y = A, Z = C;
5530       
5531       if (X) {
5532         Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
5533         return BinaryOperator::CreateAnd(NewOp, X);
5534       }
5535     }
5536   }
5537     
5538   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5539   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5540     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5541       return R;
5542
5543   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5544   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5545     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5546       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5547         const Type *SrcTy = Op0C->getOperand(0)->getType();
5548         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5549             // Only do this if the casts both really cause code to be generated.
5550             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5551                               I.getType(), TD) &&
5552             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5553                               I.getType(), TD)) {
5554           Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5555                                             Op1C->getOperand(0), I.getName());
5556           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5557         }
5558       }
5559   }
5560
5561   return Changed ? &I : 0;
5562 }
5563
5564 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5565                                    LLVMContext *Context) {
5566   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5567 }
5568
5569 static bool HasAddOverflow(ConstantInt *Result,
5570                            ConstantInt *In1, ConstantInt *In2,
5571                            bool IsSigned) {
5572   if (IsSigned)
5573     if (In2->getValue().isNegative())
5574       return Result->getValue().sgt(In1->getValue());
5575     else
5576       return Result->getValue().slt(In1->getValue());
5577   else
5578     return Result->getValue().ult(In1->getValue());
5579 }
5580
5581 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5582 /// overflowed for this type.
5583 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5584                             Constant *In2, LLVMContext *Context,
5585                             bool IsSigned = false) {
5586   Result = ConstantExpr::getAdd(In1, In2);
5587
5588   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5589     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5590       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5591       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5592                          ExtractElement(In1, Idx, Context),
5593                          ExtractElement(In2, Idx, Context),
5594                          IsSigned))
5595         return true;
5596     }
5597     return false;
5598   }
5599
5600   return HasAddOverflow(cast<ConstantInt>(Result),
5601                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5602                         IsSigned);
5603 }
5604
5605 static bool HasSubOverflow(ConstantInt *Result,
5606                            ConstantInt *In1, ConstantInt *In2,
5607                            bool IsSigned) {
5608   if (IsSigned)
5609     if (In2->getValue().isNegative())
5610       return Result->getValue().slt(In1->getValue());
5611     else
5612       return Result->getValue().sgt(In1->getValue());
5613   else
5614     return Result->getValue().ugt(In1->getValue());
5615 }
5616
5617 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5618 /// overflowed for this type.
5619 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5620                             Constant *In2, LLVMContext *Context,
5621                             bool IsSigned = false) {
5622   Result = ConstantExpr::getSub(In1, In2);
5623
5624   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5625     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5626       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5627       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5628                          ExtractElement(In1, Idx, Context),
5629                          ExtractElement(In2, Idx, Context),
5630                          IsSigned))
5631         return true;
5632     }
5633     return false;
5634   }
5635
5636   return HasSubOverflow(cast<ConstantInt>(Result),
5637                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5638                         IsSigned);
5639 }
5640
5641
5642 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5643 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5644 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5645                                        ICmpInst::Predicate Cond,
5646                                        Instruction &I) {
5647   // Look through bitcasts.
5648   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5649     RHS = BCI->getOperand(0);
5650
5651   Value *PtrBase = GEPLHS->getOperand(0);
5652   if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5653     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5654     // This transformation (ignoring the base and scales) is valid because we
5655     // know pointers can't overflow since the gep is inbounds.  See if we can
5656     // output an optimized form.
5657     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5658     
5659     // If not, synthesize the offset the hard way.
5660     if (Offset == 0)
5661       Offset = EmitGEPOffset(GEPLHS, *this);
5662     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5663                         Constant::getNullValue(Offset->getType()));
5664   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5665     // If the base pointers are different, but the indices are the same, just
5666     // compare the base pointer.
5667     if (PtrBase != GEPRHS->getOperand(0)) {
5668       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5669       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5670                         GEPRHS->getOperand(0)->getType();
5671       if (IndicesTheSame)
5672         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5673           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5674             IndicesTheSame = false;
5675             break;
5676           }
5677
5678       // If all indices are the same, just compare the base pointers.
5679       if (IndicesTheSame)
5680         return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5681                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5682
5683       // Otherwise, the base pointers are different and the indices are
5684       // different, bail out.
5685       return 0;
5686     }
5687
5688     // If one of the GEPs has all zero indices, recurse.
5689     bool AllZeros = true;
5690     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5691       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5692           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5693         AllZeros = false;
5694         break;
5695       }
5696     if (AllZeros)
5697       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5698                           ICmpInst::getSwappedPredicate(Cond), I);
5699
5700     // If the other GEP has all zero indices, recurse.
5701     AllZeros = true;
5702     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5703       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5704           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5705         AllZeros = false;
5706         break;
5707       }
5708     if (AllZeros)
5709       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5710
5711     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5712       // If the GEPs only differ by one index, compare it.
5713       unsigned NumDifferences = 0;  // Keep track of # differences.
5714       unsigned DiffOperand = 0;     // The operand that differs.
5715       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5716         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5717           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5718                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5719             // Irreconcilable differences.
5720             NumDifferences = 2;
5721             break;
5722           } else {
5723             if (NumDifferences++) break;
5724             DiffOperand = i;
5725           }
5726         }
5727
5728       if (NumDifferences == 0)   // SAME GEP?
5729         return ReplaceInstUsesWith(I, // No comparison is needed here.
5730                                    ConstantInt::get(Type::getInt1Ty(*Context),
5731                                              ICmpInst::isTrueWhenEqual(Cond)));
5732
5733       else if (NumDifferences == 1) {
5734         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5735         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5736         // Make sure we do a signed comparison here.
5737         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5738       }
5739     }
5740
5741     // Only lower this if the icmp is the only user of the GEP or if we expect
5742     // the result to fold to a constant!
5743     if (TD &&
5744         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5745         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5746       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5747       Value *L = EmitGEPOffset(GEPLHS, *this);
5748       Value *R = EmitGEPOffset(GEPRHS, *this);
5749       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5750     }
5751   }
5752   return 0;
5753 }
5754
5755 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5756 ///
5757 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5758                                                 Instruction *LHSI,
5759                                                 Constant *RHSC) {
5760   if (!isa<ConstantFP>(RHSC)) return 0;
5761   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5762   
5763   // Get the width of the mantissa.  We don't want to hack on conversions that
5764   // might lose information from the integer, e.g. "i64 -> float"
5765   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5766   if (MantissaWidth == -1) return 0;  // Unknown.
5767   
5768   // Check to see that the input is converted from an integer type that is small
5769   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5770   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5771   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5772   
5773   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5774   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5775   if (LHSUnsigned)
5776     ++InputSize;
5777   
5778   // If the conversion would lose info, don't hack on this.
5779   if ((int)InputSize > MantissaWidth)
5780     return 0;
5781   
5782   // Otherwise, we can potentially simplify the comparison.  We know that it
5783   // will always come through as an integer value and we know the constant is
5784   // not a NAN (it would have been previously simplified).
5785   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5786   
5787   ICmpInst::Predicate Pred;
5788   switch (I.getPredicate()) {
5789   default: llvm_unreachable("Unexpected predicate!");
5790   case FCmpInst::FCMP_UEQ:
5791   case FCmpInst::FCMP_OEQ:
5792     Pred = ICmpInst::ICMP_EQ;
5793     break;
5794   case FCmpInst::FCMP_UGT:
5795   case FCmpInst::FCMP_OGT:
5796     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5797     break;
5798   case FCmpInst::FCMP_UGE:
5799   case FCmpInst::FCMP_OGE:
5800     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5801     break;
5802   case FCmpInst::FCMP_ULT:
5803   case FCmpInst::FCMP_OLT:
5804     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5805     break;
5806   case FCmpInst::FCMP_ULE:
5807   case FCmpInst::FCMP_OLE:
5808     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5809     break;
5810   case FCmpInst::FCMP_UNE:
5811   case FCmpInst::FCMP_ONE:
5812     Pred = ICmpInst::ICMP_NE;
5813     break;
5814   case FCmpInst::FCMP_ORD:
5815     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5816   case FCmpInst::FCMP_UNO:
5817     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5818   }
5819   
5820   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5821   
5822   // Now we know that the APFloat is a normal number, zero or inf.
5823   
5824   // See if the FP constant is too large for the integer.  For example,
5825   // comparing an i8 to 300.0.
5826   unsigned IntWidth = IntTy->getScalarSizeInBits();
5827   
5828   if (!LHSUnsigned) {
5829     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5830     // and large values.
5831     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5832     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5833                           APFloat::rmNearestTiesToEven);
5834     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5835       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5836           Pred == ICmpInst::ICMP_SLE)
5837         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5838       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5839     }
5840   } else {
5841     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5842     // +INF and large values.
5843     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5844     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5845                           APFloat::rmNearestTiesToEven);
5846     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5847       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5848           Pred == ICmpInst::ICMP_ULE)
5849         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5850       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5851     }
5852   }
5853   
5854   if (!LHSUnsigned) {
5855     // See if the RHS value is < SignedMin.
5856     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5857     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5858                           APFloat::rmNearestTiesToEven);
5859     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5860       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5861           Pred == ICmpInst::ICMP_SGE)
5862         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5863       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5864     }
5865   }
5866
5867   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5868   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5869   // casting the FP value to the integer value and back, checking for equality.
5870   // Don't do this for zero, because -0.0 is not fractional.
5871   Constant *RHSInt = LHSUnsigned
5872     ? ConstantExpr::getFPToUI(RHSC, IntTy)
5873     : ConstantExpr::getFPToSI(RHSC, IntTy);
5874   if (!RHS.isZero()) {
5875     bool Equal = LHSUnsigned
5876       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5877       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5878     if (!Equal) {
5879       // If we had a comparison against a fractional value, we have to adjust
5880       // the compare predicate and sometimes the value.  RHSC is rounded towards
5881       // zero at this point.
5882       switch (Pred) {
5883       default: llvm_unreachable("Unexpected integer comparison!");
5884       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5885         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5886       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5887         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5888       case ICmpInst::ICMP_ULE:
5889         // (float)int <= 4.4   --> int <= 4
5890         // (float)int <= -4.4  --> false
5891         if (RHS.isNegative())
5892           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5893         break;
5894       case ICmpInst::ICMP_SLE:
5895         // (float)int <= 4.4   --> int <= 4
5896         // (float)int <= -4.4  --> int < -4
5897         if (RHS.isNegative())
5898           Pred = ICmpInst::ICMP_SLT;
5899         break;
5900       case ICmpInst::ICMP_ULT:
5901         // (float)int < -4.4   --> false
5902         // (float)int < 4.4    --> int <= 4
5903         if (RHS.isNegative())
5904           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5905         Pred = ICmpInst::ICMP_ULE;
5906         break;
5907       case ICmpInst::ICMP_SLT:
5908         // (float)int < -4.4   --> int < -4
5909         // (float)int < 4.4    --> int <= 4
5910         if (!RHS.isNegative())
5911           Pred = ICmpInst::ICMP_SLE;
5912         break;
5913       case ICmpInst::ICMP_UGT:
5914         // (float)int > 4.4    --> int > 4
5915         // (float)int > -4.4   --> true
5916         if (RHS.isNegative())
5917           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5918         break;
5919       case ICmpInst::ICMP_SGT:
5920         // (float)int > 4.4    --> int > 4
5921         // (float)int > -4.4   --> int >= -4
5922         if (RHS.isNegative())
5923           Pred = ICmpInst::ICMP_SGE;
5924         break;
5925       case ICmpInst::ICMP_UGE:
5926         // (float)int >= -4.4   --> true
5927         // (float)int >= 4.4    --> int > 4
5928         if (!RHS.isNegative())
5929           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5930         Pred = ICmpInst::ICMP_UGT;
5931         break;
5932       case ICmpInst::ICMP_SGE:
5933         // (float)int >= -4.4   --> int >= -4
5934         // (float)int >= 4.4    --> int > 4
5935         if (!RHS.isNegative())
5936           Pred = ICmpInst::ICMP_SGT;
5937         break;
5938       }
5939     }
5940   }
5941
5942   // Lower this FP comparison into an appropriate integer version of the
5943   // comparison.
5944   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5945 }
5946
5947 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5948   bool Changed = SimplifyCompare(I);
5949   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5950
5951   // Fold trivial predicates.
5952   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5953     return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
5954   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5955     return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
5956   
5957   // Simplify 'fcmp pred X, X'
5958   if (Op0 == Op1) {
5959     switch (I.getPredicate()) {
5960     default: llvm_unreachable("Unknown predicate!");
5961     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5962     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5963     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5964       return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
5965     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5966     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5967     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5968       return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
5969       
5970     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5971     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5972     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5973     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5974       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5975       I.setPredicate(FCmpInst::FCMP_UNO);
5976       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5977       return &I;
5978       
5979     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5980     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5981     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5982     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5983       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5984       I.setPredicate(FCmpInst::FCMP_ORD);
5985       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5986       return &I;
5987     }
5988   }
5989     
5990   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5991     return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
5992
5993   // Handle fcmp with constant RHS
5994   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5995     // If the constant is a nan, see if we can fold the comparison based on it.
5996     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5997       if (CFP->getValueAPF().isNaN()) {
5998         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5999           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6000         assert(FCmpInst::isUnordered(I.getPredicate()) &&
6001                "Comparison must be either ordered or unordered!");
6002         // True if unordered.
6003         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6004       }
6005     }
6006     
6007     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6008       switch (LHSI->getOpcode()) {
6009       case Instruction::PHI:
6010         // Only fold fcmp into the PHI if the phi and fcmp are in the same
6011         // block.  If in the same block, we're encouraging jump threading.  If
6012         // not, we are just pessimizing the code by making an i1 phi.
6013         if (LHSI->getParent() == I.getParent())
6014           if (Instruction *NV = FoldOpIntoPhi(I, true))
6015             return NV;
6016         break;
6017       case Instruction::SIToFP:
6018       case Instruction::UIToFP:
6019         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
6020           return NV;
6021         break;
6022       case Instruction::Select:
6023         // If either operand of the select is a constant, we can fold the
6024         // comparison into the select arms, which will cause one to be
6025         // constant folded and the select turned into a bitwise or.
6026         Value *Op1 = 0, *Op2 = 0;
6027         if (LHSI->hasOneUse()) {
6028           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6029             // Fold the known value into the constant operand.
6030             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
6031             // Insert a new FCmp of the other select operand.
6032             Op2 = Builder->CreateFCmp(I.getPredicate(),
6033                                       LHSI->getOperand(2), RHSC, I.getName());
6034           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6035             // Fold the known value into the constant operand.
6036             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
6037             // Insert a new FCmp of the other select operand.
6038             Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
6039                                       RHSC, I.getName());
6040           }
6041         }
6042
6043         if (Op1)
6044           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6045         break;
6046       }
6047   }
6048
6049   return Changed ? &I : 0;
6050 }
6051
6052 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
6053   bool Changed = SimplifyCompare(I);
6054   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6055   const Type *Ty = Op0->getType();
6056
6057   // icmp X, X
6058   if (Op0 == Op1)
6059     return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
6060                                                    I.isTrueWhenEqual()));
6061
6062   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
6063     return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
6064   
6065   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
6066   // addresses never equal each other!  We already know that Op0 != Op1.
6067   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) || 
6068        isa<ConstantPointerNull>(Op0)) &&
6069       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) || 
6070        isa<ConstantPointerNull>(Op1)))
6071     return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context), 
6072                                                    !I.isTrueWhenEqual()));
6073
6074   // icmp's with boolean values can always be turned into bitwise operations
6075   if (Ty == Type::getInt1Ty(*Context)) {
6076     switch (I.getPredicate()) {
6077     default: llvm_unreachable("Invalid icmp instruction!");
6078     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
6079       Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
6080       return BinaryOperator::CreateNot(Xor);
6081     }
6082     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
6083       return BinaryOperator::CreateXor(Op0, Op1);
6084
6085     case ICmpInst::ICMP_UGT:
6086       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
6087       // FALL THROUGH
6088     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
6089       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
6090       return BinaryOperator::CreateAnd(Not, Op1);
6091     }
6092     case ICmpInst::ICMP_SGT:
6093       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
6094       // FALL THROUGH
6095     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
6096       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
6097       return BinaryOperator::CreateAnd(Not, Op0);
6098     }
6099     case ICmpInst::ICMP_UGE:
6100       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6101       // FALL THROUGH
6102     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6103       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
6104       return BinaryOperator::CreateOr(Not, Op1);
6105     }
6106     case ICmpInst::ICMP_SGE:
6107       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6108       // FALL THROUGH
6109     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6110       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
6111       return BinaryOperator::CreateOr(Not, Op0);
6112     }
6113     }
6114   }
6115
6116   unsigned BitWidth = 0;
6117   if (TD)
6118     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6119   else if (Ty->isIntOrIntVector())
6120     BitWidth = Ty->getScalarSizeInBits();
6121
6122   bool isSignBit = false;
6123
6124   // See if we are doing a comparison with a constant.
6125   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6126     Value *A = 0, *B = 0;
6127     
6128     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6129     if (I.isEquality() && CI->isNullValue() &&
6130         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
6131       // (icmp cond A B) if cond is equality
6132       return new ICmpInst(I.getPredicate(), A, B);
6133     }
6134     
6135     // If we have an icmp le or icmp ge instruction, turn it into the
6136     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6137     // them being folded in the code below.
6138     switch (I.getPredicate()) {
6139     default: break;
6140     case ICmpInst::ICMP_ULE:
6141       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6142         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6143       return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
6144                           AddOne(CI));
6145     case ICmpInst::ICMP_SLE:
6146       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6147         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6148       return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6149                           AddOne(CI));
6150     case ICmpInst::ICMP_UGE:
6151       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6152         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6153       return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
6154                           SubOne(CI));
6155     case ICmpInst::ICMP_SGE:
6156       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6157         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6158       return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6159                           SubOne(CI));
6160     }
6161     
6162     // If this comparison is a normal comparison, it demands all
6163     // bits, if it is a sign bit comparison, it only demands the sign bit.
6164     bool UnusedBit;
6165     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6166   }
6167
6168   // See if we can fold the comparison based on range information we can get
6169   // by checking whether bits are known to be zero or one in the input.
6170   if (BitWidth != 0) {
6171     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6172     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6173
6174     if (SimplifyDemandedBits(I.getOperandUse(0),
6175                              isSignBit ? APInt::getSignBit(BitWidth)
6176                                        : APInt::getAllOnesValue(BitWidth),
6177                              Op0KnownZero, Op0KnownOne, 0))
6178       return &I;
6179     if (SimplifyDemandedBits(I.getOperandUse(1),
6180                              APInt::getAllOnesValue(BitWidth),
6181                              Op1KnownZero, Op1KnownOne, 0))
6182       return &I;
6183
6184     // Given the known and unknown bits, compute a range that the LHS could be
6185     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6186     // EQ and NE we use unsigned values.
6187     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6188     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6189     if (I.isSigned()) {
6190       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6191                                              Op0Min, Op0Max);
6192       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6193                                              Op1Min, Op1Max);
6194     } else {
6195       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6196                                                Op0Min, Op0Max);
6197       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6198                                                Op1Min, Op1Max);
6199     }
6200
6201     // If Min and Max are known to be the same, then SimplifyDemandedBits
6202     // figured out that the LHS is a constant.  Just constant fold this now so
6203     // that code below can assume that Min != Max.
6204     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6205       return new ICmpInst(I.getPredicate(),
6206                           ConstantInt::get(*Context, Op0Min), Op1);
6207     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6208       return new ICmpInst(I.getPredicate(), Op0,
6209                           ConstantInt::get(*Context, Op1Min));
6210
6211     // Based on the range information we know about the LHS, see if we can
6212     // simplify this comparison.  For example, (x&4) < 8  is always true.
6213     switch (I.getPredicate()) {
6214     default: llvm_unreachable("Unknown icmp opcode!");
6215     case ICmpInst::ICMP_EQ:
6216       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6217         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6218       break;
6219     case ICmpInst::ICMP_NE:
6220       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6221         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6222       break;
6223     case ICmpInst::ICMP_ULT:
6224       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6225         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6226       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6227         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6228       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6229         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6230       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6231         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6232           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6233                               SubOne(CI));
6234
6235         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6236         if (CI->isMinValue(true))
6237           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6238                            Constant::getAllOnesValue(Op0->getType()));
6239       }
6240       break;
6241     case ICmpInst::ICMP_UGT:
6242       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6243         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6244       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6245         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6246
6247       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6248         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6249       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6250         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6251           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6252                               AddOne(CI));
6253
6254         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6255         if (CI->isMaxValue(true))
6256           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6257                               Constant::getNullValue(Op0->getType()));
6258       }
6259       break;
6260     case ICmpInst::ICMP_SLT:
6261       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6262         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6263       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6264         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6265       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6266         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6267       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6268         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6269           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6270                               SubOne(CI));
6271       }
6272       break;
6273     case ICmpInst::ICMP_SGT:
6274       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6275         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6276       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6277         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6278
6279       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6280         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6281       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6282         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6283           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6284                               AddOne(CI));
6285       }
6286       break;
6287     case ICmpInst::ICMP_SGE:
6288       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6289       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6290         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6291       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6292         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6293       break;
6294     case ICmpInst::ICMP_SLE:
6295       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6296       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6297         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6298       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6299         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6300       break;
6301     case ICmpInst::ICMP_UGE:
6302       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6303       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6304         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6305       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6306         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6307       break;
6308     case ICmpInst::ICMP_ULE:
6309       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6310       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6311         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6312       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6313         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6314       break;
6315     }
6316
6317     // Turn a signed comparison into an unsigned one if both operands
6318     // are known to have the same sign.
6319     if (I.isSigned() &&
6320         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6321          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6322       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6323   }
6324
6325   // Test if the ICmpInst instruction is used exclusively by a select as
6326   // part of a minimum or maximum operation. If so, refrain from doing
6327   // any other folding. This helps out other analyses which understand
6328   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6329   // and CodeGen. And in this case, at least one of the comparison
6330   // operands has at least one user besides the compare (the select),
6331   // which would often largely negate the benefit of folding anyway.
6332   if (I.hasOneUse())
6333     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6334       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6335           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6336         return 0;
6337
6338   // See if we are doing a comparison between a constant and an instruction that
6339   // can be folded into the comparison.
6340   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6341     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6342     // instruction, see if that instruction also has constants so that the 
6343     // instruction can be folded into the icmp 
6344     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6345       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6346         return Res;
6347   }
6348
6349   // Handle icmp with constant (but not simple integer constant) RHS
6350   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6351     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6352       switch (LHSI->getOpcode()) {
6353       case Instruction::GetElementPtr:
6354         if (RHSC->isNullValue()) {
6355           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6356           bool isAllZeros = true;
6357           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6358             if (!isa<Constant>(LHSI->getOperand(i)) ||
6359                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6360               isAllZeros = false;
6361               break;
6362             }
6363           if (isAllZeros)
6364             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6365                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6366         }
6367         break;
6368
6369       case Instruction::PHI:
6370         // Only fold icmp into the PHI if the phi and icmp are in the same
6371         // block.  If in the same block, we're encouraging jump threading.  If
6372         // not, we are just pessimizing the code by making an i1 phi.
6373         if (LHSI->getParent() == I.getParent())
6374           if (Instruction *NV = FoldOpIntoPhi(I, true))
6375             return NV;
6376         break;
6377       case Instruction::Select: {
6378         // If either operand of the select is a constant, we can fold the
6379         // comparison into the select arms, which will cause one to be
6380         // constant folded and the select turned into a bitwise or.
6381         Value *Op1 = 0, *Op2 = 0;
6382         if (LHSI->hasOneUse()) {
6383           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6384             // Fold the known value into the constant operand.
6385             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6386             // Insert a new ICmp of the other select operand.
6387             Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6388                                       RHSC, I.getName());
6389           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6390             // Fold the known value into the constant operand.
6391             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6392             // Insert a new ICmp of the other select operand.
6393             Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6394                                       RHSC, I.getName());
6395           }
6396         }
6397
6398         if (Op1)
6399           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6400         break;
6401       }
6402       case Instruction::Call:
6403         // If we have (malloc != null), and if the malloc has a single use, we
6404         // can assume it is successful and remove the malloc.
6405         if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6406             isa<ConstantPointerNull>(RHSC)) {
6407           // Need to explicitly erase malloc call here, instead of adding it to
6408           // Worklist, because it won't get DCE'd from the Worklist since
6409           // isInstructionTriviallyDead() returns false for function calls.
6410           // It is OK to replace LHSI/MallocCall with Undef because the 
6411           // instruction that uses it will be erased via Worklist.
6412           if (extractMallocCall(LHSI)) {
6413             LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6414             EraseInstFromFunction(*LHSI);
6415             return ReplaceInstUsesWith(I,
6416                                      ConstantInt::get(Type::getInt1Ty(*Context),
6417                                                       !I.isTrueWhenEqual()));
6418           }
6419           if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6420             if (MallocCall->hasOneUse()) {
6421               MallocCall->replaceAllUsesWith(
6422                                         UndefValue::get(MallocCall->getType()));
6423               EraseInstFromFunction(*MallocCall);
6424               Worklist.Add(LHSI); // The malloc's bitcast use.
6425               return ReplaceInstUsesWith(I,
6426                                      ConstantInt::get(Type::getInt1Ty(*Context),
6427                                                       !I.isTrueWhenEqual()));
6428             }
6429         }
6430         break;
6431       }
6432   }
6433
6434   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6435   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6436     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6437       return NI;
6438   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6439     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6440                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6441       return NI;
6442
6443   // Test to see if the operands of the icmp are casted versions of other
6444   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6445   // now.
6446   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6447     if (isa<PointerType>(Op0->getType()) && 
6448         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6449       // We keep moving the cast from the left operand over to the right
6450       // operand, where it can often be eliminated completely.
6451       Op0 = CI->getOperand(0);
6452
6453       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6454       // so eliminate it as well.
6455       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6456         Op1 = CI2->getOperand(0);
6457
6458       // If Op1 is a constant, we can fold the cast into the constant.
6459       if (Op0->getType() != Op1->getType()) {
6460         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6461           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6462         } else {
6463           // Otherwise, cast the RHS right before the icmp
6464           Op1 = Builder->CreateBitCast(Op1, Op0->getType());
6465         }
6466       }
6467       return new ICmpInst(I.getPredicate(), Op0, Op1);
6468     }
6469   }
6470   
6471   if (isa<CastInst>(Op0)) {
6472     // Handle the special case of: icmp (cast bool to X), <cst>
6473     // This comes up when you have code like
6474     //   int X = A < B;
6475     //   if (X) ...
6476     // For generality, we handle any zero-extension of any operand comparison
6477     // with a constant or another cast from the same type.
6478     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6479       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6480         return R;
6481   }
6482   
6483   // See if it's the same type of instruction on the left and right.
6484   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6485     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6486       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6487           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6488         switch (Op0I->getOpcode()) {
6489         default: break;
6490         case Instruction::Add:
6491         case Instruction::Sub:
6492         case Instruction::Xor:
6493           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6494             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6495                                 Op1I->getOperand(0));
6496           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6497           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6498             if (CI->getValue().isSignBit()) {
6499               ICmpInst::Predicate Pred = I.isSigned()
6500                                              ? I.getUnsignedPredicate()
6501                                              : I.getSignedPredicate();
6502               return new ICmpInst(Pred, Op0I->getOperand(0),
6503                                   Op1I->getOperand(0));
6504             }
6505             
6506             if (CI->getValue().isMaxSignedValue()) {
6507               ICmpInst::Predicate Pred = I.isSigned()
6508                                              ? I.getUnsignedPredicate()
6509                                              : I.getSignedPredicate();
6510               Pred = I.getSwappedPredicate(Pred);
6511               return new ICmpInst(Pred, Op0I->getOperand(0),
6512                                   Op1I->getOperand(0));
6513             }
6514           }
6515           break;
6516         case Instruction::Mul:
6517           if (!I.isEquality())
6518             break;
6519
6520           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6521             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6522             // Mask = -1 >> count-trailing-zeros(Cst).
6523             if (!CI->isZero() && !CI->isOne()) {
6524               const APInt &AP = CI->getValue();
6525               ConstantInt *Mask = ConstantInt::get(*Context, 
6526                                       APInt::getLowBitsSet(AP.getBitWidth(),
6527                                                            AP.getBitWidth() -
6528                                                       AP.countTrailingZeros()));
6529               Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6530               Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
6531               return new ICmpInst(I.getPredicate(), And1, And2);
6532             }
6533           }
6534           break;
6535         }
6536       }
6537     }
6538   }
6539   
6540   // ~x < ~y --> y < x
6541   { Value *A, *B;
6542     if (match(Op0, m_Not(m_Value(A))) &&
6543         match(Op1, m_Not(m_Value(B))))
6544       return new ICmpInst(I.getPredicate(), B, A);
6545   }
6546   
6547   if (I.isEquality()) {
6548     Value *A, *B, *C, *D;
6549     
6550     // -x == -y --> x == y
6551     if (match(Op0, m_Neg(m_Value(A))) &&
6552         match(Op1, m_Neg(m_Value(B))))
6553       return new ICmpInst(I.getPredicate(), A, B);
6554     
6555     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6556       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6557         Value *OtherVal = A == Op1 ? B : A;
6558         return new ICmpInst(I.getPredicate(), OtherVal,
6559                             Constant::getNullValue(A->getType()));
6560       }
6561
6562       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6563         // A^c1 == C^c2 --> A == C^(c1^c2)
6564         ConstantInt *C1, *C2;
6565         if (match(B, m_ConstantInt(C1)) &&
6566             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6567           Constant *NC = 
6568                    ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6569           Value *Xor = Builder->CreateXor(C, NC, "tmp");
6570           return new ICmpInst(I.getPredicate(), A, Xor);
6571         }
6572         
6573         // A^B == A^D -> B == D
6574         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6575         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6576         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6577         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6578       }
6579     }
6580     
6581     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6582         (A == Op0 || B == Op0)) {
6583       // A == (A^B)  ->  B == 0
6584       Value *OtherVal = A == Op0 ? B : A;
6585       return new ICmpInst(I.getPredicate(), OtherVal,
6586                           Constant::getNullValue(A->getType()));
6587     }
6588
6589     // (A-B) == A  ->  B == 0
6590     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6591       return new ICmpInst(I.getPredicate(), B, 
6592                           Constant::getNullValue(B->getType()));
6593
6594     // A == (A-B)  ->  B == 0
6595     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6596       return new ICmpInst(I.getPredicate(), B,
6597                           Constant::getNullValue(B->getType()));
6598     
6599     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6600     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6601         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6602         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6603       Value *X = 0, *Y = 0, *Z = 0;
6604       
6605       if (A == C) {
6606         X = B; Y = D; Z = A;
6607       } else if (A == D) {
6608         X = B; Y = C; Z = A;
6609       } else if (B == C) {
6610         X = A; Y = D; Z = B;
6611       } else if (B == D) {
6612         X = A; Y = C; Z = B;
6613       }
6614       
6615       if (X) {   // Build (X^Y) & Z
6616         Op1 = Builder->CreateXor(X, Y, "tmp");
6617         Op1 = Builder->CreateAnd(Op1, Z, "tmp");
6618         I.setOperand(0, Op1);
6619         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6620         return &I;
6621       }
6622     }
6623   }
6624   return Changed ? &I : 0;
6625 }
6626
6627
6628 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6629 /// and CmpRHS are both known to be integer constants.
6630 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6631                                           ConstantInt *DivRHS) {
6632   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6633   const APInt &CmpRHSV = CmpRHS->getValue();
6634   
6635   // FIXME: If the operand types don't match the type of the divide 
6636   // then don't attempt this transform. The code below doesn't have the
6637   // logic to deal with a signed divide and an unsigned compare (and
6638   // vice versa). This is because (x /s C1) <s C2  produces different 
6639   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6640   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6641   // work. :(  The if statement below tests that condition and bails 
6642   // if it finds it. 
6643   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6644   if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
6645     return 0;
6646   if (DivRHS->isZero())
6647     return 0; // The ProdOV computation fails on divide by zero.
6648   if (DivIsSigned && DivRHS->isAllOnesValue())
6649     return 0; // The overflow computation also screws up here
6650   if (DivRHS->isOne())
6651     return 0; // Not worth bothering, and eliminates some funny cases
6652               // with INT_MIN.
6653
6654   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6655   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6656   // C2 (CI). By solving for X we can turn this into a range check 
6657   // instead of computing a divide. 
6658   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6659
6660   // Determine if the product overflows by seeing if the product is
6661   // not equal to the divide. Make sure we do the same kind of divide
6662   // as in the LHS instruction that we're folding. 
6663   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6664                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6665
6666   // Get the ICmp opcode
6667   ICmpInst::Predicate Pred = ICI.getPredicate();
6668
6669   // Figure out the interval that is being checked.  For example, a comparison
6670   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6671   // Compute this interval based on the constants involved and the signedness of
6672   // the compare/divide.  This computes a half-open interval, keeping track of
6673   // whether either value in the interval overflows.  After analysis each
6674   // overflow variable is set to 0 if it's corresponding bound variable is valid
6675   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6676   int LoOverflow = 0, HiOverflow = 0;
6677   Constant *LoBound = 0, *HiBound = 0;
6678   
6679   if (!DivIsSigned) {  // udiv
6680     // e.g. X/5 op 3  --> [15, 20)
6681     LoBound = Prod;
6682     HiOverflow = LoOverflow = ProdOV;
6683     if (!HiOverflow)
6684       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6685   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6686     if (CmpRHSV == 0) {       // (X / pos) op 0
6687       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6688       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6689       HiBound = DivRHS;
6690     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6691       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6692       HiOverflow = LoOverflow = ProdOV;
6693       if (!HiOverflow)
6694         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6695     } else {                       // (X / pos) op neg
6696       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6697       HiBound = AddOne(Prod);
6698       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6699       if (!LoOverflow) {
6700         ConstantInt* DivNeg =
6701                          cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6702         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6703                                      true) ? -1 : 0;
6704        }
6705     }
6706   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6707     if (CmpRHSV == 0) {       // (X / neg) op 0
6708       // e.g. X/-5 op 0  --> [-4, 5)
6709       LoBound = AddOne(DivRHS);
6710       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6711       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6712         HiOverflow = 1;            // [INTMIN+1, overflow)
6713         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6714       }
6715     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6716       // e.g. X/-5 op 3  --> [-19, -14)
6717       HiBound = AddOne(Prod);
6718       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6719       if (!LoOverflow)
6720         LoOverflow = AddWithOverflow(LoBound, HiBound,
6721                                      DivRHS, Context, true) ? -1 : 0;
6722     } else {                       // (X / neg) op neg
6723       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6724       LoOverflow = HiOverflow = ProdOV;
6725       if (!HiOverflow)
6726         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6727     }
6728     
6729     // Dividing by a negative swaps the condition.  LT <-> GT
6730     Pred = ICmpInst::getSwappedPredicate(Pred);
6731   }
6732
6733   Value *X = DivI->getOperand(0);
6734   switch (Pred) {
6735   default: llvm_unreachable("Unhandled icmp opcode!");
6736   case ICmpInst::ICMP_EQ:
6737     if (LoOverflow && HiOverflow)
6738       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6739     else if (HiOverflow)
6740       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6741                           ICmpInst::ICMP_UGE, X, LoBound);
6742     else if (LoOverflow)
6743       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6744                           ICmpInst::ICMP_ULT, X, HiBound);
6745     else
6746       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6747   case ICmpInst::ICMP_NE:
6748     if (LoOverflow && HiOverflow)
6749       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6750     else if (HiOverflow)
6751       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6752                           ICmpInst::ICMP_ULT, X, LoBound);
6753     else if (LoOverflow)
6754       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6755                           ICmpInst::ICMP_UGE, X, HiBound);
6756     else
6757       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6758   case ICmpInst::ICMP_ULT:
6759   case ICmpInst::ICMP_SLT:
6760     if (LoOverflow == +1)   // Low bound is greater than input range.
6761       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6762     if (LoOverflow == -1)   // Low bound is less than input range.
6763       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6764     return new ICmpInst(Pred, X, LoBound);
6765   case ICmpInst::ICMP_UGT:
6766   case ICmpInst::ICMP_SGT:
6767     if (HiOverflow == +1)       // High bound greater than input range.
6768       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6769     else if (HiOverflow == -1)  // High bound less than input range.
6770       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6771     if (Pred == ICmpInst::ICMP_UGT)
6772       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6773     else
6774       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6775   }
6776 }
6777
6778
6779 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6780 ///
6781 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6782                                                           Instruction *LHSI,
6783                                                           ConstantInt *RHS) {
6784   const APInt &RHSV = RHS->getValue();
6785   
6786   switch (LHSI->getOpcode()) {
6787   case Instruction::Trunc:
6788     if (ICI.isEquality() && LHSI->hasOneUse()) {
6789       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6790       // of the high bits truncated out of x are known.
6791       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6792              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6793       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6794       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6795       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6796       
6797       // If all the high bits are known, we can do this xform.
6798       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6799         // Pull in the high bits from known-ones set.
6800         APInt NewRHS(RHS->getValue());
6801         NewRHS.zext(SrcBits);
6802         NewRHS |= KnownOne;
6803         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6804                             ConstantInt::get(*Context, NewRHS));
6805       }
6806     }
6807     break;
6808       
6809   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6810     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6811       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6812       // fold the xor.
6813       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6814           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6815         Value *CompareVal = LHSI->getOperand(0);
6816         
6817         // If the sign bit of the XorCST is not set, there is no change to
6818         // the operation, just stop using the Xor.
6819         if (!XorCST->getValue().isNegative()) {
6820           ICI.setOperand(0, CompareVal);
6821           Worklist.Add(LHSI);
6822           return &ICI;
6823         }
6824         
6825         // Was the old condition true if the operand is positive?
6826         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6827         
6828         // If so, the new one isn't.
6829         isTrueIfPositive ^= true;
6830         
6831         if (isTrueIfPositive)
6832           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
6833                               SubOne(RHS));
6834         else
6835           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
6836                               AddOne(RHS));
6837       }
6838
6839       if (LHSI->hasOneUse()) {
6840         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6841         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6842           const APInt &SignBit = XorCST->getValue();
6843           ICmpInst::Predicate Pred = ICI.isSigned()
6844                                          ? ICI.getUnsignedPredicate()
6845                                          : ICI.getSignedPredicate();
6846           return new ICmpInst(Pred, LHSI->getOperand(0),
6847                               ConstantInt::get(*Context, RHSV ^ SignBit));
6848         }
6849
6850         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6851         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6852           const APInt &NotSignBit = XorCST->getValue();
6853           ICmpInst::Predicate Pred = ICI.isSigned()
6854                                          ? ICI.getUnsignedPredicate()
6855                                          : ICI.getSignedPredicate();
6856           Pred = ICI.getSwappedPredicate(Pred);
6857           return new ICmpInst(Pred, LHSI->getOperand(0),
6858                               ConstantInt::get(*Context, RHSV ^ NotSignBit));
6859         }
6860       }
6861     }
6862     break;
6863   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6864     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6865         LHSI->getOperand(0)->hasOneUse()) {
6866       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6867       
6868       // If the LHS is an AND of a truncating cast, we can widen the
6869       // and/compare to be the input width without changing the value
6870       // produced, eliminating a cast.
6871       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6872         // We can do this transformation if either the AND constant does not
6873         // have its sign bit set or if it is an equality comparison. 
6874         // Extending a relational comparison when we're checking the sign
6875         // bit would not work.
6876         if (Cast->hasOneUse() &&
6877             (ICI.isEquality() ||
6878              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6879           uint32_t BitWidth = 
6880             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6881           APInt NewCST = AndCST->getValue();
6882           NewCST.zext(BitWidth);
6883           APInt NewCI = RHSV;
6884           NewCI.zext(BitWidth);
6885           Value *NewAnd = 
6886             Builder->CreateAnd(Cast->getOperand(0),
6887                            ConstantInt::get(*Context, NewCST), LHSI->getName());
6888           return new ICmpInst(ICI.getPredicate(), NewAnd,
6889                               ConstantInt::get(*Context, NewCI));
6890         }
6891       }
6892       
6893       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6894       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6895       // happens a LOT in code produced by the C front-end, for bitfield
6896       // access.
6897       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6898       if (Shift && !Shift->isShift())
6899         Shift = 0;
6900       
6901       ConstantInt *ShAmt;
6902       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6903       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6904       const Type *AndTy = AndCST->getType();          // Type of the and.
6905       
6906       // We can fold this as long as we can't shift unknown bits
6907       // into the mask.  This can only happen with signed shift
6908       // rights, as they sign-extend.
6909       if (ShAmt) {
6910         bool CanFold = Shift->isLogicalShift();
6911         if (!CanFold) {
6912           // To test for the bad case of the signed shr, see if any
6913           // of the bits shifted in could be tested after the mask.
6914           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6915           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6916           
6917           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6918           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6919                AndCST->getValue()) == 0)
6920             CanFold = true;
6921         }
6922         
6923         if (CanFold) {
6924           Constant *NewCst;
6925           if (Shift->getOpcode() == Instruction::Shl)
6926             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6927           else
6928             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6929           
6930           // Check to see if we are shifting out any of the bits being
6931           // compared.
6932           if (ConstantExpr::get(Shift->getOpcode(),
6933                                        NewCst, ShAmt) != RHS) {
6934             // If we shifted bits out, the fold is not going to work out.
6935             // As a special case, check to see if this means that the
6936             // result is always true or false now.
6937             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6938               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6939             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6940               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6941           } else {
6942             ICI.setOperand(1, NewCst);
6943             Constant *NewAndCST;
6944             if (Shift->getOpcode() == Instruction::Shl)
6945               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6946             else
6947               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6948             LHSI->setOperand(1, NewAndCST);
6949             LHSI->setOperand(0, Shift->getOperand(0));
6950             Worklist.Add(Shift); // Shift is dead.
6951             return &ICI;
6952           }
6953         }
6954       }
6955       
6956       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6957       // preferable because it allows the C<<Y expression to be hoisted out
6958       // of a loop if Y is invariant and X is not.
6959       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6960           ICI.isEquality() && !Shift->isArithmeticShift() &&
6961           !isa<Constant>(Shift->getOperand(0))) {
6962         // Compute C << Y.
6963         Value *NS;
6964         if (Shift->getOpcode() == Instruction::LShr) {
6965           NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
6966         } else {
6967           // Insert a logical shift.
6968           NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
6969         }
6970         
6971         // Compute X & (C << Y).
6972         Value *NewAnd = 
6973           Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6974         
6975         ICI.setOperand(0, NewAnd);
6976         return &ICI;
6977       }
6978     }
6979     break;
6980     
6981   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6982     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6983     if (!ShAmt) break;
6984     
6985     uint32_t TypeBits = RHSV.getBitWidth();
6986     
6987     // Check that the shift amount is in range.  If not, don't perform
6988     // undefined shifts.  When the shift is visited it will be
6989     // simplified.
6990     if (ShAmt->uge(TypeBits))
6991       break;
6992     
6993     if (ICI.isEquality()) {
6994       // If we are comparing against bits always shifted out, the
6995       // comparison cannot succeed.
6996       Constant *Comp =
6997         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
6998                                                                  ShAmt);
6999       if (Comp != RHS) {// Comparing against a bit that we know is zero.
7000         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7001         Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
7002         return ReplaceInstUsesWith(ICI, Cst);
7003       }
7004       
7005       if (LHSI->hasOneUse()) {
7006         // Otherwise strength reduce the shift into an and.
7007         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
7008         Constant *Mask =
7009           ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits, 
7010                                                        TypeBits-ShAmtVal));
7011         
7012         Value *And =
7013           Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
7014         return new ICmpInst(ICI.getPredicate(), And,
7015                             ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
7016       }
7017     }
7018     
7019     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
7020     bool TrueIfSigned = false;
7021     if (LHSI->hasOneUse() &&
7022         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
7023       // (X << 31) <s 0  --> (X&1) != 0
7024       Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
7025                                            (TypeBits-ShAmt->getZExtValue()-1));
7026       Value *And =
7027         Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
7028       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
7029                           And, Constant::getNullValue(And->getType()));
7030     }
7031     break;
7032   }
7033     
7034   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
7035   case Instruction::AShr: {
7036     // Only handle equality comparisons of shift-by-constant.
7037     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7038     if (!ShAmt || !ICI.isEquality()) break;
7039
7040     // Check that the shift amount is in range.  If not, don't perform
7041     // undefined shifts.  When the shift is visited it will be
7042     // simplified.
7043     uint32_t TypeBits = RHSV.getBitWidth();
7044     if (ShAmt->uge(TypeBits))
7045       break;
7046     
7047     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
7048       
7049     // If we are comparing against bits always shifted out, the
7050     // comparison cannot succeed.
7051     APInt Comp = RHSV << ShAmtVal;
7052     if (LHSI->getOpcode() == Instruction::LShr)
7053       Comp = Comp.lshr(ShAmtVal);
7054     else
7055       Comp = Comp.ashr(ShAmtVal);
7056     
7057     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7058       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7059       Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
7060       return ReplaceInstUsesWith(ICI, Cst);
7061     }
7062     
7063     // Otherwise, check to see if the bits shifted out are known to be zero.
7064     // If so, we can compare against the unshifted value:
7065     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
7066     if (LHSI->hasOneUse() &&
7067         MaskedValueIsZero(LHSI->getOperand(0), 
7068                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
7069       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
7070                           ConstantExpr::getShl(RHS, ShAmt));
7071     }
7072       
7073     if (LHSI->hasOneUse()) {
7074       // Otherwise strength reduce the shift into an and.
7075       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7076       Constant *Mask = ConstantInt::get(*Context, Val);
7077       
7078       Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7079                                       Mask, LHSI->getName()+".mask");
7080       return new ICmpInst(ICI.getPredicate(), And,
7081                           ConstantExpr::getShl(RHS, ShAmt));
7082     }
7083     break;
7084   }
7085     
7086   case Instruction::SDiv:
7087   case Instruction::UDiv:
7088     // Fold: icmp pred ([us]div X, C1), C2 -> range test
7089     // Fold this div into the comparison, producing a range check. 
7090     // Determine, based on the divide type, what the range is being 
7091     // checked.  If there is an overflow on the low or high side, remember 
7092     // it, otherwise compute the range [low, hi) bounding the new value.
7093     // See: InsertRangeTest above for the kinds of replacements possible.
7094     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7095       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7096                                           DivRHS))
7097         return R;
7098     break;
7099
7100   case Instruction::Add:
7101     // Fold: icmp pred (add, X, C1), C2
7102
7103     if (!ICI.isEquality()) {
7104       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7105       if (!LHSC) break;
7106       const APInt &LHSV = LHSC->getValue();
7107
7108       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7109                             .subtract(LHSV);
7110
7111       if (ICI.isSigned()) {
7112         if (CR.getLower().isSignBit()) {
7113           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7114                               ConstantInt::get(*Context, CR.getUpper()));
7115         } else if (CR.getUpper().isSignBit()) {
7116           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7117                               ConstantInt::get(*Context, CR.getLower()));
7118         }
7119       } else {
7120         if (CR.getLower().isMinValue()) {
7121           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7122                               ConstantInt::get(*Context, CR.getUpper()));
7123         } else if (CR.getUpper().isMinValue()) {
7124           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7125                               ConstantInt::get(*Context, CR.getLower()));
7126         }
7127       }
7128     }
7129     break;
7130   }
7131   
7132   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7133   if (ICI.isEquality()) {
7134     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7135     
7136     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7137     // the second operand is a constant, simplify a bit.
7138     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7139       switch (BO->getOpcode()) {
7140       case Instruction::SRem:
7141         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7142         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7143           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7144           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7145             Value *NewRem =
7146               Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7147                                   BO->getName());
7148             return new ICmpInst(ICI.getPredicate(), NewRem,
7149                                 Constant::getNullValue(BO->getType()));
7150           }
7151         }
7152         break;
7153       case Instruction::Add:
7154         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7155         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7156           if (BO->hasOneUse())
7157             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7158                                 ConstantExpr::getSub(RHS, BOp1C));
7159         } else if (RHSV == 0) {
7160           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7161           // efficiently invertible, or if the add has just this one use.
7162           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7163           
7164           if (Value *NegVal = dyn_castNegVal(BOp1))
7165             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
7166           else if (Value *NegVal = dyn_castNegVal(BOp0))
7167             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
7168           else if (BO->hasOneUse()) {
7169             Value *Neg = Builder->CreateNeg(BOp1);
7170             Neg->takeName(BO);
7171             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
7172           }
7173         }
7174         break;
7175       case Instruction::Xor:
7176         // For the xor case, we can xor two constants together, eliminating
7177         // the explicit xor.
7178         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7179           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
7180                               ConstantExpr::getXor(RHS, BOC));
7181         
7182         // FALLTHROUGH
7183       case Instruction::Sub:
7184         // Replace (([sub|xor] A, B) != 0) with (A != B)
7185         if (RHSV == 0)
7186           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7187                               BO->getOperand(1));
7188         break;
7189         
7190       case Instruction::Or:
7191         // If bits are being or'd in that are not present in the constant we
7192         // are comparing against, then the comparison could never succeed!
7193         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7194           Constant *NotCI = ConstantExpr::getNot(RHS);
7195           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7196             return ReplaceInstUsesWith(ICI,
7197                                        ConstantInt::get(Type::getInt1Ty(*Context), 
7198                                        isICMP_NE));
7199         }
7200         break;
7201         
7202       case Instruction::And:
7203         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7204           // If bits are being compared against that are and'd out, then the
7205           // comparison can never succeed!
7206           if ((RHSV & ~BOC->getValue()) != 0)
7207             return ReplaceInstUsesWith(ICI,
7208                                        ConstantInt::get(Type::getInt1Ty(*Context),
7209                                        isICMP_NE));
7210           
7211           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7212           if (RHS == BOC && RHSV.isPowerOf2())
7213             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7214                                 ICmpInst::ICMP_NE, LHSI,
7215                                 Constant::getNullValue(RHS->getType()));
7216           
7217           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7218           if (BOC->getValue().isSignBit()) {
7219             Value *X = BO->getOperand(0);
7220             Constant *Zero = Constant::getNullValue(X->getType());
7221             ICmpInst::Predicate pred = isICMP_NE ? 
7222               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7223             return new ICmpInst(pred, X, Zero);
7224           }
7225           
7226           // ((X & ~7) == 0) --> X < 8
7227           if (RHSV == 0 && isHighOnes(BOC)) {
7228             Value *X = BO->getOperand(0);
7229             Constant *NegX = ConstantExpr::getNeg(BOC);
7230             ICmpInst::Predicate pred = isICMP_NE ? 
7231               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7232             return new ICmpInst(pred, X, NegX);
7233           }
7234         }
7235       default: break;
7236       }
7237     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7238       // Handle icmp {eq|ne} <intrinsic>, intcst.
7239       if (II->getIntrinsicID() == Intrinsic::bswap) {
7240         Worklist.Add(II);
7241         ICI.setOperand(0, II->getOperand(1));
7242         ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7243         return &ICI;
7244       }
7245     }
7246   }
7247   return 0;
7248 }
7249
7250 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7251 /// We only handle extending casts so far.
7252 ///
7253 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7254   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7255   Value *LHSCIOp        = LHSCI->getOperand(0);
7256   const Type *SrcTy     = LHSCIOp->getType();
7257   const Type *DestTy    = LHSCI->getType();
7258   Value *RHSCIOp;
7259
7260   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7261   // integer type is the same size as the pointer type.
7262   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7263       TD->getPointerSizeInBits() ==
7264          cast<IntegerType>(DestTy)->getBitWidth()) {
7265     Value *RHSOp = 0;
7266     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7267       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7268     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7269       RHSOp = RHSC->getOperand(0);
7270       // If the pointer types don't match, insert a bitcast.
7271       if (LHSCIOp->getType() != RHSOp->getType())
7272         RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
7273     }
7274
7275     if (RHSOp)
7276       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7277   }
7278   
7279   // The code below only handles extension cast instructions, so far.
7280   // Enforce this.
7281   if (LHSCI->getOpcode() != Instruction::ZExt &&
7282       LHSCI->getOpcode() != Instruction::SExt)
7283     return 0;
7284
7285   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7286   bool isSignedCmp = ICI.isSigned();
7287
7288   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7289     // Not an extension from the same type?
7290     RHSCIOp = CI->getOperand(0);
7291     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7292       return 0;
7293     
7294     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7295     // and the other is a zext), then we can't handle this.
7296     if (CI->getOpcode() != LHSCI->getOpcode())
7297       return 0;
7298
7299     // Deal with equality cases early.
7300     if (ICI.isEquality())
7301       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7302
7303     // A signed comparison of sign extended values simplifies into a
7304     // signed comparison.
7305     if (isSignedCmp && isSignedExt)
7306       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7307
7308     // The other three cases all fold into an unsigned comparison.
7309     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7310   }
7311
7312   // If we aren't dealing with a constant on the RHS, exit early
7313   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7314   if (!CI)
7315     return 0;
7316
7317   // Compute the constant that would happen if we truncated to SrcTy then
7318   // reextended to DestTy.
7319   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7320   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7321                                                 Res1, DestTy);
7322
7323   // If the re-extended constant didn't change...
7324   if (Res2 == CI) {
7325     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7326     // For example, we might have:
7327     //    %A = sext i16 %X to i32
7328     //    %B = icmp ugt i32 %A, 1330
7329     // It is incorrect to transform this into 
7330     //    %B = icmp ugt i16 %X, 1330
7331     // because %A may have negative value. 
7332     //
7333     // However, we allow this when the compare is EQ/NE, because they are
7334     // signless.
7335     if (isSignedExt == isSignedCmp || ICI.isEquality())
7336       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7337     return 0;
7338   }
7339
7340   // The re-extended constant changed so the constant cannot be represented 
7341   // in the shorter type. Consequently, we cannot emit a simple comparison.
7342
7343   // First, handle some easy cases. We know the result cannot be equal at this
7344   // point so handle the ICI.isEquality() cases
7345   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7346     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7347   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7348     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7349
7350   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7351   // should have been folded away previously and not enter in here.
7352   Value *Result;
7353   if (isSignedCmp) {
7354     // We're performing a signed comparison.
7355     if (cast<ConstantInt>(CI)->getValue().isNegative())
7356       Result = ConstantInt::getFalse(*Context);          // X < (small) --> false
7357     else
7358       Result = ConstantInt::getTrue(*Context);           // X < (large) --> true
7359   } else {
7360     // We're performing an unsigned comparison.
7361     if (isSignedExt) {
7362       // We're performing an unsigned comp with a sign extended value.
7363       // This is true if the input is >= 0. [aka >s -1]
7364       Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7365       Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
7366     } else {
7367       // Unsigned extend & unsigned compare -> always true.
7368       Result = ConstantInt::getTrue(*Context);
7369     }
7370   }
7371
7372   // Finally, return the value computed.
7373   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7374       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7375     return ReplaceInstUsesWith(ICI, Result);
7376
7377   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7378           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7379          "ICmp should be folded!");
7380   if (Constant *CI = dyn_cast<Constant>(Result))
7381     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7382   return BinaryOperator::CreateNot(Result);
7383 }
7384
7385 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7386   return commonShiftTransforms(I);
7387 }
7388
7389 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7390   return commonShiftTransforms(I);
7391 }
7392
7393 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7394   if (Instruction *R = commonShiftTransforms(I))
7395     return R;
7396   
7397   Value *Op0 = I.getOperand(0);
7398   
7399   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7400   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7401     if (CSI->isAllOnesValue())
7402       return ReplaceInstUsesWith(I, CSI);
7403
7404   // See if we can turn a signed shr into an unsigned shr.
7405   if (MaskedValueIsZero(Op0,
7406                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7407     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7408
7409   // Arithmetic shifting an all-sign-bit value is a no-op.
7410   unsigned NumSignBits = ComputeNumSignBits(Op0);
7411   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7412     return ReplaceInstUsesWith(I, Op0);
7413
7414   return 0;
7415 }
7416
7417 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7418   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7419   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7420
7421   // shl X, 0 == X and shr X, 0 == X
7422   // shl 0, X == 0 and shr 0, X == 0
7423   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7424       Op0 == Constant::getNullValue(Op0->getType()))
7425     return ReplaceInstUsesWith(I, Op0);
7426   
7427   if (isa<UndefValue>(Op0)) {            
7428     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7429       return ReplaceInstUsesWith(I, Op0);
7430     else                                    // undef << X -> 0, undef >>u X -> 0
7431       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7432   }
7433   if (isa<UndefValue>(Op1)) {
7434     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7435       return ReplaceInstUsesWith(I, Op0);          
7436     else                                     // X << undef, X >>u undef -> 0
7437       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7438   }
7439
7440   // See if we can fold away this shift.
7441   if (SimplifyDemandedInstructionBits(I))
7442     return &I;
7443
7444   // Try to fold constant and into select arguments.
7445   if (isa<Constant>(Op0))
7446     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7447       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7448         return R;
7449
7450   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7451     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7452       return Res;
7453   return 0;
7454 }
7455
7456 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7457                                                BinaryOperator &I) {
7458   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7459
7460   // See if we can simplify any instructions used by the instruction whose sole 
7461   // purpose is to compute bits we don't care about.
7462   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7463   
7464   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7465   // a signed shift.
7466   //
7467   if (Op1->uge(TypeBits)) {
7468     if (I.getOpcode() != Instruction::AShr)
7469       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7470     else {
7471       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7472       return &I;
7473     }
7474   }
7475   
7476   // ((X*C1) << C2) == (X * (C1 << C2))
7477   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7478     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7479       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7480         return BinaryOperator::CreateMul(BO->getOperand(0),
7481                                         ConstantExpr::getShl(BOOp, Op1));
7482   
7483   // Try to fold constant and into select arguments.
7484   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7485     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7486       return R;
7487   if (isa<PHINode>(Op0))
7488     if (Instruction *NV = FoldOpIntoPhi(I))
7489       return NV;
7490   
7491   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7492   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7493     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7494     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7495     // place.  Don't try to do this transformation in this case.  Also, we
7496     // require that the input operand is a shift-by-constant so that we have
7497     // confidence that the shifts will get folded together.  We could do this
7498     // xform in more cases, but it is unlikely to be profitable.
7499     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7500         isa<ConstantInt>(TrOp->getOperand(1))) {
7501       // Okay, we'll do this xform.  Make the shift of shift.
7502       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7503       // (shift2 (shift1 & 0x00FF), c2)
7504       Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
7505
7506       // For logical shifts, the truncation has the effect of making the high
7507       // part of the register be zeros.  Emulate this by inserting an AND to
7508       // clear the top bits as needed.  This 'and' will usually be zapped by
7509       // other xforms later if dead.
7510       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7511       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7512       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7513       
7514       // The mask we constructed says what the trunc would do if occurring
7515       // between the shifts.  We want to know the effect *after* the second
7516       // shift.  We know that it is a logical shift by a constant, so adjust the
7517       // mask as appropriate.
7518       if (I.getOpcode() == Instruction::Shl)
7519         MaskV <<= Op1->getZExtValue();
7520       else {
7521         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7522         MaskV = MaskV.lshr(Op1->getZExtValue());
7523       }
7524
7525       // shift1 & 0x00FF
7526       Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7527                                       TI->getName());
7528
7529       // Return the value truncated to the interesting size.
7530       return new TruncInst(And, I.getType());
7531     }
7532   }
7533   
7534   if (Op0->hasOneUse()) {
7535     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7536       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7537       Value *V1, *V2;
7538       ConstantInt *CC;
7539       switch (Op0BO->getOpcode()) {
7540         default: break;
7541         case Instruction::Add:
7542         case Instruction::And:
7543         case Instruction::Or:
7544         case Instruction::Xor: {
7545           // These operators commute.
7546           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7547           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7548               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7549                     m_Specific(Op1)))) {
7550             Value *YS =         // (Y << C)
7551               Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7552             // (X + (Y << C))
7553             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7554                                             Op0BO->getOperand(1)->getName());
7555             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7556             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7557                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7558           }
7559           
7560           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7561           Value *Op0BOOp1 = Op0BO->getOperand(1);
7562           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7563               match(Op0BOOp1, 
7564                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7565                           m_ConstantInt(CC))) &&
7566               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7567             Value *YS =   // (Y << C)
7568               Builder->CreateShl(Op0BO->getOperand(0), Op1,
7569                                            Op0BO->getName());
7570             // X & (CC << C)
7571             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7572                                            V1->getName()+".mask");
7573             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7574           }
7575         }
7576           
7577         // FALL THROUGH.
7578         case Instruction::Sub: {
7579           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7580           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7581               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7582                     m_Specific(Op1)))) {
7583             Value *YS =  // (Y << C)
7584               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7585             // (X + (Y << C))
7586             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7587                                             Op0BO->getOperand(0)->getName());
7588             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7589             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7590                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7591           }
7592           
7593           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7594           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7595               match(Op0BO->getOperand(0),
7596                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7597                           m_ConstantInt(CC))) && V2 == Op1 &&
7598               cast<BinaryOperator>(Op0BO->getOperand(0))
7599                   ->getOperand(0)->hasOneUse()) {
7600             Value *YS = // (Y << C)
7601               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7602             // X & (CC << C)
7603             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7604                                            V1->getName()+".mask");
7605             
7606             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7607           }
7608           
7609           break;
7610         }
7611       }
7612       
7613       
7614       // If the operand is an bitwise operator with a constant RHS, and the
7615       // shift is the only use, we can pull it out of the shift.
7616       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7617         bool isValid = true;     // Valid only for And, Or, Xor
7618         bool highBitSet = false; // Transform if high bit of constant set?
7619         
7620         switch (Op0BO->getOpcode()) {
7621           default: isValid = false; break;   // Do not perform transform!
7622           case Instruction::Add:
7623             isValid = isLeftShift;
7624             break;
7625           case Instruction::Or:
7626           case Instruction::Xor:
7627             highBitSet = false;
7628             break;
7629           case Instruction::And:
7630             highBitSet = true;
7631             break;
7632         }
7633         
7634         // If this is a signed shift right, and the high bit is modified
7635         // by the logical operation, do not perform the transformation.
7636         // The highBitSet boolean indicates the value of the high bit of
7637         // the constant which would cause it to be modified for this
7638         // operation.
7639         //
7640         if (isValid && I.getOpcode() == Instruction::AShr)
7641           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7642         
7643         if (isValid) {
7644           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7645           
7646           Value *NewShift =
7647             Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
7648           NewShift->takeName(Op0BO);
7649           
7650           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7651                                         NewRHS);
7652         }
7653       }
7654     }
7655   }
7656   
7657   // Find out if this is a shift of a shift by a constant.
7658   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7659   if (ShiftOp && !ShiftOp->isShift())
7660     ShiftOp = 0;
7661   
7662   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7663     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7664     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7665     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7666     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7667     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7668     Value *X = ShiftOp->getOperand(0);
7669     
7670     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7671     
7672     const IntegerType *Ty = cast<IntegerType>(I.getType());
7673     
7674     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7675     if (I.getOpcode() == ShiftOp->getOpcode()) {
7676       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7677       // saturates.
7678       if (AmtSum >= TypeBits) {
7679         if (I.getOpcode() != Instruction::AShr)
7680           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7681         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7682       }
7683       
7684       return BinaryOperator::Create(I.getOpcode(), X,
7685                                     ConstantInt::get(Ty, AmtSum));
7686     }
7687     
7688     if (ShiftOp->getOpcode() == Instruction::LShr &&
7689         I.getOpcode() == Instruction::AShr) {
7690       if (AmtSum >= TypeBits)
7691         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7692       
7693       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7694       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7695     }
7696     
7697     if (ShiftOp->getOpcode() == Instruction::AShr &&
7698         I.getOpcode() == Instruction::LShr) {
7699       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7700       if (AmtSum >= TypeBits)
7701         AmtSum = TypeBits-1;
7702       
7703       Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7704
7705       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7706       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7707     }
7708     
7709     // Okay, if we get here, one shift must be left, and the other shift must be
7710     // right.  See if the amounts are equal.
7711     if (ShiftAmt1 == ShiftAmt2) {
7712       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7713       if (I.getOpcode() == Instruction::Shl) {
7714         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7715         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7716       }
7717       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7718       if (I.getOpcode() == Instruction::LShr) {
7719         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7720         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7721       }
7722       // We can simplify ((X << C) >>s C) into a trunc + sext.
7723       // NOTE: we could do this for any C, but that would make 'unusual' integer
7724       // types.  For now, just stick to ones well-supported by the code
7725       // generators.
7726       const Type *SExtType = 0;
7727       switch (Ty->getBitWidth() - ShiftAmt1) {
7728       case 1  :
7729       case 8  :
7730       case 16 :
7731       case 32 :
7732       case 64 :
7733       case 128:
7734         SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
7735         break;
7736       default: break;
7737       }
7738       if (SExtType)
7739         return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
7740       // Otherwise, we can't handle it yet.
7741     } else if (ShiftAmt1 < ShiftAmt2) {
7742       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7743       
7744       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7745       if (I.getOpcode() == Instruction::Shl) {
7746         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7747                ShiftOp->getOpcode() == Instruction::AShr);
7748         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7749         
7750         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7751         return BinaryOperator::CreateAnd(Shift,
7752                                          ConstantInt::get(*Context, Mask));
7753       }
7754       
7755       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7756       if (I.getOpcode() == Instruction::LShr) {
7757         assert(ShiftOp->getOpcode() == Instruction::Shl);
7758         Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7759         
7760         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7761         return BinaryOperator::CreateAnd(Shift,
7762                                          ConstantInt::get(*Context, Mask));
7763       }
7764       
7765       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7766     } else {
7767       assert(ShiftAmt2 < ShiftAmt1);
7768       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7769
7770       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7771       if (I.getOpcode() == Instruction::Shl) {
7772         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7773                ShiftOp->getOpcode() == Instruction::AShr);
7774         Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7775                                             ConstantInt::get(Ty, ShiftDiff));
7776         
7777         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7778         return BinaryOperator::CreateAnd(Shift,
7779                                          ConstantInt::get(*Context, Mask));
7780       }
7781       
7782       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7783       if (I.getOpcode() == Instruction::LShr) {
7784         assert(ShiftOp->getOpcode() == Instruction::Shl);
7785         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7786         
7787         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7788         return BinaryOperator::CreateAnd(Shift,
7789                                          ConstantInt::get(*Context, Mask));
7790       }
7791       
7792       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7793     }
7794   }
7795   return 0;
7796 }
7797
7798
7799 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7800 /// expression.  If so, decompose it, returning some value X, such that Val is
7801 /// X*Scale+Offset.
7802 ///
7803 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7804                                         int &Offset, LLVMContext *Context) {
7805   assert(Val->getType() == Type::getInt32Ty(*Context) && 
7806          "Unexpected allocation size type!");
7807   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7808     Offset = CI->getZExtValue();
7809     Scale  = 0;
7810     return ConstantInt::get(Type::getInt32Ty(*Context), 0);
7811   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7812     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7813       if (I->getOpcode() == Instruction::Shl) {
7814         // This is a value scaled by '1 << the shift amt'.
7815         Scale = 1U << RHS->getZExtValue();
7816         Offset = 0;
7817         return I->getOperand(0);
7818       } else if (I->getOpcode() == Instruction::Mul) {
7819         // This value is scaled by 'RHS'.
7820         Scale = RHS->getZExtValue();
7821         Offset = 0;
7822         return I->getOperand(0);
7823       } else if (I->getOpcode() == Instruction::Add) {
7824         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7825         // where C1 is divisible by C2.
7826         unsigned SubScale;
7827         Value *SubVal = 
7828           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7829                                     Offset, Context);
7830         Offset += RHS->getZExtValue();
7831         Scale = SubScale;
7832         return SubVal;
7833       }
7834     }
7835   }
7836
7837   // Otherwise, we can't look past this.
7838   Scale = 1;
7839   Offset = 0;
7840   return Val;
7841 }
7842
7843
7844 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7845 /// try to eliminate the cast by moving the type information into the alloc.
7846 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7847                                                    AllocaInst &AI) {
7848   const PointerType *PTy = cast<PointerType>(CI.getType());
7849   
7850   BuilderTy AllocaBuilder(*Builder);
7851   AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7852   
7853   // Remove any uses of AI that are dead.
7854   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7855   
7856   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7857     Instruction *User = cast<Instruction>(*UI++);
7858     if (isInstructionTriviallyDead(User)) {
7859       while (UI != E && *UI == User)
7860         ++UI; // If this instruction uses AI more than once, don't break UI.
7861       
7862       ++NumDeadInst;
7863       DEBUG(errs() << "IC: DCE: " << *User << '\n');
7864       EraseInstFromFunction(*User);
7865     }
7866   }
7867
7868   // This requires TargetData to get the alloca alignment and size information.
7869   if (!TD) return 0;
7870
7871   // Get the type really allocated and the type casted to.
7872   const Type *AllocElTy = AI.getAllocatedType();
7873   const Type *CastElTy = PTy->getElementType();
7874   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7875
7876   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7877   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7878   if (CastElTyAlign < AllocElTyAlign) return 0;
7879
7880   // If the allocation has multiple uses, only promote it if we are strictly
7881   // increasing the alignment of the resultant allocation.  If we keep it the
7882   // same, we open the door to infinite loops of various kinds.  (A reference
7883   // from a dbg.declare doesn't count as a use for this purpose.)
7884   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7885       CastElTyAlign == AllocElTyAlign) return 0;
7886
7887   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7888   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7889   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7890
7891   // See if we can satisfy the modulus by pulling a scale out of the array
7892   // size argument.
7893   unsigned ArraySizeScale;
7894   int ArrayOffset;
7895   Value *NumElements = // See if the array size is a decomposable linear expr.
7896     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7897                               ArrayOffset, Context);
7898  
7899   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7900   // do the xform.
7901   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7902       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7903
7904   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7905   Value *Amt = 0;
7906   if (Scale == 1) {
7907     Amt = NumElements;
7908   } else {
7909     Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
7910     // Insert before the alloca, not before the cast.
7911     Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
7912   }
7913   
7914   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7915     Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
7916     Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
7917   }
7918   
7919   AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7920   New->setAlignment(AI.getAlignment());
7921   New->takeName(&AI);
7922   
7923   // If the allocation has one real use plus a dbg.declare, just remove the
7924   // declare.
7925   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7926     EraseInstFromFunction(*DI);
7927   }
7928   // If the allocation has multiple real uses, insert a cast and change all
7929   // things that used it to use the new cast.  This will also hack on CI, but it
7930   // will die soon.
7931   else if (!AI.hasOneUse()) {
7932     // New is the allocation instruction, pointer typed. AI is the original
7933     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7934     Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
7935     AI.replaceAllUsesWith(NewCast);
7936   }
7937   return ReplaceInstUsesWith(CI, New);
7938 }
7939
7940 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7941 /// and return it as type Ty without inserting any new casts and without
7942 /// changing the computed value.  This is used by code that tries to decide
7943 /// whether promoting or shrinking integer operations to wider or smaller types
7944 /// will allow us to eliminate a truncate or extend.
7945 ///
7946 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7947 /// extension operation if Ty is larger.
7948 ///
7949 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7950 /// should return true if trunc(V) can be computed by computing V in the smaller
7951 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7952 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7953 /// efficiently truncated.
7954 ///
7955 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7956 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7957 /// the final result.
7958 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7959                                               unsigned CastOpc,
7960                                               int &NumCastsRemoved){
7961   // We can always evaluate constants in another type.
7962   if (isa<Constant>(V))
7963     return true;
7964   
7965   Instruction *I = dyn_cast<Instruction>(V);
7966   if (!I) return false;
7967   
7968   const Type *OrigTy = V->getType();
7969   
7970   // If this is an extension or truncate, we can often eliminate it.
7971   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7972     // If this is a cast from the destination type, we can trivially eliminate
7973     // it, and this will remove a cast overall.
7974     if (I->getOperand(0)->getType() == Ty) {
7975       // If the first operand is itself a cast, and is eliminable, do not count
7976       // this as an eliminable cast.  We would prefer to eliminate those two
7977       // casts first.
7978       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7979         ++NumCastsRemoved;
7980       return true;
7981     }
7982   }
7983
7984   // We can't extend or shrink something that has multiple uses: doing so would
7985   // require duplicating the instruction in general, which isn't profitable.
7986   if (!I->hasOneUse()) return false;
7987
7988   unsigned Opc = I->getOpcode();
7989   switch (Opc) {
7990   case Instruction::Add:
7991   case Instruction::Sub:
7992   case Instruction::Mul:
7993   case Instruction::And:
7994   case Instruction::Or:
7995   case Instruction::Xor:
7996     // These operators can all arbitrarily be extended or truncated.
7997     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7998                                       NumCastsRemoved) &&
7999            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8000                                       NumCastsRemoved);
8001
8002   case Instruction::UDiv:
8003   case Instruction::URem: {
8004     // UDiv and URem can be truncated if all the truncated bits are zero.
8005     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8006     uint32_t BitWidth = Ty->getScalarSizeInBits();
8007     if (BitWidth < OrigBitWidth) {
8008       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
8009       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
8010           MaskedValueIsZero(I->getOperand(1), Mask)) {
8011         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8012                                           NumCastsRemoved) &&
8013                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8014                                           NumCastsRemoved);
8015       }
8016     }
8017     break;
8018   }
8019   case Instruction::Shl:
8020     // If we are truncating the result of this SHL, and if it's a shift of a
8021     // constant amount, we can always perform a SHL in a smaller type.
8022     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8023       uint32_t BitWidth = Ty->getScalarSizeInBits();
8024       if (BitWidth < OrigTy->getScalarSizeInBits() &&
8025           CI->getLimitedValue(BitWidth) < BitWidth)
8026         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8027                                           NumCastsRemoved);
8028     }
8029     break;
8030   case Instruction::LShr:
8031     // If this is a truncate of a logical shr, we can truncate it to a smaller
8032     // lshr iff we know that the bits we would otherwise be shifting in are
8033     // already zeros.
8034     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8035       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8036       uint32_t BitWidth = Ty->getScalarSizeInBits();
8037       if (BitWidth < OrigBitWidth &&
8038           MaskedValueIsZero(I->getOperand(0),
8039             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8040           CI->getLimitedValue(BitWidth) < BitWidth) {
8041         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8042                                           NumCastsRemoved);
8043       }
8044     }
8045     break;
8046   case Instruction::ZExt:
8047   case Instruction::SExt:
8048   case Instruction::Trunc:
8049     // If this is the same kind of case as our original (e.g. zext+zext), we
8050     // can safely replace it.  Note that replacing it does not reduce the number
8051     // of casts in the input.
8052     if (Opc == CastOpc)
8053       return true;
8054
8055     // sext (zext ty1), ty2 -> zext ty2
8056     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8057       return true;
8058     break;
8059   case Instruction::Select: {
8060     SelectInst *SI = cast<SelectInst>(I);
8061     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8062                                       NumCastsRemoved) &&
8063            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8064                                       NumCastsRemoved);
8065   }
8066   case Instruction::PHI: {
8067     // We can change a phi if we can change all operands.
8068     PHINode *PN = cast<PHINode>(I);
8069     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8070       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8071                                       NumCastsRemoved))
8072         return false;
8073     return true;
8074   }
8075   default:
8076     // TODO: Can handle more cases here.
8077     break;
8078   }
8079   
8080   return false;
8081 }
8082
8083 /// EvaluateInDifferentType - Given an expression that 
8084 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8085 /// evaluate the expression.
8086 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
8087                                              bool isSigned) {
8088   if (Constant *C = dyn_cast<Constant>(V))
8089     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
8090
8091   // Otherwise, it must be an instruction.
8092   Instruction *I = cast<Instruction>(V);
8093   Instruction *Res = 0;
8094   unsigned Opc = I->getOpcode();
8095   switch (Opc) {
8096   case Instruction::Add:
8097   case Instruction::Sub:
8098   case Instruction::Mul:
8099   case Instruction::And:
8100   case Instruction::Or:
8101   case Instruction::Xor:
8102   case Instruction::AShr:
8103   case Instruction::LShr:
8104   case Instruction::Shl:
8105   case Instruction::UDiv:
8106   case Instruction::URem: {
8107     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8108     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8109     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8110     break;
8111   }    
8112   case Instruction::Trunc:
8113   case Instruction::ZExt:
8114   case Instruction::SExt:
8115     // If the source type of the cast is the type we're trying for then we can
8116     // just return the source.  There's no need to insert it because it is not
8117     // new.
8118     if (I->getOperand(0)->getType() == Ty)
8119       return I->getOperand(0);
8120     
8121     // Otherwise, must be the same type of cast, so just reinsert a new one.
8122     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
8123     break;
8124   case Instruction::Select: {
8125     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8126     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8127     Res = SelectInst::Create(I->getOperand(0), True, False);
8128     break;
8129   }
8130   case Instruction::PHI: {
8131     PHINode *OPN = cast<PHINode>(I);
8132     PHINode *NPN = PHINode::Create(Ty);
8133     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8134       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8135       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8136     }
8137     Res = NPN;
8138     break;
8139   }
8140   default: 
8141     // TODO: Can handle more cases here.
8142     llvm_unreachable("Unreachable!");
8143     break;
8144   }
8145   
8146   Res->takeName(I);
8147   return InsertNewInstBefore(Res, *I);
8148 }
8149
8150 /// @brief Implement the transforms common to all CastInst visitors.
8151 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8152   Value *Src = CI.getOperand(0);
8153
8154   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8155   // eliminate it now.
8156   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8157     if (Instruction::CastOps opc = 
8158         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8159       // The first cast (CSrc) is eliminable so we need to fix up or replace
8160       // the second cast (CI). CSrc will then have a good chance of being dead.
8161       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8162     }
8163   }
8164
8165   // If we are casting a select then fold the cast into the select
8166   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8167     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8168       return NV;
8169
8170   // If we are casting a PHI then fold the cast into the PHI
8171   if (isa<PHINode>(Src)) {
8172     // We don't do this if this would create a PHI node with an illegal type if
8173     // it is currently legal.
8174     if (!isa<IntegerType>(Src->getType()) ||
8175         !isa<IntegerType>(CI.getType()) ||
8176         (TD && TD->isLegalInteger(CI.getType()->getPrimitiveSizeInBits())) ||
8177         (TD && !TD->isLegalInteger(Src->getType()->getPrimitiveSizeInBits())))
8178       if (Instruction *NV = FoldOpIntoPhi(CI))
8179         return NV;
8180     
8181   }
8182   
8183   return 0;
8184 }
8185
8186 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8187 /// or not there is a sequence of GEP indices into the type that will land us at
8188 /// the specified offset.  If so, fill them into NewIndices and return the
8189 /// resultant element type, otherwise return null.
8190 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8191                                        SmallVectorImpl<Value*> &NewIndices,
8192                                        const TargetData *TD,
8193                                        LLVMContext *Context) {
8194   if (!TD) return 0;
8195   if (!Ty->isSized()) return 0;
8196   
8197   // Start with the index over the outer type.  Note that the type size
8198   // might be zero (even if the offset isn't zero) if the indexed type
8199   // is something like [0 x {int, int}]
8200   const Type *IntPtrTy = TD->getIntPtrType(*Context);
8201   int64_t FirstIdx = 0;
8202   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8203     FirstIdx = Offset/TySize;
8204     Offset -= FirstIdx*TySize;
8205     
8206     // Handle hosts where % returns negative instead of values [0..TySize).
8207     if (Offset < 0) {
8208       --FirstIdx;
8209       Offset += TySize;
8210       assert(Offset >= 0);
8211     }
8212     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8213   }
8214   
8215   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8216     
8217   // Index into the types.  If we fail, set OrigBase to null.
8218   while (Offset) {
8219     // Indexing into tail padding between struct/array elements.
8220     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8221       return 0;
8222     
8223     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8224       const StructLayout *SL = TD->getStructLayout(STy);
8225       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8226              "Offset must stay within the indexed type");
8227       
8228       unsigned Elt = SL->getElementContainingOffset(Offset);
8229       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8230       
8231       Offset -= SL->getElementOffset(Elt);
8232       Ty = STy->getElementType(Elt);
8233     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8234       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8235       assert(EltSize && "Cannot index into a zero-sized array");
8236       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8237       Offset %= EltSize;
8238       Ty = AT->getElementType();
8239     } else {
8240       // Otherwise, we can't index into the middle of this atomic type, bail.
8241       return 0;
8242     }
8243   }
8244   
8245   return Ty;
8246 }
8247
8248 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8249 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8250   Value *Src = CI.getOperand(0);
8251   
8252   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8253     // If casting the result of a getelementptr instruction with no offset, turn
8254     // this into a cast of the original pointer!
8255     if (GEP->hasAllZeroIndices()) {
8256       // Changing the cast operand is usually not a good idea but it is safe
8257       // here because the pointer operand is being replaced with another 
8258       // pointer operand so the opcode doesn't need to change.
8259       Worklist.Add(GEP);
8260       CI.setOperand(0, GEP->getOperand(0));
8261       return &CI;
8262     }
8263     
8264     // If the GEP has a single use, and the base pointer is a bitcast, and the
8265     // GEP computes a constant offset, see if we can convert these three
8266     // instructions into fewer.  This typically happens with unions and other
8267     // non-type-safe code.
8268     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8269       if (GEP->hasAllConstantIndices()) {
8270         // We are guaranteed to get a constant from EmitGEPOffset.
8271         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, *this));
8272         int64_t Offset = OffsetV->getSExtValue();
8273         
8274         // Get the base pointer input of the bitcast, and the type it points to.
8275         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8276         const Type *GEPIdxTy =
8277           cast<PointerType>(OrigBase->getType())->getElementType();
8278         SmallVector<Value*, 8> NewIndices;
8279         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8280           // If we were able to index down into an element, create the GEP
8281           // and bitcast the result.  This eliminates one bitcast, potentially
8282           // two.
8283           Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8284             Builder->CreateInBoundsGEP(OrigBase,
8285                                        NewIndices.begin(), NewIndices.end()) :
8286             Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
8287           NGEP->takeName(GEP);
8288           
8289           if (isa<BitCastInst>(CI))
8290             return new BitCastInst(NGEP, CI.getType());
8291           assert(isa<PtrToIntInst>(CI));
8292           return new PtrToIntInst(NGEP, CI.getType());
8293         }
8294       }      
8295     }
8296   }
8297     
8298   return commonCastTransforms(CI);
8299 }
8300
8301 /// commonIntCastTransforms - This function implements the common transforms
8302 /// for trunc, zext, and sext.
8303 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8304   if (Instruction *Result = commonCastTransforms(CI))
8305     return Result;
8306
8307   Value *Src = CI.getOperand(0);
8308   const Type *SrcTy = Src->getType();
8309   const Type *DestTy = CI.getType();
8310   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8311   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8312
8313   // See if we can simplify any instructions used by the LHS whose sole 
8314   // purpose is to compute bits we don't care about.
8315   if (SimplifyDemandedInstructionBits(CI))
8316     return &CI;
8317
8318   // If the source isn't an instruction or has more than one use then we
8319   // can't do anything more. 
8320   Instruction *SrcI = dyn_cast<Instruction>(Src);
8321   if (!SrcI || !Src->hasOneUse())
8322     return 0;
8323
8324   // Attempt to propagate the cast into the instruction for int->int casts.
8325   int NumCastsRemoved = 0;
8326   // Only do this if the dest type is a simple type, don't convert the
8327   // expression tree to something weird like i93 unless the source is also
8328   // strange.
8329   if (TD &&
8330       (TD->isLegalInteger(DestTy->getScalarType()->getPrimitiveSizeInBits()) ||
8331        !TD->isLegalInteger((SrcI->getType()->getScalarType()
8332                             ->getPrimitiveSizeInBits()))) &&
8333       CanEvaluateInDifferentType(SrcI, DestTy,
8334                                  CI.getOpcode(), NumCastsRemoved)) {
8335     // If this cast is a truncate, evaluting in a different type always
8336     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8337     // we need to do an AND to maintain the clear top-part of the computation,
8338     // so we require that the input have eliminated at least one cast.  If this
8339     // is a sign extension, we insert two new casts (to do the extension) so we
8340     // require that two casts have been eliminated.
8341     bool DoXForm = false;
8342     bool JustReplace = false;
8343     switch (CI.getOpcode()) {
8344     default:
8345       // All the others use floating point so we shouldn't actually 
8346       // get here because of the check above.
8347       llvm_unreachable("Unknown cast type");
8348     case Instruction::Trunc:
8349       DoXForm = true;
8350       break;
8351     case Instruction::ZExt: {
8352       DoXForm = NumCastsRemoved >= 1;
8353       
8354       if (!DoXForm && 0) {
8355         // If it's unnecessary to issue an AND to clear the high bits, it's
8356         // always profitable to do this xform.
8357         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8358         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8359         if (MaskedValueIsZero(TryRes, Mask))
8360           return ReplaceInstUsesWith(CI, TryRes);
8361         
8362         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8363           if (TryI->use_empty())
8364             EraseInstFromFunction(*TryI);
8365       }
8366       break;
8367     }
8368     case Instruction::SExt: {
8369       DoXForm = NumCastsRemoved >= 2;
8370       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8371         // If we do not have to emit the truncate + sext pair, then it's always
8372         // profitable to do this xform.
8373         //
8374         // It's not safe to eliminate the trunc + sext pair if one of the
8375         // eliminated cast is a truncate. e.g.
8376         // t2 = trunc i32 t1 to i16
8377         // t3 = sext i16 t2 to i32
8378         // !=
8379         // i32 t1
8380         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8381         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8382         if (NumSignBits > (DestBitSize - SrcBitSize))
8383           return ReplaceInstUsesWith(CI, TryRes);
8384         
8385         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8386           if (TryI->use_empty())
8387             EraseInstFromFunction(*TryI);
8388       }
8389       break;
8390     }
8391     }
8392     
8393     if (DoXForm) {
8394       DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8395             " to avoid cast: " << CI);
8396       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8397                                            CI.getOpcode() == Instruction::SExt);
8398       if (JustReplace)
8399         // Just replace this cast with the result.
8400         return ReplaceInstUsesWith(CI, Res);
8401
8402       assert(Res->getType() == DestTy);
8403       switch (CI.getOpcode()) {
8404       default: llvm_unreachable("Unknown cast type!");
8405       case Instruction::Trunc:
8406         // Just replace this cast with the result.
8407         return ReplaceInstUsesWith(CI, Res);
8408       case Instruction::ZExt: {
8409         assert(SrcBitSize < DestBitSize && "Not a zext?");
8410
8411         // If the high bits are already zero, just replace this cast with the
8412         // result.
8413         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8414         if (MaskedValueIsZero(Res, Mask))
8415           return ReplaceInstUsesWith(CI, Res);
8416
8417         // We need to emit an AND to clear the high bits.
8418         Constant *C = ConstantInt::get(*Context, 
8419                                  APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8420         return BinaryOperator::CreateAnd(Res, C);
8421       }
8422       case Instruction::SExt: {
8423         // If the high bits are already filled with sign bit, just replace this
8424         // cast with the result.
8425         unsigned NumSignBits = ComputeNumSignBits(Res);
8426         if (NumSignBits > (DestBitSize - SrcBitSize))
8427           return ReplaceInstUsesWith(CI, Res);
8428
8429         // We need to emit a cast to truncate, then a cast to sext.
8430         return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
8431       }
8432       }
8433     }
8434   }
8435   
8436   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8437   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8438
8439   switch (SrcI->getOpcode()) {
8440   case Instruction::Add:
8441   case Instruction::Mul:
8442   case Instruction::And:
8443   case Instruction::Or:
8444   case Instruction::Xor:
8445     // If we are discarding information, rewrite.
8446     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8447       // Don't insert two casts unless at least one can be eliminated.
8448       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8449           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8450         Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8451         Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8452         return BinaryOperator::Create(
8453             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8454       }
8455     }
8456
8457     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8458     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8459         SrcI->getOpcode() == Instruction::Xor &&
8460         Op1 == ConstantInt::getTrue(*Context) &&
8461         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8462       Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
8463       return BinaryOperator::CreateXor(New,
8464                                       ConstantInt::get(CI.getType(), 1));
8465     }
8466     break;
8467
8468   case Instruction::Shl: {
8469     // Canonicalize trunc inside shl, if we can.
8470     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8471     if (CI && DestBitSize < SrcBitSize &&
8472         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8473       Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8474       Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8475       return BinaryOperator::CreateShl(Op0c, Op1c);
8476     }
8477     break;
8478   }
8479   }
8480   return 0;
8481 }
8482
8483 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8484   if (Instruction *Result = commonIntCastTransforms(CI))
8485     return Result;
8486   
8487   Value *Src = CI.getOperand(0);
8488   const Type *Ty = CI.getType();
8489   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8490   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8491
8492   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8493   if (DestBitWidth == 1) {
8494     Constant *One = ConstantInt::get(Src->getType(), 1);
8495     Src = Builder->CreateAnd(Src, One, "tmp");
8496     Value *Zero = Constant::getNullValue(Src->getType());
8497     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8498   }
8499
8500   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8501   ConstantInt *ShAmtV = 0;
8502   Value *ShiftOp = 0;
8503   if (Src->hasOneUse() &&
8504       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8505     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8506     
8507     // Get a mask for the bits shifting in.
8508     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8509     if (MaskedValueIsZero(ShiftOp, Mask)) {
8510       if (ShAmt >= DestBitWidth)        // All zeros.
8511         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8512       
8513       // Okay, we can shrink this.  Truncate the input, then return a new
8514       // shift.
8515       Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
8516       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8517       return BinaryOperator::CreateLShr(V1, V2);
8518     }
8519   }
8520  
8521   return 0;
8522 }
8523
8524 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8525 /// in order to eliminate the icmp.
8526 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8527                                              bool DoXform) {
8528   // If we are just checking for a icmp eq of a single bit and zext'ing it
8529   // to an integer, then shift the bit to the appropriate place and then
8530   // cast to integer to avoid the comparison.
8531   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8532     const APInt &Op1CV = Op1C->getValue();
8533       
8534     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8535     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8536     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8537         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8538       if (!DoXform) return ICI;
8539
8540       Value *In = ICI->getOperand(0);
8541       Value *Sh = ConstantInt::get(In->getType(),
8542                                    In->getType()->getScalarSizeInBits()-1);
8543       In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
8544       if (In->getType() != CI.getType())
8545         In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
8546
8547       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8548         Constant *One = ConstantInt::get(In->getType(), 1);
8549         In = Builder->CreateXor(In, One, In->getName()+".not");
8550       }
8551
8552       return ReplaceInstUsesWith(CI, In);
8553     }
8554       
8555       
8556       
8557     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8558     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8559     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8560     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8561     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8562     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8563     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8564     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8565     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8566         // This only works for EQ and NE
8567         ICI->isEquality()) {
8568       // If Op1C some other power of two, convert:
8569       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8570       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8571       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8572       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8573         
8574       APInt KnownZeroMask(~KnownZero);
8575       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8576         if (!DoXform) return ICI;
8577
8578         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8579         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8580           // (X&4) == 2 --> false
8581           // (X&4) != 2 --> true
8582           Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8583           Res = ConstantExpr::getZExt(Res, CI.getType());
8584           return ReplaceInstUsesWith(CI, Res);
8585         }
8586           
8587         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8588         Value *In = ICI->getOperand(0);
8589         if (ShiftAmt) {
8590           // Perform a logical shr by shiftamt.
8591           // Insert the shift to put the result in the low bit.
8592           In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8593                                    In->getName()+".lobit");
8594         }
8595           
8596         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8597           Constant *One = ConstantInt::get(In->getType(), 1);
8598           In = Builder->CreateXor(In, One, "tmp");
8599         }
8600           
8601         if (CI.getType() == In->getType())
8602           return ReplaceInstUsesWith(CI, In);
8603         else
8604           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8605       }
8606     }
8607   }
8608
8609   return 0;
8610 }
8611
8612 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8613   // If one of the common conversion will work ..
8614   if (Instruction *Result = commonIntCastTransforms(CI))
8615     return Result;
8616
8617   Value *Src = CI.getOperand(0);
8618
8619   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8620   // types and if the sizes are just right we can convert this into a logical
8621   // 'and' which will be much cheaper than the pair of casts.
8622   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8623     // Get the sizes of the types involved.  We know that the intermediate type
8624     // will be smaller than A or C, but don't know the relation between A and C.
8625     Value *A = CSrc->getOperand(0);
8626     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8627     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8628     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8629     // If we're actually extending zero bits, then if
8630     // SrcSize <  DstSize: zext(a & mask)
8631     // SrcSize == DstSize: a & mask
8632     // SrcSize  > DstSize: trunc(a) & mask
8633     if (SrcSize < DstSize) {
8634       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8635       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8636       Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
8637       return new ZExtInst(And, CI.getType());
8638     }
8639     
8640     if (SrcSize == DstSize) {
8641       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8642       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8643                                                            AndValue));
8644     }
8645     if (SrcSize > DstSize) {
8646       Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
8647       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8648       return BinaryOperator::CreateAnd(Trunc, 
8649                                        ConstantInt::get(Trunc->getType(),
8650                                                                AndValue));
8651     }
8652   }
8653
8654   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8655     return transformZExtICmp(ICI, CI);
8656
8657   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8658   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8659     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8660     // of the (zext icmp) will be transformed.
8661     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8662     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8663     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8664         (transformZExtICmp(LHS, CI, false) ||
8665          transformZExtICmp(RHS, CI, false))) {
8666       Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8667       Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
8668       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8669     }
8670   }
8671
8672   // zext(trunc(t) & C) -> (t & zext(C)).
8673   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8674     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8675       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8676         Value *TI0 = TI->getOperand(0);
8677         if (TI0->getType() == CI.getType())
8678           return
8679             BinaryOperator::CreateAnd(TI0,
8680                                 ConstantExpr::getZExt(C, CI.getType()));
8681       }
8682
8683   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8684   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8685     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8686       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8687         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8688             And->getOperand(1) == C)
8689           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8690             Value *TI0 = TI->getOperand(0);
8691             if (TI0->getType() == CI.getType()) {
8692               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8693               Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
8694               return BinaryOperator::CreateXor(NewAnd, ZC);
8695             }
8696           }
8697
8698   return 0;
8699 }
8700
8701 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8702   if (Instruction *I = commonIntCastTransforms(CI))
8703     return I;
8704   
8705   Value *Src = CI.getOperand(0);
8706   
8707   // Canonicalize sign-extend from i1 to a select.
8708   if (Src->getType() == Type::getInt1Ty(*Context))
8709     return SelectInst::Create(Src,
8710                               Constant::getAllOnesValue(CI.getType()),
8711                               Constant::getNullValue(CI.getType()));
8712
8713   // See if the value being truncated is already sign extended.  If so, just
8714   // eliminate the trunc/sext pair.
8715   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8716     Value *Op = cast<User>(Src)->getOperand(0);
8717     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8718     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8719     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8720     unsigned NumSignBits = ComputeNumSignBits(Op);
8721
8722     if (OpBits == DestBits) {
8723       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8724       // bits, it is already ready.
8725       if (NumSignBits > DestBits-MidBits)
8726         return ReplaceInstUsesWith(CI, Op);
8727     } else if (OpBits < DestBits) {
8728       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8729       // bits, just sext from i32.
8730       if (NumSignBits > OpBits-MidBits)
8731         return new SExtInst(Op, CI.getType(), "tmp");
8732     } else {
8733       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8734       // bits, just truncate to i32.
8735       if (NumSignBits > OpBits-MidBits)
8736         return new TruncInst(Op, CI.getType(), "tmp");
8737     }
8738   }
8739
8740   // If the input is a shl/ashr pair of a same constant, then this is a sign
8741   // extension from a smaller value.  If we could trust arbitrary bitwidth
8742   // integers, we could turn this into a truncate to the smaller bit and then
8743   // use a sext for the whole extension.  Since we don't, look deeper and check
8744   // for a truncate.  If the source and dest are the same type, eliminate the
8745   // trunc and extend and just do shifts.  For example, turn:
8746   //   %a = trunc i32 %i to i8
8747   //   %b = shl i8 %a, 6
8748   //   %c = ashr i8 %b, 6
8749   //   %d = sext i8 %c to i32
8750   // into:
8751   //   %a = shl i32 %i, 30
8752   //   %d = ashr i32 %a, 30
8753   Value *A = 0;
8754   ConstantInt *BA = 0, *CA = 0;
8755   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8756                         m_ConstantInt(CA))) &&
8757       BA == CA && isa<TruncInst>(A)) {
8758     Value *I = cast<TruncInst>(A)->getOperand(0);
8759     if (I->getType() == CI.getType()) {
8760       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8761       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8762       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8763       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8764       I = Builder->CreateShl(I, ShAmtV, CI.getName());
8765       return BinaryOperator::CreateAShr(I, ShAmtV);
8766     }
8767   }
8768   
8769   return 0;
8770 }
8771
8772 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8773 /// in the specified FP type without changing its value.
8774 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8775                               LLVMContext *Context) {
8776   bool losesInfo;
8777   APFloat F = CFP->getValueAPF();
8778   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8779   if (!losesInfo)
8780     return ConstantFP::get(*Context, F);
8781   return 0;
8782 }
8783
8784 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8785 /// through it until we get the source value.
8786 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8787   if (Instruction *I = dyn_cast<Instruction>(V))
8788     if (I->getOpcode() == Instruction::FPExt)
8789       return LookThroughFPExtensions(I->getOperand(0), Context);
8790   
8791   // If this value is a constant, return the constant in the smallest FP type
8792   // that can accurately represent it.  This allows us to turn
8793   // (float)((double)X+2.0) into x+2.0f.
8794   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8795     if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
8796       return V;  // No constant folding of this.
8797     // See if the value can be truncated to float and then reextended.
8798     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8799       return V;
8800     if (CFP->getType() == Type::getDoubleTy(*Context))
8801       return V;  // Won't shrink.
8802     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8803       return V;
8804     // Don't try to shrink to various long double types.
8805   }
8806   
8807   return V;
8808 }
8809
8810 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8811   if (Instruction *I = commonCastTransforms(CI))
8812     return I;
8813   
8814   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8815   // smaller than the destination type, we can eliminate the truncate by doing
8816   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8817   // many builtins (sqrt, etc).
8818   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8819   if (OpI && OpI->hasOneUse()) {
8820     switch (OpI->getOpcode()) {
8821     default: break;
8822     case Instruction::FAdd:
8823     case Instruction::FSub:
8824     case Instruction::FMul:
8825     case Instruction::FDiv:
8826     case Instruction::FRem:
8827       const Type *SrcTy = OpI->getType();
8828       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8829       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8830       if (LHSTrunc->getType() != SrcTy && 
8831           RHSTrunc->getType() != SrcTy) {
8832         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8833         // If the source types were both smaller than the destination type of
8834         // the cast, do this xform.
8835         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8836             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8837           LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8838           RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
8839           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8840         }
8841       }
8842       break;  
8843     }
8844   }
8845   return 0;
8846 }
8847
8848 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8849   return commonCastTransforms(CI);
8850 }
8851
8852 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8853   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8854   if (OpI == 0)
8855     return commonCastTransforms(FI);
8856
8857   // fptoui(uitofp(X)) --> X
8858   // fptoui(sitofp(X)) --> X
8859   // This is safe if the intermediate type has enough bits in its mantissa to
8860   // accurately represent all values of X.  For example, do not do this with
8861   // i64->float->i64.  This is also safe for sitofp case, because any negative
8862   // 'X' value would cause an undefined result for the fptoui. 
8863   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8864       OpI->getOperand(0)->getType() == FI.getType() &&
8865       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8866                     OpI->getType()->getFPMantissaWidth())
8867     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8868
8869   return commonCastTransforms(FI);
8870 }
8871
8872 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8873   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8874   if (OpI == 0)
8875     return commonCastTransforms(FI);
8876   
8877   // fptosi(sitofp(X)) --> X
8878   // fptosi(uitofp(X)) --> X
8879   // This is safe if the intermediate type has enough bits in its mantissa to
8880   // accurately represent all values of X.  For example, do not do this with
8881   // i64->float->i64.  This is also safe for sitofp case, because any negative
8882   // 'X' value would cause an undefined result for the fptoui. 
8883   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8884       OpI->getOperand(0)->getType() == FI.getType() &&
8885       (int)FI.getType()->getScalarSizeInBits() <=
8886                     OpI->getType()->getFPMantissaWidth())
8887     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8888   
8889   return commonCastTransforms(FI);
8890 }
8891
8892 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8893   return commonCastTransforms(CI);
8894 }
8895
8896 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8897   return commonCastTransforms(CI);
8898 }
8899
8900 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8901   // If the destination integer type is smaller than the intptr_t type for
8902   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8903   // trunc to be exposed to other transforms.  Don't do this for extending
8904   // ptrtoint's, because we don't know if the target sign or zero extends its
8905   // pointers.
8906   if (TD &&
8907       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8908     Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8909                                        TD->getIntPtrType(CI.getContext()),
8910                                        "tmp");
8911     return new TruncInst(P, CI.getType());
8912   }
8913   
8914   return commonPointerCastTransforms(CI);
8915 }
8916
8917 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8918   // If the source integer type is larger than the intptr_t type for
8919   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8920   // allows the trunc to be exposed to other transforms.  Don't do this for
8921   // extending inttoptr's, because we don't know if the target sign or zero
8922   // extends to pointers.
8923   if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
8924       TD->getPointerSizeInBits()) {
8925     Value *P = Builder->CreateTrunc(CI.getOperand(0),
8926                                     TD->getIntPtrType(CI.getContext()), "tmp");
8927     return new IntToPtrInst(P, CI.getType());
8928   }
8929   
8930   if (Instruction *I = commonCastTransforms(CI))
8931     return I;
8932
8933   return 0;
8934 }
8935
8936 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8937   // If the operands are integer typed then apply the integer transforms,
8938   // otherwise just apply the common ones.
8939   Value *Src = CI.getOperand(0);
8940   const Type *SrcTy = Src->getType();
8941   const Type *DestTy = CI.getType();
8942
8943   if (isa<PointerType>(SrcTy)) {
8944     if (Instruction *I = commonPointerCastTransforms(CI))
8945       return I;
8946   } else {
8947     if (Instruction *Result = commonCastTransforms(CI))
8948       return Result;
8949   }
8950
8951
8952   // Get rid of casts from one type to the same type. These are useless and can
8953   // be replaced by the operand.
8954   if (DestTy == Src->getType())
8955     return ReplaceInstUsesWith(CI, Src);
8956
8957   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8958     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8959     const Type *DstElTy = DstPTy->getElementType();
8960     const Type *SrcElTy = SrcPTy->getElementType();
8961     
8962     // If the address spaces don't match, don't eliminate the bitcast, which is
8963     // required for changing types.
8964     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8965       return 0;
8966     
8967     // If we are casting a alloca to a pointer to a type of the same
8968     // size, rewrite the allocation instruction to allocate the "right" type.
8969     // There is no need to modify malloc calls because it is their bitcast that
8970     // needs to be cleaned up.
8971     if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
8972       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8973         return V;
8974     
8975     // If the source and destination are pointers, and this cast is equivalent
8976     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8977     // This can enhance SROA and other transforms that want type-safe pointers.
8978     Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
8979     unsigned NumZeros = 0;
8980     while (SrcElTy != DstElTy && 
8981            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8982            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8983       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8984       ++NumZeros;
8985     }
8986
8987     // If we found a path from the src to dest, create the getelementptr now.
8988     if (SrcElTy == DstElTy) {
8989       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8990       return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8991                                                ((Instruction*) NULL));
8992     }
8993   }
8994
8995   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8996     if (DestVTy->getNumElements() == 1) {
8997       if (!isa<VectorType>(SrcTy)) {
8998         Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
8999         return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
9000                             Constant::getNullValue(Type::getInt32Ty(*Context)));
9001       }
9002       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9003     }
9004   }
9005
9006   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9007     if (SrcVTy->getNumElements() == 1) {
9008       if (!isa<VectorType>(DestTy)) {
9009         Value *Elem = 
9010           Builder->CreateExtractElement(Src,
9011                             Constant::getNullValue(Type::getInt32Ty(*Context)));
9012         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9013       }
9014     }
9015   }
9016
9017   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9018     if (SVI->hasOneUse()) {
9019       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
9020       // a bitconvert to a vector with the same # elts.
9021       if (isa<VectorType>(DestTy) && 
9022           cast<VectorType>(DestTy)->getNumElements() ==
9023                 SVI->getType()->getNumElements() &&
9024           SVI->getType()->getNumElements() ==
9025             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9026         CastInst *Tmp;
9027         // If either of the operands is a cast from CI.getType(), then
9028         // evaluating the shuffle in the casted destination's type will allow
9029         // us to eliminate at least one cast.
9030         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
9031              Tmp->getOperand(0)->getType() == DestTy) ||
9032             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
9033              Tmp->getOperand(0)->getType() == DestTy)) {
9034           Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
9035           Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
9036           // Return a new shuffle vector.  Use the same element ID's, as we
9037           // know the vector types match #elts.
9038           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9039         }
9040       }
9041     }
9042   }
9043   return 0;
9044 }
9045
9046 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9047 ///   %C = or %A, %B
9048 ///   %D = select %cond, %C, %A
9049 /// into:
9050 ///   %C = select %cond, %B, 0
9051 ///   %D = or %A, %C
9052 ///
9053 /// Assuming that the specified instruction is an operand to the select, return
9054 /// a bitmask indicating which operands of this instruction are foldable if they
9055 /// equal the other incoming value of the select.
9056 ///
9057 static unsigned GetSelectFoldableOperands(Instruction *I) {
9058   switch (I->getOpcode()) {
9059   case Instruction::Add:
9060   case Instruction::Mul:
9061   case Instruction::And:
9062   case Instruction::Or:
9063   case Instruction::Xor:
9064     return 3;              // Can fold through either operand.
9065   case Instruction::Sub:   // Can only fold on the amount subtracted.
9066   case Instruction::Shl:   // Can only fold on the shift amount.
9067   case Instruction::LShr:
9068   case Instruction::AShr:
9069     return 1;
9070   default:
9071     return 0;              // Cannot fold
9072   }
9073 }
9074
9075 /// GetSelectFoldableConstant - For the same transformation as the previous
9076 /// function, return the identity constant that goes into the select.
9077 static Constant *GetSelectFoldableConstant(Instruction *I,
9078                                            LLVMContext *Context) {
9079   switch (I->getOpcode()) {
9080   default: llvm_unreachable("This cannot happen!");
9081   case Instruction::Add:
9082   case Instruction::Sub:
9083   case Instruction::Or:
9084   case Instruction::Xor:
9085   case Instruction::Shl:
9086   case Instruction::LShr:
9087   case Instruction::AShr:
9088     return Constant::getNullValue(I->getType());
9089   case Instruction::And:
9090     return Constant::getAllOnesValue(I->getType());
9091   case Instruction::Mul:
9092     return ConstantInt::get(I->getType(), 1);
9093   }
9094 }
9095
9096 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9097 /// have the same opcode and only one use each.  Try to simplify this.
9098 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9099                                           Instruction *FI) {
9100   if (TI->getNumOperands() == 1) {
9101     // If this is a non-volatile load or a cast from the same type,
9102     // merge.
9103     if (TI->isCast()) {
9104       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9105         return 0;
9106     } else {
9107       return 0;  // unknown unary op.
9108     }
9109
9110     // Fold this by inserting a select from the input values.
9111     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9112                                           FI->getOperand(0), SI.getName()+".v");
9113     InsertNewInstBefore(NewSI, SI);
9114     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9115                             TI->getType());
9116   }
9117
9118   // Only handle binary operators here.
9119   if (!isa<BinaryOperator>(TI))
9120     return 0;
9121
9122   // Figure out if the operations have any operands in common.
9123   Value *MatchOp, *OtherOpT, *OtherOpF;
9124   bool MatchIsOpZero;
9125   if (TI->getOperand(0) == FI->getOperand(0)) {
9126     MatchOp  = TI->getOperand(0);
9127     OtherOpT = TI->getOperand(1);
9128     OtherOpF = FI->getOperand(1);
9129     MatchIsOpZero = true;
9130   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9131     MatchOp  = TI->getOperand(1);
9132     OtherOpT = TI->getOperand(0);
9133     OtherOpF = FI->getOperand(0);
9134     MatchIsOpZero = false;
9135   } else if (!TI->isCommutative()) {
9136     return 0;
9137   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9138     MatchOp  = TI->getOperand(0);
9139     OtherOpT = TI->getOperand(1);
9140     OtherOpF = FI->getOperand(0);
9141     MatchIsOpZero = true;
9142   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9143     MatchOp  = TI->getOperand(1);
9144     OtherOpT = TI->getOperand(0);
9145     OtherOpF = FI->getOperand(1);
9146     MatchIsOpZero = true;
9147   } else {
9148     return 0;
9149   }
9150
9151   // If we reach here, they do have operations in common.
9152   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9153                                          OtherOpF, SI.getName()+".v");
9154   InsertNewInstBefore(NewSI, SI);
9155
9156   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9157     if (MatchIsOpZero)
9158       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9159     else
9160       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9161   }
9162   llvm_unreachable("Shouldn't get here");
9163   return 0;
9164 }
9165
9166 static bool isSelect01(Constant *C1, Constant *C2) {
9167   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9168   if (!C1I)
9169     return false;
9170   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9171   if (!C2I)
9172     return false;
9173   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9174 }
9175
9176 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9177 /// facilitate further optimization.
9178 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9179                                             Value *FalseVal) {
9180   // See the comment above GetSelectFoldableOperands for a description of the
9181   // transformation we are doing here.
9182   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9183     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9184         !isa<Constant>(FalseVal)) {
9185       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9186         unsigned OpToFold = 0;
9187         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9188           OpToFold = 1;
9189         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9190           OpToFold = 2;
9191         }
9192
9193         if (OpToFold) {
9194           Constant *C = GetSelectFoldableConstant(TVI, Context);
9195           Value *OOp = TVI->getOperand(2-OpToFold);
9196           // Avoid creating select between 2 constants unless it's selecting
9197           // between 0 and 1.
9198           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9199             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9200             InsertNewInstBefore(NewSel, SI);
9201             NewSel->takeName(TVI);
9202             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9203               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9204             llvm_unreachable("Unknown instruction!!");
9205           }
9206         }
9207       }
9208     }
9209   }
9210
9211   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9212     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9213         !isa<Constant>(TrueVal)) {
9214       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9215         unsigned OpToFold = 0;
9216         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9217           OpToFold = 1;
9218         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9219           OpToFold = 2;
9220         }
9221
9222         if (OpToFold) {
9223           Constant *C = GetSelectFoldableConstant(FVI, Context);
9224           Value *OOp = FVI->getOperand(2-OpToFold);
9225           // Avoid creating select between 2 constants unless it's selecting
9226           // between 0 and 1.
9227           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9228             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9229             InsertNewInstBefore(NewSel, SI);
9230             NewSel->takeName(FVI);
9231             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9232               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9233             llvm_unreachable("Unknown instruction!!");
9234           }
9235         }
9236       }
9237     }
9238   }
9239
9240   return 0;
9241 }
9242
9243 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9244 /// ICmpInst as its first operand.
9245 ///
9246 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9247                                                    ICmpInst *ICI) {
9248   bool Changed = false;
9249   ICmpInst::Predicate Pred = ICI->getPredicate();
9250   Value *CmpLHS = ICI->getOperand(0);
9251   Value *CmpRHS = ICI->getOperand(1);
9252   Value *TrueVal = SI.getTrueValue();
9253   Value *FalseVal = SI.getFalseValue();
9254
9255   // Check cases where the comparison is with a constant that
9256   // can be adjusted to fit the min/max idiom. We may edit ICI in
9257   // place here, so make sure the select is the only user.
9258   if (ICI->hasOneUse())
9259     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9260       switch (Pred) {
9261       default: break;
9262       case ICmpInst::ICMP_ULT:
9263       case ICmpInst::ICMP_SLT: {
9264         // X < MIN ? T : F  -->  F
9265         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9266           return ReplaceInstUsesWith(SI, FalseVal);
9267         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9268         Constant *AdjustedRHS = SubOne(CI);
9269         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9270             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9271           Pred = ICmpInst::getSwappedPredicate(Pred);
9272           CmpRHS = AdjustedRHS;
9273           std::swap(FalseVal, TrueVal);
9274           ICI->setPredicate(Pred);
9275           ICI->setOperand(1, CmpRHS);
9276           SI.setOperand(1, TrueVal);
9277           SI.setOperand(2, FalseVal);
9278           Changed = true;
9279         }
9280         break;
9281       }
9282       case ICmpInst::ICMP_UGT:
9283       case ICmpInst::ICMP_SGT: {
9284         // X > MAX ? T : F  -->  F
9285         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9286           return ReplaceInstUsesWith(SI, FalseVal);
9287         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9288         Constant *AdjustedRHS = AddOne(CI);
9289         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9290             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9291           Pred = ICmpInst::getSwappedPredicate(Pred);
9292           CmpRHS = AdjustedRHS;
9293           std::swap(FalseVal, TrueVal);
9294           ICI->setPredicate(Pred);
9295           ICI->setOperand(1, CmpRHS);
9296           SI.setOperand(1, TrueVal);
9297           SI.setOperand(2, FalseVal);
9298           Changed = true;
9299         }
9300         break;
9301       }
9302       }
9303
9304       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9305       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9306       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9307       if (match(TrueVal, m_ConstantInt<-1>()) &&
9308           match(FalseVal, m_ConstantInt<0>()))
9309         Pred = ICI->getPredicate();
9310       else if (match(TrueVal, m_ConstantInt<0>()) &&
9311                match(FalseVal, m_ConstantInt<-1>()))
9312         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9313       
9314       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9315         // If we are just checking for a icmp eq of a single bit and zext'ing it
9316         // to an integer, then shift the bit to the appropriate place and then
9317         // cast to integer to avoid the comparison.
9318         const APInt &Op1CV = CI->getValue();
9319     
9320         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9321         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9322         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9323             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9324           Value *In = ICI->getOperand(0);
9325           Value *Sh = ConstantInt::get(In->getType(),
9326                                        In->getType()->getScalarSizeInBits()-1);
9327           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9328                                                         In->getName()+".lobit"),
9329                                    *ICI);
9330           if (In->getType() != SI.getType())
9331             In = CastInst::CreateIntegerCast(In, SI.getType(),
9332                                              true/*SExt*/, "tmp", ICI);
9333     
9334           if (Pred == ICmpInst::ICMP_SGT)
9335             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9336                                        In->getName()+".not"), *ICI);
9337     
9338           return ReplaceInstUsesWith(SI, In);
9339         }
9340       }
9341     }
9342
9343   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9344     // Transform (X == Y) ? X : Y  -> Y
9345     if (Pred == ICmpInst::ICMP_EQ)
9346       return ReplaceInstUsesWith(SI, FalseVal);
9347     // Transform (X != Y) ? X : Y  -> X
9348     if (Pred == ICmpInst::ICMP_NE)
9349       return ReplaceInstUsesWith(SI, TrueVal);
9350     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9351
9352   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9353     // Transform (X == Y) ? Y : X  -> X
9354     if (Pred == ICmpInst::ICMP_EQ)
9355       return ReplaceInstUsesWith(SI, FalseVal);
9356     // Transform (X != Y) ? Y : X  -> Y
9357     if (Pred == ICmpInst::ICMP_NE)
9358       return ReplaceInstUsesWith(SI, TrueVal);
9359     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9360   }
9361
9362   /// NOTE: if we wanted to, this is where to detect integer ABS
9363
9364   return Changed ? &SI : 0;
9365 }
9366
9367
9368 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9369 /// PHI node (but the two may be in different blocks).  See if the true/false
9370 /// values (V) are live in all of the predecessor blocks of the PHI.  For
9371 /// example, cases like this cannot be mapped:
9372 ///
9373 ///   X = phi [ C1, BB1], [C2, BB2]
9374 ///   Y = add
9375 ///   Z = select X, Y, 0
9376 ///
9377 /// because Y is not live in BB1/BB2.
9378 ///
9379 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9380                                                    const SelectInst &SI) {
9381   // If the value is a non-instruction value like a constant or argument, it
9382   // can always be mapped.
9383   const Instruction *I = dyn_cast<Instruction>(V);
9384   if (I == 0) return true;
9385   
9386   // If V is a PHI node defined in the same block as the condition PHI, we can
9387   // map the arguments.
9388   const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9389   
9390   if (const PHINode *VP = dyn_cast<PHINode>(I))
9391     if (VP->getParent() == CondPHI->getParent())
9392       return true;
9393   
9394   // Otherwise, if the PHI and select are defined in the same block and if V is
9395   // defined in a different block, then we can transform it.
9396   if (SI.getParent() == CondPHI->getParent() &&
9397       I->getParent() != CondPHI->getParent())
9398     return true;
9399   
9400   // Otherwise we have a 'hard' case and we can't tell without doing more
9401   // detailed dominator based analysis, punt.
9402   return false;
9403 }
9404
9405 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9406   Value *CondVal = SI.getCondition();
9407   Value *TrueVal = SI.getTrueValue();
9408   Value *FalseVal = SI.getFalseValue();
9409
9410   // select true, X, Y  -> X
9411   // select false, X, Y -> Y
9412   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9413     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9414
9415   // select C, X, X -> X
9416   if (TrueVal == FalseVal)
9417     return ReplaceInstUsesWith(SI, TrueVal);
9418
9419   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9420     return ReplaceInstUsesWith(SI, FalseVal);
9421   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9422     return ReplaceInstUsesWith(SI, TrueVal);
9423   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9424     if (isa<Constant>(TrueVal))
9425       return ReplaceInstUsesWith(SI, TrueVal);
9426     else
9427       return ReplaceInstUsesWith(SI, FalseVal);
9428   }
9429
9430   if (SI.getType() == Type::getInt1Ty(*Context)) {
9431     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9432       if (C->getZExtValue()) {
9433         // Change: A = select B, true, C --> A = or B, C
9434         return BinaryOperator::CreateOr(CondVal, FalseVal);
9435       } else {
9436         // Change: A = select B, false, C --> A = and !B, C
9437         Value *NotCond =
9438           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9439                                              "not."+CondVal->getName()), SI);
9440         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9441       }
9442     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9443       if (C->getZExtValue() == false) {
9444         // Change: A = select B, C, false --> A = and B, C
9445         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9446       } else {
9447         // Change: A = select B, C, true --> A = or !B, C
9448         Value *NotCond =
9449           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9450                                              "not."+CondVal->getName()), SI);
9451         return BinaryOperator::CreateOr(NotCond, TrueVal);
9452       }
9453     }
9454     
9455     // select a, b, a  -> a&b
9456     // select a, a, b  -> a|b
9457     if (CondVal == TrueVal)
9458       return BinaryOperator::CreateOr(CondVal, FalseVal);
9459     else if (CondVal == FalseVal)
9460       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9461   }
9462
9463   // Selecting between two integer constants?
9464   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9465     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9466       // select C, 1, 0 -> zext C to int
9467       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9468         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9469       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9470         // select C, 0, 1 -> zext !C to int
9471         Value *NotCond =
9472           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9473                                                "not."+CondVal->getName()), SI);
9474         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9475       }
9476
9477       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9478         // If one of the constants is zero (we know they can't both be) and we
9479         // have an icmp instruction with zero, and we have an 'and' with the
9480         // non-constant value, eliminate this whole mess.  This corresponds to
9481         // cases like this: ((X & 27) ? 27 : 0)
9482         if (TrueValC->isZero() || FalseValC->isZero())
9483           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9484               cast<Constant>(IC->getOperand(1))->isNullValue())
9485             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9486               if (ICA->getOpcode() == Instruction::And &&
9487                   isa<ConstantInt>(ICA->getOperand(1)) &&
9488                   (ICA->getOperand(1) == TrueValC ||
9489                    ICA->getOperand(1) == FalseValC) &&
9490                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9491                 // Okay, now we know that everything is set up, we just don't
9492                 // know whether we have a icmp_ne or icmp_eq and whether the 
9493                 // true or false val is the zero.
9494                 bool ShouldNotVal = !TrueValC->isZero();
9495                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9496                 Value *V = ICA;
9497                 if (ShouldNotVal)
9498                   V = InsertNewInstBefore(BinaryOperator::Create(
9499                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9500                 return ReplaceInstUsesWith(SI, V);
9501               }
9502       }
9503     }
9504
9505   // See if we are selecting two values based on a comparison of the two values.
9506   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9507     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9508       // Transform (X == Y) ? X : Y  -> Y
9509       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9510         // This is not safe in general for floating point:  
9511         // consider X== -0, Y== +0.
9512         // It becomes safe if either operand is a nonzero constant.
9513         ConstantFP *CFPt, *CFPf;
9514         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9515               !CFPt->getValueAPF().isZero()) ||
9516             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9517              !CFPf->getValueAPF().isZero()))
9518         return ReplaceInstUsesWith(SI, FalseVal);
9519       }
9520       // Transform (X != Y) ? X : Y  -> X
9521       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9522         return ReplaceInstUsesWith(SI, TrueVal);
9523       // NOTE: if we wanted to, this is where to detect MIN/MAX
9524
9525     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9526       // Transform (X == Y) ? Y : X  -> X
9527       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9528         // This is not safe in general for floating point:  
9529         // consider X== -0, Y== +0.
9530         // It becomes safe if either operand is a nonzero constant.
9531         ConstantFP *CFPt, *CFPf;
9532         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9533               !CFPt->getValueAPF().isZero()) ||
9534             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9535              !CFPf->getValueAPF().isZero()))
9536           return ReplaceInstUsesWith(SI, FalseVal);
9537       }
9538       // Transform (X != Y) ? Y : X  -> Y
9539       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9540         return ReplaceInstUsesWith(SI, TrueVal);
9541       // NOTE: if we wanted to, this is where to detect MIN/MAX
9542     }
9543     // NOTE: if we wanted to, this is where to detect ABS
9544   }
9545
9546   // See if we are selecting two values based on a comparison of the two values.
9547   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9548     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9549       return Result;
9550
9551   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9552     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9553       if (TI->hasOneUse() && FI->hasOneUse()) {
9554         Instruction *AddOp = 0, *SubOp = 0;
9555
9556         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9557         if (TI->getOpcode() == FI->getOpcode())
9558           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9559             return IV;
9560
9561         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9562         // even legal for FP.
9563         if ((TI->getOpcode() == Instruction::Sub &&
9564              FI->getOpcode() == Instruction::Add) ||
9565             (TI->getOpcode() == Instruction::FSub &&
9566              FI->getOpcode() == Instruction::FAdd)) {
9567           AddOp = FI; SubOp = TI;
9568         } else if ((FI->getOpcode() == Instruction::Sub &&
9569                     TI->getOpcode() == Instruction::Add) ||
9570                    (FI->getOpcode() == Instruction::FSub &&
9571                     TI->getOpcode() == Instruction::FAdd)) {
9572           AddOp = TI; SubOp = FI;
9573         }
9574
9575         if (AddOp) {
9576           Value *OtherAddOp = 0;
9577           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9578             OtherAddOp = AddOp->getOperand(1);
9579           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9580             OtherAddOp = AddOp->getOperand(0);
9581           }
9582
9583           if (OtherAddOp) {
9584             // So at this point we know we have (Y -> OtherAddOp):
9585             //        select C, (add X, Y), (sub X, Z)
9586             Value *NegVal;  // Compute -Z
9587             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9588               NegVal = ConstantExpr::getNeg(C);
9589             } else {
9590               NegVal = InsertNewInstBefore(
9591                     BinaryOperator::CreateNeg(SubOp->getOperand(1),
9592                                               "tmp"), SI);
9593             }
9594
9595             Value *NewTrueOp = OtherAddOp;
9596             Value *NewFalseOp = NegVal;
9597             if (AddOp != TI)
9598               std::swap(NewTrueOp, NewFalseOp);
9599             Instruction *NewSel =
9600               SelectInst::Create(CondVal, NewTrueOp,
9601                                  NewFalseOp, SI.getName() + ".p");
9602
9603             NewSel = InsertNewInstBefore(NewSel, SI);
9604             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9605           }
9606         }
9607       }
9608
9609   // See if we can fold the select into one of our operands.
9610   if (SI.getType()->isInteger()) {
9611     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9612     if (FoldI)
9613       return FoldI;
9614   }
9615
9616   // See if we can fold the select into a phi node if the condition is a select.
9617   if (isa<PHINode>(SI.getCondition())) 
9618     // The true/false values have to be live in the PHI predecessor's blocks.
9619     if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
9620         CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
9621       if (Instruction *NV = FoldOpIntoPhi(SI))
9622         return NV;
9623
9624   if (BinaryOperator::isNot(CondVal)) {
9625     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9626     SI.setOperand(1, FalseVal);
9627     SI.setOperand(2, TrueVal);
9628     return &SI;
9629   }
9630
9631   return 0;
9632 }
9633
9634 /// EnforceKnownAlignment - If the specified pointer points to an object that
9635 /// we control, modify the object's alignment to PrefAlign. This isn't
9636 /// often possible though. If alignment is important, a more reliable approach
9637 /// is to simply align all global variables and allocation instructions to
9638 /// their preferred alignment from the beginning.
9639 ///
9640 static unsigned EnforceKnownAlignment(Value *V,
9641                                       unsigned Align, unsigned PrefAlign) {
9642
9643   User *U = dyn_cast<User>(V);
9644   if (!U) return Align;
9645
9646   switch (Operator::getOpcode(U)) {
9647   default: break;
9648   case Instruction::BitCast:
9649     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9650   case Instruction::GetElementPtr: {
9651     // If all indexes are zero, it is just the alignment of the base pointer.
9652     bool AllZeroOperands = true;
9653     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9654       if (!isa<Constant>(*i) ||
9655           !cast<Constant>(*i)->isNullValue()) {
9656         AllZeroOperands = false;
9657         break;
9658       }
9659
9660     if (AllZeroOperands) {
9661       // Treat this like a bitcast.
9662       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9663     }
9664     break;
9665   }
9666   }
9667
9668   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9669     // If there is a large requested alignment and we can, bump up the alignment
9670     // of the global.
9671     if (!GV->isDeclaration()) {
9672       if (GV->getAlignment() >= PrefAlign)
9673         Align = GV->getAlignment();
9674       else {
9675         GV->setAlignment(PrefAlign);
9676         Align = PrefAlign;
9677       }
9678     }
9679   } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9680     // If there is a requested alignment and if this is an alloca, round up.
9681     if (AI->getAlignment() >= PrefAlign)
9682       Align = AI->getAlignment();
9683     else {
9684       AI->setAlignment(PrefAlign);
9685       Align = PrefAlign;
9686     }
9687   }
9688
9689   return Align;
9690 }
9691
9692 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9693 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9694 /// and it is more than the alignment of the ultimate object, see if we can
9695 /// increase the alignment of the ultimate object, making this check succeed.
9696 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9697                                                   unsigned PrefAlign) {
9698   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9699                       sizeof(PrefAlign) * CHAR_BIT;
9700   APInt Mask = APInt::getAllOnesValue(BitWidth);
9701   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9702   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9703   unsigned TrailZ = KnownZero.countTrailingOnes();
9704   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9705
9706   if (PrefAlign > Align)
9707     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9708   
9709     // We don't need to make any adjustment.
9710   return Align;
9711 }
9712
9713 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9714   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9715   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9716   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9717   unsigned CopyAlign = MI->getAlignment();
9718
9719   if (CopyAlign < MinAlign) {
9720     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 
9721                                              MinAlign, false));
9722     return MI;
9723   }
9724   
9725   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9726   // load/store.
9727   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9728   if (MemOpLength == 0) return 0;
9729   
9730   // Source and destination pointer types are always "i8*" for intrinsic.  See
9731   // if the size is something we can handle with a single primitive load/store.
9732   // A single load+store correctly handles overlapping memory in the memmove
9733   // case.
9734   unsigned Size = MemOpLength->getZExtValue();
9735   if (Size == 0) return MI;  // Delete this mem transfer.
9736   
9737   if (Size > 8 || (Size&(Size-1)))
9738     return 0;  // If not 1/2/4/8 bytes, exit.
9739   
9740   // Use an integer load+store unless we can find something better.
9741   Type *NewPtrTy =
9742                 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
9743   
9744   // Memcpy forces the use of i8* for the source and destination.  That means
9745   // that if you're using memcpy to move one double around, you'll get a cast
9746   // from double* to i8*.  We'd much rather use a double load+store rather than
9747   // an i64 load+store, here because this improves the odds that the source or
9748   // dest address will be promotable.  See if we can find a better type than the
9749   // integer datatype.
9750   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9751     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9752     if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9753       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9754       // down through these levels if so.
9755       while (!SrcETy->isSingleValueType()) {
9756         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9757           if (STy->getNumElements() == 1)
9758             SrcETy = STy->getElementType(0);
9759           else
9760             break;
9761         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9762           if (ATy->getNumElements() == 1)
9763             SrcETy = ATy->getElementType();
9764           else
9765             break;
9766         } else
9767           break;
9768       }
9769       
9770       if (SrcETy->isSingleValueType())
9771         NewPtrTy = PointerType::getUnqual(SrcETy);
9772     }
9773   }
9774   
9775   
9776   // If the memcpy/memmove provides better alignment info than we can
9777   // infer, use it.
9778   SrcAlign = std::max(SrcAlign, CopyAlign);
9779   DstAlign = std::max(DstAlign, CopyAlign);
9780   
9781   Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9782   Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
9783   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9784   InsertNewInstBefore(L, *MI);
9785   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9786
9787   // Set the size of the copy to 0, it will be deleted on the next iteration.
9788   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9789   return MI;
9790 }
9791
9792 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9793   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9794   if (MI->getAlignment() < Alignment) {
9795     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9796                                              Alignment, false));
9797     return MI;
9798   }
9799   
9800   // Extract the length and alignment and fill if they are constant.
9801   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9802   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9803   if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
9804     return 0;
9805   uint64_t Len = LenC->getZExtValue();
9806   Alignment = MI->getAlignment();
9807   
9808   // If the length is zero, this is a no-op
9809   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9810   
9811   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9812   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9813     const Type *ITy = IntegerType::get(*Context, Len*8);  // n=1 -> i8.
9814     
9815     Value *Dest = MI->getDest();
9816     Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
9817
9818     // Alignment 0 is identity for alignment 1 for memset, but not store.
9819     if (Alignment == 0) Alignment = 1;
9820     
9821     // Extract the fill value and store.
9822     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9823     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9824                                       Dest, false, Alignment), *MI);
9825     
9826     // Set the size of the copy to 0, it will be deleted on the next iteration.
9827     MI->setLength(Constant::getNullValue(LenC->getType()));
9828     return MI;
9829   }
9830
9831   return 0;
9832 }
9833
9834
9835 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9836 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9837 /// the heavy lifting.
9838 ///
9839 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9840   if (isFreeCall(&CI))
9841     return visitFree(CI);
9842
9843   // If the caller function is nounwind, mark the call as nounwind, even if the
9844   // callee isn't.
9845   if (CI.getParent()->getParent()->doesNotThrow() &&
9846       !CI.doesNotThrow()) {
9847     CI.setDoesNotThrow();
9848     return &CI;
9849   }
9850   
9851   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9852   if (!II) return visitCallSite(&CI);
9853   
9854   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9855   // visitCallSite.
9856   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9857     bool Changed = false;
9858
9859     // memmove/cpy/set of zero bytes is a noop.
9860     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9861       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9862
9863       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9864         if (CI->getZExtValue() == 1) {
9865           // Replace the instruction with just byte operations.  We would
9866           // transform other cases to loads/stores, but we don't know if
9867           // alignment is sufficient.
9868         }
9869     }
9870
9871     // If we have a memmove and the source operation is a constant global,
9872     // then the source and dest pointers can't alias, so we can change this
9873     // into a call to memcpy.
9874     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9875       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9876         if (GVSrc->isConstant()) {
9877           Module *M = CI.getParent()->getParent()->getParent();
9878           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9879           const Type *Tys[1];
9880           Tys[0] = CI.getOperand(3)->getType();
9881           CI.setOperand(0, 
9882                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9883           Changed = true;
9884         }
9885
9886       // memmove(x,x,size) -> noop.
9887       if (MMI->getSource() == MMI->getDest())
9888         return EraseInstFromFunction(CI);
9889     }
9890
9891     // If we can determine a pointer alignment that is bigger than currently
9892     // set, update the alignment.
9893     if (isa<MemTransferInst>(MI)) {
9894       if (Instruction *I = SimplifyMemTransfer(MI))
9895         return I;
9896     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9897       if (Instruction *I = SimplifyMemSet(MSI))
9898         return I;
9899     }
9900           
9901     if (Changed) return II;
9902   }
9903   
9904   switch (II->getIntrinsicID()) {
9905   default: break;
9906   case Intrinsic::bswap:
9907     // bswap(bswap(x)) -> x
9908     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9909       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9910         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9911     break;
9912   case Intrinsic::ppc_altivec_lvx:
9913   case Intrinsic::ppc_altivec_lvxl:
9914   case Intrinsic::x86_sse_loadu_ps:
9915   case Intrinsic::x86_sse2_loadu_pd:
9916   case Intrinsic::x86_sse2_loadu_dq:
9917     // Turn PPC lvx     -> load if the pointer is known aligned.
9918     // Turn X86 loadups -> load if the pointer is known aligned.
9919     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9920       Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9921                                          PointerType::getUnqual(II->getType()));
9922       return new LoadInst(Ptr);
9923     }
9924     break;
9925   case Intrinsic::ppc_altivec_stvx:
9926   case Intrinsic::ppc_altivec_stvxl:
9927     // Turn stvx -> store if the pointer is known aligned.
9928     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9929       const Type *OpPtrTy = 
9930         PointerType::getUnqual(II->getOperand(1)->getType());
9931       Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
9932       return new StoreInst(II->getOperand(1), Ptr);
9933     }
9934     break;
9935   case Intrinsic::x86_sse_storeu_ps:
9936   case Intrinsic::x86_sse2_storeu_pd:
9937   case Intrinsic::x86_sse2_storeu_dq:
9938     // Turn X86 storeu -> store if the pointer is known aligned.
9939     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9940       const Type *OpPtrTy = 
9941         PointerType::getUnqual(II->getOperand(2)->getType());
9942       Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
9943       return new StoreInst(II->getOperand(2), Ptr);
9944     }
9945     break;
9946     
9947   case Intrinsic::x86_sse_cvttss2si: {
9948     // These intrinsics only demands the 0th element of its input vector.  If
9949     // we can simplify the input based on that, do so now.
9950     unsigned VWidth =
9951       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9952     APInt DemandedElts(VWidth, 1);
9953     APInt UndefElts(VWidth, 0);
9954     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9955                                               UndefElts)) {
9956       II->setOperand(1, V);
9957       return II;
9958     }
9959     break;
9960   }
9961     
9962   case Intrinsic::ppc_altivec_vperm:
9963     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9964     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9965       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9966       
9967       // Check that all of the elements are integer constants or undefs.
9968       bool AllEltsOk = true;
9969       for (unsigned i = 0; i != 16; ++i) {
9970         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9971             !isa<UndefValue>(Mask->getOperand(i))) {
9972           AllEltsOk = false;
9973           break;
9974         }
9975       }
9976       
9977       if (AllEltsOk) {
9978         // Cast the input vectors to byte vectors.
9979         Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9980         Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
9981         Value *Result = UndefValue::get(Op0->getType());
9982         
9983         // Only extract each element once.
9984         Value *ExtractedElts[32];
9985         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9986         
9987         for (unsigned i = 0; i != 16; ++i) {
9988           if (isa<UndefValue>(Mask->getOperand(i)))
9989             continue;
9990           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9991           Idx &= 31;  // Match the hardware behavior.
9992           
9993           if (ExtractedElts[Idx] == 0) {
9994             ExtractedElts[Idx] = 
9995               Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1, 
9996                   ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9997                                             "tmp");
9998           }
9999         
10000           // Insert this value into the result vector.
10001           Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
10002                          ConstantInt::get(Type::getInt32Ty(*Context), i, false),
10003                                                 "tmp");
10004         }
10005         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
10006       }
10007     }
10008     break;
10009
10010   case Intrinsic::stackrestore: {
10011     // If the save is right next to the restore, remove the restore.  This can
10012     // happen when variable allocas are DCE'd.
10013     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10014       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10015         BasicBlock::iterator BI = SS;
10016         if (&*++BI == II)
10017           return EraseInstFromFunction(CI);
10018       }
10019     }
10020     
10021     // Scan down this block to see if there is another stack restore in the
10022     // same block without an intervening call/alloca.
10023     BasicBlock::iterator BI = II;
10024     TerminatorInst *TI = II->getParent()->getTerminator();
10025     bool CannotRemove = false;
10026     for (++BI; &*BI != TI; ++BI) {
10027       if (isa<AllocaInst>(BI) || isMalloc(BI)) {
10028         CannotRemove = true;
10029         break;
10030       }
10031       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10032         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10033           // If there is a stackrestore below this one, remove this one.
10034           if (II->getIntrinsicID() == Intrinsic::stackrestore)
10035             return EraseInstFromFunction(CI);
10036           // Otherwise, ignore the intrinsic.
10037         } else {
10038           // If we found a non-intrinsic call, we can't remove the stack
10039           // restore.
10040           CannotRemove = true;
10041           break;
10042         }
10043       }
10044     }
10045     
10046     // If the stack restore is in a return/unwind block and if there are no
10047     // allocas or calls between the restore and the return, nuke the restore.
10048     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10049       return EraseInstFromFunction(CI);
10050     break;
10051   }
10052   }
10053
10054   return visitCallSite(II);
10055 }
10056
10057 // InvokeInst simplification
10058 //
10059 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10060   return visitCallSite(&II);
10061 }
10062
10063 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
10064 /// passed through the varargs area, we can eliminate the use of the cast.
10065 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10066                                          const CastInst * const CI,
10067                                          const TargetData * const TD,
10068                                          const int ix) {
10069   if (!CI->isLosslessCast())
10070     return false;
10071
10072   // The size of ByVal arguments is derived from the type, so we
10073   // can't change to a type with a different size.  If the size were
10074   // passed explicitly we could avoid this check.
10075   if (!CS.paramHasAttr(ix, Attribute::ByVal))
10076     return true;
10077
10078   const Type* SrcTy = 
10079             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10080   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10081   if (!SrcTy->isSized() || !DstTy->isSized())
10082     return false;
10083   if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10084     return false;
10085   return true;
10086 }
10087
10088 // visitCallSite - Improvements for call and invoke instructions.
10089 //
10090 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10091   bool Changed = false;
10092
10093   // If the callee is a constexpr cast of a function, attempt to move the cast
10094   // to the arguments of the call/invoke.
10095   if (transformConstExprCastCall(CS)) return 0;
10096
10097   Value *Callee = CS.getCalledValue();
10098
10099   if (Function *CalleeF = dyn_cast<Function>(Callee))
10100     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10101       Instruction *OldCall = CS.getInstruction();
10102       // If the call and callee calling conventions don't match, this call must
10103       // be unreachable, as the call is undefined.
10104       new StoreInst(ConstantInt::getTrue(*Context),
10105                 UndefValue::get(Type::getInt1PtrTy(*Context)), 
10106                                   OldCall);
10107       // If OldCall dues not return void then replaceAllUsesWith undef.
10108       // This allows ValueHandlers and custom metadata to adjust itself.
10109       if (!OldCall->getType()->isVoidTy())
10110         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
10111       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10112         return EraseInstFromFunction(*OldCall);
10113       return 0;
10114     }
10115
10116   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10117     // This instruction is not reachable, just remove it.  We insert a store to
10118     // undef so that we know that this code is not reachable, despite the fact
10119     // that we can't modify the CFG here.
10120     new StoreInst(ConstantInt::getTrue(*Context),
10121                UndefValue::get(Type::getInt1PtrTy(*Context)),
10122                   CS.getInstruction());
10123
10124     // If CS dues not return void then replaceAllUsesWith undef.
10125     // This allows ValueHandlers and custom metadata to adjust itself.
10126     if (!CS.getInstruction()->getType()->isVoidTy())
10127       CS.getInstruction()->
10128         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
10129
10130     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10131       // Don't break the CFG, insert a dummy cond branch.
10132       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10133                          ConstantInt::getTrue(*Context), II);
10134     }
10135     return EraseInstFromFunction(*CS.getInstruction());
10136   }
10137
10138   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10139     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10140       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10141         return transformCallThroughTrampoline(CS);
10142
10143   const PointerType *PTy = cast<PointerType>(Callee->getType());
10144   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10145   if (FTy->isVarArg()) {
10146     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10147     // See if we can optimize any arguments passed through the varargs area of
10148     // the call.
10149     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10150            E = CS.arg_end(); I != E; ++I, ++ix) {
10151       CastInst *CI = dyn_cast<CastInst>(*I);
10152       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10153         *I = CI->getOperand(0);
10154         Changed = true;
10155       }
10156     }
10157   }
10158
10159   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10160     // Inline asm calls cannot throw - mark them 'nounwind'.
10161     CS.setDoesNotThrow();
10162     Changed = true;
10163   }
10164
10165   return Changed ? CS.getInstruction() : 0;
10166 }
10167
10168 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10169 // attempt to move the cast to the arguments of the call/invoke.
10170 //
10171 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10172   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10173   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10174   if (CE->getOpcode() != Instruction::BitCast || 
10175       !isa<Function>(CE->getOperand(0)))
10176     return false;
10177   Function *Callee = cast<Function>(CE->getOperand(0));
10178   Instruction *Caller = CS.getInstruction();
10179   const AttrListPtr &CallerPAL = CS.getAttributes();
10180
10181   // Okay, this is a cast from a function to a different type.  Unless doing so
10182   // would cause a type conversion of one of our arguments, change this call to
10183   // be a direct call with arguments casted to the appropriate types.
10184   //
10185   const FunctionType *FT = Callee->getFunctionType();
10186   const Type *OldRetTy = Caller->getType();
10187   const Type *NewRetTy = FT->getReturnType();
10188
10189   if (isa<StructType>(NewRetTy))
10190     return false; // TODO: Handle multiple return values.
10191
10192   // Check to see if we are changing the return type...
10193   if (OldRetTy != NewRetTy) {
10194     if (Callee->isDeclaration() &&
10195         // Conversion is ok if changing from one pointer type to another or from
10196         // a pointer to an integer of the same size.
10197         !((isa<PointerType>(OldRetTy) || !TD ||
10198            OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
10199           (isa<PointerType>(NewRetTy) || !TD ||
10200            NewRetTy == TD->getIntPtrType(Caller->getContext()))))
10201       return false;   // Cannot transform this return value.
10202
10203     if (!Caller->use_empty() &&
10204         // void -> non-void is handled specially
10205         !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
10206       return false;   // Cannot transform this return value.
10207
10208     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10209       Attributes RAttrs = CallerPAL.getRetAttributes();
10210       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10211         return false;   // Attribute not compatible with transformed value.
10212     }
10213
10214     // If the callsite is an invoke instruction, and the return value is used by
10215     // a PHI node in a successor, we cannot change the return type of the call
10216     // because there is no place to put the cast instruction (without breaking
10217     // the critical edge).  Bail out in this case.
10218     if (!Caller->use_empty())
10219       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10220         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10221              UI != E; ++UI)
10222           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10223             if (PN->getParent() == II->getNormalDest() ||
10224                 PN->getParent() == II->getUnwindDest())
10225               return false;
10226   }
10227
10228   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10229   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10230
10231   CallSite::arg_iterator AI = CS.arg_begin();
10232   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10233     const Type *ParamTy = FT->getParamType(i);
10234     const Type *ActTy = (*AI)->getType();
10235
10236     if (!CastInst::isCastable(ActTy, ParamTy))
10237       return false;   // Cannot transform this parameter value.
10238
10239     if (CallerPAL.getParamAttributes(i + 1) 
10240         & Attribute::typeIncompatible(ParamTy))
10241       return false;   // Attribute not compatible with transformed value.
10242
10243     // Converting from one pointer type to another or between a pointer and an
10244     // integer of the same size is safe even if we do not have a body.
10245     bool isConvertible = ActTy == ParamTy ||
10246       (TD && ((isa<PointerType>(ParamTy) ||
10247       ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10248               (isa<PointerType>(ActTy) ||
10249               ActTy == TD->getIntPtrType(Caller->getContext()))));
10250     if (Callee->isDeclaration() && !isConvertible) return false;
10251   }
10252
10253   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10254       Callee->isDeclaration())
10255     return false;   // Do not delete arguments unless we have a function body.
10256
10257   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10258       !CallerPAL.isEmpty())
10259     // In this case we have more arguments than the new function type, but we
10260     // won't be dropping them.  Check that these extra arguments have attributes
10261     // that are compatible with being a vararg call argument.
10262     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10263       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10264         break;
10265       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10266       if (PAttrs & Attribute::VarArgsIncompatible)
10267         return false;
10268     }
10269
10270   // Okay, we decided that this is a safe thing to do: go ahead and start
10271   // inserting cast instructions as necessary...
10272   std::vector<Value*> Args;
10273   Args.reserve(NumActualArgs);
10274   SmallVector<AttributeWithIndex, 8> attrVec;
10275   attrVec.reserve(NumCommonArgs);
10276
10277   // Get any return attributes.
10278   Attributes RAttrs = CallerPAL.getRetAttributes();
10279
10280   // If the return value is not being used, the type may not be compatible
10281   // with the existing attributes.  Wipe out any problematic attributes.
10282   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10283
10284   // Add the new return attributes.
10285   if (RAttrs)
10286     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10287
10288   AI = CS.arg_begin();
10289   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10290     const Type *ParamTy = FT->getParamType(i);
10291     if ((*AI)->getType() == ParamTy) {
10292       Args.push_back(*AI);
10293     } else {
10294       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10295           false, ParamTy, false);
10296       Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
10297     }
10298
10299     // Add any parameter attributes.
10300     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10301       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10302   }
10303
10304   // If the function takes more arguments than the call was taking, add them
10305   // now.
10306   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10307     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10308
10309   // If we are removing arguments to the function, emit an obnoxious warning.
10310   if (FT->getNumParams() < NumActualArgs) {
10311     if (!FT->isVarArg()) {
10312       errs() << "WARNING: While resolving call to function '"
10313              << Callee->getName() << "' arguments were dropped!\n";
10314     } else {
10315       // Add all of the arguments in their promoted form to the arg list.
10316       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10317         const Type *PTy = getPromotedType((*AI)->getType());
10318         if (PTy != (*AI)->getType()) {
10319           // Must promote to pass through va_arg area!
10320           Instruction::CastOps opcode =
10321             CastInst::getCastOpcode(*AI, false, PTy, false);
10322           Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
10323         } else {
10324           Args.push_back(*AI);
10325         }
10326
10327         // Add any parameter attributes.
10328         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10329           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10330       }
10331     }
10332   }
10333
10334   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10335     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10336
10337   if (NewRetTy->isVoidTy())
10338     Caller->setName("");   // Void type should not have a name.
10339
10340   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10341                                                      attrVec.end());
10342
10343   Instruction *NC;
10344   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10345     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10346                             Args.begin(), Args.end(),
10347                             Caller->getName(), Caller);
10348     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10349     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10350   } else {
10351     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10352                           Caller->getName(), Caller);
10353     CallInst *CI = cast<CallInst>(Caller);
10354     if (CI->isTailCall())
10355       cast<CallInst>(NC)->setTailCall();
10356     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10357     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10358   }
10359
10360   // Insert a cast of the return type as necessary.
10361   Value *NV = NC;
10362   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10363     if (!NV->getType()->isVoidTy()) {
10364       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10365                                                             OldRetTy, false);
10366       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10367
10368       // If this is an invoke instruction, we should insert it after the first
10369       // non-phi, instruction in the normal successor block.
10370       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10371         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10372         InsertNewInstBefore(NC, *I);
10373       } else {
10374         // Otherwise, it's a call, just insert cast right after the call instr
10375         InsertNewInstBefore(NC, *Caller);
10376       }
10377       Worklist.AddUsersToWorkList(*Caller);
10378     } else {
10379       NV = UndefValue::get(Caller->getType());
10380     }
10381   }
10382
10383
10384   if (!Caller->use_empty())
10385     Caller->replaceAllUsesWith(NV);
10386   
10387   EraseInstFromFunction(*Caller);
10388   return true;
10389 }
10390
10391 // transformCallThroughTrampoline - Turn a call to a function created by the
10392 // init_trampoline intrinsic into a direct call to the underlying function.
10393 //
10394 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10395   Value *Callee = CS.getCalledValue();
10396   const PointerType *PTy = cast<PointerType>(Callee->getType());
10397   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10398   const AttrListPtr &Attrs = CS.getAttributes();
10399
10400   // If the call already has the 'nest' attribute somewhere then give up -
10401   // otherwise 'nest' would occur twice after splicing in the chain.
10402   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10403     return 0;
10404
10405   IntrinsicInst *Tramp =
10406     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10407
10408   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10409   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10410   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10411
10412   const AttrListPtr &NestAttrs = NestF->getAttributes();
10413   if (!NestAttrs.isEmpty()) {
10414     unsigned NestIdx = 1;
10415     const Type *NestTy = 0;
10416     Attributes NestAttr = Attribute::None;
10417
10418     // Look for a parameter marked with the 'nest' attribute.
10419     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10420          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10421       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10422         // Record the parameter type and any other attributes.
10423         NestTy = *I;
10424         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10425         break;
10426       }
10427
10428     if (NestTy) {
10429       Instruction *Caller = CS.getInstruction();
10430       std::vector<Value*> NewArgs;
10431       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10432
10433       SmallVector<AttributeWithIndex, 8> NewAttrs;
10434       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10435
10436       // Insert the nest argument into the call argument list, which may
10437       // mean appending it.  Likewise for attributes.
10438
10439       // Add any result attributes.
10440       if (Attributes Attr = Attrs.getRetAttributes())
10441         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10442
10443       {
10444         unsigned Idx = 1;
10445         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10446         do {
10447           if (Idx == NestIdx) {
10448             // Add the chain argument and attributes.
10449             Value *NestVal = Tramp->getOperand(3);
10450             if (NestVal->getType() != NestTy)
10451               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10452             NewArgs.push_back(NestVal);
10453             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10454           }
10455
10456           if (I == E)
10457             break;
10458
10459           // Add the original argument and attributes.
10460           NewArgs.push_back(*I);
10461           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10462             NewAttrs.push_back
10463               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10464
10465           ++Idx, ++I;
10466         } while (1);
10467       }
10468
10469       // Add any function attributes.
10470       if (Attributes Attr = Attrs.getFnAttributes())
10471         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10472
10473       // The trampoline may have been bitcast to a bogus type (FTy).
10474       // Handle this by synthesizing a new function type, equal to FTy
10475       // with the chain parameter inserted.
10476
10477       std::vector<const Type*> NewTypes;
10478       NewTypes.reserve(FTy->getNumParams()+1);
10479
10480       // Insert the chain's type into the list of parameter types, which may
10481       // mean appending it.
10482       {
10483         unsigned Idx = 1;
10484         FunctionType::param_iterator I = FTy->param_begin(),
10485           E = FTy->param_end();
10486
10487         do {
10488           if (Idx == NestIdx)
10489             // Add the chain's type.
10490             NewTypes.push_back(NestTy);
10491
10492           if (I == E)
10493             break;
10494
10495           // Add the original type.
10496           NewTypes.push_back(*I);
10497
10498           ++Idx, ++I;
10499         } while (1);
10500       }
10501
10502       // Replace the trampoline call with a direct call.  Let the generic
10503       // code sort out any function type mismatches.
10504       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 
10505                                                 FTy->isVarArg());
10506       Constant *NewCallee =
10507         NestF->getType() == PointerType::getUnqual(NewFTy) ?
10508         NestF : ConstantExpr::getBitCast(NestF, 
10509                                          PointerType::getUnqual(NewFTy));
10510       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10511                                                    NewAttrs.end());
10512
10513       Instruction *NewCaller;
10514       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10515         NewCaller = InvokeInst::Create(NewCallee,
10516                                        II->getNormalDest(), II->getUnwindDest(),
10517                                        NewArgs.begin(), NewArgs.end(),
10518                                        Caller->getName(), Caller);
10519         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10520         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10521       } else {
10522         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10523                                      Caller->getName(), Caller);
10524         if (cast<CallInst>(Caller)->isTailCall())
10525           cast<CallInst>(NewCaller)->setTailCall();
10526         cast<CallInst>(NewCaller)->
10527           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10528         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10529       }
10530       if (!Caller->getType()->isVoidTy())
10531         Caller->replaceAllUsesWith(NewCaller);
10532       Caller->eraseFromParent();
10533       Worklist.Remove(Caller);
10534       return 0;
10535     }
10536   }
10537
10538   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10539   // parameter, there is no need to adjust the argument list.  Let the generic
10540   // code sort out any function type mismatches.
10541   Constant *NewCallee =
10542     NestF->getType() == PTy ? NestF : 
10543                               ConstantExpr::getBitCast(NestF, PTy);
10544   CS.setCalledFunction(NewCallee);
10545   return CS.getInstruction();
10546 }
10547
10548 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10549 /// and if a/b/c and the add's all have a single use, turn this into a phi
10550 /// and a single binop.
10551 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10552   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10553   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10554   unsigned Opc = FirstInst->getOpcode();
10555   Value *LHSVal = FirstInst->getOperand(0);
10556   Value *RHSVal = FirstInst->getOperand(1);
10557     
10558   const Type *LHSType = LHSVal->getType();
10559   const Type *RHSType = RHSVal->getType();
10560   
10561   // Scan to see if all operands are the same opcode, and all have one use.
10562   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10563     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10564     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10565         // Verify type of the LHS matches so we don't fold cmp's of different
10566         // types or GEP's with different index types.
10567         I->getOperand(0)->getType() != LHSType ||
10568         I->getOperand(1)->getType() != RHSType)
10569       return 0;
10570
10571     // If they are CmpInst instructions, check their predicates
10572     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10573       if (cast<CmpInst>(I)->getPredicate() !=
10574           cast<CmpInst>(FirstInst)->getPredicate())
10575         return 0;
10576     
10577     // Keep track of which operand needs a phi node.
10578     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10579     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10580   }
10581
10582   // If both LHS and RHS would need a PHI, don't do this transformation,
10583   // because it would increase the number of PHIs entering the block,
10584   // which leads to higher register pressure. This is especially
10585   // bad when the PHIs are in the header of a loop.
10586   if (!LHSVal && !RHSVal)
10587     return 0;
10588   
10589   // Otherwise, this is safe to transform!
10590   
10591   Value *InLHS = FirstInst->getOperand(0);
10592   Value *InRHS = FirstInst->getOperand(1);
10593   PHINode *NewLHS = 0, *NewRHS = 0;
10594   if (LHSVal == 0) {
10595     NewLHS = PHINode::Create(LHSType,
10596                              FirstInst->getOperand(0)->getName() + ".pn");
10597     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10598     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10599     InsertNewInstBefore(NewLHS, PN);
10600     LHSVal = NewLHS;
10601   }
10602   
10603   if (RHSVal == 0) {
10604     NewRHS = PHINode::Create(RHSType,
10605                              FirstInst->getOperand(1)->getName() + ".pn");
10606     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10607     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10608     InsertNewInstBefore(NewRHS, PN);
10609     RHSVal = NewRHS;
10610   }
10611   
10612   // Add all operands to the new PHIs.
10613   if (NewLHS || NewRHS) {
10614     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10615       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10616       if (NewLHS) {
10617         Value *NewInLHS = InInst->getOperand(0);
10618         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10619       }
10620       if (NewRHS) {
10621         Value *NewInRHS = InInst->getOperand(1);
10622         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10623       }
10624     }
10625   }
10626     
10627   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10628     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10629   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10630   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10631                          LHSVal, RHSVal);
10632 }
10633
10634 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10635   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10636   
10637   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10638                                         FirstInst->op_end());
10639   // This is true if all GEP bases are allocas and if all indices into them are
10640   // constants.
10641   bool AllBasePointersAreAllocas = true;
10642
10643   // We don't want to replace this phi if the replacement would require
10644   // more than one phi, which leads to higher register pressure. This is
10645   // especially bad when the PHIs are in the header of a loop.
10646   bool NeededPhi = false;
10647   
10648   // Scan to see if all operands are the same opcode, and all have one use.
10649   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10650     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10651     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10652       GEP->getNumOperands() != FirstInst->getNumOperands())
10653       return 0;
10654
10655     // Keep track of whether or not all GEPs are of alloca pointers.
10656     if (AllBasePointersAreAllocas &&
10657         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10658          !GEP->hasAllConstantIndices()))
10659       AllBasePointersAreAllocas = false;
10660     
10661     // Compare the operand lists.
10662     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10663       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10664         continue;
10665       
10666       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10667       // if one of the PHIs has a constant for the index.  The index may be
10668       // substantially cheaper to compute for the constants, so making it a
10669       // variable index could pessimize the path.  This also handles the case
10670       // for struct indices, which must always be constant.
10671       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10672           isa<ConstantInt>(GEP->getOperand(op)))
10673         return 0;
10674       
10675       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10676         return 0;
10677
10678       // If we already needed a PHI for an earlier operand, and another operand
10679       // also requires a PHI, we'd be introducing more PHIs than we're
10680       // eliminating, which increases register pressure on entry to the PHI's
10681       // block.
10682       if (NeededPhi)
10683         return 0;
10684
10685       FixedOperands[op] = 0;  // Needs a PHI.
10686       NeededPhi = true;
10687     }
10688   }
10689   
10690   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10691   // bother doing this transformation.  At best, this will just save a bit of
10692   // offset calculation, but all the predecessors will have to materialize the
10693   // stack address into a register anyway.  We'd actually rather *clone* the
10694   // load up into the predecessors so that we have a load of a gep of an alloca,
10695   // which can usually all be folded into the load.
10696   if (AllBasePointersAreAllocas)
10697     return 0;
10698   
10699   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10700   // that is variable.
10701   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10702   
10703   bool HasAnyPHIs = false;
10704   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10705     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10706     Value *FirstOp = FirstInst->getOperand(i);
10707     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10708                                      FirstOp->getName()+".pn");
10709     InsertNewInstBefore(NewPN, PN);
10710     
10711     NewPN->reserveOperandSpace(e);
10712     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10713     OperandPhis[i] = NewPN;
10714     FixedOperands[i] = NewPN;
10715     HasAnyPHIs = true;
10716   }
10717
10718   
10719   // Add all operands to the new PHIs.
10720   if (HasAnyPHIs) {
10721     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10722       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10723       BasicBlock *InBB = PN.getIncomingBlock(i);
10724       
10725       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10726         if (PHINode *OpPhi = OperandPhis[op])
10727           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10728     }
10729   }
10730   
10731   Value *Base = FixedOperands[0];
10732   return cast<GEPOperator>(FirstInst)->isInBounds() ?
10733     GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10734                                       FixedOperands.end()) :
10735     GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10736                               FixedOperands.end());
10737 }
10738
10739
10740 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10741 /// sink the load out of the block that defines it.  This means that it must be
10742 /// obvious the value of the load is not changed from the point of the load to
10743 /// the end of the block it is in.
10744 ///
10745 /// Finally, it is safe, but not profitable, to sink a load targetting a
10746 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10747 /// to a register.
10748 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10749   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10750   
10751   for (++BBI; BBI != E; ++BBI)
10752     if (BBI->mayWriteToMemory())
10753       return false;
10754   
10755   // Check for non-address taken alloca.  If not address-taken already, it isn't
10756   // profitable to do this xform.
10757   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10758     bool isAddressTaken = false;
10759     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10760          UI != E; ++UI) {
10761       if (isa<LoadInst>(UI)) continue;
10762       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10763         // If storing TO the alloca, then the address isn't taken.
10764         if (SI->getOperand(1) == AI) continue;
10765       }
10766       isAddressTaken = true;
10767       break;
10768     }
10769     
10770     if (!isAddressTaken && AI->isStaticAlloca())
10771       return false;
10772   }
10773   
10774   // If this load is a load from a GEP with a constant offset from an alloca,
10775   // then we don't want to sink it.  In its present form, it will be
10776   // load [constant stack offset].  Sinking it will cause us to have to
10777   // materialize the stack addresses in each predecessor in a register only to
10778   // do a shared load from register in the successor.
10779   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10780     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10781       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10782         return false;
10783   
10784   return true;
10785 }
10786
10787 Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
10788   LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
10789   
10790   // When processing loads, we need to propagate two bits of information to the
10791   // sunk load: whether it is volatile, and what its alignment is.  We currently
10792   // don't sink loads when some have their alignment specified and some don't.
10793   // visitLoadInst will propagate an alignment onto the load when TD is around,
10794   // and if TD isn't around, we can't handle the mixed case.
10795   bool isVolatile = FirstLI->isVolatile();
10796   unsigned LoadAlignment = FirstLI->getAlignment();
10797   
10798   // We can't sink the load if the loaded value could be modified between the
10799   // load and the PHI.
10800   if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
10801       !isSafeAndProfitableToSinkLoad(FirstLI))
10802     return 0;
10803   
10804   // If the PHI is of volatile loads and the load block has multiple
10805   // successors, sinking it would remove a load of the volatile value from
10806   // the path through the other successor.
10807   if (isVolatile && 
10808       FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
10809     return 0;
10810   
10811   // Check to see if all arguments are the same operation.
10812   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10813     LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
10814     if (!LI || !LI->hasOneUse())
10815       return 0;
10816     
10817     // We can't sink the load if the loaded value could be modified between 
10818     // the load and the PHI.
10819     if (LI->isVolatile() != isVolatile ||
10820         LI->getParent() != PN.getIncomingBlock(i) ||
10821         !isSafeAndProfitableToSinkLoad(LI))
10822       return 0;
10823       
10824     // If some of the loads have an alignment specified but not all of them,
10825     // we can't do the transformation.
10826     if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
10827       return 0;
10828     
10829     LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
10830     
10831     // If the PHI is of volatile loads and the load block has multiple
10832     // successors, sinking it would remove a load of the volatile value from
10833     // the path through the other successor.
10834     if (isVolatile &&
10835         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10836       return 0;
10837   }
10838   
10839   // Okay, they are all the same operation.  Create a new PHI node of the
10840   // correct type, and PHI together all of the LHS's of the instructions.
10841   PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
10842                                    PN.getName()+".in");
10843   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10844   
10845   Value *InVal = FirstLI->getOperand(0);
10846   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10847   
10848   // Add all operands to the new PHI.
10849   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10850     Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
10851     if (NewInVal != InVal)
10852       InVal = 0;
10853     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10854   }
10855   
10856   Value *PhiVal;
10857   if (InVal) {
10858     // The new PHI unions all of the same values together.  This is really
10859     // common, so we handle it intelligently here for compile-time speed.
10860     PhiVal = InVal;
10861     delete NewPN;
10862   } else {
10863     InsertNewInstBefore(NewPN, PN);
10864     PhiVal = NewPN;
10865   }
10866   
10867   // If this was a volatile load that we are merging, make sure to loop through
10868   // and mark all the input loads as non-volatile.  If we don't do this, we will
10869   // insert a new volatile load and the old ones will not be deletable.
10870   if (isVolatile)
10871     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10872       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10873   
10874   return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
10875 }
10876
10877
10878 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10879 // operator and they all are only used by the PHI, PHI together their
10880 // inputs, and do the operation once, to the result of the PHI.
10881 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10882   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10883
10884   if (isa<GetElementPtrInst>(FirstInst))
10885     return FoldPHIArgGEPIntoPHI(PN);
10886   if (isa<LoadInst>(FirstInst))
10887     return FoldPHIArgLoadIntoPHI(PN);
10888   
10889   // Scan the instruction, looking for input operations that can be folded away.
10890   // If all input operands to the phi are the same instruction (e.g. a cast from
10891   // the same type or "+42") we can pull the operation through the PHI, reducing
10892   // code size and simplifying code.
10893   Constant *ConstantOp = 0;
10894   const Type *CastSrcTy = 0;
10895   
10896   if (isa<CastInst>(FirstInst)) {
10897     CastSrcTy = FirstInst->getOperand(0)->getType();
10898
10899     // Be careful about transforming integer PHIs.  We don't want to pessimize
10900     // the code by turning an i32 into an i1293.
10901     if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
10902       // If we don't have TD, we don't know if the original PHI was legal.
10903       if (!TD) return 0;
10904
10905       unsigned PHIWidth = PN.getType()->getPrimitiveSizeInBits();
10906       unsigned NewWidth = CastSrcTy->getPrimitiveSizeInBits();
10907       bool PHILegal = TD->isLegalInteger(PHIWidth);
10908       bool NewLegal = TD->isLegalInteger(NewWidth);
10909     
10910       // If this is a legal integer PHI node, and pulling the operation through
10911       // would cause it to be an illegal integer PHI, don't do the
10912       // transformation.
10913       if (PHILegal && !NewLegal)
10914         return 0;
10915       
10916       // Otherwise, if both are illegal, do not increase the size of the PHI. We
10917       // do allow things like i160 -> i64, but not i64 -> i160.
10918       if (!PHILegal && !NewLegal && NewWidth > PHIWidth)
10919         return 0;
10920     }
10921   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10922     // Can fold binop, compare or shift here if the RHS is a constant, 
10923     // otherwise call FoldPHIArgBinOpIntoPHI.
10924     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10925     if (ConstantOp == 0)
10926       return FoldPHIArgBinOpIntoPHI(PN);
10927   } else {
10928     return 0;  // Cannot fold this operation.
10929   }
10930
10931   // Check to see if all arguments are the same operation.
10932   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10933     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10934     if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10935       return 0;
10936     if (CastSrcTy) {
10937       if (I->getOperand(0)->getType() != CastSrcTy)
10938         return 0;  // Cast operation must match.
10939     } else if (I->getOperand(1) != ConstantOp) {
10940       return 0;
10941     }
10942   }
10943
10944   // Okay, they are all the same operation.  Create a new PHI node of the
10945   // correct type, and PHI together all of the LHS's of the instructions.
10946   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10947                                    PN.getName()+".in");
10948   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10949
10950   Value *InVal = FirstInst->getOperand(0);
10951   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10952
10953   // Add all operands to the new PHI.
10954   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10955     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10956     if (NewInVal != InVal)
10957       InVal = 0;
10958     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10959   }
10960
10961   Value *PhiVal;
10962   if (InVal) {
10963     // The new PHI unions all of the same values together.  This is really
10964     // common, so we handle it intelligently here for compile-time speed.
10965     PhiVal = InVal;
10966     delete NewPN;
10967   } else {
10968     InsertNewInstBefore(NewPN, PN);
10969     PhiVal = NewPN;
10970   }
10971
10972   // Insert and return the new operation.
10973   if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
10974     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10975   
10976   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10977     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10978   
10979   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10980   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10981                          PhiVal, ConstantOp);
10982 }
10983
10984 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10985 /// that is dead.
10986 static bool DeadPHICycle(PHINode *PN,
10987                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10988   if (PN->use_empty()) return true;
10989   if (!PN->hasOneUse()) return false;
10990
10991   // Remember this node, and if we find the cycle, return.
10992   if (!PotentiallyDeadPHIs.insert(PN))
10993     return true;
10994   
10995   // Don't scan crazily complex things.
10996   if (PotentiallyDeadPHIs.size() == 16)
10997     return false;
10998
10999   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
11000     return DeadPHICycle(PU, PotentiallyDeadPHIs);
11001
11002   return false;
11003 }
11004
11005 /// PHIsEqualValue - Return true if this phi node is always equal to
11006 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
11007 ///   z = some value; x = phi (y, z); y = phi (x, z)
11008 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
11009                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
11010   // See if we already saw this PHI node.
11011   if (!ValueEqualPHIs.insert(PN))
11012     return true;
11013   
11014   // Don't scan crazily complex things.
11015   if (ValueEqualPHIs.size() == 16)
11016     return false;
11017  
11018   // Scan the operands to see if they are either phi nodes or are equal to
11019   // the value.
11020   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11021     Value *Op = PN->getIncomingValue(i);
11022     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
11023       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
11024         return false;
11025     } else if (Op != NonPhiInVal)
11026       return false;
11027   }
11028   
11029   return true;
11030 }
11031
11032
11033 namespace {
11034 struct PHIUsageRecord {
11035   unsigned PHIId;     // The ID # of the PHI (something determinstic to sort on)
11036   unsigned Shift;     // The amount shifted.
11037   Instruction *Inst;  // The trunc instruction.
11038   
11039   PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
11040     : PHIId(pn), Shift(Sh), Inst(User) {}
11041   
11042   bool operator<(const PHIUsageRecord &RHS) const {
11043     if (PHIId < RHS.PHIId) return true;
11044     if (PHIId > RHS.PHIId) return false;
11045     if (Shift < RHS.Shift) return true;
11046     if (Shift > RHS.Shift) return false;
11047     return Inst->getType()->getPrimitiveSizeInBits() <
11048            RHS.Inst->getType()->getPrimitiveSizeInBits();
11049   }
11050 };
11051   
11052 struct LoweredPHIRecord {
11053   PHINode *PN;        // The PHI that was lowered.
11054   unsigned Shift;     // The amount shifted.
11055   unsigned Width;     // The width extracted.
11056   
11057   LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
11058     : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
11059   
11060   // Ctor form used by DenseMap.
11061   LoweredPHIRecord(PHINode *pn, unsigned Sh)
11062     : PN(pn), Shift(Sh), Width(0) {}
11063 };
11064 }
11065
11066 namespace llvm {
11067   template<>
11068   struct DenseMapInfo<LoweredPHIRecord> {
11069     static inline LoweredPHIRecord getEmptyKey() {
11070       return LoweredPHIRecord(0, 0);
11071     }
11072     static inline LoweredPHIRecord getTombstoneKey() {
11073       return LoweredPHIRecord(0, 1);
11074     }
11075     static unsigned getHashValue(const LoweredPHIRecord &Val) {
11076       return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
11077              (Val.Width>>3);
11078     }
11079     static bool isEqual(const LoweredPHIRecord &LHS,
11080                         const LoweredPHIRecord &RHS) {
11081       return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
11082              LHS.Width == RHS.Width;
11083     }
11084     static bool isPod() { return true; }
11085   };
11086 }
11087
11088
11089 /// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
11090 /// illegal type: see if it is only used by trunc or trunc(lshr) operations.  If
11091 /// so, we split the PHI into the various pieces being extracted.  This sort of
11092 /// thing is introduced when SROA promotes an aggregate to large integer values.
11093 ///
11094 /// TODO: The user of the trunc may be an bitcast to float/double/vector or an
11095 /// inttoptr.  We should produce new PHIs in the right type.
11096 ///
11097 Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
11098   // PHIUsers - Keep track of all of the truncated values extracted from a set
11099   // of PHIs, along with their offset.  These are the things we want to rewrite.
11100   SmallVector<PHIUsageRecord, 16> PHIUsers;
11101   
11102   // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
11103   // nodes which are extracted from. PHIsToSlice is a set we use to avoid
11104   // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
11105   // check the uses of (to ensure they are all extracts).
11106   SmallVector<PHINode*, 8> PHIsToSlice;
11107   SmallPtrSet<PHINode*, 8> PHIsInspected;
11108   
11109   PHIsToSlice.push_back(&FirstPhi);
11110   PHIsInspected.insert(&FirstPhi);
11111   
11112   for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
11113     PHINode *PN = PHIsToSlice[PHIId];
11114     
11115     for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
11116          UI != E; ++UI) {
11117       Instruction *User = cast<Instruction>(*UI);
11118       
11119       // If the user is a PHI, inspect its uses recursively.
11120       if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
11121         if (PHIsInspected.insert(UserPN))
11122           PHIsToSlice.push_back(UserPN);
11123         continue;
11124       }
11125       
11126       // Truncates are always ok.
11127       if (isa<TruncInst>(User)) {
11128         PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
11129         continue;
11130       }
11131       
11132       // Otherwise it must be a lshr which can only be used by one trunc.
11133       if (User->getOpcode() != Instruction::LShr ||
11134           !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
11135           !isa<ConstantInt>(User->getOperand(1)))
11136         return 0;
11137       
11138       unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
11139       PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
11140     }
11141   }
11142   
11143   // If we have no users, they must be all self uses, just nuke the PHI.
11144   if (PHIUsers.empty())
11145     return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
11146   
11147   // If this phi node is transformable, create new PHIs for all the pieces
11148   // extracted out of it.  First, sort the users by their offset and size.
11149   array_pod_sort(PHIUsers.begin(), PHIUsers.end());
11150   
11151   DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
11152             for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11153               errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
11154         );
11155   
11156   // PredValues - This is a temporary used when rewriting PHI nodes.  It is
11157   // hoisted out here to avoid construction/destruction thrashing.
11158   DenseMap<BasicBlock*, Value*> PredValues;
11159   
11160   // ExtractedVals - Each new PHI we introduce is saved here so we don't
11161   // introduce redundant PHIs.
11162   DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
11163   
11164   for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
11165     unsigned PHIId = PHIUsers[UserI].PHIId;
11166     PHINode *PN = PHIsToSlice[PHIId];
11167     unsigned Offset = PHIUsers[UserI].Shift;
11168     const Type *Ty = PHIUsers[UserI].Inst->getType();
11169     
11170     PHINode *EltPHI;
11171     
11172     // If we've already lowered a user like this, reuse the previously lowered
11173     // value.
11174     if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
11175       
11176       // Otherwise, Create the new PHI node for this user.
11177       EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
11178       assert(EltPHI->getType() != PN->getType() &&
11179              "Truncate didn't shrink phi?");
11180     
11181       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11182         BasicBlock *Pred = PN->getIncomingBlock(i);
11183         Value *&PredVal = PredValues[Pred];
11184         
11185         // If we already have a value for this predecessor, reuse it.
11186         if (PredVal) {
11187           EltPHI->addIncoming(PredVal, Pred);
11188           continue;
11189         }
11190
11191         // Handle the PHI self-reuse case.
11192         Value *InVal = PN->getIncomingValue(i);
11193         if (InVal == PN) {
11194           PredVal = EltPHI;
11195           EltPHI->addIncoming(PredVal, Pred);
11196           continue;
11197         } else if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
11198           // If the incoming value was a PHI, and if it was one of the PHIs we
11199           // already rewrote it, just use the lowered value.
11200           if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
11201             PredVal = Res;
11202             EltPHI->addIncoming(PredVal, Pred);
11203             continue;
11204           }
11205         }
11206         
11207         // Otherwise, do an extract in the predecessor.
11208         Builder->SetInsertPoint(Pred, Pred->getTerminator());
11209         Value *Res = InVal;
11210         if (Offset)
11211           Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
11212                                                           Offset), "extract");
11213         Res = Builder->CreateTrunc(Res, Ty, "extract.t");
11214         PredVal = Res;
11215         EltPHI->addIncoming(Res, Pred);
11216         
11217         // If the incoming value was a PHI, and if it was one of the PHIs we are
11218         // rewriting, we will ultimately delete the code we inserted.  This
11219         // means we need to revisit that PHI to make sure we extract out the
11220         // needed piece.
11221         if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
11222           if (PHIsInspected.count(OldInVal)) {
11223             unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
11224                                           OldInVal)-PHIsToSlice.begin();
11225             PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset, 
11226                                               cast<Instruction>(Res)));
11227             ++UserE;
11228           }
11229       }
11230       PredValues.clear();
11231       
11232       DEBUG(errs() << "  Made element PHI for offset " << Offset << ": "
11233                    << *EltPHI << '\n');
11234       ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
11235     }
11236     
11237     // Replace the use of this piece with the PHI node.
11238     ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
11239   }
11240   
11241   // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
11242   // with undefs.
11243   Value *Undef = UndefValue::get(FirstPhi.getType());
11244   for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11245     ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
11246   return ReplaceInstUsesWith(FirstPhi, Undef);
11247 }
11248
11249 // PHINode simplification
11250 //
11251 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
11252   // If LCSSA is around, don't mess with Phi nodes
11253   if (MustPreserveLCSSA) return 0;
11254   
11255   if (Value *V = PN.hasConstantValue())
11256     return ReplaceInstUsesWith(PN, V);
11257
11258   // If all PHI operands are the same operation, pull them through the PHI,
11259   // reducing code size.
11260   if (isa<Instruction>(PN.getIncomingValue(0)) &&
11261       isa<Instruction>(PN.getIncomingValue(1)) &&
11262       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
11263       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
11264       // FIXME: The hasOneUse check will fail for PHIs that use the value more
11265       // than themselves more than once.
11266       PN.getIncomingValue(0)->hasOneUse())
11267     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
11268       return Result;
11269
11270   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
11271   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
11272   // PHI)... break the cycle.
11273   if (PN.hasOneUse()) {
11274     Instruction *PHIUser = cast<Instruction>(PN.use_back());
11275     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
11276       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
11277       PotentiallyDeadPHIs.insert(&PN);
11278       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
11279         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
11280     }
11281    
11282     // If this phi has a single use, and if that use just computes a value for
11283     // the next iteration of a loop, delete the phi.  This occurs with unused
11284     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
11285     // common case here is good because the only other things that catch this
11286     // are induction variable analysis (sometimes) and ADCE, which is only run
11287     // late.
11288     if (PHIUser->hasOneUse() &&
11289         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
11290         PHIUser->use_back() == &PN) {
11291       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
11292     }
11293   }
11294
11295   // We sometimes end up with phi cycles that non-obviously end up being the
11296   // same value, for example:
11297   //   z = some value; x = phi (y, z); y = phi (x, z)
11298   // where the phi nodes don't necessarily need to be in the same block.  Do a
11299   // quick check to see if the PHI node only contains a single non-phi value, if
11300   // so, scan to see if the phi cycle is actually equal to that value.
11301   {
11302     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
11303     // Scan for the first non-phi operand.
11304     while (InValNo != NumOperandVals && 
11305            isa<PHINode>(PN.getIncomingValue(InValNo)))
11306       ++InValNo;
11307
11308     if (InValNo != NumOperandVals) {
11309       Value *NonPhiInVal = PN.getOperand(InValNo);
11310       
11311       // Scan the rest of the operands to see if there are any conflicts, if so
11312       // there is no need to recursively scan other phis.
11313       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11314         Value *OpVal = PN.getIncomingValue(InValNo);
11315         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11316           break;
11317       }
11318       
11319       // If we scanned over all operands, then we have one unique value plus
11320       // phi values.  Scan PHI nodes to see if they all merge in each other or
11321       // the value.
11322       if (InValNo == NumOperandVals) {
11323         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11324         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11325           return ReplaceInstUsesWith(PN, NonPhiInVal);
11326       }
11327     }
11328   }
11329
11330   // If there are multiple PHIs, sort their operands so that they all list
11331   // the blocks in the same order. This will help identical PHIs be eliminated
11332   // by other passes. Other passes shouldn't depend on this for correctness
11333   // however.
11334   PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
11335   if (&PN != FirstPN)
11336     for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
11337       BasicBlock *BBA = PN.getIncomingBlock(i);
11338       BasicBlock *BBB = FirstPN->getIncomingBlock(i);
11339       if (BBA != BBB) {
11340         Value *VA = PN.getIncomingValue(i);
11341         unsigned j = PN.getBasicBlockIndex(BBB);
11342         Value *VB = PN.getIncomingValue(j);
11343         PN.setIncomingBlock(i, BBB);
11344         PN.setIncomingValue(i, VB);
11345         PN.setIncomingBlock(j, BBA);
11346         PN.setIncomingValue(j, VA);
11347         // NOTE: Instcombine normally would want us to "return &PN" if we
11348         // modified any of the operands of an instruction.  However, since we
11349         // aren't adding or removing uses (just rearranging them) we don't do
11350         // this in this case.
11351       }
11352     }
11353
11354   // If this is an integer PHI and we know that it has an illegal type, see if
11355   // it is only used by trunc or trunc(lshr) operations.  If so, we split the
11356   // PHI into the various pieces being extracted.  This sort of thing is
11357   // introduced when SROA promotes an aggregate to a single large integer type.
11358   if (isa<IntegerType>(PN.getType()) && TD &&
11359       !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
11360     if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
11361       return Res;
11362   
11363   return 0;
11364 }
11365
11366 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
11367   Value *PtrOp = GEP.getOperand(0);
11368   // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
11369   if (GEP.getNumOperands() == 1)
11370     return ReplaceInstUsesWith(GEP, PtrOp);
11371
11372   if (isa<UndefValue>(GEP.getOperand(0)))
11373     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
11374
11375   bool HasZeroPointerIndex = false;
11376   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11377     HasZeroPointerIndex = C->isNullValue();
11378
11379   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11380     return ReplaceInstUsesWith(GEP, PtrOp);
11381
11382   // Eliminate unneeded casts for indices.
11383   if (TD) {
11384     bool MadeChange = false;
11385     unsigned PtrSize = TD->getPointerSizeInBits();
11386     
11387     gep_type_iterator GTI = gep_type_begin(GEP);
11388     for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11389          I != E; ++I, ++GTI) {
11390       if (!isa<SequentialType>(*GTI)) continue;
11391       
11392       // If we are using a wider index than needed for this platform, shrink it
11393       // to what we need.  If narrower, sign-extend it to what we need.  This
11394       // explicit cast can make subsequent optimizations more obvious.
11395       unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
11396       if (OpBits == PtrSize)
11397         continue;
11398       
11399       *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
11400       MadeChange = true;
11401     }
11402     if (MadeChange) return &GEP;
11403   }
11404
11405   // Combine Indices - If the source pointer to this getelementptr instruction
11406   // is a getelementptr instruction, combine the indices of the two
11407   // getelementptr instructions into a single instruction.
11408   //
11409   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
11410     // Note that if our source is a gep chain itself that we wait for that
11411     // chain to be resolved before we perform this transformation.  This
11412     // avoids us creating a TON of code in some cases.
11413     //
11414     if (GetElementPtrInst *SrcGEP =
11415           dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11416       if (SrcGEP->getNumOperands() == 2)
11417         return 0;   // Wait until our source is folded to completion.
11418
11419     SmallVector<Value*, 8> Indices;
11420
11421     // Find out whether the last index in the source GEP is a sequential idx.
11422     bool EndsWithSequential = false;
11423     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11424          I != E; ++I)
11425       EndsWithSequential = !isa<StructType>(*I);
11426
11427     // Can we combine the two pointer arithmetics offsets?
11428     if (EndsWithSequential) {
11429       // Replace: gep (gep %P, long B), long A, ...
11430       // With:    T = long A+B; gep %P, T, ...
11431       //
11432       Value *Sum;
11433       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11434       Value *GO1 = GEP.getOperand(1);
11435       if (SO1 == Constant::getNullValue(SO1->getType())) {
11436         Sum = GO1;
11437       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
11438         Sum = SO1;
11439       } else {
11440         // If they aren't the same type, then the input hasn't been processed
11441         // by the loop above yet (which canonicalizes sequential index types to
11442         // intptr_t).  Just avoid transforming this until the input has been
11443         // normalized.
11444         if (SO1->getType() != GO1->getType())
11445           return 0;
11446         Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11447       }
11448
11449       // Update the GEP in place if possible.
11450       if (Src->getNumOperands() == 2) {
11451         GEP.setOperand(0, Src->getOperand(0));
11452         GEP.setOperand(1, Sum);
11453         return &GEP;
11454       }
11455       Indices.append(Src->op_begin()+1, Src->op_end()-1);
11456       Indices.push_back(Sum);
11457       Indices.append(GEP.op_begin()+2, GEP.op_end());
11458     } else if (isa<Constant>(*GEP.idx_begin()) &&
11459                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11460                Src->getNumOperands() != 1) {
11461       // Otherwise we can do the fold if the first index of the GEP is a zero
11462       Indices.append(Src->op_begin()+1, Src->op_end());
11463       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
11464     }
11465
11466     if (!Indices.empty())
11467       return (cast<GEPOperator>(&GEP)->isInBounds() &&
11468               Src->isInBounds()) ?
11469         GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11470                                           Indices.end(), GEP.getName()) :
11471         GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
11472                                   Indices.end(), GEP.getName());
11473   }
11474   
11475   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11476   if (Value *X = getBitCastOperand(PtrOp)) {
11477     assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
11478
11479     // If the input bitcast is actually "bitcast(bitcast(x))", then we don't 
11480     // want to change the gep until the bitcasts are eliminated.
11481     if (getBitCastOperand(X)) {
11482       Worklist.AddValue(PtrOp);
11483       return 0;
11484     }
11485     
11486     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11487     // into     : GEP [10 x i8]* X, i32 0, ...
11488     //
11489     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11490     //           into     : GEP i8* X, ...
11491     // 
11492     // This occurs when the program declares an array extern like "int X[];"
11493     if (HasZeroPointerIndex) {
11494       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11495       const PointerType *XTy = cast<PointerType>(X->getType());
11496       if (const ArrayType *CATy =
11497           dyn_cast<ArrayType>(CPTy->getElementType())) {
11498         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11499         if (CATy->getElementType() == XTy->getElementType()) {
11500           // -> GEP i8* X, ...
11501           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11502           return cast<GEPOperator>(&GEP)->isInBounds() ?
11503             GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11504                                               GEP.getName()) :
11505             GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11506                                       GEP.getName());
11507         }
11508         
11509         if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
11510           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11511           if (CATy->getElementType() == XATy->getElementType()) {
11512             // -> GEP [10 x i8]* X, i32 0, ...
11513             // At this point, we know that the cast source type is a pointer
11514             // to an array of the same type as the destination pointer
11515             // array.  Because the array type is never stepped over (there
11516             // is a leading zero) we can fold the cast into this GEP.
11517             GEP.setOperand(0, X);
11518             return &GEP;
11519           }
11520         }
11521       }
11522     } else if (GEP.getNumOperands() == 2) {
11523       // Transform things like:
11524       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11525       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11526       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11527       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11528       if (TD && isa<ArrayType>(SrcElTy) &&
11529           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11530           TD->getTypeAllocSize(ResElTy)) {
11531         Value *Idx[2];
11532         Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11533         Idx[1] = GEP.getOperand(1);
11534         Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11535           Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11536           Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11537         // V and GEP are both pointer types --> BitCast
11538         return new BitCastInst(NewGEP, GEP.getType());
11539       }
11540       
11541       // Transform things like:
11542       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11543       //   (where tmp = 8*tmp2) into:
11544       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11545       
11546       if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
11547         uint64_t ArrayEltSize =
11548             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11549         
11550         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11551         // allow either a mul, shift, or constant here.
11552         Value *NewIdx = 0;
11553         ConstantInt *Scale = 0;
11554         if (ArrayEltSize == 1) {
11555           NewIdx = GEP.getOperand(1);
11556           Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11557         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11558           NewIdx = ConstantInt::get(CI->getType(), 1);
11559           Scale = CI;
11560         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11561           if (Inst->getOpcode() == Instruction::Shl &&
11562               isa<ConstantInt>(Inst->getOperand(1))) {
11563             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11564             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11565             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11566                                      1ULL << ShAmtVal);
11567             NewIdx = Inst->getOperand(0);
11568           } else if (Inst->getOpcode() == Instruction::Mul &&
11569                      isa<ConstantInt>(Inst->getOperand(1))) {
11570             Scale = cast<ConstantInt>(Inst->getOperand(1));
11571             NewIdx = Inst->getOperand(0);
11572           }
11573         }
11574         
11575         // If the index will be to exactly the right offset with the scale taken
11576         // out, perform the transformation. Note, we don't know whether Scale is
11577         // signed or not. We'll use unsigned version of division/modulo
11578         // operation after making sure Scale doesn't have the sign bit set.
11579         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11580             Scale->getZExtValue() % ArrayEltSize == 0) {
11581           Scale = ConstantInt::get(Scale->getType(),
11582                                    Scale->getZExtValue() / ArrayEltSize);
11583           if (Scale->getZExtValue() != 1) {
11584             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11585                                                        false /*ZExt*/);
11586             NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
11587           }
11588
11589           // Insert the new GEP instruction.
11590           Value *Idx[2];
11591           Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11592           Idx[1] = NewIdx;
11593           Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11594             Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11595             Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11596           // The NewGEP must be pointer typed, so must the old one -> BitCast
11597           return new BitCastInst(NewGEP, GEP.getType());
11598         }
11599       }
11600     }
11601   }
11602   
11603   /// See if we can simplify:
11604   ///   X = bitcast A* to B*
11605   ///   Y = gep X, <...constant indices...>
11606   /// into a gep of the original struct.  This is important for SROA and alias
11607   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11608   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11609     if (TD &&
11610         !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11611       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11612       // a constant back from EmitGEPOffset.
11613       ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, *this));
11614       int64_t Offset = OffsetV->getSExtValue();
11615       
11616       // If this GEP instruction doesn't move the pointer, just replace the GEP
11617       // with a bitcast of the real input to the dest type.
11618       if (Offset == 0) {
11619         // If the bitcast is of an allocation, and the allocation will be
11620         // converted to match the type of the cast, don't touch this.
11621         if (isa<AllocaInst>(BCI->getOperand(0)) ||
11622             isMalloc(BCI->getOperand(0))) {
11623           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11624           if (Instruction *I = visitBitCast(*BCI)) {
11625             if (I != BCI) {
11626               I->takeName(BCI);
11627               BCI->getParent()->getInstList().insert(BCI, I);
11628               ReplaceInstUsesWith(*BCI, I);
11629             }
11630             return &GEP;
11631           }
11632         }
11633         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11634       }
11635       
11636       // Otherwise, if the offset is non-zero, we need to find out if there is a
11637       // field at Offset in 'A's type.  If so, we can pull the cast through the
11638       // GEP.
11639       SmallVector<Value*, 8> NewIndices;
11640       const Type *InTy =
11641         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11642       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11643         Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11644           Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11645                                      NewIndices.end()) :
11646           Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11647                              NewIndices.end());
11648         
11649         if (NGEP->getType() == GEP.getType())
11650           return ReplaceInstUsesWith(GEP, NGEP);
11651         NGEP->takeName(&GEP);
11652         return new BitCastInst(NGEP, GEP.getType());
11653       }
11654     }
11655   }    
11656     
11657   return 0;
11658 }
11659
11660 Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
11661   // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
11662   if (AI.isArrayAllocation()) {  // Check C != 1
11663     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11664       const Type *NewTy = 
11665         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11666       assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11667       AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
11668       New->setAlignment(AI.getAlignment());
11669
11670       // Scan to the end of the allocation instructions, to skip over a block of
11671       // allocas if possible...also skip interleaved debug info
11672       //
11673       BasicBlock::iterator It = New;
11674       while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11675
11676       // Now that I is pointing to the first non-allocation-inst in the block,
11677       // insert our getelementptr instruction...
11678       //
11679       Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
11680       Value *Idx[2];
11681       Idx[0] = NullIdx;
11682       Idx[1] = NullIdx;
11683       Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11684                                                    New->getName()+".sub", It);
11685
11686       // Now make everything use the getelementptr instead of the original
11687       // allocation.
11688       return ReplaceInstUsesWith(AI, V);
11689     } else if (isa<UndefValue>(AI.getArraySize())) {
11690       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11691     }
11692   }
11693
11694   if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11695     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11696     // Note that we only do this for alloca's, because malloc should allocate
11697     // and return a unique pointer, even for a zero byte allocation.
11698     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11699       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11700
11701     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11702     if (AI.getAlignment() == 0)
11703       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11704   }
11705
11706   return 0;
11707 }
11708
11709 Instruction *InstCombiner::visitFree(Instruction &FI) {
11710   Value *Op = FI.getOperand(1);
11711
11712   // free undef -> unreachable.
11713   if (isa<UndefValue>(Op)) {
11714     // Insert a new store to null because we cannot modify the CFG here.
11715     new StoreInst(ConstantInt::getTrue(*Context),
11716            UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
11717     return EraseInstFromFunction(FI);
11718   }
11719   
11720   // If we have 'free null' delete the instruction.  This can happen in stl code
11721   // when lots of inlining happens.
11722   if (isa<ConstantPointerNull>(Op))
11723     return EraseInstFromFunction(FI);
11724
11725   // If we have a malloc call whose only use is a free call, delete both.
11726   if (isMalloc(Op)) {
11727     if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11728       if (Op->hasOneUse() && CI->hasOneUse()) {
11729         EraseInstFromFunction(FI);
11730         EraseInstFromFunction(*CI);
11731         return EraseInstFromFunction(*cast<Instruction>(Op));
11732       }
11733     } else {
11734       // Op is a call to malloc
11735       if (Op->hasOneUse()) {
11736         EraseInstFromFunction(FI);
11737         return EraseInstFromFunction(*cast<Instruction>(Op));
11738       }
11739     }
11740   }
11741
11742   return 0;
11743 }
11744
11745 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11746 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11747                                         const TargetData *TD) {
11748   User *CI = cast<User>(LI.getOperand(0));
11749   Value *CastOp = CI->getOperand(0);
11750   LLVMContext *Context = IC.getContext();
11751
11752   const PointerType *DestTy = cast<PointerType>(CI->getType());
11753   const Type *DestPTy = DestTy->getElementType();
11754   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11755
11756     // If the address spaces don't match, don't eliminate the cast.
11757     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11758       return 0;
11759
11760     const Type *SrcPTy = SrcTy->getElementType();
11761
11762     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11763          isa<VectorType>(DestPTy)) {
11764       // If the source is an array, the code below will not succeed.  Check to
11765       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11766       // constants.
11767       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11768         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11769           if (ASrcTy->getNumElements() != 0) {
11770             Value *Idxs[2];
11771             Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11772             Idxs[1] = Idxs[0];
11773             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11774             SrcTy = cast<PointerType>(CastOp->getType());
11775             SrcPTy = SrcTy->getElementType();
11776           }
11777
11778       if (IC.getTargetData() &&
11779           (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11780             isa<VectorType>(SrcPTy)) &&
11781           // Do not allow turning this into a load of an integer, which is then
11782           // casted to a pointer, this pessimizes pointer analysis a lot.
11783           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11784           IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11785                IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11786
11787         // Okay, we are casting from one integer or pointer type to another of
11788         // the same size.  Instead of casting the pointer before the load, cast
11789         // the result of the loaded value.
11790         Value *NewLoad = 
11791           IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
11792         // Now cast the result of the load.
11793         return new BitCastInst(NewLoad, LI.getType());
11794       }
11795     }
11796   }
11797   return 0;
11798 }
11799
11800 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11801   Value *Op = LI.getOperand(0);
11802
11803   // Attempt to improve the alignment.
11804   if (TD) {
11805     unsigned KnownAlign =
11806       GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11807     if (KnownAlign >
11808         (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11809                                   LI.getAlignment()))
11810       LI.setAlignment(KnownAlign);
11811   }
11812
11813   // load (cast X) --> cast (load X) iff safe.
11814   if (isa<CastInst>(Op))
11815     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11816       return Res;
11817
11818   // None of the following transforms are legal for volatile loads.
11819   if (LI.isVolatile()) return 0;
11820   
11821   // Do really simple store-to-load forwarding and load CSE, to catch cases
11822   // where there are several consequtive memory accesses to the same location,
11823   // separated by a few arithmetic operations.
11824   BasicBlock::iterator BBI = &LI;
11825   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11826     return ReplaceInstUsesWith(LI, AvailableVal);
11827
11828   // load(gep null, ...) -> unreachable
11829   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11830     const Value *GEPI0 = GEPI->getOperand(0);
11831     // TODO: Consider a target hook for valid address spaces for this xform.
11832     if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
11833       // Insert a new store to null instruction before the load to indicate
11834       // that this code is not reachable.  We do this instead of inserting
11835       // an unreachable instruction directly because we cannot modify the
11836       // CFG.
11837       new StoreInst(UndefValue::get(LI.getType()),
11838                     Constant::getNullValue(Op->getType()), &LI);
11839       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11840     }
11841   } 
11842
11843   // load null/undef -> unreachable
11844   // TODO: Consider a target hook for valid address spaces for this xform.
11845   if (isa<UndefValue>(Op) ||
11846       (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
11847     // Insert a new store to null instruction before the load to indicate that
11848     // this code is not reachable.  We do this instead of inserting an
11849     // unreachable instruction directly because we cannot modify the CFG.
11850     new StoreInst(UndefValue::get(LI.getType()),
11851                   Constant::getNullValue(Op->getType()), &LI);
11852     return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11853   }
11854
11855   // Instcombine load (constantexpr_cast global) -> cast (load global)
11856   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
11857     if (CE->isCast())
11858       if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11859         return Res;
11860   
11861   if (Op->hasOneUse()) {
11862     // Change select and PHI nodes to select values instead of addresses: this
11863     // helps alias analysis out a lot, allows many others simplifications, and
11864     // exposes redundancy in the code.
11865     //
11866     // Note that we cannot do the transformation unless we know that the
11867     // introduced loads cannot trap!  Something like this is valid as long as
11868     // the condition is always false: load (select bool %C, int* null, int* %G),
11869     // but it would not be valid if we transformed it to load from null
11870     // unconditionally.
11871     //
11872     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11873       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11874       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11875           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11876         Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11877                                         SI->getOperand(1)->getName()+".val");
11878         Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11879                                         SI->getOperand(2)->getName()+".val");
11880         return SelectInst::Create(SI->getCondition(), V1, V2);
11881       }
11882
11883       // load (select (cond, null, P)) -> load P
11884       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11885         if (C->isNullValue()) {
11886           LI.setOperand(0, SI->getOperand(2));
11887           return &LI;
11888         }
11889
11890       // load (select (cond, P, null)) -> load P
11891       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11892         if (C->isNullValue()) {
11893           LI.setOperand(0, SI->getOperand(1));
11894           return &LI;
11895         }
11896     }
11897   }
11898   return 0;
11899 }
11900
11901 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11902 /// when possible.  This makes it generally easy to do alias analysis and/or
11903 /// SROA/mem2reg of the memory object.
11904 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11905   User *CI = cast<User>(SI.getOperand(1));
11906   Value *CastOp = CI->getOperand(0);
11907
11908   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11909   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11910   if (SrcTy == 0) return 0;
11911   
11912   const Type *SrcPTy = SrcTy->getElementType();
11913
11914   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11915     return 0;
11916   
11917   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11918   /// to its first element.  This allows us to handle things like:
11919   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11920   /// on 32-bit hosts.
11921   SmallVector<Value*, 4> NewGEPIndices;
11922   
11923   // If the source is an array, the code below will not succeed.  Check to
11924   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11925   // constants.
11926   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11927     // Index through pointer.
11928     Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
11929     NewGEPIndices.push_back(Zero);
11930     
11931     while (1) {
11932       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11933         if (!STy->getNumElements()) /* Struct can be empty {} */
11934           break;
11935         NewGEPIndices.push_back(Zero);
11936         SrcPTy = STy->getElementType(0);
11937       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11938         NewGEPIndices.push_back(Zero);
11939         SrcPTy = ATy->getElementType();
11940       } else {
11941         break;
11942       }
11943     }
11944     
11945     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11946   }
11947
11948   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11949     return 0;
11950   
11951   // If the pointers point into different address spaces or if they point to
11952   // values with different sizes, we can't do the transformation.
11953   if (!IC.getTargetData() ||
11954       SrcTy->getAddressSpace() != 
11955         cast<PointerType>(CI->getType())->getAddressSpace() ||
11956       IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11957       IC.getTargetData()->getTypeSizeInBits(DestPTy))
11958     return 0;
11959
11960   // Okay, we are casting from one integer or pointer type to another of
11961   // the same size.  Instead of casting the pointer before 
11962   // the store, cast the value to be stored.
11963   Value *NewCast;
11964   Value *SIOp0 = SI.getOperand(0);
11965   Instruction::CastOps opcode = Instruction::BitCast;
11966   const Type* CastSrcTy = SIOp0->getType();
11967   const Type* CastDstTy = SrcPTy;
11968   if (isa<PointerType>(CastDstTy)) {
11969     if (CastSrcTy->isInteger())
11970       opcode = Instruction::IntToPtr;
11971   } else if (isa<IntegerType>(CastDstTy)) {
11972     if (isa<PointerType>(SIOp0->getType()))
11973       opcode = Instruction::PtrToInt;
11974   }
11975   
11976   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11977   // emit a GEP to index into its first field.
11978   if (!NewGEPIndices.empty())
11979     CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11980                                            NewGEPIndices.end());
11981   
11982   NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11983                                    SIOp0->getName()+".c");
11984   return new StoreInst(NewCast, CastOp);
11985 }
11986
11987 /// equivalentAddressValues - Test if A and B will obviously have the same
11988 /// value. This includes recognizing that %t0 and %t1 will have the same
11989 /// value in code like this:
11990 ///   %t0 = getelementptr \@a, 0, 3
11991 ///   store i32 0, i32* %t0
11992 ///   %t1 = getelementptr \@a, 0, 3
11993 ///   %t2 = load i32* %t1
11994 ///
11995 static bool equivalentAddressValues(Value *A, Value *B) {
11996   // Test if the values are trivially equivalent.
11997   if (A == B) return true;
11998   
11999   // Test if the values come form identical arithmetic instructions.
12000   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
12001   // its only used to compare two uses within the same basic block, which
12002   // means that they'll always either have the same value or one of them
12003   // will have an undefined value.
12004   if (isa<BinaryOperator>(A) ||
12005       isa<CastInst>(A) ||
12006       isa<PHINode>(A) ||
12007       isa<GetElementPtrInst>(A))
12008     if (Instruction *BI = dyn_cast<Instruction>(B))
12009       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
12010         return true;
12011   
12012   // Otherwise they may not be equivalent.
12013   return false;
12014 }
12015
12016 // If this instruction has two uses, one of which is a llvm.dbg.declare,
12017 // return the llvm.dbg.declare.
12018 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
12019   if (!V->hasNUses(2))
12020     return 0;
12021   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
12022        UI != E; ++UI) {
12023     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
12024       return DI;
12025     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
12026       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
12027         return DI;
12028       }
12029   }
12030   return 0;
12031 }
12032
12033 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
12034   Value *Val = SI.getOperand(0);
12035   Value *Ptr = SI.getOperand(1);
12036
12037   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
12038     EraseInstFromFunction(SI);
12039     ++NumCombined;
12040     return 0;
12041   }
12042   
12043   // If the RHS is an alloca with a single use, zapify the store, making the
12044   // alloca dead.
12045   // If the RHS is an alloca with a two uses, the other one being a 
12046   // llvm.dbg.declare, zapify the store and the declare, making the
12047   // alloca dead.  We must do this to prevent declare's from affecting
12048   // codegen.
12049   if (!SI.isVolatile()) {
12050     if (Ptr->hasOneUse()) {
12051       if (isa<AllocaInst>(Ptr)) {
12052         EraseInstFromFunction(SI);
12053         ++NumCombined;
12054         return 0;
12055       }
12056       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
12057         if (isa<AllocaInst>(GEP->getOperand(0))) {
12058           if (GEP->getOperand(0)->hasOneUse()) {
12059             EraseInstFromFunction(SI);
12060             ++NumCombined;
12061             return 0;
12062           }
12063           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
12064             EraseInstFromFunction(*DI);
12065             EraseInstFromFunction(SI);
12066             ++NumCombined;
12067             return 0;
12068           }
12069         }
12070       }
12071     }
12072     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
12073       EraseInstFromFunction(*DI);
12074       EraseInstFromFunction(SI);
12075       ++NumCombined;
12076       return 0;
12077     }
12078   }
12079
12080   // Attempt to improve the alignment.
12081   if (TD) {
12082     unsigned KnownAlign =
12083       GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
12084     if (KnownAlign >
12085         (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
12086                                   SI.getAlignment()))
12087       SI.setAlignment(KnownAlign);
12088   }
12089
12090   // Do really simple DSE, to catch cases where there are several consecutive
12091   // stores to the same location, separated by a few arithmetic operations. This
12092   // situation often occurs with bitfield accesses.
12093   BasicBlock::iterator BBI = &SI;
12094   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
12095        --ScanInsts) {
12096     --BBI;
12097     // Don't count debug info directives, lest they affect codegen,
12098     // and we skip pointer-to-pointer bitcasts, which are NOPs.
12099     // It is necessary for correctness to skip those that feed into a
12100     // llvm.dbg.declare, as these are not present when debugging is off.
12101     if (isa<DbgInfoIntrinsic>(BBI) ||
12102         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12103       ScanInsts++;
12104       continue;
12105     }    
12106     
12107     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
12108       // Prev store isn't volatile, and stores to the same location?
12109       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
12110                                                           SI.getOperand(1))) {
12111         ++NumDeadStore;
12112         ++BBI;
12113         EraseInstFromFunction(*PrevSI);
12114         continue;
12115       }
12116       break;
12117     }
12118     
12119     // If this is a load, we have to stop.  However, if the loaded value is from
12120     // the pointer we're loading and is producing the pointer we're storing,
12121     // then *this* store is dead (X = load P; store X -> P).
12122     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
12123       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
12124           !SI.isVolatile()) {
12125         EraseInstFromFunction(SI);
12126         ++NumCombined;
12127         return 0;
12128       }
12129       // Otherwise, this is a load from some other location.  Stores before it
12130       // may not be dead.
12131       break;
12132     }
12133     
12134     // Don't skip over loads or things that can modify memory.
12135     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
12136       break;
12137   }
12138   
12139   
12140   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
12141
12142   // store X, null    -> turns into 'unreachable' in SimplifyCFG
12143   if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
12144     if (!isa<UndefValue>(Val)) {
12145       SI.setOperand(0, UndefValue::get(Val->getType()));
12146       if (Instruction *U = dyn_cast<Instruction>(Val))
12147         Worklist.Add(U);  // Dropped a use.
12148       ++NumCombined;
12149     }
12150     return 0;  // Do not modify these!
12151   }
12152
12153   // store undef, Ptr -> noop
12154   if (isa<UndefValue>(Val)) {
12155     EraseInstFromFunction(SI);
12156     ++NumCombined;
12157     return 0;
12158   }
12159
12160   // If the pointer destination is a cast, see if we can fold the cast into the
12161   // source instead.
12162   if (isa<CastInst>(Ptr))
12163     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12164       return Res;
12165   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
12166     if (CE->isCast())
12167       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12168         return Res;
12169
12170   
12171   // If this store is the last instruction in the basic block (possibly
12172   // excepting debug info instructions and the pointer bitcasts that feed
12173   // into them), and if the block ends with an unconditional branch, try
12174   // to move it to the successor block.
12175   BBI = &SI; 
12176   do {
12177     ++BBI;
12178   } while (isa<DbgInfoIntrinsic>(BBI) ||
12179            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
12180   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
12181     if (BI->isUnconditional())
12182       if (SimplifyStoreAtEndOfBlock(SI))
12183         return 0;  // xform done!
12184   
12185   return 0;
12186 }
12187
12188 /// SimplifyStoreAtEndOfBlock - Turn things like:
12189 ///   if () { *P = v1; } else { *P = v2 }
12190 /// into a phi node with a store in the successor.
12191 ///
12192 /// Simplify things like:
12193 ///   *P = v1; if () { *P = v2; }
12194 /// into a phi node with a store in the successor.
12195 ///
12196 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12197   BasicBlock *StoreBB = SI.getParent();
12198   
12199   // Check to see if the successor block has exactly two incoming edges.  If
12200   // so, see if the other predecessor contains a store to the same location.
12201   // if so, insert a PHI node (if needed) and move the stores down.
12202   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
12203   
12204   // Determine whether Dest has exactly two predecessors and, if so, compute
12205   // the other predecessor.
12206   pred_iterator PI = pred_begin(DestBB);
12207   BasicBlock *OtherBB = 0;
12208   if (*PI != StoreBB)
12209     OtherBB = *PI;
12210   ++PI;
12211   if (PI == pred_end(DestBB))
12212     return false;
12213   
12214   if (*PI != StoreBB) {
12215     if (OtherBB)
12216       return false;
12217     OtherBB = *PI;
12218   }
12219   if (++PI != pred_end(DestBB))
12220     return false;
12221
12222   // Bail out if all the relevant blocks aren't distinct (this can happen,
12223   // for example, if SI is in an infinite loop)
12224   if (StoreBB == DestBB || OtherBB == DestBB)
12225     return false;
12226
12227   // Verify that the other block ends in a branch and is not otherwise empty.
12228   BasicBlock::iterator BBI = OtherBB->getTerminator();
12229   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12230   if (!OtherBr || BBI == OtherBB->begin())
12231     return false;
12232   
12233   // If the other block ends in an unconditional branch, check for the 'if then
12234   // else' case.  there is an instruction before the branch.
12235   StoreInst *OtherStore = 0;
12236   if (OtherBr->isUnconditional()) {
12237     --BBI;
12238     // Skip over debugging info.
12239     while (isa<DbgInfoIntrinsic>(BBI) ||
12240            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12241       if (BBI==OtherBB->begin())
12242         return false;
12243       --BBI;
12244     }
12245     // If this isn't a store, isn't a store to the same location, or if the
12246     // alignments differ, bail out.
12247     OtherStore = dyn_cast<StoreInst>(BBI);
12248     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
12249         OtherStore->getAlignment() != SI.getAlignment())
12250       return false;
12251   } else {
12252     // Otherwise, the other block ended with a conditional branch. If one of the
12253     // destinations is StoreBB, then we have the if/then case.
12254     if (OtherBr->getSuccessor(0) != StoreBB && 
12255         OtherBr->getSuccessor(1) != StoreBB)
12256       return false;
12257     
12258     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12259     // if/then triangle.  See if there is a store to the same ptr as SI that
12260     // lives in OtherBB.
12261     for (;; --BBI) {
12262       // Check to see if we find the matching store.
12263       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12264         if (OtherStore->getOperand(1) != SI.getOperand(1) ||
12265             OtherStore->getAlignment() != SI.getAlignment())
12266           return false;
12267         break;
12268       }
12269       // If we find something that may be using or overwriting the stored
12270       // value, or if we run out of instructions, we can't do the xform.
12271       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12272           BBI == OtherBB->begin())
12273         return false;
12274     }
12275     
12276     // In order to eliminate the store in OtherBr, we have to
12277     // make sure nothing reads or overwrites the stored value in
12278     // StoreBB.
12279     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12280       // FIXME: This should really be AA driven.
12281       if (I->mayReadFromMemory() || I->mayWriteToMemory())
12282         return false;
12283     }
12284   }
12285   
12286   // Insert a PHI node now if we need it.
12287   Value *MergedVal = OtherStore->getOperand(0);
12288   if (MergedVal != SI.getOperand(0)) {
12289     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12290     PN->reserveOperandSpace(2);
12291     PN->addIncoming(SI.getOperand(0), SI.getParent());
12292     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12293     MergedVal = InsertNewInstBefore(PN, DestBB->front());
12294   }
12295   
12296   // Advance to a place where it is safe to insert the new store and
12297   // insert it.
12298   BBI = DestBB->getFirstNonPHI();
12299   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12300                                     OtherStore->isVolatile(),
12301                                     SI.getAlignment()), *BBI);
12302   
12303   // Nuke the old stores.
12304   EraseInstFromFunction(SI);
12305   EraseInstFromFunction(*OtherStore);
12306   ++NumCombined;
12307   return true;
12308 }
12309
12310
12311 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12312   // Change br (not X), label True, label False to: br X, label False, True
12313   Value *X = 0;
12314   BasicBlock *TrueDest;
12315   BasicBlock *FalseDest;
12316   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
12317       !isa<Constant>(X)) {
12318     // Swap Destinations and condition...
12319     BI.setCondition(X);
12320     BI.setSuccessor(0, FalseDest);
12321     BI.setSuccessor(1, TrueDest);
12322     return &BI;
12323   }
12324
12325   // Cannonicalize fcmp_one -> fcmp_oeq
12326   FCmpInst::Predicate FPred; Value *Y;
12327   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12328                              TrueDest, FalseDest)) &&
12329       BI.getCondition()->hasOneUse())
12330     if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12331         FPred == FCmpInst::FCMP_OGE) {
12332       FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12333       Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12334       
12335       // Swap Destinations and condition.
12336       BI.setSuccessor(0, FalseDest);
12337       BI.setSuccessor(1, TrueDest);
12338       Worklist.Add(Cond);
12339       return &BI;
12340     }
12341
12342   // Cannonicalize icmp_ne -> icmp_eq
12343   ICmpInst::Predicate IPred;
12344   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12345                       TrueDest, FalseDest)) &&
12346       BI.getCondition()->hasOneUse())
12347     if (IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12348         IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12349         IPred == ICmpInst::ICMP_SGE) {
12350       ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12351       Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12352       // Swap Destinations and condition.
12353       BI.setSuccessor(0, FalseDest);
12354       BI.setSuccessor(1, TrueDest);
12355       Worklist.Add(Cond);
12356       return &BI;
12357     }
12358
12359   return 0;
12360 }
12361
12362 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12363   Value *Cond = SI.getCondition();
12364   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12365     if (I->getOpcode() == Instruction::Add)
12366       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12367         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12368         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12369           SI.setOperand(i,
12370                    ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
12371                                                 AddRHS));
12372         SI.setOperand(0, I->getOperand(0));
12373         Worklist.Add(I);
12374         return &SI;
12375       }
12376   }
12377   return 0;
12378 }
12379
12380 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12381   Value *Agg = EV.getAggregateOperand();
12382
12383   if (!EV.hasIndices())
12384     return ReplaceInstUsesWith(EV, Agg);
12385
12386   if (Constant *C = dyn_cast<Constant>(Agg)) {
12387     if (isa<UndefValue>(C))
12388       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12389       
12390     if (isa<ConstantAggregateZero>(C))
12391       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12392
12393     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12394       // Extract the element indexed by the first index out of the constant
12395       Value *V = C->getOperand(*EV.idx_begin());
12396       if (EV.getNumIndices() > 1)
12397         // Extract the remaining indices out of the constant indexed by the
12398         // first index
12399         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12400       else
12401         return ReplaceInstUsesWith(EV, V);
12402     }
12403     return 0; // Can't handle other constants
12404   } 
12405   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12406     // We're extracting from an insertvalue instruction, compare the indices
12407     const unsigned *exti, *exte, *insi, *inse;
12408     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12409          exte = EV.idx_end(), inse = IV->idx_end();
12410          exti != exte && insi != inse;
12411          ++exti, ++insi) {
12412       if (*insi != *exti)
12413         // The insert and extract both reference distinctly different elements.
12414         // This means the extract is not influenced by the insert, and we can
12415         // replace the aggregate operand of the extract with the aggregate
12416         // operand of the insert. i.e., replace
12417         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12418         // %E = extractvalue { i32, { i32 } } %I, 0
12419         // with
12420         // %E = extractvalue { i32, { i32 } } %A, 0
12421         return ExtractValueInst::Create(IV->getAggregateOperand(),
12422                                         EV.idx_begin(), EV.idx_end());
12423     }
12424     if (exti == exte && insi == inse)
12425       // Both iterators are at the end: Index lists are identical. Replace
12426       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12427       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12428       // with "i32 42"
12429       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12430     if (exti == exte) {
12431       // The extract list is a prefix of the insert list. i.e. replace
12432       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12433       // %E = extractvalue { i32, { i32 } } %I, 1
12434       // with
12435       // %X = extractvalue { i32, { i32 } } %A, 1
12436       // %E = insertvalue { i32 } %X, i32 42, 0
12437       // by switching the order of the insert and extract (though the
12438       // insertvalue should be left in, since it may have other uses).
12439       Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12440                                                  EV.idx_begin(), EV.idx_end());
12441       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12442                                      insi, inse);
12443     }
12444     if (insi == inse)
12445       // The insert list is a prefix of the extract list
12446       // We can simply remove the common indices from the extract and make it
12447       // operate on the inserted value instead of the insertvalue result.
12448       // i.e., replace
12449       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12450       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12451       // with
12452       // %E extractvalue { i32 } { i32 42 }, 0
12453       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12454                                       exti, exte);
12455   }
12456   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
12457     // We're extracting from an intrinsic, see if we're the only user, which
12458     // allows us to simplify multiple result intrinsics to simpler things that
12459     // just get one value..
12460     if (II->hasOneUse()) {
12461       // Check if we're grabbing the overflow bit or the result of a 'with
12462       // overflow' intrinsic.  If it's the latter we can remove the intrinsic
12463       // and replace it with a traditional binary instruction.
12464       switch (II->getIntrinsicID()) {
12465       case Intrinsic::uadd_with_overflow:
12466       case Intrinsic::sadd_with_overflow:
12467         if (*EV.idx_begin() == 0) {  // Normal result.
12468           Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12469           II->replaceAllUsesWith(UndefValue::get(II->getType()));
12470           EraseInstFromFunction(*II);
12471           return BinaryOperator::CreateAdd(LHS, RHS);
12472         }
12473         break;
12474       case Intrinsic::usub_with_overflow:
12475       case Intrinsic::ssub_with_overflow:
12476         if (*EV.idx_begin() == 0) {  // Normal result.
12477           Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12478           II->replaceAllUsesWith(UndefValue::get(II->getType()));
12479           EraseInstFromFunction(*II);
12480           return BinaryOperator::CreateSub(LHS, RHS);
12481         }
12482         break;
12483       case Intrinsic::umul_with_overflow:
12484       case Intrinsic::smul_with_overflow:
12485         if (*EV.idx_begin() == 0) {  // Normal result.
12486           Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12487           II->replaceAllUsesWith(UndefValue::get(II->getType()));
12488           EraseInstFromFunction(*II);
12489           return BinaryOperator::CreateMul(LHS, RHS);
12490         }
12491         break;
12492       default:
12493         break;
12494       }
12495     }
12496   }
12497   // Can't simplify extracts from other values. Note that nested extracts are
12498   // already simplified implicitely by the above (extract ( extract (insert) )
12499   // will be translated into extract ( insert ( extract ) ) first and then just
12500   // the value inserted, if appropriate).
12501   return 0;
12502 }
12503
12504 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12505 /// is to leave as a vector operation.
12506 static bool CheapToScalarize(Value *V, bool isConstant) {
12507   if (isa<ConstantAggregateZero>(V)) 
12508     return true;
12509   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12510     if (isConstant) return true;
12511     // If all elts are the same, we can extract.
12512     Constant *Op0 = C->getOperand(0);
12513     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12514       if (C->getOperand(i) != Op0)
12515         return false;
12516     return true;
12517   }
12518   Instruction *I = dyn_cast<Instruction>(V);
12519   if (!I) return false;
12520   
12521   // Insert element gets simplified to the inserted element or is deleted if
12522   // this is constant idx extract element and its a constant idx insertelt.
12523   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12524       isa<ConstantInt>(I->getOperand(2)))
12525     return true;
12526   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12527     return true;
12528   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12529     if (BO->hasOneUse() &&
12530         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12531          CheapToScalarize(BO->getOperand(1), isConstant)))
12532       return true;
12533   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12534     if (CI->hasOneUse() &&
12535         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12536          CheapToScalarize(CI->getOperand(1), isConstant)))
12537       return true;
12538   
12539   return false;
12540 }
12541
12542 /// Read and decode a shufflevector mask.
12543 ///
12544 /// It turns undef elements into values that are larger than the number of
12545 /// elements in the input.
12546 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12547   unsigned NElts = SVI->getType()->getNumElements();
12548   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12549     return std::vector<unsigned>(NElts, 0);
12550   if (isa<UndefValue>(SVI->getOperand(2)))
12551     return std::vector<unsigned>(NElts, 2*NElts);
12552
12553   std::vector<unsigned> Result;
12554   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12555   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12556     if (isa<UndefValue>(*i))
12557       Result.push_back(NElts*2);  // undef -> 8
12558     else
12559       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12560   return Result;
12561 }
12562
12563 /// FindScalarElement - Given a vector and an element number, see if the scalar
12564 /// value is already around as a register, for example if it were inserted then
12565 /// extracted from the vector.
12566 static Value *FindScalarElement(Value *V, unsigned EltNo,
12567                                 LLVMContext *Context) {
12568   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12569   const VectorType *PTy = cast<VectorType>(V->getType());
12570   unsigned Width = PTy->getNumElements();
12571   if (EltNo >= Width)  // Out of range access.
12572     return UndefValue::get(PTy->getElementType());
12573   
12574   if (isa<UndefValue>(V))
12575     return UndefValue::get(PTy->getElementType());
12576   else if (isa<ConstantAggregateZero>(V))
12577     return Constant::getNullValue(PTy->getElementType());
12578   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12579     return CP->getOperand(EltNo);
12580   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12581     // If this is an insert to a variable element, we don't know what it is.
12582     if (!isa<ConstantInt>(III->getOperand(2))) 
12583       return 0;
12584     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12585     
12586     // If this is an insert to the element we are looking for, return the
12587     // inserted value.
12588     if (EltNo == IIElt) 
12589       return III->getOperand(1);
12590     
12591     // Otherwise, the insertelement doesn't modify the value, recurse on its
12592     // vector input.
12593     return FindScalarElement(III->getOperand(0), EltNo, Context);
12594   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12595     unsigned LHSWidth =
12596       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12597     unsigned InEl = getShuffleMask(SVI)[EltNo];
12598     if (InEl < LHSWidth)
12599       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12600     else if (InEl < LHSWidth*2)
12601       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12602     else
12603       return UndefValue::get(PTy->getElementType());
12604   }
12605   
12606   // Otherwise, we don't know.
12607   return 0;
12608 }
12609
12610 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12611   // If vector val is undef, replace extract with scalar undef.
12612   if (isa<UndefValue>(EI.getOperand(0)))
12613     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12614
12615   // If vector val is constant 0, replace extract with scalar 0.
12616   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12617     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12618   
12619   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12620     // If vector val is constant with all elements the same, replace EI with
12621     // that element. When the elements are not identical, we cannot replace yet
12622     // (we do that below, but only when the index is constant).
12623     Constant *op0 = C->getOperand(0);
12624     for (unsigned i = 1; i != C->getNumOperands(); ++i)
12625       if (C->getOperand(i) != op0) {
12626         op0 = 0; 
12627         break;
12628       }
12629     if (op0)
12630       return ReplaceInstUsesWith(EI, op0);
12631   }
12632   
12633   // If extracting a specified index from the vector, see if we can recursively
12634   // find a previously computed scalar that was inserted into the vector.
12635   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12636     unsigned IndexVal = IdxC->getZExtValue();
12637     unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
12638       
12639     // If this is extracting an invalid index, turn this into undef, to avoid
12640     // crashing the code below.
12641     if (IndexVal >= VectorWidth)
12642       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12643     
12644     // This instruction only demands the single element from the input vector.
12645     // If the input vector has a single use, simplify it based on this use
12646     // property.
12647     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12648       APInt UndefElts(VectorWidth, 0);
12649       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12650       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12651                                                 DemandedMask, UndefElts)) {
12652         EI.setOperand(0, V);
12653         return &EI;
12654       }
12655     }
12656     
12657     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12658       return ReplaceInstUsesWith(EI, Elt);
12659     
12660     // If the this extractelement is directly using a bitcast from a vector of
12661     // the same number of elements, see if we can find the source element from
12662     // it.  In this case, we will end up needing to bitcast the scalars.
12663     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12664       if (const VectorType *VT = 
12665               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12666         if (VT->getNumElements() == VectorWidth)
12667           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12668                                              IndexVal, Context))
12669             return new BitCastInst(Elt, EI.getType());
12670     }
12671   }
12672   
12673   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12674     // Push extractelement into predecessor operation if legal and
12675     // profitable to do so
12676     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12677       if (I->hasOneUse() &&
12678           CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12679         Value *newEI0 =
12680           Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12681                                         EI.getName()+".lhs");
12682         Value *newEI1 =
12683           Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12684                                         EI.getName()+".rhs");
12685         return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12686       }
12687     } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12688       // Extracting the inserted element?
12689       if (IE->getOperand(2) == EI.getOperand(1))
12690         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12691       // If the inserted and extracted elements are constants, they must not
12692       // be the same value, extract from the pre-inserted value instead.
12693       if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
12694         Worklist.AddValue(EI.getOperand(0));
12695         EI.setOperand(0, IE->getOperand(0));
12696         return &EI;
12697       }
12698     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12699       // If this is extracting an element from a shufflevector, figure out where
12700       // it came from and extract from the appropriate input element instead.
12701       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12702         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12703         Value *Src;
12704         unsigned LHSWidth =
12705           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12706
12707         if (SrcIdx < LHSWidth)
12708           Src = SVI->getOperand(0);
12709         else if (SrcIdx < LHSWidth*2) {
12710           SrcIdx -= LHSWidth;
12711           Src = SVI->getOperand(1);
12712         } else {
12713           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12714         }
12715         return ExtractElementInst::Create(Src,
12716                          ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12717                                           false));
12718       }
12719     }
12720     // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12721   }
12722   return 0;
12723 }
12724
12725 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12726 /// elements from either LHS or RHS, return the shuffle mask and true. 
12727 /// Otherwise, return false.
12728 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12729                                          std::vector<Constant*> &Mask,
12730                                          LLVMContext *Context) {
12731   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12732          "Invalid CollectSingleShuffleElements");
12733   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12734
12735   if (isa<UndefValue>(V)) {
12736     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12737     return true;
12738   } else if (V == LHS) {
12739     for (unsigned i = 0; i != NumElts; ++i)
12740       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12741     return true;
12742   } else if (V == RHS) {
12743     for (unsigned i = 0; i != NumElts; ++i)
12744       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
12745     return true;
12746   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12747     // If this is an insert of an extract from some other vector, include it.
12748     Value *VecOp    = IEI->getOperand(0);
12749     Value *ScalarOp = IEI->getOperand(1);
12750     Value *IdxOp    = IEI->getOperand(2);
12751     
12752     if (!isa<ConstantInt>(IdxOp))
12753       return false;
12754     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12755     
12756     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12757       // Okay, we can handle this if the vector we are insertinting into is
12758       // transitively ok.
12759       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12760         // If so, update the mask to reflect the inserted undef.
12761         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
12762         return true;
12763       }      
12764     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12765       if (isa<ConstantInt>(EI->getOperand(1)) &&
12766           EI->getOperand(0)->getType() == V->getType()) {
12767         unsigned ExtractedIdx =
12768           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12769         
12770         // This must be extracting from either LHS or RHS.
12771         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12772           // Okay, we can handle this if the vector we are insertinting into is
12773           // transitively ok.
12774           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12775             // If so, update the mask to reflect the inserted value.
12776             if (EI->getOperand(0) == LHS) {
12777               Mask[InsertedIdx % NumElts] = 
12778                  ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12779             } else {
12780               assert(EI->getOperand(0) == RHS);
12781               Mask[InsertedIdx % NumElts] = 
12782                 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
12783               
12784             }
12785             return true;
12786           }
12787         }
12788       }
12789     }
12790   }
12791   // TODO: Handle shufflevector here!
12792   
12793   return false;
12794 }
12795
12796 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12797 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12798 /// that computes V and the LHS value of the shuffle.
12799 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12800                                      Value *&RHS, LLVMContext *Context) {
12801   assert(isa<VectorType>(V->getType()) && 
12802          (RHS == 0 || V->getType() == RHS->getType()) &&
12803          "Invalid shuffle!");
12804   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12805
12806   if (isa<UndefValue>(V)) {
12807     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12808     return V;
12809   } else if (isa<ConstantAggregateZero>(V)) {
12810     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
12811     return V;
12812   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12813     // If this is an insert of an extract from some other vector, include it.
12814     Value *VecOp    = IEI->getOperand(0);
12815     Value *ScalarOp = IEI->getOperand(1);
12816     Value *IdxOp    = IEI->getOperand(2);
12817     
12818     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12819       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12820           EI->getOperand(0)->getType() == V->getType()) {
12821         unsigned ExtractedIdx =
12822           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12823         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12824         
12825         // Either the extracted from or inserted into vector must be RHSVec,
12826         // otherwise we'd end up with a shuffle of three inputs.
12827         if (EI->getOperand(0) == RHS || RHS == 0) {
12828           RHS = EI->getOperand(0);
12829           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12830           Mask[InsertedIdx % NumElts] = 
12831             ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
12832           return V;
12833         }
12834         
12835         if (VecOp == RHS) {
12836           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12837                                             RHS, Context);
12838           // Everything but the extracted element is replaced with the RHS.
12839           for (unsigned i = 0; i != NumElts; ++i) {
12840             if (i != InsertedIdx)
12841               Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
12842           }
12843           return V;
12844         }
12845         
12846         // If this insertelement is a chain that comes from exactly these two
12847         // vectors, return the vector and the effective shuffle.
12848         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12849                                          Context))
12850           return EI->getOperand(0);
12851         
12852       }
12853     }
12854   }
12855   // TODO: Handle shufflevector here!
12856   
12857   // Otherwise, can't do anything fancy.  Return an identity vector.
12858   for (unsigned i = 0; i != NumElts; ++i)
12859     Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12860   return V;
12861 }
12862
12863 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12864   Value *VecOp    = IE.getOperand(0);
12865   Value *ScalarOp = IE.getOperand(1);
12866   Value *IdxOp    = IE.getOperand(2);
12867   
12868   // Inserting an undef or into an undefined place, remove this.
12869   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12870     ReplaceInstUsesWith(IE, VecOp);
12871   
12872   // If the inserted element was extracted from some other vector, and if the 
12873   // indexes are constant, try to turn this into a shufflevector operation.
12874   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12875     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12876         EI->getOperand(0)->getType() == IE.getType()) {
12877       unsigned NumVectorElts = IE.getType()->getNumElements();
12878       unsigned ExtractedIdx =
12879         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12880       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12881       
12882       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12883         return ReplaceInstUsesWith(IE, VecOp);
12884       
12885       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12886         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12887       
12888       // If we are extracting a value from a vector, then inserting it right
12889       // back into the same place, just use the input vector.
12890       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12891         return ReplaceInstUsesWith(IE, VecOp);      
12892       
12893       // If this insertelement isn't used by some other insertelement, turn it
12894       // (and any insertelements it points to), into one big shuffle.
12895       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12896         std::vector<Constant*> Mask;
12897         Value *RHS = 0;
12898         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12899         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12900         // We now have a shuffle of LHS, RHS, Mask.
12901         return new ShuffleVectorInst(LHS, RHS,
12902                                      ConstantVector::get(Mask));
12903       }
12904     }
12905   }
12906
12907   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12908   APInt UndefElts(VWidth, 0);
12909   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12910   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12911     return &IE;
12912
12913   return 0;
12914 }
12915
12916
12917 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12918   Value *LHS = SVI.getOperand(0);
12919   Value *RHS = SVI.getOperand(1);
12920   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12921
12922   bool MadeChange = false;
12923
12924   // Undefined shuffle mask -> undefined value.
12925   if (isa<UndefValue>(SVI.getOperand(2)))
12926     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12927
12928   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12929
12930   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12931     return 0;
12932
12933   APInt UndefElts(VWidth, 0);
12934   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12935   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12936     LHS = SVI.getOperand(0);
12937     RHS = SVI.getOperand(1);
12938     MadeChange = true;
12939   }
12940   
12941   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12942   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12943   if (LHS == RHS || isa<UndefValue>(LHS)) {
12944     if (isa<UndefValue>(LHS) && LHS == RHS) {
12945       // shuffle(undef,undef,mask) -> undef.
12946       return ReplaceInstUsesWith(SVI, LHS);
12947     }
12948     
12949     // Remap any references to RHS to use LHS.
12950     std::vector<Constant*> Elts;
12951     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12952       if (Mask[i] >= 2*e)
12953         Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12954       else {
12955         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12956             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12957           Mask[i] = 2*e;     // Turn into undef.
12958           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12959         } else {
12960           Mask[i] = Mask[i] % e;  // Force to LHS.
12961           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
12962         }
12963       }
12964     }
12965     SVI.setOperand(0, SVI.getOperand(1));
12966     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12967     SVI.setOperand(2, ConstantVector::get(Elts));
12968     LHS = SVI.getOperand(0);
12969     RHS = SVI.getOperand(1);
12970     MadeChange = true;
12971   }
12972   
12973   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12974   bool isLHSID = true, isRHSID = true;
12975     
12976   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12977     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12978     // Is this an identity shuffle of the LHS value?
12979     isLHSID &= (Mask[i] == i);
12980       
12981     // Is this an identity shuffle of the RHS value?
12982     isRHSID &= (Mask[i]-e == i);
12983   }
12984
12985   // Eliminate identity shuffles.
12986   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12987   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12988   
12989   // If the LHS is a shufflevector itself, see if we can combine it with this
12990   // one without producing an unusual shuffle.  Here we are really conservative:
12991   // we are absolutely afraid of producing a shuffle mask not in the input
12992   // program, because the code gen may not be smart enough to turn a merged
12993   // shuffle into two specific shuffles: it may produce worse code.  As such,
12994   // we only merge two shuffles if the result is one of the two input shuffle
12995   // masks.  In this case, merging the shuffles just removes one instruction,
12996   // which we know is safe.  This is good for things like turning:
12997   // (splat(splat)) -> splat.
12998   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12999     if (isa<UndefValue>(RHS)) {
13000       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
13001
13002       std::vector<unsigned> NewMask;
13003       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
13004         if (Mask[i] >= 2*e)
13005           NewMask.push_back(2*e);
13006         else
13007           NewMask.push_back(LHSMask[Mask[i]]);
13008       
13009       // If the result mask is equal to the src shuffle or this shuffle mask, do
13010       // the replacement.
13011       if (NewMask == LHSMask || NewMask == Mask) {
13012         unsigned LHSInNElts =
13013           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
13014         std::vector<Constant*> Elts;
13015         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
13016           if (NewMask[i] >= LHSInNElts*2) {
13017             Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13018           } else {
13019             Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
13020           }
13021         }
13022         return new ShuffleVectorInst(LHSSVI->getOperand(0),
13023                                      LHSSVI->getOperand(1),
13024                                      ConstantVector::get(Elts));
13025       }
13026     }
13027   }
13028
13029   return MadeChange ? &SVI : 0;
13030 }
13031
13032
13033
13034
13035 /// TryToSinkInstruction - Try to move the specified instruction from its
13036 /// current block into the beginning of DestBlock, which can only happen if it's
13037 /// safe to move the instruction past all of the instructions between it and the
13038 /// end of its block.
13039 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
13040   assert(I->hasOneUse() && "Invariants didn't hold!");
13041
13042   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
13043   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
13044     return false;
13045
13046   // Do not sink alloca instructions out of the entry block.
13047   if (isa<AllocaInst>(I) && I->getParent() ==
13048         &DestBlock->getParent()->getEntryBlock())
13049     return false;
13050
13051   // We can only sink load instructions if there is nothing between the load and
13052   // the end of block that could change the value.
13053   if (I->mayReadFromMemory()) {
13054     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
13055          Scan != E; ++Scan)
13056       if (Scan->mayWriteToMemory())
13057         return false;
13058   }
13059
13060   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
13061
13062   CopyPrecedingStopPoint(I, InsertPos);
13063   I->moveBefore(InsertPos);
13064   ++NumSunkInst;
13065   return true;
13066 }
13067
13068
13069 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
13070 /// all reachable code to the worklist.
13071 ///
13072 /// This has a couple of tricks to make the code faster and more powerful.  In
13073 /// particular, we constant fold and DCE instructions as we go, to avoid adding
13074 /// them to the worklist (this significantly speeds up instcombine on code where
13075 /// many instructions are dead or constant).  Additionally, if we find a branch
13076 /// whose condition is a known constant, we only visit the reachable successors.
13077 ///
13078 static bool AddReachableCodeToWorklist(BasicBlock *BB, 
13079                                        SmallPtrSet<BasicBlock*, 64> &Visited,
13080                                        InstCombiner &IC,
13081                                        const TargetData *TD) {
13082   bool MadeIRChange = false;
13083   SmallVector<BasicBlock*, 256> Worklist;
13084   Worklist.push_back(BB);
13085   
13086   std::vector<Instruction*> InstrsForInstCombineWorklist;
13087   InstrsForInstCombineWorklist.reserve(128);
13088
13089   SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
13090   
13091   while (!Worklist.empty()) {
13092     BB = Worklist.back();
13093     Worklist.pop_back();
13094     
13095     // We have now visited this block!  If we've already been here, ignore it.
13096     if (!Visited.insert(BB)) continue;
13097
13098     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
13099       Instruction *Inst = BBI++;
13100       
13101       // DCE instruction if trivially dead.
13102       if (isInstructionTriviallyDead(Inst)) {
13103         ++NumDeadInst;
13104         DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
13105         Inst->eraseFromParent();
13106         continue;
13107       }
13108       
13109       // ConstantProp instruction if trivially constant.
13110       if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
13111         if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
13112           DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
13113                        << *Inst << '\n');
13114           Inst->replaceAllUsesWith(C);
13115           ++NumConstProp;
13116           Inst->eraseFromParent();
13117           continue;
13118         }
13119       
13120       
13121       
13122       if (TD) {
13123         // See if we can constant fold its operands.
13124         for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
13125              i != e; ++i) {
13126           ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
13127           if (CE == 0) continue;
13128           
13129           // If we already folded this constant, don't try again.
13130           if (!FoldedConstants.insert(CE))
13131             continue;
13132           
13133           Constant *NewC = ConstantFoldConstantExpression(CE, TD);
13134           if (NewC && NewC != CE) {
13135             *i = NewC;
13136             MadeIRChange = true;
13137           }
13138         }
13139       }
13140       
13141
13142       InstrsForInstCombineWorklist.push_back(Inst);
13143     }
13144
13145     // Recursively visit successors.  If this is a branch or switch on a
13146     // constant, only visit the reachable successor.
13147     TerminatorInst *TI = BB->getTerminator();
13148     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
13149       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
13150         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
13151         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
13152         Worklist.push_back(ReachableBB);
13153         continue;
13154       }
13155     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
13156       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
13157         // See if this is an explicit destination.
13158         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
13159           if (SI->getCaseValue(i) == Cond) {
13160             BasicBlock *ReachableBB = SI->getSuccessor(i);
13161             Worklist.push_back(ReachableBB);
13162             continue;
13163           }
13164         
13165         // Otherwise it is the default destination.
13166         Worklist.push_back(SI->getSuccessor(0));
13167         continue;
13168       }
13169     }
13170     
13171     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
13172       Worklist.push_back(TI->getSuccessor(i));
13173   }
13174   
13175   // Once we've found all of the instructions to add to instcombine's worklist,
13176   // add them in reverse order.  This way instcombine will visit from the top
13177   // of the function down.  This jives well with the way that it adds all uses
13178   // of instructions to the worklist after doing a transformation, thus avoiding
13179   // some N^2 behavior in pathological cases.
13180   IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
13181                               InstrsForInstCombineWorklist.size());
13182   
13183   return MadeIRChange;
13184 }
13185
13186 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
13187   MadeIRChange = false;
13188   
13189   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
13190         << F.getNameStr() << "\n");
13191
13192   {
13193     // Do a depth-first traversal of the function, populate the worklist with
13194     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
13195     // track of which blocks we visit.
13196     SmallPtrSet<BasicBlock*, 64> Visited;
13197     MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
13198
13199     // Do a quick scan over the function.  If we find any blocks that are
13200     // unreachable, remove any instructions inside of them.  This prevents
13201     // the instcombine code from having to deal with some bad special cases.
13202     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
13203       if (!Visited.count(BB)) {
13204         Instruction *Term = BB->getTerminator();
13205         while (Term != BB->begin()) {   // Remove instrs bottom-up
13206           BasicBlock::iterator I = Term; --I;
13207
13208           DEBUG(errs() << "IC: DCE: " << *I << '\n');
13209           // A debug intrinsic shouldn't force another iteration if we weren't
13210           // going to do one without it.
13211           if (!isa<DbgInfoIntrinsic>(I)) {
13212             ++NumDeadInst;
13213             MadeIRChange = true;
13214           }
13215
13216           // If I is not void type then replaceAllUsesWith undef.
13217           // This allows ValueHandlers and custom metadata to adjust itself.
13218           if (!I->getType()->isVoidTy())
13219             I->replaceAllUsesWith(UndefValue::get(I->getType()));
13220           I->eraseFromParent();
13221         }
13222       }
13223   }
13224
13225   while (!Worklist.isEmpty()) {
13226     Instruction *I = Worklist.RemoveOne();
13227     if (I == 0) continue;  // skip null values.
13228
13229     // Check to see if we can DCE the instruction.
13230     if (isInstructionTriviallyDead(I)) {
13231       DEBUG(errs() << "IC: DCE: " << *I << '\n');
13232       EraseInstFromFunction(*I);
13233       ++NumDeadInst;
13234       MadeIRChange = true;
13235       continue;
13236     }
13237
13238     // Instruction isn't dead, see if we can constant propagate it.
13239     if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
13240       if (Constant *C = ConstantFoldInstruction(I, TD)) {
13241         DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
13242
13243         // Add operands to the worklist.
13244         ReplaceInstUsesWith(*I, C);
13245         ++NumConstProp;
13246         EraseInstFromFunction(*I);
13247         MadeIRChange = true;
13248         continue;
13249       }
13250
13251     // See if we can trivially sink this instruction to a successor basic block.
13252     if (I->hasOneUse()) {
13253       BasicBlock *BB = I->getParent();
13254       Instruction *UserInst = cast<Instruction>(I->use_back());
13255       BasicBlock *UserParent;
13256       
13257       // Get the block the use occurs in.
13258       if (PHINode *PN = dyn_cast<PHINode>(UserInst))
13259         UserParent = PN->getIncomingBlock(I->use_begin().getUse());
13260       else
13261         UserParent = UserInst->getParent();
13262       
13263       if (UserParent != BB) {
13264         bool UserIsSuccessor = false;
13265         // See if the user is one of our successors.
13266         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13267           if (*SI == UserParent) {
13268             UserIsSuccessor = true;
13269             break;
13270           }
13271
13272         // If the user is one of our immediate successors, and if that successor
13273         // only has us as a predecessors (we'd have to split the critical edge
13274         // otherwise), we can keep going.
13275         if (UserIsSuccessor && UserParent->getSinglePredecessor())
13276           // Okay, the CFG is simple enough, try to sink this instruction.
13277           MadeIRChange |= TryToSinkInstruction(I, UserParent);
13278       }
13279     }
13280
13281     // Now that we have an instruction, try combining it to simplify it.
13282     Builder->SetInsertPoint(I->getParent(), I);
13283     
13284 #ifndef NDEBUG
13285     std::string OrigI;
13286 #endif
13287     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
13288     DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
13289
13290     if (Instruction *Result = visit(*I)) {
13291       ++NumCombined;
13292       // Should we replace the old instruction with a new one?
13293       if (Result != I) {
13294         DEBUG(errs() << "IC: Old = " << *I << '\n'
13295                      << "    New = " << *Result << '\n');
13296
13297         // Everything uses the new instruction now.
13298         I->replaceAllUsesWith(Result);
13299
13300         // Push the new instruction and any users onto the worklist.
13301         Worklist.Add(Result);
13302         Worklist.AddUsersToWorkList(*Result);
13303
13304         // Move the name to the new instruction first.
13305         Result->takeName(I);
13306
13307         // Insert the new instruction into the basic block...
13308         BasicBlock *InstParent = I->getParent();
13309         BasicBlock::iterator InsertPos = I;
13310
13311         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
13312           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13313             ++InsertPos;
13314
13315         InstParent->getInstList().insert(InsertPos, Result);
13316
13317         EraseInstFromFunction(*I);
13318       } else {
13319 #ifndef NDEBUG
13320         DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13321                      << "    New = " << *I << '\n');
13322 #endif
13323
13324         // If the instruction was modified, it's possible that it is now dead.
13325         // if so, remove it.
13326         if (isInstructionTriviallyDead(I)) {
13327           EraseInstFromFunction(*I);
13328         } else {
13329           Worklist.Add(I);
13330           Worklist.AddUsersToWorkList(*I);
13331         }
13332       }
13333       MadeIRChange = true;
13334     }
13335   }
13336
13337   Worklist.Zap();
13338   return MadeIRChange;
13339 }
13340
13341
13342 bool InstCombiner::runOnFunction(Function &F) {
13343   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13344   Context = &F.getContext();
13345   TD = getAnalysisIfAvailable<TargetData>();
13346
13347   
13348   /// Builder - This is an IRBuilder that automatically inserts new
13349   /// instructions into the worklist when they are created.
13350   IRBuilder<true, TargetFolder, InstCombineIRInserter> 
13351     TheBuilder(F.getContext(), TargetFolder(TD),
13352                InstCombineIRInserter(Worklist));
13353   Builder = &TheBuilder;
13354   
13355   bool EverMadeChange = false;
13356
13357   // Iterate while there is work to do.
13358   unsigned Iteration = 0;
13359   while (DoOneIteration(F, Iteration++))
13360     EverMadeChange = true;
13361   
13362   Builder = 0;
13363   return EverMadeChange;
13364 }
13365
13366 FunctionPass *llvm::createInstructionCombiningPass() {
13367   return new InstCombiner();
13368 }