InstructionCombining.cpp revision 212904
1//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// InstructionCombining - Combine instructions to form fewer, simple
11// instructions.  This pass does not modify the CFG.  This pass is where
12// algebraic simplification happens.
13//
14// This pass combines things like:
15//    %Y = add i32 %X, 1
16//    %Z = add i32 %Y, 1
17// into:
18//    %Z = add i32 %X, 2
19//
20// This is a simple worklist driven algorithm.
21//
22// This pass guarantees that the following canonicalizations are performed on
23// the program:
24//    1. If a binary operator has a constant operand, it is moved to the RHS
25//    2. Bitwise operators with constant operands are always grouped so that
26//       shifts are performed first, then or's, then and's, then xor's.
27//    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28//    4. All cmp instructions on boolean values are replaced with logical ops
29//    5. add X, X is represented as (X*2) => (X << 1)
30//    6. Multiplies with a power-of-two constant argument are transformed into
31//       shifts.
32//   ... etc.
33//
34//===----------------------------------------------------------------------===//
35
36#define DEBUG_TYPE "instcombine"
37#include "llvm/Transforms/Scalar.h"
38#include "InstCombine.h"
39#include "llvm/IntrinsicInst.h"
40#include "llvm/Analysis/ConstantFolding.h"
41#include "llvm/Analysis/InstructionSimplify.h"
42#include "llvm/Analysis/MemoryBuiltins.h"
43#include "llvm/Target/TargetData.h"
44#include "llvm/Transforms/Utils/Local.h"
45#include "llvm/Support/CFG.h"
46#include "llvm/Support/Debug.h"
47#include "llvm/Support/GetElementPtrTypeIterator.h"
48#include "llvm/Support/PatternMatch.h"
49#include "llvm/ADT/SmallPtrSet.h"
50#include "llvm/ADT/Statistic.h"
51#include <algorithm>
52#include <climits>
53using namespace llvm;
54using namespace llvm::PatternMatch;
55
56STATISTIC(NumCombined , "Number of insts combined");
57STATISTIC(NumConstProp, "Number of constant folds");
58STATISTIC(NumDeadInst , "Number of dead inst eliminated");
59STATISTIC(NumSunkInst , "Number of instructions sunk");
60
61
62char InstCombiner::ID = 0;
63INITIALIZE_PASS(InstCombiner, "instcombine",
64                "Combine redundant instructions", false, false);
65
66void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
67  AU.addPreservedID(LCSSAID);
68  AU.setPreservesCFG();
69}
70
71
72/// ShouldChangeType - Return true if it is desirable to convert a computation
73/// from 'From' to 'To'.  We don't want to convert from a legal to an illegal
74/// type for example, or from a smaller to a larger illegal type.
75bool InstCombiner::ShouldChangeType(const Type *From, const Type *To) const {
76  assert(From->isIntegerTy() && To->isIntegerTy());
77
78  // If we don't have TD, we don't know if the source/dest are legal.
79  if (!TD) return false;
80
81  unsigned FromWidth = From->getPrimitiveSizeInBits();
82  unsigned ToWidth = To->getPrimitiveSizeInBits();
83  bool FromLegal = TD->isLegalInteger(FromWidth);
84  bool ToLegal = TD->isLegalInteger(ToWidth);
85
86  // If this is a legal integer from type, and the result would be an illegal
87  // type, don't do the transformation.
88  if (FromLegal && !ToLegal)
89    return false;
90
91  // Otherwise, if both are illegal, do not increase the size of the result. We
92  // do allow things like i160 -> i64, but not i64 -> i160.
93  if (!FromLegal && !ToLegal && ToWidth > FromWidth)
94    return false;
95
96  return true;
97}
98
99
100// SimplifyCommutative - This performs a few simplifications for commutative
101// operators:
102//
103//  1. Order operands such that they are listed from right (least complex) to
104//     left (most complex).  This puts constants before unary operators before
105//     binary operators.
106//
107//  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
108//  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
109//
110bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
111  bool Changed = false;
112  if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
113    Changed = !I.swapOperands();
114
115  if (!I.isAssociative()) return Changed;
116
117  Instruction::BinaryOps Opcode = I.getOpcode();
118  if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
119    if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
120      if (isa<Constant>(I.getOperand(1))) {
121        Constant *Folded = ConstantExpr::get(I.getOpcode(),
122                                             cast<Constant>(I.getOperand(1)),
123                                             cast<Constant>(Op->getOperand(1)));
124        I.setOperand(0, Op->getOperand(0));
125        I.setOperand(1, Folded);
126        return true;
127      }
128
129      if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1)))
130        if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
131            Op->hasOneUse() && Op1->hasOneUse()) {
132          Constant *C1 = cast<Constant>(Op->getOperand(1));
133          Constant *C2 = cast<Constant>(Op1->getOperand(1));
134
135          // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
136          Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
137          Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
138                                                    Op1->getOperand(0),
139                                                    Op1->getName(), &I);
140          Worklist.Add(New);
141          I.setOperand(0, New);
142          I.setOperand(1, Folded);
143          return true;
144        }
145    }
146  return Changed;
147}
148
149// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
150// if the LHS is a constant zero (which is the 'negate' form).
151//
152Value *InstCombiner::dyn_castNegVal(Value *V) const {
153  if (BinaryOperator::isNeg(V))
154    return BinaryOperator::getNegArgument(V);
155
156  // Constants can be considered to be negated values if they can be folded.
157  if (ConstantInt *C = dyn_cast<ConstantInt>(V))
158    return ConstantExpr::getNeg(C);
159
160  if (ConstantVector *C = dyn_cast<ConstantVector>(V))
161    if (C->getType()->getElementType()->isIntegerTy())
162      return ConstantExpr::getNeg(C);
163
164  return 0;
165}
166
167// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
168// instruction if the LHS is a constant negative zero (which is the 'negate'
169// form).
170//
171Value *InstCombiner::dyn_castFNegVal(Value *V) const {
172  if (BinaryOperator::isFNeg(V))
173    return BinaryOperator::getFNegArgument(V);
174
175  // Constants can be considered to be negated values if they can be folded.
176  if (ConstantFP *C = dyn_cast<ConstantFP>(V))
177    return ConstantExpr::getFNeg(C);
178
179  if (ConstantVector *C = dyn_cast<ConstantVector>(V))
180    if (C->getType()->getElementType()->isFloatingPointTy())
181      return ConstantExpr::getFNeg(C);
182
183  return 0;
184}
185
186static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
187                                             InstCombiner *IC) {
188  if (CastInst *CI = dyn_cast<CastInst>(&I))
189    return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
190
191  // Figure out if the constant is the left or the right argument.
192  bool ConstIsRHS = isa<Constant>(I.getOperand(1));
193  Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
194
195  if (Constant *SOC = dyn_cast<Constant>(SO)) {
196    if (ConstIsRHS)
197      return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
198    return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
199  }
200
201  Value *Op0 = SO, *Op1 = ConstOperand;
202  if (!ConstIsRHS)
203    std::swap(Op0, Op1);
204
205  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
206    return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
207                                    SO->getName()+".op");
208  if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
209    return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
210                                   SO->getName()+".cmp");
211  if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
212    return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
213                                   SO->getName()+".cmp");
214  llvm_unreachable("Unknown binary instruction type!");
215}
216
217// FoldOpIntoSelect - Given an instruction with a select as one operand and a
218// constant as the other operand, try to fold the binary operator into the
219// select arguments.  This also works for Cast instructions, which obviously do
220// not have a second operand.
221Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
222  // Don't modify shared select instructions
223  if (!SI->hasOneUse()) return 0;
224  Value *TV = SI->getOperand(1);
225  Value *FV = SI->getOperand(2);
226
227  if (isa<Constant>(TV) || isa<Constant>(FV)) {
228    // Bool selects with constant operands can be folded to logical ops.
229    if (SI->getType()->isIntegerTy(1)) return 0;
230
231    Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
232    Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
233
234    return SelectInst::Create(SI->getCondition(), SelectTrueVal,
235                              SelectFalseVal);
236  }
237  return 0;
238}
239
240
241/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
242/// has a PHI node as operand #0, see if we can fold the instruction into the
243/// PHI (which is only possible if all operands to the PHI are constants).
244///
245/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
246/// that would normally be unprofitable because they strongly encourage jump
247/// threading.
248Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
249                                         bool AllowAggressive) {
250  AllowAggressive = false;
251  PHINode *PN = cast<PHINode>(I.getOperand(0));
252  unsigned NumPHIValues = PN->getNumIncomingValues();
253  if (NumPHIValues == 0 ||
254      // We normally only transform phis with a single use, unless we're trying
255      // hard to make jump threading happen.
256      (!PN->hasOneUse() && !AllowAggressive))
257    return 0;
258
259
260  // Check to see if all of the operands of the PHI are simple constants
261  // (constantint/constantfp/undef).  If there is one non-constant value,
262  // remember the BB it is in.  If there is more than one or if *it* is a PHI,
263  // bail out.  We don't do arbitrary constant expressions here because moving
264  // their computation can be expensive without a cost model.
265  BasicBlock *NonConstBB = 0;
266  for (unsigned i = 0; i != NumPHIValues; ++i)
267    if (!isa<Constant>(PN->getIncomingValue(i)) ||
268        isa<ConstantExpr>(PN->getIncomingValue(i))) {
269      if (NonConstBB) return 0;  // More than one non-const value.
270      if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
271      NonConstBB = PN->getIncomingBlock(i);
272
273      // If the incoming non-constant value is in I's block, we have an infinite
274      // loop.
275      if (NonConstBB == I.getParent())
276        return 0;
277    }
278
279  // If there is exactly one non-constant value, we can insert a copy of the
280  // operation in that block.  However, if this is a critical edge, we would be
281  // inserting the computation one some other paths (e.g. inside a loop).  Only
282  // do this if the pred block is unconditionally branching into the phi block.
283  if (NonConstBB != 0 && !AllowAggressive) {
284    BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
285    if (!BI || !BI->isUnconditional()) return 0;
286  }
287
288  // Okay, we can do the transformation: create the new PHI node.
289  PHINode *NewPN = PHINode::Create(I.getType(), "");
290  NewPN->reserveOperandSpace(PN->getNumOperands()/2);
291  InsertNewInstBefore(NewPN, *PN);
292  NewPN->takeName(PN);
293
294  // Next, add all of the operands to the PHI.
295  if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
296    // We only currently try to fold the condition of a select when it is a phi,
297    // not the true/false values.
298    Value *TrueV = SI->getTrueValue();
299    Value *FalseV = SI->getFalseValue();
300    BasicBlock *PhiTransBB = PN->getParent();
301    for (unsigned i = 0; i != NumPHIValues; ++i) {
302      BasicBlock *ThisBB = PN->getIncomingBlock(i);
303      Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
304      Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
305      Value *InV = 0;
306      if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
307        InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
308      } else {
309        assert(PN->getIncomingBlock(i) == NonConstBB);
310        InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
311                                 FalseVInPred,
312                                 "phitmp", NonConstBB->getTerminator());
313        Worklist.Add(cast<Instruction>(InV));
314      }
315      NewPN->addIncoming(InV, ThisBB);
316    }
317  } else if (I.getNumOperands() == 2) {
318    Constant *C = cast<Constant>(I.getOperand(1));
319    for (unsigned i = 0; i != NumPHIValues; ++i) {
320      Value *InV = 0;
321      if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
322        if (CmpInst *CI = dyn_cast<CmpInst>(&I))
323          InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
324        else
325          InV = ConstantExpr::get(I.getOpcode(), InC, C);
326      } else {
327        assert(PN->getIncomingBlock(i) == NonConstBB);
328        if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
329          InV = BinaryOperator::Create(BO->getOpcode(),
330                                       PN->getIncomingValue(i), C, "phitmp",
331                                       NonConstBB->getTerminator());
332        else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
333          InV = CmpInst::Create(CI->getOpcode(),
334                                CI->getPredicate(),
335                                PN->getIncomingValue(i), C, "phitmp",
336                                NonConstBB->getTerminator());
337        else
338          llvm_unreachable("Unknown binop!");
339
340        Worklist.Add(cast<Instruction>(InV));
341      }
342      NewPN->addIncoming(InV, PN->getIncomingBlock(i));
343    }
344  } else {
345    CastInst *CI = cast<CastInst>(&I);
346    const Type *RetTy = CI->getType();
347    for (unsigned i = 0; i != NumPHIValues; ++i) {
348      Value *InV;
349      if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
350        InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
351      } else {
352        assert(PN->getIncomingBlock(i) == NonConstBB);
353        InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
354                               I.getType(), "phitmp",
355                               NonConstBB->getTerminator());
356        Worklist.Add(cast<Instruction>(InV));
357      }
358      NewPN->addIncoming(InV, PN->getIncomingBlock(i));
359    }
360  }
361  return ReplaceInstUsesWith(I, NewPN);
362}
363
364/// FindElementAtOffset - Given a type and a constant offset, determine whether
365/// or not there is a sequence of GEP indices into the type that will land us at
366/// the specified offset.  If so, fill them into NewIndices and return the
367/// resultant element type, otherwise return null.
368const Type *InstCombiner::FindElementAtOffset(const Type *Ty, int64_t Offset,
369                                          SmallVectorImpl<Value*> &NewIndices) {
370  if (!TD) return 0;
371  if (!Ty->isSized()) return 0;
372
373  // Start with the index over the outer type.  Note that the type size
374  // might be zero (even if the offset isn't zero) if the indexed type
375  // is something like [0 x {int, int}]
376  const Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
377  int64_t FirstIdx = 0;
378  if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
379    FirstIdx = Offset/TySize;
380    Offset -= FirstIdx*TySize;
381
382    // Handle hosts where % returns negative instead of values [0..TySize).
383    if (Offset < 0) {
384      --FirstIdx;
385      Offset += TySize;
386      assert(Offset >= 0);
387    }
388    assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
389  }
390
391  NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
392
393  // Index into the types.  If we fail, set OrigBase to null.
394  while (Offset) {
395    // Indexing into tail padding between struct/array elements.
396    if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
397      return 0;
398
399    if (const StructType *STy = dyn_cast<StructType>(Ty)) {
400      const StructLayout *SL = TD->getStructLayout(STy);
401      assert(Offset < (int64_t)SL->getSizeInBytes() &&
402             "Offset must stay within the indexed type");
403
404      unsigned Elt = SL->getElementContainingOffset(Offset);
405      NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
406                                            Elt));
407
408      Offset -= SL->getElementOffset(Elt);
409      Ty = STy->getElementType(Elt);
410    } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
411      uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
412      assert(EltSize && "Cannot index into a zero-sized array");
413      NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
414      Offset %= EltSize;
415      Ty = AT->getElementType();
416    } else {
417      // Otherwise, we can't index into the middle of this atomic type, bail.
418      return 0;
419    }
420  }
421
422  return Ty;
423}
424
425
426
427Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
428  SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
429
430  if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
431    return ReplaceInstUsesWith(GEP, V);
432
433  Value *PtrOp = GEP.getOperand(0);
434
435  if (isa<UndefValue>(GEP.getOperand(0)))
436    return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
437
438  // Eliminate unneeded casts for indices.
439  if (TD) {
440    bool MadeChange = false;
441    unsigned PtrSize = TD->getPointerSizeInBits();
442
443    gep_type_iterator GTI = gep_type_begin(GEP);
444    for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
445         I != E; ++I, ++GTI) {
446      if (!isa<SequentialType>(*GTI)) continue;
447
448      // If we are using a wider index than needed for this platform, shrink it
449      // to what we need.  If narrower, sign-extend it to what we need.  This
450      // explicit cast can make subsequent optimizations more obvious.
451      unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
452      if (OpBits == PtrSize)
453        continue;
454
455      *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
456      MadeChange = true;
457    }
458    if (MadeChange) return &GEP;
459  }
460
461  // Combine Indices - If the source pointer to this getelementptr instruction
462  // is a getelementptr instruction, combine the indices of the two
463  // getelementptr instructions into a single instruction.
464  //
465  if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
466    // Note that if our source is a gep chain itself that we wait for that
467    // chain to be resolved before we perform this transformation.  This
468    // avoids us creating a TON of code in some cases.
469    //
470    if (GetElementPtrInst *SrcGEP =
471          dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
472      if (SrcGEP->getNumOperands() == 2)
473        return 0;   // Wait until our source is folded to completion.
474
475    SmallVector<Value*, 8> Indices;
476
477    // Find out whether the last index in the source GEP is a sequential idx.
478    bool EndsWithSequential = false;
479    for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
480         I != E; ++I)
481      EndsWithSequential = !(*I)->isStructTy();
482
483    // Can we combine the two pointer arithmetics offsets?
484    if (EndsWithSequential) {
485      // Replace: gep (gep %P, long B), long A, ...
486      // With:    T = long A+B; gep %P, T, ...
487      //
488      Value *Sum;
489      Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
490      Value *GO1 = GEP.getOperand(1);
491      if (SO1 == Constant::getNullValue(SO1->getType())) {
492        Sum = GO1;
493      } else if (GO1 == Constant::getNullValue(GO1->getType())) {
494        Sum = SO1;
495      } else {
496        // If they aren't the same type, then the input hasn't been processed
497        // by the loop above yet (which canonicalizes sequential index types to
498        // intptr_t).  Just avoid transforming this until the input has been
499        // normalized.
500        if (SO1->getType() != GO1->getType())
501          return 0;
502        Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
503      }
504
505      // Update the GEP in place if possible.
506      if (Src->getNumOperands() == 2) {
507        GEP.setOperand(0, Src->getOperand(0));
508        GEP.setOperand(1, Sum);
509        return &GEP;
510      }
511      Indices.append(Src->op_begin()+1, Src->op_end()-1);
512      Indices.push_back(Sum);
513      Indices.append(GEP.op_begin()+2, GEP.op_end());
514    } else if (isa<Constant>(*GEP.idx_begin()) &&
515               cast<Constant>(*GEP.idx_begin())->isNullValue() &&
516               Src->getNumOperands() != 1) {
517      // Otherwise we can do the fold if the first index of the GEP is a zero
518      Indices.append(Src->op_begin()+1, Src->op_end());
519      Indices.append(GEP.idx_begin()+1, GEP.idx_end());
520    }
521
522    if (!Indices.empty())
523      return (GEP.isInBounds() && Src->isInBounds()) ?
524        GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
525                                          Indices.end(), GEP.getName()) :
526        GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
527                                  Indices.end(), GEP.getName());
528  }
529
530  // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
531  Value *StrippedPtr = PtrOp->stripPointerCasts();
532  if (StrippedPtr != PtrOp) {
533    const PointerType *StrippedPtrTy =cast<PointerType>(StrippedPtr->getType());
534
535    bool HasZeroPointerIndex = false;
536    if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
537      HasZeroPointerIndex = C->isZero();
538
539    // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
540    // into     : GEP [10 x i8]* X, i32 0, ...
541    //
542    // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
543    //           into     : GEP i8* X, ...
544    //
545    // This occurs when the program declares an array extern like "int X[];"
546    if (HasZeroPointerIndex) {
547      const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
548      if (const ArrayType *CATy =
549          dyn_cast<ArrayType>(CPTy->getElementType())) {
550        // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
551        if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
552          // -> GEP i8* X, ...
553          SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
554          GetElementPtrInst *Res =
555            GetElementPtrInst::Create(StrippedPtr, Idx.begin(),
556                                      Idx.end(), GEP.getName());
557          Res->setIsInBounds(GEP.isInBounds());
558          return Res;
559        }
560
561        if (const ArrayType *XATy =
562              dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
563          // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
564          if (CATy->getElementType() == XATy->getElementType()) {
565            // -> GEP [10 x i8]* X, i32 0, ...
566            // At this point, we know that the cast source type is a pointer
567            // to an array of the same type as the destination pointer
568            // array.  Because the array type is never stepped over (there
569            // is a leading zero) we can fold the cast into this GEP.
570            GEP.setOperand(0, StrippedPtr);
571            return &GEP;
572          }
573        }
574      }
575    } else if (GEP.getNumOperands() == 2) {
576      // Transform things like:
577      // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
578      // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
579      const Type *SrcElTy = StrippedPtrTy->getElementType();
580      const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
581      if (TD && SrcElTy->isArrayTy() &&
582          TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
583          TD->getTypeAllocSize(ResElTy)) {
584        Value *Idx[2];
585        Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
586        Idx[1] = GEP.getOperand(1);
587        Value *NewGEP = GEP.isInBounds() ?
588          Builder->CreateInBoundsGEP(StrippedPtr, Idx, Idx + 2, GEP.getName()) :
589          Builder->CreateGEP(StrippedPtr, Idx, Idx + 2, GEP.getName());
590        // V and GEP are both pointer types --> BitCast
591        return new BitCastInst(NewGEP, GEP.getType());
592      }
593
594      // Transform things like:
595      // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
596      //   (where tmp = 8*tmp2) into:
597      // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
598
599      if (TD && SrcElTy->isArrayTy() && ResElTy->isIntegerTy(8)) {
600        uint64_t ArrayEltSize =
601            TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
602
603        // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
604        // allow either a mul, shift, or constant here.
605        Value *NewIdx = 0;
606        ConstantInt *Scale = 0;
607        if (ArrayEltSize == 1) {
608          NewIdx = GEP.getOperand(1);
609          Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
610        } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
611          NewIdx = ConstantInt::get(CI->getType(), 1);
612          Scale = CI;
613        } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
614          if (Inst->getOpcode() == Instruction::Shl &&
615              isa<ConstantInt>(Inst->getOperand(1))) {
616            ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
617            uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
618            Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
619                                     1ULL << ShAmtVal);
620            NewIdx = Inst->getOperand(0);
621          } else if (Inst->getOpcode() == Instruction::Mul &&
622                     isa<ConstantInt>(Inst->getOperand(1))) {
623            Scale = cast<ConstantInt>(Inst->getOperand(1));
624            NewIdx = Inst->getOperand(0);
625          }
626        }
627
628        // If the index will be to exactly the right offset with the scale taken
629        // out, perform the transformation. Note, we don't know whether Scale is
630        // signed or not. We'll use unsigned version of division/modulo
631        // operation after making sure Scale doesn't have the sign bit set.
632        if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
633            Scale->getZExtValue() % ArrayEltSize == 0) {
634          Scale = ConstantInt::get(Scale->getType(),
635                                   Scale->getZExtValue() / ArrayEltSize);
636          if (Scale->getZExtValue() != 1) {
637            Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
638                                                       false /*ZExt*/);
639            NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
640          }
641
642          // Insert the new GEP instruction.
643          Value *Idx[2];
644          Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
645          Idx[1] = NewIdx;
646          Value *NewGEP = GEP.isInBounds() ?
647            Builder->CreateInBoundsGEP(StrippedPtr, Idx, Idx + 2,GEP.getName()):
648            Builder->CreateGEP(StrippedPtr, Idx, Idx + 2, GEP.getName());
649          // The NewGEP must be pointer typed, so must the old one -> BitCast
650          return new BitCastInst(NewGEP, GEP.getType());
651        }
652      }
653    }
654  }
655
656  /// See if we can simplify:
657  ///   X = bitcast A* to B*
658  ///   Y = gep X, <...constant indices...>
659  /// into a gep of the original struct.  This is important for SROA and alias
660  /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
661  if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
662    if (TD &&
663        !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
664      // Determine how much the GEP moves the pointer.  We are guaranteed to get
665      // a constant back from EmitGEPOffset.
666      ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP));
667      int64_t Offset = OffsetV->getSExtValue();
668
669      // If this GEP instruction doesn't move the pointer, just replace the GEP
670      // with a bitcast of the real input to the dest type.
671      if (Offset == 0) {
672        // If the bitcast is of an allocation, and the allocation will be
673        // converted to match the type of the cast, don't touch this.
674        if (isa<AllocaInst>(BCI->getOperand(0)) ||
675            isMalloc(BCI->getOperand(0))) {
676          // See if the bitcast simplifies, if so, don't nuke this GEP yet.
677          if (Instruction *I = visitBitCast(*BCI)) {
678            if (I != BCI) {
679              I->takeName(BCI);
680              BCI->getParent()->getInstList().insert(BCI, I);
681              ReplaceInstUsesWith(*BCI, I);
682            }
683            return &GEP;
684          }
685        }
686        return new BitCastInst(BCI->getOperand(0), GEP.getType());
687      }
688
689      // Otherwise, if the offset is non-zero, we need to find out if there is a
690      // field at Offset in 'A's type.  If so, we can pull the cast through the
691      // GEP.
692      SmallVector<Value*, 8> NewIndices;
693      const Type *InTy =
694        cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
695      if (FindElementAtOffset(InTy, Offset, NewIndices)) {
696        Value *NGEP = GEP.isInBounds() ?
697          Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
698                                     NewIndices.end()) :
699          Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
700                             NewIndices.end());
701
702        if (NGEP->getType() == GEP.getType())
703          return ReplaceInstUsesWith(GEP, NGEP);
704        NGEP->takeName(&GEP);
705        return new BitCastInst(NGEP, GEP.getType());
706      }
707    }
708  }
709
710  return 0;
711}
712
713
714
715static bool IsOnlyNullComparedAndFreed(const Value &V) {
716  for (Value::const_use_iterator UI = V.use_begin(), UE = V.use_end();
717       UI != UE; ++UI) {
718    const User *U = *UI;
719    if (isFreeCall(U))
720      continue;
721    if (const ICmpInst *ICI = dyn_cast<ICmpInst>(U))
722      if (ICI->isEquality() && isa<ConstantPointerNull>(ICI->getOperand(1)))
723        continue;
724    return false;
725  }
726  return true;
727}
728
729Instruction *InstCombiner::visitMalloc(Instruction &MI) {
730  // If we have a malloc call which is only used in any amount of comparisons
731  // to null and free calls, delete the calls and replace the comparisons with
732  // true or false as appropriate.
733  if (IsOnlyNullComparedAndFreed(MI)) {
734    for (Value::use_iterator UI = MI.use_begin(), UE = MI.use_end();
735         UI != UE;) {
736      // We can assume that every remaining use is a free call or an icmp eq/ne
737      // to null, so the cast is safe.
738      Instruction *I = cast<Instruction>(*UI);
739
740      // Early increment here, as we're about to get rid of the user.
741      ++UI;
742
743      if (isFreeCall(I)) {
744        EraseInstFromFunction(*cast<CallInst>(I));
745        continue;
746      }
747      // Again, the cast is safe.
748      ICmpInst *C = cast<ICmpInst>(I);
749      ReplaceInstUsesWith(*C, ConstantInt::get(Type::getInt1Ty(C->getContext()),
750                                               C->isFalseWhenEqual()));
751      EraseInstFromFunction(*C);
752    }
753    return EraseInstFromFunction(MI);
754  }
755  return 0;
756}
757
758
759
760Instruction *InstCombiner::visitFree(CallInst &FI) {
761  Value *Op = FI.getArgOperand(0);
762
763  // free undef -> unreachable.
764  if (isa<UndefValue>(Op)) {
765    // Insert a new store to null because we cannot modify the CFG here.
766    new StoreInst(ConstantInt::getTrue(FI.getContext()),
767           UndefValue::get(Type::getInt1PtrTy(FI.getContext())), &FI);
768    return EraseInstFromFunction(FI);
769  }
770
771  // If we have 'free null' delete the instruction.  This can happen in stl code
772  // when lots of inlining happens.
773  if (isa<ConstantPointerNull>(Op))
774    return EraseInstFromFunction(FI);
775
776  return 0;
777}
778
779
780
781Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
782  // Change br (not X), label True, label False to: br X, label False, True
783  Value *X = 0;
784  BasicBlock *TrueDest;
785  BasicBlock *FalseDest;
786  if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
787      !isa<Constant>(X)) {
788    // Swap Destinations and condition...
789    BI.setCondition(X);
790    BI.setSuccessor(0, FalseDest);
791    BI.setSuccessor(1, TrueDest);
792    return &BI;
793  }
794
795  // Cannonicalize fcmp_one -> fcmp_oeq
796  FCmpInst::Predicate FPred; Value *Y;
797  if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
798                             TrueDest, FalseDest)) &&
799      BI.getCondition()->hasOneUse())
800    if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
801        FPred == FCmpInst::FCMP_OGE) {
802      FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
803      Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
804
805      // Swap Destinations and condition.
806      BI.setSuccessor(0, FalseDest);
807      BI.setSuccessor(1, TrueDest);
808      Worklist.Add(Cond);
809      return &BI;
810    }
811
812  // Cannonicalize icmp_ne -> icmp_eq
813  ICmpInst::Predicate IPred;
814  if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
815                      TrueDest, FalseDest)) &&
816      BI.getCondition()->hasOneUse())
817    if (IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
818        IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
819        IPred == ICmpInst::ICMP_SGE) {
820      ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
821      Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
822      // Swap Destinations and condition.
823      BI.setSuccessor(0, FalseDest);
824      BI.setSuccessor(1, TrueDest);
825      Worklist.Add(Cond);
826      return &BI;
827    }
828
829  return 0;
830}
831
832Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
833  Value *Cond = SI.getCondition();
834  if (Instruction *I = dyn_cast<Instruction>(Cond)) {
835    if (I->getOpcode() == Instruction::Add)
836      if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
837        // change 'switch (X+4) case 1:' into 'switch (X) case -3'
838        for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
839          SI.setOperand(i,
840                   ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
841                                                AddRHS));
842        SI.setOperand(0, I->getOperand(0));
843        Worklist.Add(I);
844        return &SI;
845      }
846  }
847  return 0;
848}
849
850Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
851  Value *Agg = EV.getAggregateOperand();
852
853  if (!EV.hasIndices())
854    return ReplaceInstUsesWith(EV, Agg);
855
856  if (Constant *C = dyn_cast<Constant>(Agg)) {
857    if (isa<UndefValue>(C))
858      return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
859
860    if (isa<ConstantAggregateZero>(C))
861      return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
862
863    if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
864      // Extract the element indexed by the first index out of the constant
865      Value *V = C->getOperand(*EV.idx_begin());
866      if (EV.getNumIndices() > 1)
867        // Extract the remaining indices out of the constant indexed by the
868        // first index
869        return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
870      else
871        return ReplaceInstUsesWith(EV, V);
872    }
873    return 0; // Can't handle other constants
874  }
875  if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
876    // We're extracting from an insertvalue instruction, compare the indices
877    const unsigned *exti, *exte, *insi, *inse;
878    for (exti = EV.idx_begin(), insi = IV->idx_begin(),
879         exte = EV.idx_end(), inse = IV->idx_end();
880         exti != exte && insi != inse;
881         ++exti, ++insi) {
882      if (*insi != *exti)
883        // The insert and extract both reference distinctly different elements.
884        // This means the extract is not influenced by the insert, and we can
885        // replace the aggregate operand of the extract with the aggregate
886        // operand of the insert. i.e., replace
887        // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
888        // %E = extractvalue { i32, { i32 } } %I, 0
889        // with
890        // %E = extractvalue { i32, { i32 } } %A, 0
891        return ExtractValueInst::Create(IV->getAggregateOperand(),
892                                        EV.idx_begin(), EV.idx_end());
893    }
894    if (exti == exte && insi == inse)
895      // Both iterators are at the end: Index lists are identical. Replace
896      // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
897      // %C = extractvalue { i32, { i32 } } %B, 1, 0
898      // with "i32 42"
899      return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
900    if (exti == exte) {
901      // The extract list is a prefix of the insert list. i.e. replace
902      // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
903      // %E = extractvalue { i32, { i32 } } %I, 1
904      // with
905      // %X = extractvalue { i32, { i32 } } %A, 1
906      // %E = insertvalue { i32 } %X, i32 42, 0
907      // by switching the order of the insert and extract (though the
908      // insertvalue should be left in, since it may have other uses).
909      Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
910                                                 EV.idx_begin(), EV.idx_end());
911      return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
912                                     insi, inse);
913    }
914    if (insi == inse)
915      // The insert list is a prefix of the extract list
916      // We can simply remove the common indices from the extract and make it
917      // operate on the inserted value instead of the insertvalue result.
918      // i.e., replace
919      // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
920      // %E = extractvalue { i32, { i32 } } %I, 1, 0
921      // with
922      // %E extractvalue { i32 } { i32 42 }, 0
923      return ExtractValueInst::Create(IV->getInsertedValueOperand(),
924                                      exti, exte);
925  }
926  if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
927    // We're extracting from an intrinsic, see if we're the only user, which
928    // allows us to simplify multiple result intrinsics to simpler things that
929    // just get one value.
930    if (II->hasOneUse()) {
931      // Check if we're grabbing the overflow bit or the result of a 'with
932      // overflow' intrinsic.  If it's the latter we can remove the intrinsic
933      // and replace it with a traditional binary instruction.
934      switch (II->getIntrinsicID()) {
935      case Intrinsic::uadd_with_overflow:
936      case Intrinsic::sadd_with_overflow:
937        if (*EV.idx_begin() == 0) {  // Normal result.
938          Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
939          II->replaceAllUsesWith(UndefValue::get(II->getType()));
940          EraseInstFromFunction(*II);
941          return BinaryOperator::CreateAdd(LHS, RHS);
942        }
943        break;
944      case Intrinsic::usub_with_overflow:
945      case Intrinsic::ssub_with_overflow:
946        if (*EV.idx_begin() == 0) {  // Normal result.
947          Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
948          II->replaceAllUsesWith(UndefValue::get(II->getType()));
949          EraseInstFromFunction(*II);
950          return BinaryOperator::CreateSub(LHS, RHS);
951        }
952        break;
953      case Intrinsic::umul_with_overflow:
954      case Intrinsic::smul_with_overflow:
955        if (*EV.idx_begin() == 0) {  // Normal result.
956          Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
957          II->replaceAllUsesWith(UndefValue::get(II->getType()));
958          EraseInstFromFunction(*II);
959          return BinaryOperator::CreateMul(LHS, RHS);
960        }
961        break;
962      default:
963        break;
964      }
965    }
966  }
967  // Can't simplify extracts from other values. Note that nested extracts are
968  // already simplified implicitely by the above (extract ( extract (insert) )
969  // will be translated into extract ( insert ( extract ) ) first and then just
970  // the value inserted, if appropriate).
971  return 0;
972}
973
974
975
976
977/// TryToSinkInstruction - Try to move the specified instruction from its
978/// current block into the beginning of DestBlock, which can only happen if it's
979/// safe to move the instruction past all of the instructions between it and the
980/// end of its block.
981static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
982  assert(I->hasOneUse() && "Invariants didn't hold!");
983
984  // Cannot move control-flow-involving, volatile loads, vaarg, etc.
985  if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
986    return false;
987
988  // Do not sink alloca instructions out of the entry block.
989  if (isa<AllocaInst>(I) && I->getParent() ==
990        &DestBlock->getParent()->getEntryBlock())
991    return false;
992
993  // We can only sink load instructions if there is nothing between the load and
994  // the end of block that could change the value.
995  if (I->mayReadFromMemory()) {
996    for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
997         Scan != E; ++Scan)
998      if (Scan->mayWriteToMemory())
999        return false;
1000  }
1001
1002  BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
1003
1004  I->moveBefore(InsertPos);
1005  ++NumSunkInst;
1006  return true;
1007}
1008
1009
1010/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
1011/// all reachable code to the worklist.
1012///
1013/// This has a couple of tricks to make the code faster and more powerful.  In
1014/// particular, we constant fold and DCE instructions as we go, to avoid adding
1015/// them to the worklist (this significantly speeds up instcombine on code where
1016/// many instructions are dead or constant).  Additionally, if we find a branch
1017/// whose condition is a known constant, we only visit the reachable successors.
1018///
1019static bool AddReachableCodeToWorklist(BasicBlock *BB,
1020                                       SmallPtrSet<BasicBlock*, 64> &Visited,
1021                                       InstCombiner &IC,
1022                                       const TargetData *TD) {
1023  bool MadeIRChange = false;
1024  SmallVector<BasicBlock*, 256> Worklist;
1025  Worklist.push_back(BB);
1026
1027  std::vector<Instruction*> InstrsForInstCombineWorklist;
1028  InstrsForInstCombineWorklist.reserve(128);
1029
1030  SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
1031
1032  do {
1033    BB = Worklist.pop_back_val();
1034
1035    // We have now visited this block!  If we've already been here, ignore it.
1036    if (!Visited.insert(BB)) continue;
1037
1038    for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
1039      Instruction *Inst = BBI++;
1040
1041      // DCE instruction if trivially dead.
1042      if (isInstructionTriviallyDead(Inst)) {
1043        ++NumDeadInst;
1044        DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
1045        Inst->eraseFromParent();
1046        continue;
1047      }
1048
1049      // ConstantProp instruction if trivially constant.
1050      if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
1051        if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
1052          DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
1053                       << *Inst << '\n');
1054          Inst->replaceAllUsesWith(C);
1055          ++NumConstProp;
1056          Inst->eraseFromParent();
1057          continue;
1058        }
1059
1060      if (TD) {
1061        // See if we can constant fold its operands.
1062        for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
1063             i != e; ++i) {
1064          ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
1065          if (CE == 0) continue;
1066
1067          // If we already folded this constant, don't try again.
1068          if (!FoldedConstants.insert(CE))
1069            continue;
1070
1071          Constant *NewC = ConstantFoldConstantExpression(CE, TD);
1072          if (NewC && NewC != CE) {
1073            *i = NewC;
1074            MadeIRChange = true;
1075          }
1076        }
1077      }
1078
1079      InstrsForInstCombineWorklist.push_back(Inst);
1080    }
1081
1082    // Recursively visit successors.  If this is a branch or switch on a
1083    // constant, only visit the reachable successor.
1084    TerminatorInst *TI = BB->getTerminator();
1085    if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1086      if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
1087        bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
1088        BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
1089        Worklist.push_back(ReachableBB);
1090        continue;
1091      }
1092    } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1093      if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
1094        // See if this is an explicit destination.
1095        for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
1096          if (SI->getCaseValue(i) == Cond) {
1097            BasicBlock *ReachableBB = SI->getSuccessor(i);
1098            Worklist.push_back(ReachableBB);
1099            continue;
1100          }
1101
1102        // Otherwise it is the default destination.
1103        Worklist.push_back(SI->getSuccessor(0));
1104        continue;
1105      }
1106    }
1107
1108    for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
1109      Worklist.push_back(TI->getSuccessor(i));
1110  } while (!Worklist.empty());
1111
1112  // Once we've found all of the instructions to add to instcombine's worklist,
1113  // add them in reverse order.  This way instcombine will visit from the top
1114  // of the function down.  This jives well with the way that it adds all uses
1115  // of instructions to the worklist after doing a transformation, thus avoiding
1116  // some N^2 behavior in pathological cases.
1117  IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
1118                              InstrsForInstCombineWorklist.size());
1119
1120  return MadeIRChange;
1121}
1122
1123bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
1124  MadeIRChange = false;
1125
1126  DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
1127        << F.getNameStr() << "\n");
1128
1129  {
1130    // Do a depth-first traversal of the function, populate the worklist with
1131    // the reachable instructions.  Ignore blocks that are not reachable.  Keep
1132    // track of which blocks we visit.
1133    SmallPtrSet<BasicBlock*, 64> Visited;
1134    MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
1135
1136    // Do a quick scan over the function.  If we find any blocks that are
1137    // unreachable, remove any instructions inside of them.  This prevents
1138    // the instcombine code from having to deal with some bad special cases.
1139    for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1140      if (!Visited.count(BB)) {
1141        Instruction *Term = BB->getTerminator();
1142        while (Term != BB->begin()) {   // Remove instrs bottom-up
1143          BasicBlock::iterator I = Term; --I;
1144
1145          DEBUG(errs() << "IC: DCE: " << *I << '\n');
1146          // A debug intrinsic shouldn't force another iteration if we weren't
1147          // going to do one without it.
1148          if (!isa<DbgInfoIntrinsic>(I)) {
1149            ++NumDeadInst;
1150            MadeIRChange = true;
1151          }
1152
1153          // If I is not void type then replaceAllUsesWith undef.
1154          // This allows ValueHandlers and custom metadata to adjust itself.
1155          if (!I->getType()->isVoidTy())
1156            I->replaceAllUsesWith(UndefValue::get(I->getType()));
1157          I->eraseFromParent();
1158        }
1159      }
1160  }
1161
1162  while (!Worklist.isEmpty()) {
1163    Instruction *I = Worklist.RemoveOne();
1164    if (I == 0) continue;  // skip null values.
1165
1166    // Check to see if we can DCE the instruction.
1167    if (isInstructionTriviallyDead(I)) {
1168      DEBUG(errs() << "IC: DCE: " << *I << '\n');
1169      EraseInstFromFunction(*I);
1170      ++NumDeadInst;
1171      MadeIRChange = true;
1172      continue;
1173    }
1174
1175    // Instruction isn't dead, see if we can constant propagate it.
1176    if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
1177      if (Constant *C = ConstantFoldInstruction(I, TD)) {
1178        DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
1179
1180        // Add operands to the worklist.
1181        ReplaceInstUsesWith(*I, C);
1182        ++NumConstProp;
1183        EraseInstFromFunction(*I);
1184        MadeIRChange = true;
1185        continue;
1186      }
1187
1188    // See if we can trivially sink this instruction to a successor basic block.
1189    if (I->hasOneUse()) {
1190      BasicBlock *BB = I->getParent();
1191      Instruction *UserInst = cast<Instruction>(I->use_back());
1192      BasicBlock *UserParent;
1193
1194      // Get the block the use occurs in.
1195      if (PHINode *PN = dyn_cast<PHINode>(UserInst))
1196        UserParent = PN->getIncomingBlock(I->use_begin().getUse());
1197      else
1198        UserParent = UserInst->getParent();
1199
1200      if (UserParent != BB) {
1201        bool UserIsSuccessor = false;
1202        // See if the user is one of our successors.
1203        for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
1204          if (*SI == UserParent) {
1205            UserIsSuccessor = true;
1206            break;
1207          }
1208
1209        // If the user is one of our immediate successors, and if that successor
1210        // only has us as a predecessors (we'd have to split the critical edge
1211        // otherwise), we can keep going.
1212        if (UserIsSuccessor && UserParent->getSinglePredecessor())
1213          // Okay, the CFG is simple enough, try to sink this instruction.
1214          MadeIRChange |= TryToSinkInstruction(I, UserParent);
1215      }
1216    }
1217
1218    // Now that we have an instruction, try combining it to simplify it.
1219    Builder->SetInsertPoint(I->getParent(), I);
1220
1221#ifndef NDEBUG
1222    std::string OrigI;
1223#endif
1224    DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
1225    DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
1226
1227    if (Instruction *Result = visit(*I)) {
1228      ++NumCombined;
1229      // Should we replace the old instruction with a new one?
1230      if (Result != I) {
1231        DEBUG(errs() << "IC: Old = " << *I << '\n'
1232                     << "    New = " << *Result << '\n');
1233
1234        // Everything uses the new instruction now.
1235        I->replaceAllUsesWith(Result);
1236
1237        // Push the new instruction and any users onto the worklist.
1238        Worklist.Add(Result);
1239        Worklist.AddUsersToWorkList(*Result);
1240
1241        // Move the name to the new instruction first.
1242        Result->takeName(I);
1243
1244        // Insert the new instruction into the basic block...
1245        BasicBlock *InstParent = I->getParent();
1246        BasicBlock::iterator InsertPos = I;
1247
1248        if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
1249          while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
1250            ++InsertPos;
1251
1252        InstParent->getInstList().insert(InsertPos, Result);
1253
1254        EraseInstFromFunction(*I);
1255      } else {
1256#ifndef NDEBUG
1257        DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
1258                     << "    New = " << *I << '\n');
1259#endif
1260
1261        // If the instruction was modified, it's possible that it is now dead.
1262        // if so, remove it.
1263        if (isInstructionTriviallyDead(I)) {
1264          EraseInstFromFunction(*I);
1265        } else {
1266          Worklist.Add(I);
1267          Worklist.AddUsersToWorkList(*I);
1268        }
1269      }
1270      MadeIRChange = true;
1271    }
1272  }
1273
1274  Worklist.Zap();
1275  return MadeIRChange;
1276}
1277
1278
1279bool InstCombiner::runOnFunction(Function &F) {
1280  MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
1281  TD = getAnalysisIfAvailable<TargetData>();
1282
1283
1284  /// Builder - This is an IRBuilder that automatically inserts new
1285  /// instructions into the worklist when they are created.
1286  IRBuilder<true, TargetFolder, InstCombineIRInserter>
1287    TheBuilder(F.getContext(), TargetFolder(TD),
1288               InstCombineIRInserter(Worklist));
1289  Builder = &TheBuilder;
1290
1291  bool EverMadeChange = false;
1292
1293  // Iterate while there is work to do.
1294  unsigned Iteration = 0;
1295  while (DoOneIteration(F, Iteration++))
1296    EverMadeChange = true;
1297
1298  Builder = 0;
1299  return EverMadeChange;
1300}
1301
1302FunctionPass *llvm::createInstructionCombiningPass() {
1303  return new InstCombiner();
1304}
1305