LLVM API Documentation

InstructionCombining.cpp
Go to the documentation of this file.
00001 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // InstructionCombining - Combine instructions to form fewer, simple
00011 // instructions.  This pass does not modify the CFG.  This pass is where
00012 // algebraic simplification happens.
00013 //
00014 // This pass combines things like:
00015 //    %Y = add i32 %X, 1
00016 //    %Z = add i32 %Y, 1
00017 // into:
00018 //    %Z = add i32 %X, 2
00019 //
00020 // This is a simple worklist driven algorithm.
00021 //
00022 // This pass guarantees that the following canonicalizations are performed on
00023 // the program:
00024 //    1. If a binary operator has a constant operand, it is moved to the RHS
00025 //    2. Bitwise operators with constant operands are always grouped so that
00026 //       shifts are performed first, then or's, then and's, then xor's.
00027 //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
00028 //    4. All cmp instructions on boolean values are replaced with logical ops
00029 //    5. add X, X is represented as (X*2) => (X << 1)
00030 //    6. Multiplies with a power-of-two constant argument are transformed into
00031 //       shifts.
00032 //   ... etc.
00033 //
00034 //===----------------------------------------------------------------------===//
00035 
00036 #include "llvm/Transforms/Scalar.h"
00037 #include "InstCombine.h"
00038 #include "llvm-c/Initialization.h"
00039 #include "llvm/ADT/SmallPtrSet.h"
00040 #include "llvm/ADT/Statistic.h"
00041 #include "llvm/ADT/StringSwitch.h"
00042 #include "llvm/Analysis/ConstantFolding.h"
00043 #include "llvm/Analysis/InstructionSimplify.h"
00044 #include "llvm/Analysis/MemoryBuiltins.h"
00045 #include "llvm/IR/CFG.h"
00046 #include "llvm/IR/DataLayout.h"
00047 #include "llvm/IR/GetElementPtrTypeIterator.h"
00048 #include "llvm/IR/IntrinsicInst.h"
00049 #include "llvm/IR/PatternMatch.h"
00050 #include "llvm/IR/ValueHandle.h"
00051 #include "llvm/Support/CommandLine.h"
00052 #include "llvm/Support/Debug.h"
00053 #include "llvm/Target/TargetLibraryInfo.h"
00054 #include "llvm/Transforms/Utils/Local.h"
00055 #include <algorithm>
00056 #include <climits>
00057 using namespace llvm;
00058 using namespace llvm::PatternMatch;
00059 
00060 #define DEBUG_TYPE "instcombine"
00061 
00062 STATISTIC(NumCombined , "Number of insts combined");
00063 STATISTIC(NumConstProp, "Number of constant folds");
00064 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
00065 STATISTIC(NumSunkInst , "Number of instructions sunk");
00066 STATISTIC(NumExpand,    "Number of expansions");
00067 STATISTIC(NumFactor   , "Number of factorizations");
00068 STATISTIC(NumReassoc  , "Number of reassociations");
00069 
00070 static cl::opt<bool> UnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
00071                                    cl::init(false),
00072                                    cl::desc("Enable unsafe double to float "
00073                                             "shrinking for math lib calls"));
00074 
00075 // Initialization Routines
00076 void llvm::initializeInstCombine(PassRegistry &Registry) {
00077   initializeInstCombinerPass(Registry);
00078 }
00079 
00080 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
00081   initializeInstCombine(*unwrap(R));
00082 }
00083 
00084 char InstCombiner::ID = 0;
00085 INITIALIZE_PASS_BEGIN(InstCombiner, "instcombine",
00086                 "Combine redundant instructions", false, false)
00087 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
00088 INITIALIZE_PASS_END(InstCombiner, "instcombine",
00089                 "Combine redundant instructions", false, false)
00090 
00091 void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
00092   AU.setPreservesCFG();
00093   AU.addRequired<TargetLibraryInfo>();
00094 }
00095 
00096 
00097 Value *InstCombiner::EmitGEPOffset(User *GEP) {
00098   return llvm::EmitGEPOffset(Builder, *getDataLayout(), GEP);
00099 }
00100 
00101 /// ShouldChangeType - Return true if it is desirable to convert a computation
00102 /// from 'From' to 'To'.  We don't want to convert from a legal to an illegal
00103 /// type for example, or from a smaller to a larger illegal type.
00104 bool InstCombiner::ShouldChangeType(Type *From, Type *To) const {
00105   assert(From->isIntegerTy() && To->isIntegerTy());
00106 
00107   // If we don't have DL, we don't know if the source/dest are legal.
00108   if (!DL) return false;
00109 
00110   unsigned FromWidth = From->getPrimitiveSizeInBits();
00111   unsigned ToWidth = To->getPrimitiveSizeInBits();
00112   bool FromLegal = DL->isLegalInteger(FromWidth);
00113   bool ToLegal = DL->isLegalInteger(ToWidth);
00114 
00115   // If this is a legal integer from type, and the result would be an illegal
00116   // type, don't do the transformation.
00117   if (FromLegal && !ToLegal)
00118     return false;
00119 
00120   // Otherwise, if both are illegal, do not increase the size of the result. We
00121   // do allow things like i160 -> i64, but not i64 -> i160.
00122   if (!FromLegal && !ToLegal && ToWidth > FromWidth)
00123     return false;
00124 
00125   return true;
00126 }
00127 
00128 // Return true, if No Signed Wrap should be maintained for I.
00129 // The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
00130 // where both B and C should be ConstantInts, results in a constant that does
00131 // not overflow. This function only handles the Add and Sub opcodes. For
00132 // all other opcodes, the function conservatively returns false.
00133 static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
00134   OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
00135   if (!OBO || !OBO->hasNoSignedWrap()) {
00136     return false;
00137   }
00138 
00139   // We reason about Add and Sub Only.
00140   Instruction::BinaryOps Opcode = I.getOpcode();
00141   if (Opcode != Instruction::Add &&
00142       Opcode != Instruction::Sub) {
00143     return false;
00144   }
00145 
00146   ConstantInt *CB = dyn_cast<ConstantInt>(B);
00147   ConstantInt *CC = dyn_cast<ConstantInt>(C);
00148 
00149   if (!CB || !CC) {
00150     return false;
00151   }
00152 
00153   const APInt &BVal = CB->getValue();
00154   const APInt &CVal = CC->getValue();
00155   bool Overflow = false;
00156 
00157   if (Opcode == Instruction::Add) {
00158     BVal.sadd_ov(CVal, Overflow);
00159   } else {
00160     BVal.ssub_ov(CVal, Overflow);
00161   }
00162 
00163   return !Overflow;
00164 }
00165 
00166 /// Conservatively clears subclassOptionalData after a reassociation or
00167 /// commutation. We preserve fast-math flags when applicable as they can be
00168 /// preserved.
00169 static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {
00170   FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
00171   if (!FPMO) {
00172     I.clearSubclassOptionalData();
00173     return;
00174   }
00175 
00176   FastMathFlags FMF = I.getFastMathFlags();
00177   I.clearSubclassOptionalData();
00178   I.setFastMathFlags(FMF);
00179 }
00180 
00181 /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
00182 /// operators which are associative or commutative:
00183 //
00184 //  Commutative operators:
00185 //
00186 //  1. Order operands such that they are listed from right (least complex) to
00187 //     left (most complex).  This puts constants before unary operators before
00188 //     binary operators.
00189 //
00190 //  Associative operators:
00191 //
00192 //  2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
00193 //  3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
00194 //
00195 //  Associative and commutative operators:
00196 //
00197 //  4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
00198 //  5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
00199 //  6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
00200 //     if C1 and C2 are constants.
00201 //
00202 bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
00203   Instruction::BinaryOps Opcode = I.getOpcode();
00204   bool Changed = false;
00205 
00206   do {
00207     // Order operands such that they are listed from right (least complex) to
00208     // left (most complex).  This puts constants before unary operators before
00209     // binary operators.
00210     if (I.isCommutative() && getComplexity(I.getOperand(0)) <
00211         getComplexity(I.getOperand(1)))
00212       Changed = !I.swapOperands();
00213 
00214     BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
00215     BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
00216 
00217     if (I.isAssociative()) {
00218       // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
00219       if (Op0 && Op0->getOpcode() == Opcode) {
00220         Value *A = Op0->getOperand(0);
00221         Value *B = Op0->getOperand(1);
00222         Value *C = I.getOperand(1);
00223 
00224         // Does "B op C" simplify?
00225         if (Value *V = SimplifyBinOp(Opcode, B, C, DL)) {
00226           // It simplifies to V.  Form "A op V".
00227           I.setOperand(0, A);
00228           I.setOperand(1, V);
00229           // Conservatively clear the optional flags, since they may not be
00230           // preserved by the reassociation.
00231           if (MaintainNoSignedWrap(I, B, C) &&
00232               (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
00233             // Note: this is only valid because SimplifyBinOp doesn't look at
00234             // the operands to Op0.
00235             I.clearSubclassOptionalData();
00236             I.setHasNoSignedWrap(true);
00237           } else {
00238             ClearSubclassDataAfterReassociation(I);
00239           }
00240 
00241           Changed = true;
00242           ++NumReassoc;
00243           continue;
00244         }
00245       }
00246 
00247       // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
00248       if (Op1 && Op1->getOpcode() == Opcode) {
00249         Value *A = I.getOperand(0);
00250         Value *B = Op1->getOperand(0);
00251         Value *C = Op1->getOperand(1);
00252 
00253         // Does "A op B" simplify?
00254         if (Value *V = SimplifyBinOp(Opcode, A, B, DL)) {
00255           // It simplifies to V.  Form "V op C".
00256           I.setOperand(0, V);
00257           I.setOperand(1, C);
00258           // Conservatively clear the optional flags, since they may not be
00259           // preserved by the reassociation.
00260           ClearSubclassDataAfterReassociation(I);
00261           Changed = true;
00262           ++NumReassoc;
00263           continue;
00264         }
00265       }
00266     }
00267 
00268     if (I.isAssociative() && I.isCommutative()) {
00269       // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
00270       if (Op0 && Op0->getOpcode() == Opcode) {
00271         Value *A = Op0->getOperand(0);
00272         Value *B = Op0->getOperand(1);
00273         Value *C = I.getOperand(1);
00274 
00275         // Does "C op A" simplify?
00276         if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
00277           // It simplifies to V.  Form "V op B".
00278           I.setOperand(0, V);
00279           I.setOperand(1, B);
00280           // Conservatively clear the optional flags, since they may not be
00281           // preserved by the reassociation.
00282           ClearSubclassDataAfterReassociation(I);
00283           Changed = true;
00284           ++NumReassoc;
00285           continue;
00286         }
00287       }
00288 
00289       // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
00290       if (Op1 && Op1->getOpcode() == Opcode) {
00291         Value *A = I.getOperand(0);
00292         Value *B = Op1->getOperand(0);
00293         Value *C = Op1->getOperand(1);
00294 
00295         // Does "C op A" simplify?
00296         if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
00297           // It simplifies to V.  Form "B op V".
00298           I.setOperand(0, B);
00299           I.setOperand(1, V);
00300           // Conservatively clear the optional flags, since they may not be
00301           // preserved by the reassociation.
00302           ClearSubclassDataAfterReassociation(I);
00303           Changed = true;
00304           ++NumReassoc;
00305           continue;
00306         }
00307       }
00308 
00309       // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
00310       // if C1 and C2 are constants.
00311       if (Op0 && Op1 &&
00312           Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
00313           isa<Constant>(Op0->getOperand(1)) &&
00314           isa<Constant>(Op1->getOperand(1)) &&
00315           Op0->hasOneUse() && Op1->hasOneUse()) {
00316         Value *A = Op0->getOperand(0);
00317         Constant *C1 = cast<Constant>(Op0->getOperand(1));
00318         Value *B = Op1->getOperand(0);
00319         Constant *C2 = cast<Constant>(Op1->getOperand(1));
00320 
00321         Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
00322         BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
00323         if (isa<FPMathOperator>(New)) {
00324           FastMathFlags Flags = I.getFastMathFlags();
00325           Flags &= Op0->getFastMathFlags();
00326           Flags &= Op1->getFastMathFlags();
00327           New->setFastMathFlags(Flags);
00328         }
00329         InsertNewInstWith(New, I);
00330         New->takeName(Op1);
00331         I.setOperand(0, New);
00332         I.setOperand(1, Folded);
00333         // Conservatively clear the optional flags, since they may not be
00334         // preserved by the reassociation.
00335         ClearSubclassDataAfterReassociation(I);
00336 
00337         Changed = true;
00338         continue;
00339       }
00340     }
00341 
00342     // No further simplifications.
00343     return Changed;
00344   } while (1);
00345 }
00346 
00347 /// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
00348 /// "(X LOp Y) ROp (X LOp Z)".
00349 static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
00350                                      Instruction::BinaryOps ROp) {
00351   switch (LOp) {
00352   default:
00353     return false;
00354 
00355   case Instruction::And:
00356     // And distributes over Or and Xor.
00357     switch (ROp) {
00358     default:
00359       return false;
00360     case Instruction::Or:
00361     case Instruction::Xor:
00362       return true;
00363     }
00364 
00365   case Instruction::Mul:
00366     // Multiplication distributes over addition and subtraction.
00367     switch (ROp) {
00368     default:
00369       return false;
00370     case Instruction::Add:
00371     case Instruction::Sub:
00372       return true;
00373     }
00374 
00375   case Instruction::Or:
00376     // Or distributes over And.
00377     switch (ROp) {
00378     default:
00379       return false;
00380     case Instruction::And:
00381       return true;
00382     }
00383   }
00384 }
00385 
00386 /// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
00387 /// "(X ROp Z) LOp (Y ROp Z)".
00388 static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
00389                                      Instruction::BinaryOps ROp) {
00390   if (Instruction::isCommutative(ROp))
00391     return LeftDistributesOverRight(ROp, LOp);
00392   // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
00393   // but this requires knowing that the addition does not overflow and other
00394   // such subtleties.
00395   return false;
00396 }
00397 
00398 /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
00399 /// which some other binary operation distributes over either by factorizing
00400 /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
00401 /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
00402 /// a win).  Returns the simplified value, or null if it didn't simplify.
00403 Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
00404   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
00405   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
00406   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
00407   Instruction::BinaryOps TopLevelOpcode = I.getOpcode(); // op
00408 
00409   // Factorization.
00410   if (Op0 && Op1 && Op0->getOpcode() == Op1->getOpcode()) {
00411     // The instruction has the form "(A op' B) op (C op' D)".  Try to factorize
00412     // a common term.
00413     Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
00414     Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
00415     Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
00416 
00417     // Does "X op' Y" always equal "Y op' X"?
00418     bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
00419 
00420     // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
00421     if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
00422       // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
00423       // commutative case, "(A op' B) op (C op' A)"?
00424       if (A == C || (InnerCommutative && A == D)) {
00425         if (A != C)
00426           std::swap(C, D);
00427         // Consider forming "A op' (B op D)".
00428         // If "B op D" simplifies then it can be formed with no cost.
00429         Value *V = SimplifyBinOp(TopLevelOpcode, B, D, DL);
00430         // If "B op D" doesn't simplify then only go on if both of the existing
00431         // operations "A op' B" and "C op' D" will be zapped as no longer used.
00432         if (!V && Op0->hasOneUse() && Op1->hasOneUse())
00433           V = Builder->CreateBinOp(TopLevelOpcode, B, D, Op1->getName());
00434         if (V) {
00435           ++NumFactor;
00436           V = Builder->CreateBinOp(InnerOpcode, A, V);
00437           V->takeName(&I);
00438           return V;
00439         }
00440       }
00441 
00442     // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
00443     if (RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
00444       // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
00445       // commutative case, "(A op' B) op (B op' D)"?
00446       if (B == D || (InnerCommutative && B == C)) {
00447         if (B != D)
00448           std::swap(C, D);
00449         // Consider forming "(A op C) op' B".
00450         // If "A op C" simplifies then it can be formed with no cost.
00451         Value *V = SimplifyBinOp(TopLevelOpcode, A, C, DL);
00452         // If "A op C" doesn't simplify then only go on if both of the existing
00453         // operations "A op' B" and "C op' D" will be zapped as no longer used.
00454         if (!V && Op0->hasOneUse() && Op1->hasOneUse())
00455           V = Builder->CreateBinOp(TopLevelOpcode, A, C, Op0->getName());
00456         if (V) {
00457           ++NumFactor;
00458           V = Builder->CreateBinOp(InnerOpcode, V, B);
00459           V->takeName(&I);
00460           return V;
00461         }
00462       }
00463   }
00464 
00465   // Expansion.
00466   if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
00467     // The instruction has the form "(A op' B) op C".  See if expanding it out
00468     // to "(A op C) op' (B op C)" results in simplifications.
00469     Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
00470     Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
00471 
00472     // Do "A op C" and "B op C" both simplify?
00473     if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, DL))
00474       if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, DL)) {
00475         // They do! Return "L op' R".
00476         ++NumExpand;
00477         // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
00478         if ((L == A && R == B) ||
00479             (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
00480           return Op0;
00481         // Otherwise return "L op' R" if it simplifies.
00482         if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
00483           return V;
00484         // Otherwise, create a new instruction.
00485         C = Builder->CreateBinOp(InnerOpcode, L, R);
00486         C->takeName(&I);
00487         return C;
00488       }
00489   }
00490 
00491   if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
00492     // The instruction has the form "A op (B op' C)".  See if expanding it out
00493     // to "(A op B) op' (A op C)" results in simplifications.
00494     Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
00495     Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
00496 
00497     // Do "A op B" and "A op C" both simplify?
00498     if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, DL))
00499       if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, DL)) {
00500         // They do! Return "L op' R".
00501         ++NumExpand;
00502         // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
00503         if ((L == B && R == C) ||
00504             (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
00505           return Op1;
00506         // Otherwise return "L op' R" if it simplifies.
00507         if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
00508           return V;
00509         // Otherwise, create a new instruction.
00510         A = Builder->CreateBinOp(InnerOpcode, L, R);
00511         A->takeName(&I);
00512         return A;
00513       }
00514   }
00515 
00516   return 0;
00517 }
00518 
00519 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
00520 // if the LHS is a constant zero (which is the 'negate' form).
00521 //
00522 Value *InstCombiner::dyn_castNegVal(Value *V) const {
00523   if (BinaryOperator::isNeg(V))
00524     return BinaryOperator::getNegArgument(V);
00525 
00526   // Constants can be considered to be negated values if they can be folded.
00527   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
00528     return ConstantExpr::getNeg(C);
00529 
00530   if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
00531     if (C->getType()->getElementType()->isIntegerTy())
00532       return ConstantExpr::getNeg(C);
00533 
00534   return 0;
00535 }
00536 
00537 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
00538 // instruction if the LHS is a constant negative zero (which is the 'negate'
00539 // form).
00540 //
00541 Value *InstCombiner::dyn_castFNegVal(Value *V, bool IgnoreZeroSign) const {
00542   if (BinaryOperator::isFNeg(V, IgnoreZeroSign))
00543     return BinaryOperator::getFNegArgument(V);
00544 
00545   // Constants can be considered to be negated values if they can be folded.
00546   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
00547     return ConstantExpr::getFNeg(C);
00548 
00549   if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
00550     if (C->getType()->getElementType()->isFloatingPointTy())
00551       return ConstantExpr::getFNeg(C);
00552 
00553   return 0;
00554 }
00555 
00556 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
00557                                              InstCombiner *IC) {
00558   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
00559     return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
00560   }
00561 
00562   // Figure out if the constant is the left or the right argument.
00563   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
00564   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
00565 
00566   if (Constant *SOC = dyn_cast<Constant>(SO)) {
00567     if (ConstIsRHS)
00568       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
00569     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
00570   }
00571 
00572   Value *Op0 = SO, *Op1 = ConstOperand;
00573   if (!ConstIsRHS)
00574     std::swap(Op0, Op1);
00575 
00576   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) {
00577     Value *RI = IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
00578                                     SO->getName()+".op");
00579     Instruction *FPInst = dyn_cast<Instruction>(RI);
00580     if (FPInst && isa<FPMathOperator>(FPInst))
00581       FPInst->copyFastMathFlags(BO);
00582     return RI;
00583   }
00584   if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
00585     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
00586                                    SO->getName()+".cmp");
00587   if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
00588     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
00589                                    SO->getName()+".cmp");
00590   llvm_unreachable("Unknown binary instruction type!");
00591 }
00592 
00593 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
00594 // constant as the other operand, try to fold the binary operator into the
00595 // select arguments.  This also works for Cast instructions, which obviously do
00596 // not have a second operand.
00597 Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
00598   // Don't modify shared select instructions
00599   if (!SI->hasOneUse()) return 0;
00600   Value *TV = SI->getOperand(1);
00601   Value *FV = SI->getOperand(2);
00602 
00603   if (isa<Constant>(TV) || isa<Constant>(FV)) {
00604     // Bool selects with constant operands can be folded to logical ops.
00605     if (SI->getType()->isIntegerTy(1)) return 0;
00606 
00607     // If it's a bitcast involving vectors, make sure it has the same number of
00608     // elements on both sides.
00609     if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
00610       VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
00611       VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
00612 
00613       // Verify that either both or neither are vectors.
00614       if ((SrcTy == NULL) != (DestTy == NULL)) return 0;
00615       // If vectors, verify that they have the same number of elements.
00616       if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
00617         return 0;
00618     }
00619 
00620     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
00621     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
00622 
00623     return SelectInst::Create(SI->getCondition(),
00624                               SelectTrueVal, SelectFalseVal);
00625   }
00626   return 0;
00627 }
00628 
00629 
00630 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
00631 /// has a PHI node as operand #0, see if we can fold the instruction into the
00632 /// PHI (which is only possible if all operands to the PHI are constants).
00633 ///
00634 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
00635   PHINode *PN = cast<PHINode>(I.getOperand(0));
00636   unsigned NumPHIValues = PN->getNumIncomingValues();
00637   if (NumPHIValues == 0)
00638     return 0;
00639 
00640   // We normally only transform phis with a single use.  However, if a PHI has
00641   // multiple uses and they are all the same operation, we can fold *all* of the
00642   // uses into the PHI.
00643   if (!PN->hasOneUse()) {
00644     // Walk the use list for the instruction, comparing them to I.
00645     for (User *U : PN->users()) {
00646       Instruction *UI = cast<Instruction>(U);
00647       if (UI != &I && !I.isIdenticalTo(UI))
00648         return 0;
00649     }
00650     // Otherwise, we can replace *all* users with the new PHI we form.
00651   }
00652 
00653   // Check to see if all of the operands of the PHI are simple constants
00654   // (constantint/constantfp/undef).  If there is one non-constant value,
00655   // remember the BB it is in.  If there is more than one or if *it* is a PHI,
00656   // bail out.  We don't do arbitrary constant expressions here because moving
00657   // their computation can be expensive without a cost model.
00658   BasicBlock *NonConstBB = 0;
00659   for (unsigned i = 0; i != NumPHIValues; ++i) {
00660     Value *InVal = PN->getIncomingValue(i);
00661     if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
00662       continue;
00663 
00664     if (isa<PHINode>(InVal)) return 0;  // Itself a phi.
00665     if (NonConstBB) return 0;  // More than one non-const value.
00666 
00667     NonConstBB = PN->getIncomingBlock(i);
00668 
00669     // If the InVal is an invoke at the end of the pred block, then we can't
00670     // insert a computation after it without breaking the edge.
00671     if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
00672       if (II->getParent() == NonConstBB)
00673         return 0;
00674 
00675     // If the incoming non-constant value is in I's block, we will remove one
00676     // instruction, but insert another equivalent one, leading to infinite
00677     // instcombine.
00678     if (NonConstBB == I.getParent())
00679       return 0;
00680   }
00681 
00682   // If there is exactly one non-constant value, we can insert a copy of the
00683   // operation in that block.  However, if this is a critical edge, we would be
00684   // inserting the computation one some other paths (e.g. inside a loop).  Only
00685   // do this if the pred block is unconditionally branching into the phi block.
00686   if (NonConstBB != 0) {
00687     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
00688     if (!BI || !BI->isUnconditional()) return 0;
00689   }
00690 
00691   // Okay, we can do the transformation: create the new PHI node.
00692   PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
00693   InsertNewInstBefore(NewPN, *PN);
00694   NewPN->takeName(PN);
00695 
00696   // If we are going to have to insert a new computation, do so right before the
00697   // predecessors terminator.
00698   if (NonConstBB)
00699     Builder->SetInsertPoint(NonConstBB->getTerminator());
00700 
00701   // Next, add all of the operands to the PHI.
00702   if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
00703     // We only currently try to fold the condition of a select when it is a phi,
00704     // not the true/false values.
00705     Value *TrueV = SI->getTrueValue();
00706     Value *FalseV = SI->getFalseValue();
00707     BasicBlock *PhiTransBB = PN->getParent();
00708     for (unsigned i = 0; i != NumPHIValues; ++i) {
00709       BasicBlock *ThisBB = PN->getIncomingBlock(i);
00710       Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
00711       Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
00712       Value *InV = 0;
00713       // Beware of ConstantExpr:  it may eventually evaluate to getNullValue,
00714       // even if currently isNullValue gives false.
00715       Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i));
00716       if (InC && !isa<ConstantExpr>(InC))
00717         InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
00718       else
00719         InV = Builder->CreateSelect(PN->getIncomingValue(i),
00720                                     TrueVInPred, FalseVInPred, "phitmp");
00721       NewPN->addIncoming(InV, ThisBB);
00722     }
00723   } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
00724     Constant *C = cast<Constant>(I.getOperand(1));
00725     for (unsigned i = 0; i != NumPHIValues; ++i) {
00726       Value *InV = 0;
00727       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
00728         InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
00729       else if (isa<ICmpInst>(CI))
00730         InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
00731                                   C, "phitmp");
00732       else
00733         InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
00734                                   C, "phitmp");
00735       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
00736     }
00737   } else if (I.getNumOperands() == 2) {
00738     Constant *C = cast<Constant>(I.getOperand(1));
00739     for (unsigned i = 0; i != NumPHIValues; ++i) {
00740       Value *InV = 0;
00741       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
00742         InV = ConstantExpr::get(I.getOpcode(), InC, C);
00743       else
00744         InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
00745                                    PN->getIncomingValue(i), C, "phitmp");
00746       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
00747     }
00748   } else {
00749     CastInst *CI = cast<CastInst>(&I);
00750     Type *RetTy = CI->getType();
00751     for (unsigned i = 0; i != NumPHIValues; ++i) {
00752       Value *InV;
00753       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
00754         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
00755       else
00756         InV = Builder->CreateCast(CI->getOpcode(),
00757                                 PN->getIncomingValue(i), I.getType(), "phitmp");
00758       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
00759     }
00760   }
00761 
00762   for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
00763     Instruction *User = cast<Instruction>(*UI++);
00764     if (User == &I) continue;
00765     ReplaceInstUsesWith(*User, NewPN);
00766     EraseInstFromFunction(*User);
00767   }
00768   return ReplaceInstUsesWith(I, NewPN);
00769 }
00770 
00771 /// FindElementAtOffset - Given a pointer type and a constant offset, determine
00772 /// whether or not there is a sequence of GEP indices into the pointed type that
00773 /// will land us at the specified offset.  If so, fill them into NewIndices and
00774 /// return the resultant element type, otherwise return null.
00775 Type *InstCombiner::FindElementAtOffset(Type *PtrTy, int64_t Offset,
00776                                         SmallVectorImpl<Value*> &NewIndices) {
00777   assert(PtrTy->isPtrOrPtrVectorTy());
00778 
00779   if (!DL)
00780     return 0;
00781 
00782   Type *Ty = PtrTy->getPointerElementType();
00783   if (!Ty->isSized())
00784     return 0;
00785 
00786   // Start with the index over the outer type.  Note that the type size
00787   // might be zero (even if the offset isn't zero) if the indexed type
00788   // is something like [0 x {int, int}]
00789   Type *IntPtrTy = DL->getIntPtrType(PtrTy);
00790   int64_t FirstIdx = 0;
00791   if (int64_t TySize = DL->getTypeAllocSize(Ty)) {
00792     FirstIdx = Offset/TySize;
00793     Offset -= FirstIdx*TySize;
00794 
00795     // Handle hosts where % returns negative instead of values [0..TySize).
00796     if (Offset < 0) {
00797       --FirstIdx;
00798       Offset += TySize;
00799       assert(Offset >= 0);
00800     }
00801     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
00802   }
00803 
00804   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
00805 
00806   // Index into the types.  If we fail, set OrigBase to null.
00807   while (Offset) {
00808     // Indexing into tail padding between struct/array elements.
00809     if (uint64_t(Offset*8) >= DL->getTypeSizeInBits(Ty))
00810       return 0;
00811 
00812     if (StructType *STy = dyn_cast<StructType>(Ty)) {
00813       const StructLayout *SL = DL->getStructLayout(STy);
00814       assert(Offset < (int64_t)SL->getSizeInBytes() &&
00815              "Offset must stay within the indexed type");
00816 
00817       unsigned Elt = SL->getElementContainingOffset(Offset);
00818       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
00819                                             Elt));
00820 
00821       Offset -= SL->getElementOffset(Elt);
00822       Ty = STy->getElementType(Elt);
00823     } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
00824       uint64_t EltSize = DL->getTypeAllocSize(AT->getElementType());
00825       assert(EltSize && "Cannot index into a zero-sized array");
00826       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
00827       Offset %= EltSize;
00828       Ty = AT->getElementType();
00829     } else {
00830       // Otherwise, we can't index into the middle of this atomic type, bail.
00831       return 0;
00832     }
00833   }
00834 
00835   return Ty;
00836 }
00837 
00838 static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
00839   // If this GEP has only 0 indices, it is the same pointer as
00840   // Src. If Src is not a trivial GEP too, don't combine
00841   // the indices.
00842   if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
00843       !Src.hasOneUse())
00844     return false;
00845   return true;
00846 }
00847 
00848 /// Descale - Return a value X such that Val = X * Scale, or null if none.  If
00849 /// the multiplication is known not to overflow then NoSignedWrap is set.
00850 Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
00851   assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
00852   assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
00853          Scale.getBitWidth() && "Scale not compatible with value!");
00854 
00855   // If Val is zero or Scale is one then Val = Val * Scale.
00856   if (match(Val, m_Zero()) || Scale == 1) {
00857     NoSignedWrap = true;
00858     return Val;
00859   }
00860 
00861   // If Scale is zero then it does not divide Val.
00862   if (Scale.isMinValue())
00863     return 0;
00864 
00865   // Look through chains of multiplications, searching for a constant that is
00866   // divisible by Scale.  For example, descaling X*(Y*(Z*4)) by a factor of 4
00867   // will find the constant factor 4 and produce X*(Y*Z).  Descaling X*(Y*8) by
00868   // a factor of 4 will produce X*(Y*2).  The principle of operation is to bore
00869   // down from Val:
00870   //
00871   //     Val = M1 * X          ||   Analysis starts here and works down
00872   //      M1 = M2 * Y          ||   Doesn't descend into terms with more
00873   //      M2 =  Z * 4          \/   than one use
00874   //
00875   // Then to modify a term at the bottom:
00876   //
00877   //     Val = M1 * X
00878   //      M1 =  Z * Y          ||   Replaced M2 with Z
00879   //
00880   // Then to work back up correcting nsw flags.
00881 
00882   // Op - the term we are currently analyzing.  Starts at Val then drills down.
00883   // Replaced with its descaled value before exiting from the drill down loop.
00884   Value *Op = Val;
00885 
00886   // Parent - initially null, but after drilling down notes where Op came from.
00887   // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
00888   // 0'th operand of Val.
00889   std::pair<Instruction*, unsigned> Parent;
00890 
00891   // RequireNoSignedWrap - Set if the transform requires a descaling at deeper
00892   // levels that doesn't overflow.
00893   bool RequireNoSignedWrap = false;
00894 
00895   // logScale - log base 2 of the scale.  Negative if not a power of 2.
00896   int32_t logScale = Scale.exactLogBase2();
00897 
00898   for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
00899 
00900     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
00901       // If Op is a constant divisible by Scale then descale to the quotient.
00902       APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
00903       APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
00904       if (!Remainder.isMinValue())
00905         // Not divisible by Scale.
00906         return 0;
00907       // Replace with the quotient in the parent.
00908       Op = ConstantInt::get(CI->getType(), Quotient);
00909       NoSignedWrap = true;
00910       break;
00911     }
00912 
00913     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
00914 
00915       if (BO->getOpcode() == Instruction::Mul) {
00916         // Multiplication.
00917         NoSignedWrap = BO->hasNoSignedWrap();
00918         if (RequireNoSignedWrap && !NoSignedWrap)
00919           return 0;
00920 
00921         // There are three cases for multiplication: multiplication by exactly
00922         // the scale, multiplication by a constant different to the scale, and
00923         // multiplication by something else.
00924         Value *LHS = BO->getOperand(0);
00925         Value *RHS = BO->getOperand(1);
00926 
00927         if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
00928           // Multiplication by a constant.
00929           if (CI->getValue() == Scale) {
00930             // Multiplication by exactly the scale, replace the multiplication
00931             // by its left-hand side in the parent.
00932             Op = LHS;
00933             break;
00934           }
00935 
00936           // Otherwise drill down into the constant.
00937           if (!Op->hasOneUse())
00938             return 0;
00939 
00940           Parent = std::make_pair(BO, 1);
00941           continue;
00942         }
00943 
00944         // Multiplication by something else. Drill down into the left-hand side
00945         // since that's where the reassociate pass puts the good stuff.
00946         if (!Op->hasOneUse())
00947           return 0;
00948 
00949         Parent = std::make_pair(BO, 0);
00950         continue;
00951       }
00952 
00953       if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
00954           isa<ConstantInt>(BO->getOperand(1))) {
00955         // Multiplication by a power of 2.
00956         NoSignedWrap = BO->hasNoSignedWrap();
00957         if (RequireNoSignedWrap && !NoSignedWrap)
00958           return 0;
00959 
00960         Value *LHS = BO->getOperand(0);
00961         int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
00962           getLimitedValue(Scale.getBitWidth());
00963         // Op = LHS << Amt.
00964 
00965         if (Amt == logScale) {
00966           // Multiplication by exactly the scale, replace the multiplication
00967           // by its left-hand side in the parent.
00968           Op = LHS;
00969           break;
00970         }
00971         if (Amt < logScale || !Op->hasOneUse())
00972           return 0;
00973 
00974         // Multiplication by more than the scale.  Reduce the multiplying amount
00975         // by the scale in the parent.
00976         Parent = std::make_pair(BO, 1);
00977         Op = ConstantInt::get(BO->getType(), Amt - logScale);
00978         break;
00979       }
00980     }
00981 
00982     if (!Op->hasOneUse())
00983       return 0;
00984 
00985     if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
00986       if (Cast->getOpcode() == Instruction::SExt) {
00987         // Op is sign-extended from a smaller type, descale in the smaller type.
00988         unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
00989         APInt SmallScale = Scale.trunc(SmallSize);
00990         // Suppose Op = sext X, and we descale X as Y * SmallScale.  We want to
00991         // descale Op as (sext Y) * Scale.  In order to have
00992         //   sext (Y * SmallScale) = (sext Y) * Scale
00993         // some conditions need to hold however: SmallScale must sign-extend to
00994         // Scale and the multiplication Y * SmallScale should not overflow.
00995         if (SmallScale.sext(Scale.getBitWidth()) != Scale)
00996           // SmallScale does not sign-extend to Scale.
00997           return 0;
00998         assert(SmallScale.exactLogBase2() == logScale);
00999         // Require that Y * SmallScale must not overflow.
01000         RequireNoSignedWrap = true;
01001 
01002         // Drill down through the cast.
01003         Parent = std::make_pair(Cast, 0);
01004         Scale = SmallScale;
01005         continue;
01006       }
01007 
01008       if (Cast->getOpcode() == Instruction::Trunc) {
01009         // Op is truncated from a larger type, descale in the larger type.
01010         // Suppose Op = trunc X, and we descale X as Y * sext Scale.  Then
01011         //   trunc (Y * sext Scale) = (trunc Y) * Scale
01012         // always holds.  However (trunc Y) * Scale may overflow even if
01013         // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
01014         // from this point up in the expression (see later).
01015         if (RequireNoSignedWrap)
01016           return 0;
01017 
01018         // Drill down through the cast.
01019         unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
01020         Parent = std::make_pair(Cast, 0);
01021         Scale = Scale.sext(LargeSize);
01022         if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
01023           logScale = -1;
01024         assert(Scale.exactLogBase2() == logScale);
01025         continue;
01026       }
01027     }
01028 
01029     // Unsupported expression, bail out.
01030     return 0;
01031   }
01032 
01033   // We know that we can successfully descale, so from here on we can safely
01034   // modify the IR.  Op holds the descaled version of the deepest term in the
01035   // expression.  NoSignedWrap is 'true' if multiplying Op by Scale is known
01036   // not to overflow.
01037 
01038   if (!Parent.first)
01039     // The expression only had one term.
01040     return Op;
01041 
01042   // Rewrite the parent using the descaled version of its operand.
01043   assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
01044   assert(Op != Parent.first->getOperand(Parent.second) &&
01045          "Descaling was a no-op?");
01046   Parent.first->setOperand(Parent.second, Op);
01047   Worklist.Add(Parent.first);
01048 
01049   // Now work back up the expression correcting nsw flags.  The logic is based
01050   // on the following observation: if X * Y is known not to overflow as a signed
01051   // multiplication, and Y is replaced by a value Z with smaller absolute value,
01052   // then X * Z will not overflow as a signed multiplication either.  As we work
01053   // our way up, having NoSignedWrap 'true' means that the descaled value at the
01054   // current level has strictly smaller absolute value than the original.
01055   Instruction *Ancestor = Parent.first;
01056   do {
01057     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
01058       // If the multiplication wasn't nsw then we can't say anything about the
01059       // value of the descaled multiplication, and we have to clear nsw flags
01060       // from this point on up.
01061       bool OpNoSignedWrap = BO->hasNoSignedWrap();
01062       NoSignedWrap &= OpNoSignedWrap;
01063       if (NoSignedWrap != OpNoSignedWrap) {
01064         BO->setHasNoSignedWrap(NoSignedWrap);
01065         Worklist.Add(Ancestor);
01066       }
01067     } else if (Ancestor->getOpcode() == Instruction::Trunc) {
01068       // The fact that the descaled input to the trunc has smaller absolute
01069       // value than the original input doesn't tell us anything useful about
01070       // the absolute values of the truncations.
01071       NoSignedWrap = false;
01072     }
01073     assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
01074            "Failed to keep proper track of nsw flags while drilling down?");
01075 
01076     if (Ancestor == Val)
01077       // Got to the top, all done!
01078       return Val;
01079 
01080     // Move up one level in the expression.
01081     assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
01082     Ancestor = Ancestor->user_back();
01083   } while (1);
01084 }
01085 
01086 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
01087   SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
01088 
01089   if (Value *V = SimplifyGEPInst(Ops, DL))
01090     return ReplaceInstUsesWith(GEP, V);
01091 
01092   Value *PtrOp = GEP.getOperand(0);
01093 
01094   // Eliminate unneeded casts for indices, and replace indices which displace
01095   // by multiples of a zero size type with zero.
01096   if (DL) {
01097     bool MadeChange = false;
01098     Type *IntPtrTy = DL->getIntPtrType(GEP.getPointerOperandType());
01099 
01100     gep_type_iterator GTI = gep_type_begin(GEP);
01101     for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
01102          I != E; ++I, ++GTI) {
01103       // Skip indices into struct types.
01104       SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
01105       if (!SeqTy) continue;
01106 
01107       // If the element type has zero size then any index over it is equivalent
01108       // to an index of zero, so replace it with zero if it is not zero already.
01109       if (SeqTy->getElementType()->isSized() &&
01110           DL->getTypeAllocSize(SeqTy->getElementType()) == 0)
01111         if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
01112           *I = Constant::getNullValue(IntPtrTy);
01113           MadeChange = true;
01114         }
01115 
01116       Type *IndexTy = (*I)->getType();
01117       if (IndexTy != IntPtrTy) {
01118         // If we are using a wider index than needed for this platform, shrink
01119         // it to what we need.  If narrower, sign-extend it to what we need.
01120         // This explicit cast can make subsequent optimizations more obvious.
01121         *I = Builder->CreateIntCast(*I, IntPtrTy, true);
01122         MadeChange = true;
01123       }
01124     }
01125     if (MadeChange) return &GEP;
01126   }
01127 
01128   // Combine Indices - If the source pointer to this getelementptr instruction
01129   // is a getelementptr instruction, combine the indices of the two
01130   // getelementptr instructions into a single instruction.
01131   //
01132   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
01133     if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
01134       return 0;
01135 
01136     // Note that if our source is a gep chain itself then we wait for that
01137     // chain to be resolved before we perform this transformation.  This
01138     // avoids us creating a TON of code in some cases.
01139     if (GEPOperator *SrcGEP =
01140           dyn_cast<GEPOperator>(Src->getOperand(0)))
01141       if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
01142         return 0;   // Wait until our source is folded to completion.
01143 
01144     SmallVector<Value*, 8> Indices;
01145 
01146     // Find out whether the last index in the source GEP is a sequential idx.
01147     bool EndsWithSequential = false;
01148     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
01149          I != E; ++I)
01150       EndsWithSequential = !(*I)->isStructTy();
01151 
01152     // Can we combine the two pointer arithmetics offsets?
01153     if (EndsWithSequential) {
01154       // Replace: gep (gep %P, long B), long A, ...
01155       // With:    T = long A+B; gep %P, T, ...
01156       //
01157       Value *Sum;
01158       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
01159       Value *GO1 = GEP.getOperand(1);
01160       if (SO1 == Constant::getNullValue(SO1->getType())) {
01161         Sum = GO1;
01162       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
01163         Sum = SO1;
01164       } else {
01165         // If they aren't the same type, then the input hasn't been processed
01166         // by the loop above yet (which canonicalizes sequential index types to
01167         // intptr_t).  Just avoid transforming this until the input has been
01168         // normalized.
01169         if (SO1->getType() != GO1->getType())
01170           return 0;
01171         Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
01172       }
01173 
01174       // Update the GEP in place if possible.
01175       if (Src->getNumOperands() == 2) {
01176         GEP.setOperand(0, Src->getOperand(0));
01177         GEP.setOperand(1, Sum);
01178         return &GEP;
01179       }
01180       Indices.append(Src->op_begin()+1, Src->op_end()-1);
01181       Indices.push_back(Sum);
01182       Indices.append(GEP.op_begin()+2, GEP.op_end());
01183     } else if (isa<Constant>(*GEP.idx_begin()) &&
01184                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
01185                Src->getNumOperands() != 1) {
01186       // Otherwise we can do the fold if the first index of the GEP is a zero
01187       Indices.append(Src->op_begin()+1, Src->op_end());
01188       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
01189     }
01190 
01191     if (!Indices.empty())
01192       return (GEP.isInBounds() && Src->isInBounds()) ?
01193         GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices,
01194                                           GEP.getName()) :
01195         GetElementPtrInst::Create(Src->getOperand(0), Indices, GEP.getName());
01196   }
01197 
01198   // Canonicalize (gep i8* X, -(ptrtoint Y)) to (sub (ptrtoint X), (ptrtoint Y))
01199   // The GEP pattern is emitted by the SCEV expander for certain kinds of
01200   // pointer arithmetic.
01201   if (DL && GEP.getNumIndices() == 1 &&
01202       match(GEP.getOperand(1), m_Neg(m_PtrToInt(m_Value())))) {
01203     unsigned AS = GEP.getPointerAddressSpace();
01204     if (GEP.getType() == Builder->getInt8PtrTy(AS) &&
01205         GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
01206         DL->getPointerSizeInBits(AS)) {
01207       Operator *Index = cast<Operator>(GEP.getOperand(1));
01208       Value *PtrToInt = Builder->CreatePtrToInt(PtrOp, Index->getType());
01209       Value *NewSub = Builder->CreateSub(PtrToInt, Index->getOperand(1));
01210       return CastInst::Create(Instruction::IntToPtr, NewSub, GEP.getType());
01211     }
01212   }
01213 
01214   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
01215   Value *StrippedPtr = PtrOp->stripPointerCasts();
01216   PointerType *StrippedPtrTy = dyn_cast<PointerType>(StrippedPtr->getType());
01217 
01218   // We do not handle pointer-vector geps here.
01219   if (!StrippedPtrTy)
01220     return 0;
01221 
01222   if (StrippedPtr != PtrOp) {
01223     bool HasZeroPointerIndex = false;
01224     if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
01225       HasZeroPointerIndex = C->isZero();
01226 
01227     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
01228     // into     : GEP [10 x i8]* X, i32 0, ...
01229     //
01230     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
01231     //           into     : GEP i8* X, ...
01232     //
01233     // This occurs when the program declares an array extern like "int X[];"
01234     if (HasZeroPointerIndex) {
01235       PointerType *CPTy = cast<PointerType>(PtrOp->getType());
01236       if (ArrayType *CATy =
01237           dyn_cast<ArrayType>(CPTy->getElementType())) {
01238         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
01239         if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
01240           // -> GEP i8* X, ...
01241           SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
01242           GetElementPtrInst *Res =
01243             GetElementPtrInst::Create(StrippedPtr, Idx, GEP.getName());
01244           Res->setIsInBounds(GEP.isInBounds());
01245           if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
01246             return Res;
01247           // Insert Res, and create an addrspacecast.
01248           // e.g.,
01249           // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
01250           // ->
01251           // %0 = GEP i8 addrspace(1)* X, ...
01252           // addrspacecast i8 addrspace(1)* %0 to i8*
01253           return new AddrSpaceCastInst(Builder->Insert(Res), GEP.getType());
01254         }
01255 
01256         if (ArrayType *XATy =
01257               dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
01258           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
01259           if (CATy->getElementType() == XATy->getElementType()) {
01260             // -> GEP [10 x i8]* X, i32 0, ...
01261             // At this point, we know that the cast source type is a pointer
01262             // to an array of the same type as the destination pointer
01263             // array.  Because the array type is never stepped over (there
01264             // is a leading zero) we can fold the cast into this GEP.
01265             if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
01266               GEP.setOperand(0, StrippedPtr);
01267               return &GEP;
01268             }
01269             // Cannot replace the base pointer directly because StrippedPtr's
01270             // address space is different. Instead, create a new GEP followed by
01271             // an addrspacecast.
01272             // e.g.,
01273             // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
01274             //   i32 0, ...
01275             // ->
01276             // %0 = GEP [10 x i8] addrspace(1)* X, ...
01277             // addrspacecast i8 addrspace(1)* %0 to i8*
01278             SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
01279             Value *NewGEP = GEP.isInBounds() ?
01280               Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()) :
01281               Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
01282             return new AddrSpaceCastInst(NewGEP, GEP.getType());
01283           }
01284         }
01285       }
01286     } else if (GEP.getNumOperands() == 2) {
01287       // Transform things like:
01288       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
01289       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
01290       Type *SrcElTy = StrippedPtrTy->getElementType();
01291       Type *ResElTy = PtrOp->getType()->getPointerElementType();
01292       if (DL && SrcElTy->isArrayTy() &&
01293           DL->getTypeAllocSize(SrcElTy->getArrayElementType()) ==
01294           DL->getTypeAllocSize(ResElTy)) {
01295         Type *IdxType = DL->getIntPtrType(GEP.getType());
01296         Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
01297         Value *NewGEP = GEP.isInBounds() ?
01298           Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()) :
01299           Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
01300 
01301         // V and GEP are both pointer types --> BitCast
01302         if (StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace())
01303           return new BitCastInst(NewGEP, GEP.getType());
01304         return new AddrSpaceCastInst(NewGEP, GEP.getType());
01305       }
01306 
01307       // Transform things like:
01308       // %V = mul i64 %N, 4
01309       // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
01310       // into:  %t1 = getelementptr i32* %arr, i32 %N; bitcast
01311       if (DL && ResElTy->isSized() && SrcElTy->isSized()) {
01312         // Check that changing the type amounts to dividing the index by a scale
01313         // factor.
01314         uint64_t ResSize = DL->getTypeAllocSize(ResElTy);
01315         uint64_t SrcSize = DL->getTypeAllocSize(SrcElTy);
01316         if (ResSize && SrcSize % ResSize == 0) {
01317           Value *Idx = GEP.getOperand(1);
01318           unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
01319           uint64_t Scale = SrcSize / ResSize;
01320 
01321           // Earlier transforms ensure that the index has type IntPtrType, which
01322           // considerably simplifies the logic by eliminating implicit casts.
01323           assert(Idx->getType() == DL->getIntPtrType(GEP.getType()) &&
01324                  "Index not cast to pointer width?");
01325 
01326           bool NSW;
01327           if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
01328             // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
01329             // If the multiplication NewIdx * Scale may overflow then the new
01330             // GEP may not be "inbounds".
01331             Value *NewGEP = GEP.isInBounds() && NSW ?
01332               Builder->CreateInBoundsGEP(StrippedPtr, NewIdx, GEP.getName()) :
01333               Builder->CreateGEP(StrippedPtr, NewIdx, GEP.getName());
01334 
01335             // The NewGEP must be pointer typed, so must the old one -> BitCast
01336             if (StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace())
01337               return new BitCastInst(NewGEP, GEP.getType());
01338             return new AddrSpaceCastInst(NewGEP, GEP.getType());
01339           }
01340         }
01341       }
01342 
01343       // Similarly, transform things like:
01344       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
01345       //   (where tmp = 8*tmp2) into:
01346       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
01347       if (DL && ResElTy->isSized() && SrcElTy->isSized() &&
01348           SrcElTy->isArrayTy()) {
01349         // Check that changing to the array element type amounts to dividing the
01350         // index by a scale factor.
01351         uint64_t ResSize = DL->getTypeAllocSize(ResElTy);
01352         uint64_t ArrayEltSize
01353           = DL->getTypeAllocSize(SrcElTy->getArrayElementType());
01354         if (ResSize && ArrayEltSize % ResSize == 0) {
01355           Value *Idx = GEP.getOperand(1);
01356           unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
01357           uint64_t Scale = ArrayEltSize / ResSize;
01358 
01359           // Earlier transforms ensure that the index has type IntPtrType, which
01360           // considerably simplifies the logic by eliminating implicit casts.
01361           assert(Idx->getType() == DL->getIntPtrType(GEP.getType()) &&
01362                  "Index not cast to pointer width?");
01363 
01364           bool NSW;
01365           if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
01366             // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
01367             // If the multiplication NewIdx * Scale may overflow then the new
01368             // GEP may not be "inbounds".
01369             Value *Off[2] = {
01370               Constant::getNullValue(DL->getIntPtrType(GEP.getType())),
01371               NewIdx
01372             };
01373 
01374             Value *NewGEP = GEP.isInBounds() && NSW ?
01375               Builder->CreateInBoundsGEP(StrippedPtr, Off, GEP.getName()) :
01376               Builder->CreateGEP(StrippedPtr, Off, GEP.getName());
01377             // The NewGEP must be pointer typed, so must the old one -> BitCast
01378             if (StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace())
01379               return new BitCastInst(NewGEP, GEP.getType());
01380             return new AddrSpaceCastInst(NewGEP, GEP.getType());
01381           }
01382         }
01383       }
01384     }
01385   }
01386 
01387   if (!DL)
01388     return 0;
01389 
01390   /// See if we can simplify:
01391   ///   X = bitcast A* to B*
01392   ///   Y = gep X, <...constant indices...>
01393   /// into a gep of the original struct.  This is important for SROA and alias
01394   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
01395   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
01396     Value *Operand = BCI->getOperand(0);
01397     PointerType *OpType = cast<PointerType>(Operand->getType());
01398     unsigned OffsetBits = DL->getPointerTypeSizeInBits(OpType);
01399     APInt Offset(OffsetBits, 0);
01400     if (!isa<BitCastInst>(Operand) &&
01401         GEP.accumulateConstantOffset(*DL, Offset) &&
01402         StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace()) {
01403 
01404       // If this GEP instruction doesn't move the pointer, just replace the GEP
01405       // with a bitcast of the real input to the dest type.
01406       if (!Offset) {
01407         // If the bitcast is of an allocation, and the allocation will be
01408         // converted to match the type of the cast, don't touch this.
01409         if (isa<AllocaInst>(Operand) || isAllocationFn(Operand, TLI)) {
01410           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
01411           if (Instruction *I = visitBitCast(*BCI)) {
01412             if (I != BCI) {
01413               I->takeName(BCI);
01414               BCI->getParent()->getInstList().insert(BCI, I);
01415               ReplaceInstUsesWith(*BCI, I);
01416             }
01417             return &GEP;
01418           }
01419         }
01420         return new BitCastInst(Operand, GEP.getType());
01421       }
01422 
01423       // Otherwise, if the offset is non-zero, we need to find out if there is a
01424       // field at Offset in 'A's type.  If so, we can pull the cast through the
01425       // GEP.
01426       SmallVector<Value*, 8> NewIndices;
01427       if (FindElementAtOffset(OpType, Offset.getSExtValue(), NewIndices)) {
01428         Value *NGEP = GEP.isInBounds() ?
01429           Builder->CreateInBoundsGEP(Operand, NewIndices) :
01430           Builder->CreateGEP(Operand, NewIndices);
01431 
01432         if (NGEP->getType() == GEP.getType())
01433           return ReplaceInstUsesWith(GEP, NGEP);
01434         NGEP->takeName(&GEP);
01435         return new BitCastInst(NGEP, GEP.getType());
01436       }
01437     }
01438   }
01439 
01440   return 0;
01441 }
01442 
01443 static bool
01444 isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users,
01445                      const TargetLibraryInfo *TLI) {
01446   SmallVector<Instruction*, 4> Worklist;
01447   Worklist.push_back(AI);
01448 
01449   do {
01450     Instruction *PI = Worklist.pop_back_val();
01451     for (User *U : PI->users()) {
01452       Instruction *I = cast<Instruction>(U);
01453       switch (I->getOpcode()) {
01454       default:
01455         // Give up the moment we see something we can't handle.
01456         return false;
01457 
01458       case Instruction::BitCast:
01459       case Instruction::GetElementPtr:
01460         Users.push_back(I);
01461         Worklist.push_back(I);
01462         continue;
01463 
01464       case Instruction::ICmp: {
01465         ICmpInst *ICI = cast<ICmpInst>(I);
01466         // We can fold eq/ne comparisons with null to false/true, respectively.
01467         if (!ICI->isEquality() || !isa<ConstantPointerNull>(ICI->getOperand(1)))
01468           return false;
01469         Users.push_back(I);
01470         continue;
01471       }
01472 
01473       case Instruction::Call:
01474         // Ignore no-op and store intrinsics.
01475         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
01476           switch (II->getIntrinsicID()) {
01477           default:
01478             return false;
01479 
01480           case Intrinsic::memmove:
01481           case Intrinsic::memcpy:
01482           case Intrinsic::memset: {
01483             MemIntrinsic *MI = cast<MemIntrinsic>(II);
01484             if (MI->isVolatile() || MI->getRawDest() != PI)
01485               return false;
01486           }
01487           // fall through
01488           case Intrinsic::dbg_declare:
01489           case Intrinsic::dbg_value:
01490           case Intrinsic::invariant_start:
01491           case Intrinsic::invariant_end:
01492           case Intrinsic::lifetime_start:
01493           case Intrinsic::lifetime_end:
01494           case Intrinsic::objectsize:
01495             Users.push_back(I);
01496             continue;
01497           }
01498         }
01499 
01500         if (isFreeCall(I, TLI)) {
01501           Users.push_back(I);
01502           continue;
01503         }
01504         return false;
01505 
01506       case Instruction::Store: {
01507         StoreInst *SI = cast<StoreInst>(I);
01508         if (SI->isVolatile() || SI->getPointerOperand() != PI)
01509           return false;
01510         Users.push_back(I);
01511         continue;
01512       }
01513       }
01514       llvm_unreachable("missing a return?");
01515     }
01516   } while (!Worklist.empty());
01517   return true;
01518 }
01519 
01520 Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
01521   // If we have a malloc call which is only used in any amount of comparisons
01522   // to null and free calls, delete the calls and replace the comparisons with
01523   // true or false as appropriate.
01524   SmallVector<WeakVH, 64> Users;
01525   if (isAllocSiteRemovable(&MI, Users, TLI)) {
01526     for (unsigned i = 0, e = Users.size(); i != e; ++i) {
01527       Instruction *I = cast_or_null<Instruction>(&*Users[i]);
01528       if (!I) continue;
01529 
01530       if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
01531         ReplaceInstUsesWith(*C,
01532                             ConstantInt::get(Type::getInt1Ty(C->getContext()),
01533                                              C->isFalseWhenEqual()));
01534       } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
01535         ReplaceInstUsesWith(*I, UndefValue::get(I->getType()));
01536       } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
01537         if (II->getIntrinsicID() == Intrinsic::objectsize) {
01538           ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
01539           uint64_t DontKnow = CI->isZero() ? -1ULL : 0;
01540           ReplaceInstUsesWith(*I, ConstantInt::get(I->getType(), DontKnow));
01541         }
01542       }
01543       EraseInstFromFunction(*I);
01544     }
01545 
01546     if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
01547       // Replace invoke with a NOP intrinsic to maintain the original CFG
01548       Module *M = II->getParent()->getParent()->getParent();
01549       Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
01550       InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
01551                          None, "", II->getParent());
01552     }
01553     return EraseInstFromFunction(MI);
01554   }
01555   return 0;
01556 }
01557 
01558 /// \brief Move the call to free before a NULL test.
01559 ///
01560 /// Check if this free is accessed after its argument has been test
01561 /// against NULL (property 0).
01562 /// If yes, it is legal to move this call in its predecessor block.
01563 ///
01564 /// The move is performed only if the block containing the call to free
01565 /// will be removed, i.e.:
01566 /// 1. it has only one predecessor P, and P has two successors
01567 /// 2. it contains the call and an unconditional branch
01568 /// 3. its successor is the same as its predecessor's successor
01569 ///
01570 /// The profitability is out-of concern here and this function should
01571 /// be called only if the caller knows this transformation would be
01572 /// profitable (e.g., for code size).
01573 static Instruction *
01574 tryToMoveFreeBeforeNullTest(CallInst &FI) {
01575   Value *Op = FI.getArgOperand(0);
01576   BasicBlock *FreeInstrBB = FI.getParent();
01577   BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
01578 
01579   // Validate part of constraint #1: Only one predecessor
01580   // FIXME: We can extend the number of predecessor, but in that case, we
01581   //        would duplicate the call to free in each predecessor and it may
01582   //        not be profitable even for code size.
01583   if (!PredBB)
01584     return 0;
01585 
01586   // Validate constraint #2: Does this block contains only the call to
01587   //                         free and an unconditional branch?
01588   // FIXME: We could check if we can speculate everything in the
01589   //        predecessor block
01590   if (FreeInstrBB->size() != 2)
01591     return 0;
01592   BasicBlock *SuccBB;
01593   if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
01594     return 0;
01595 
01596   // Validate the rest of constraint #1 by matching on the pred branch.
01597   TerminatorInst *TI = PredBB->getTerminator();
01598   BasicBlock *TrueBB, *FalseBB;
01599   ICmpInst::Predicate Pred;
01600   if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
01601     return 0;
01602   if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
01603     return 0;
01604 
01605   // Validate constraint #3: Ensure the null case just falls through.
01606   if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
01607     return 0;
01608   assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
01609          "Broken CFG: missing edge from predecessor to successor");
01610 
01611   FI.moveBefore(TI);
01612   return &FI;
01613 }
01614 
01615 
01616 Instruction *InstCombiner::visitFree(CallInst &FI) {
01617   Value *Op = FI.getArgOperand(0);
01618 
01619   // free undef -> unreachable.
01620   if (isa<UndefValue>(Op)) {
01621     // Insert a new store to null because we cannot modify the CFG here.
01622     Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
01623                          UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
01624     return EraseInstFromFunction(FI);
01625   }
01626 
01627   // If we have 'free null' delete the instruction.  This can happen in stl code
01628   // when lots of inlining happens.
01629   if (isa<ConstantPointerNull>(Op))
01630     return EraseInstFromFunction(FI);
01631 
01632   // If we optimize for code size, try to move the call to free before the null
01633   // test so that simplify cfg can remove the empty block and dead code
01634   // elimination the branch. I.e., helps to turn something like:
01635   // if (foo) free(foo);
01636   // into
01637   // free(foo);
01638   if (MinimizeSize)
01639     if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
01640       return I;
01641 
01642   return 0;
01643 }
01644 
01645 
01646 
01647 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
01648   // Change br (not X), label True, label False to: br X, label False, True
01649   Value *X = 0;
01650   BasicBlock *TrueDest;
01651   BasicBlock *FalseDest;
01652   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
01653       !isa<Constant>(X)) {
01654     // Swap Destinations and condition...
01655     BI.setCondition(X);
01656     BI.swapSuccessors();
01657     return &BI;
01658   }
01659 
01660   // Canonicalize fcmp_one -> fcmp_oeq
01661   FCmpInst::Predicate FPred; Value *Y;
01662   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
01663                              TrueDest, FalseDest)) &&
01664       BI.getCondition()->hasOneUse())
01665     if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
01666         FPred == FCmpInst::FCMP_OGE) {
01667       FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
01668       Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
01669 
01670       // Swap Destinations and condition.
01671       BI.swapSuccessors();
01672       Worklist.Add(Cond);
01673       return &BI;
01674     }
01675 
01676   // Canonicalize icmp_ne -> icmp_eq
01677   ICmpInst::Predicate IPred;
01678   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
01679                       TrueDest, FalseDest)) &&
01680       BI.getCondition()->hasOneUse())
01681     if (IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
01682         IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
01683         IPred == ICmpInst::ICMP_SGE) {
01684       ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
01685       Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
01686       // Swap Destinations and condition.
01687       BI.swapSuccessors();
01688       Worklist.Add(Cond);
01689       return &BI;
01690     }
01691 
01692   return 0;
01693 }
01694 
01695 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
01696   Value *Cond = SI.getCondition();
01697   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
01698     if (I->getOpcode() == Instruction::Add)
01699       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
01700         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
01701         // Skip the first item since that's the default case.
01702         for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
01703              i != e; ++i) {
01704           ConstantInt* CaseVal = i.getCaseValue();
01705           Constant* NewCaseVal = ConstantExpr::getSub(cast<Constant>(CaseVal),
01706                                                       AddRHS);
01707           assert(isa<ConstantInt>(NewCaseVal) &&
01708                  "Result of expression should be constant");
01709           i.setValue(cast<ConstantInt>(NewCaseVal));
01710         }
01711         SI.setCondition(I->getOperand(0));
01712         Worklist.Add(I);
01713         return &SI;
01714       }
01715   }
01716   return 0;
01717 }
01718 
01719 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
01720   Value *Agg = EV.getAggregateOperand();
01721 
01722   if (!EV.hasIndices())
01723     return ReplaceInstUsesWith(EV, Agg);
01724 
01725   if (Constant *C = dyn_cast<Constant>(Agg)) {
01726     if (Constant *C2 = C->getAggregateElement(*EV.idx_begin())) {
01727       if (EV.getNumIndices() == 0)
01728         return ReplaceInstUsesWith(EV, C2);
01729       // Extract the remaining indices out of the constant indexed by the
01730       // first index
01731       return ExtractValueInst::Create(C2, EV.getIndices().slice(1));
01732     }
01733     return 0; // Can't handle other constants
01734   }
01735 
01736   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
01737     // We're extracting from an insertvalue instruction, compare the indices
01738     const unsigned *exti, *exte, *insi, *inse;
01739     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
01740          exte = EV.idx_end(), inse = IV->idx_end();
01741          exti != exte && insi != inse;
01742          ++exti, ++insi) {
01743       if (*insi != *exti)
01744         // The insert and extract both reference distinctly different elements.
01745         // This means the extract is not influenced by the insert, and we can
01746         // replace the aggregate operand of the extract with the aggregate
01747         // operand of the insert. i.e., replace
01748         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
01749         // %E = extractvalue { i32, { i32 } } %I, 0
01750         // with
01751         // %E = extractvalue { i32, { i32 } } %A, 0
01752         return ExtractValueInst::Create(IV->getAggregateOperand(),
01753                                         EV.getIndices());
01754     }
01755     if (exti == exte && insi == inse)
01756       // Both iterators are at the end: Index lists are identical. Replace
01757       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
01758       // %C = extractvalue { i32, { i32 } } %B, 1, 0
01759       // with "i32 42"
01760       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
01761     if (exti == exte) {
01762       // The extract list is a prefix of the insert list. i.e. replace
01763       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
01764       // %E = extractvalue { i32, { i32 } } %I, 1
01765       // with
01766       // %X = extractvalue { i32, { i32 } } %A, 1
01767       // %E = insertvalue { i32 } %X, i32 42, 0
01768       // by switching the order of the insert and extract (though the
01769       // insertvalue should be left in, since it may have other uses).
01770       Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
01771                                                  EV.getIndices());
01772       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
01773                                      makeArrayRef(insi, inse));
01774     }
01775     if (insi == inse)
01776       // The insert list is a prefix of the extract list
01777       // We can simply remove the common indices from the extract and make it
01778       // operate on the inserted value instead of the insertvalue result.
01779       // i.e., replace
01780       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
01781       // %E = extractvalue { i32, { i32 } } %I, 1, 0
01782       // with
01783       // %E extractvalue { i32 } { i32 42 }, 0
01784       return ExtractValueInst::Create(IV->getInsertedValueOperand(),
01785                                       makeArrayRef(exti, exte));
01786   }
01787   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
01788     // We're extracting from an intrinsic, see if we're the only user, which
01789     // allows us to simplify multiple result intrinsics to simpler things that
01790     // just get one value.
01791     if (II->hasOneUse()) {
01792       // Check if we're grabbing the overflow bit or the result of a 'with
01793       // overflow' intrinsic.  If it's the latter we can remove the intrinsic
01794       // and replace it with a traditional binary instruction.
01795       switch (II->getIntrinsicID()) {
01796       case Intrinsic::uadd_with_overflow:
01797       case Intrinsic::sadd_with_overflow:
01798         if (*EV.idx_begin() == 0) {  // Normal result.
01799           Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
01800           ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
01801           EraseInstFromFunction(*II);
01802           return BinaryOperator::CreateAdd(LHS, RHS);
01803         }
01804 
01805         // If the normal result of the add is dead, and the RHS is a constant,
01806         // we can transform this into a range comparison.
01807         // overflow = uadd a, -4  -->  overflow = icmp ugt a, 3
01808         if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
01809           if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
01810             return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
01811                                 ConstantExpr::getNot(CI));
01812         break;
01813       case Intrinsic::usub_with_overflow:
01814       case Intrinsic::ssub_with_overflow:
01815         if (*EV.idx_begin() == 0) {  // Normal result.
01816           Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
01817           ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
01818           EraseInstFromFunction(*II);
01819           return BinaryOperator::CreateSub(LHS, RHS);
01820         }
01821         break;
01822       case Intrinsic::umul_with_overflow:
01823       case Intrinsic::smul_with_overflow:
01824         if (*EV.idx_begin() == 0) {  // Normal result.
01825           Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
01826           ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
01827           EraseInstFromFunction(*II);
01828           return BinaryOperator::CreateMul(LHS, RHS);
01829         }
01830         break;
01831       default:
01832         break;
01833       }
01834     }
01835   }
01836   if (LoadInst *L = dyn_cast<LoadInst>(Agg))
01837     // If the (non-volatile) load only has one use, we can rewrite this to a
01838     // load from a GEP. This reduces the size of the load.
01839     // FIXME: If a load is used only by extractvalue instructions then this
01840     //        could be done regardless of having multiple uses.
01841     if (L->isSimple() && L->hasOneUse()) {
01842       // extractvalue has integer indices, getelementptr has Value*s. Convert.
01843       SmallVector<Value*, 4> Indices;
01844       // Prefix an i32 0 since we need the first element.
01845       Indices.push_back(Builder->getInt32(0));
01846       for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
01847             I != E; ++I)
01848         Indices.push_back(Builder->getInt32(*I));
01849 
01850       // We need to insert these at the location of the old load, not at that of
01851       // the extractvalue.
01852       Builder->SetInsertPoint(L->getParent(), L);
01853       Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(), Indices);
01854       // Returning the load directly will cause the main loop to insert it in
01855       // the wrong spot, so use ReplaceInstUsesWith().
01856       return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
01857     }
01858   // We could simplify extracts from other values. Note that nested extracts may
01859   // already be simplified implicitly by the above: extract (extract (insert) )
01860   // will be translated into extract ( insert ( extract ) ) first and then just
01861   // the value inserted, if appropriate. Similarly for extracts from single-use
01862   // loads: extract (extract (load)) will be translated to extract (load (gep))
01863   // and if again single-use then via load (gep (gep)) to load (gep).
01864   // However, double extracts from e.g. function arguments or return values
01865   // aren't handled yet.
01866   return 0;
01867 }
01868 
01869 enum Personality_Type {
01870   Unknown_Personality,
01871   GNU_Ada_Personality,
01872   GNU_CXX_Personality,
01873   GNU_ObjC_Personality
01874 };
01875 
01876 /// RecognizePersonality - See if the given exception handling personality
01877 /// function is one that we understand.  If so, return a description of it;
01878 /// otherwise return Unknown_Personality.
01879 static Personality_Type RecognizePersonality(Value *Pers) {
01880   Function *F = dyn_cast<Function>(Pers->stripPointerCasts());
01881   if (!F)
01882     return Unknown_Personality;
01883   return StringSwitch<Personality_Type>(F->getName())
01884     .Case("__gnat_eh_personality", GNU_Ada_Personality)
01885     .Case("__gxx_personality_v0",  GNU_CXX_Personality)
01886     .Case("__objc_personality_v0", GNU_ObjC_Personality)
01887     .Default(Unknown_Personality);
01888 }
01889 
01890 /// isCatchAll - Return 'true' if the given typeinfo will match anything.
01891 static bool isCatchAll(Personality_Type Personality, Constant *TypeInfo) {
01892   switch (Personality) {
01893   case Unknown_Personality:
01894     return false;
01895   case GNU_Ada_Personality:
01896     // While __gnat_all_others_value will match any Ada exception, it doesn't
01897     // match foreign exceptions (or didn't, before gcc-4.7).
01898     return false;
01899   case GNU_CXX_Personality:
01900   case GNU_ObjC_Personality:
01901     return TypeInfo->isNullValue();
01902   }
01903   llvm_unreachable("Unknown personality!");
01904 }
01905 
01906 static bool shorter_filter(const Value *LHS, const Value *RHS) {
01907   return
01908     cast<ArrayType>(LHS->getType())->getNumElements()
01909   <
01910     cast<ArrayType>(RHS->getType())->getNumElements();
01911 }
01912 
01913 Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
01914   // The logic here should be correct for any real-world personality function.
01915   // However if that turns out not to be true, the offending logic can always
01916   // be conditioned on the personality function, like the catch-all logic is.
01917   Personality_Type Personality = RecognizePersonality(LI.getPersonalityFn());
01918 
01919   // Simplify the list of clauses, eg by removing repeated catch clauses
01920   // (these are often created by inlining).
01921   bool MakeNewInstruction = false; // If true, recreate using the following:
01922   SmallVector<Value *, 16> NewClauses; // - Clauses for the new instruction;
01923   bool CleanupFlag = LI.isCleanup();   // - The new instruction is a cleanup.
01924 
01925   SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
01926   for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
01927     bool isLastClause = i + 1 == e;
01928     if (LI.isCatch(i)) {
01929       // A catch clause.
01930       Value *CatchClause = LI.getClause(i);
01931       Constant *TypeInfo = cast<Constant>(CatchClause->stripPointerCasts());
01932 
01933       // If we already saw this clause, there is no point in having a second
01934       // copy of it.
01935       if (AlreadyCaught.insert(TypeInfo)) {
01936         // This catch clause was not already seen.
01937         NewClauses.push_back(CatchClause);
01938       } else {
01939         // Repeated catch clause - drop the redundant copy.
01940         MakeNewInstruction = true;
01941       }
01942 
01943       // If this is a catch-all then there is no point in keeping any following
01944       // clauses or marking the landingpad as having a cleanup.
01945       if (isCatchAll(Personality, TypeInfo)) {
01946         if (!isLastClause)
01947           MakeNewInstruction = true;
01948         CleanupFlag = false;
01949         break;
01950       }
01951     } else {
01952       // A filter clause.  If any of the filter elements were already caught
01953       // then they can be dropped from the filter.  It is tempting to try to
01954       // exploit the filter further by saying that any typeinfo that does not
01955       // occur in the filter can't be caught later (and thus can be dropped).
01956       // However this would be wrong, since typeinfos can match without being
01957       // equal (for example if one represents a C++ class, and the other some
01958       // class derived from it).
01959       assert(LI.isFilter(i) && "Unsupported landingpad clause!");
01960       Value *FilterClause = LI.getClause(i);
01961       ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
01962       unsigned NumTypeInfos = FilterType->getNumElements();
01963 
01964       // An empty filter catches everything, so there is no point in keeping any
01965       // following clauses or marking the landingpad as having a cleanup.  By
01966       // dealing with this case here the following code is made a bit simpler.
01967       if (!NumTypeInfos) {
01968         NewClauses.push_back(FilterClause);
01969         if (!isLastClause)
01970           MakeNewInstruction = true;
01971         CleanupFlag = false;
01972         break;
01973       }
01974 
01975       bool MakeNewFilter = false; // If true, make a new filter.
01976       SmallVector<Constant *, 16> NewFilterElts; // New elements.
01977       if (isa<ConstantAggregateZero>(FilterClause)) {
01978         // Not an empty filter - it contains at least one null typeinfo.
01979         assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
01980         Constant *TypeInfo =
01981           Constant::getNullValue(FilterType->getElementType());
01982         // If this typeinfo is a catch-all then the filter can never match.
01983         if (isCatchAll(Personality, TypeInfo)) {
01984           // Throw the filter away.
01985           MakeNewInstruction = true;
01986           continue;
01987         }
01988 
01989         // There is no point in having multiple copies of this typeinfo, so
01990         // discard all but the first copy if there is more than one.
01991         NewFilterElts.push_back(TypeInfo);
01992         if (NumTypeInfos > 1)
01993           MakeNewFilter = true;
01994       } else {
01995         ConstantArray *Filter = cast<ConstantArray>(FilterClause);
01996         SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
01997         NewFilterElts.reserve(NumTypeInfos);
01998 
01999         // Remove any filter elements that were already caught or that already
02000         // occurred in the filter.  While there, see if any of the elements are
02001         // catch-alls.  If so, the filter can be discarded.
02002         bool SawCatchAll = false;
02003         for (unsigned j = 0; j != NumTypeInfos; ++j) {
02004           Value *Elt = Filter->getOperand(j);
02005           Constant *TypeInfo = cast<Constant>(Elt->stripPointerCasts());
02006           if (isCatchAll(Personality, TypeInfo)) {
02007             // This element is a catch-all.  Bail out, noting this fact.
02008             SawCatchAll = true;
02009             break;
02010           }
02011           if (AlreadyCaught.count(TypeInfo))
02012             // Already caught by an earlier clause, so having it in the filter
02013             // is pointless.
02014             continue;
02015           // There is no point in having multiple copies of the same typeinfo in
02016           // a filter, so only add it if we didn't already.
02017           if (SeenInFilter.insert(TypeInfo))
02018             NewFilterElts.push_back(cast<Constant>(Elt));
02019         }
02020         // A filter containing a catch-all cannot match anything by definition.
02021         if (SawCatchAll) {
02022           // Throw the filter away.
02023           MakeNewInstruction = true;
02024           continue;
02025         }
02026 
02027         // If we dropped something from the filter, make a new one.
02028         if (NewFilterElts.size() < NumTypeInfos)
02029           MakeNewFilter = true;
02030       }
02031       if (MakeNewFilter) {
02032         FilterType = ArrayType::get(FilterType->getElementType(),
02033                                     NewFilterElts.size());
02034         FilterClause = ConstantArray::get(FilterType, NewFilterElts);
02035         MakeNewInstruction = true;
02036       }
02037 
02038       NewClauses.push_back(FilterClause);
02039 
02040       // If the new filter is empty then it will catch everything so there is
02041       // no point in keeping any following clauses or marking the landingpad
02042       // as having a cleanup.  The case of the original filter being empty was
02043       // already handled above.
02044       if (MakeNewFilter && !NewFilterElts.size()) {
02045         assert(MakeNewInstruction && "New filter but not a new instruction!");
02046         CleanupFlag = false;
02047         break;
02048       }
02049     }
02050   }
02051 
02052   // If several filters occur in a row then reorder them so that the shortest
02053   // filters come first (those with the smallest number of elements).  This is
02054   // advantageous because shorter filters are more likely to match, speeding up
02055   // unwinding, but mostly because it increases the effectiveness of the other
02056   // filter optimizations below.
02057   for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
02058     unsigned j;
02059     // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
02060     for (j = i; j != e; ++j)
02061       if (!isa<ArrayType>(NewClauses[j]->getType()))
02062         break;
02063 
02064     // Check whether the filters are already sorted by length.  We need to know
02065     // if sorting them is actually going to do anything so that we only make a
02066     // new landingpad instruction if it does.
02067     for (unsigned k = i; k + 1 < j; ++k)
02068       if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
02069         // Not sorted, so sort the filters now.  Doing an unstable sort would be
02070         // correct too but reordering filters pointlessly might confuse users.
02071         std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
02072                          shorter_filter);
02073         MakeNewInstruction = true;
02074         break;
02075       }
02076 
02077     // Look for the next batch of filters.
02078     i = j + 1;
02079   }
02080 
02081   // If typeinfos matched if and only if equal, then the elements of a filter L
02082   // that occurs later than a filter F could be replaced by the intersection of
02083   // the elements of F and L.  In reality two typeinfos can match without being
02084   // equal (for example if one represents a C++ class, and the other some class
02085   // derived from it) so it would be wrong to perform this transform in general.
02086   // However the transform is correct and useful if F is a subset of L.  In that
02087   // case L can be replaced by F, and thus removed altogether since repeating a
02088   // filter is pointless.  So here we look at all pairs of filters F and L where
02089   // L follows F in the list of clauses, and remove L if every element of F is
02090   // an element of L.  This can occur when inlining C++ functions with exception
02091   // specifications.
02092   for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
02093     // Examine each filter in turn.
02094     Value *Filter = NewClauses[i];
02095     ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
02096     if (!FTy)
02097       // Not a filter - skip it.
02098       continue;
02099     unsigned FElts = FTy->getNumElements();
02100     // Examine each filter following this one.  Doing this backwards means that
02101     // we don't have to worry about filters disappearing under us when removed.
02102     for (unsigned j = NewClauses.size() - 1; j != i; --j) {
02103       Value *LFilter = NewClauses[j];
02104       ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
02105       if (!LTy)
02106         // Not a filter - skip it.
02107         continue;
02108       // If Filter is a subset of LFilter, i.e. every element of Filter is also
02109       // an element of LFilter, then discard LFilter.
02110       SmallVectorImpl<Value *>::iterator J = NewClauses.begin() + j;
02111       // If Filter is empty then it is a subset of LFilter.
02112       if (!FElts) {
02113         // Discard LFilter.
02114         NewClauses.erase(J);
02115         MakeNewInstruction = true;
02116         // Move on to the next filter.
02117         continue;
02118       }
02119       unsigned LElts = LTy->getNumElements();
02120       // If Filter is longer than LFilter then it cannot be a subset of it.
02121       if (FElts > LElts)
02122         // Move on to the next filter.
02123         continue;
02124       // At this point we know that LFilter has at least one element.
02125       if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
02126         // Filter is a subset of LFilter iff Filter contains only zeros (as we
02127         // already know that Filter is not longer than LFilter).
02128         if (isa<ConstantAggregateZero>(Filter)) {
02129           assert(FElts <= LElts && "Should have handled this case earlier!");
02130           // Discard LFilter.
02131           NewClauses.erase(J);
02132           MakeNewInstruction = true;
02133         }
02134         // Move on to the next filter.
02135         continue;
02136       }
02137       ConstantArray *LArray = cast<ConstantArray>(LFilter);
02138       if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
02139         // Since Filter is non-empty and contains only zeros, it is a subset of
02140         // LFilter iff LFilter contains a zero.
02141         assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
02142         for (unsigned l = 0; l != LElts; ++l)
02143           if (LArray->getOperand(l)->isNullValue()) {
02144             // LFilter contains a zero - discard it.
02145             NewClauses.erase(J);
02146             MakeNewInstruction = true;
02147             break;
02148           }
02149         // Move on to the next filter.
02150         continue;
02151       }
02152       // At this point we know that both filters are ConstantArrays.  Loop over
02153       // operands to see whether every element of Filter is also an element of
02154       // LFilter.  Since filters tend to be short this is probably faster than
02155       // using a method that scales nicely.
02156       ConstantArray *FArray = cast<ConstantArray>(Filter);
02157       bool AllFound = true;
02158       for (unsigned f = 0; f != FElts; ++f) {
02159         Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
02160         AllFound = false;
02161         for (unsigned l = 0; l != LElts; ++l) {
02162           Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
02163           if (LTypeInfo == FTypeInfo) {
02164             AllFound = true;
02165             break;
02166           }
02167         }
02168         if (!AllFound)
02169           break;
02170       }
02171       if (AllFound) {
02172         // Discard LFilter.
02173         NewClauses.erase(J);
02174         MakeNewInstruction = true;
02175       }
02176       // Move on to the next filter.
02177     }
02178   }
02179 
02180   // If we changed any of the clauses, replace the old landingpad instruction
02181   // with a new one.
02182   if (MakeNewInstruction) {
02183     LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
02184                                                  LI.getPersonalityFn(),
02185                                                  NewClauses.size());
02186     for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
02187       NLI->addClause(NewClauses[i]);
02188     // A landing pad with no clauses must have the cleanup flag set.  It is
02189     // theoretically possible, though highly unlikely, that we eliminated all
02190     // clauses.  If so, force the cleanup flag to true.
02191     if (NewClauses.empty())
02192       CleanupFlag = true;
02193     NLI->setCleanup(CleanupFlag);
02194     return NLI;
02195   }
02196 
02197   // Even if none of the clauses changed, we may nonetheless have understood
02198   // that the cleanup flag is pointless.  Clear it if so.
02199   if (LI.isCleanup() != CleanupFlag) {
02200     assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
02201     LI.setCleanup(CleanupFlag);
02202     return &LI;
02203   }
02204 
02205   return 0;
02206 }
02207 
02208 
02209 
02210 
02211 /// TryToSinkInstruction - Try to move the specified instruction from its
02212 /// current block into the beginning of DestBlock, which can only happen if it's
02213 /// safe to move the instruction past all of the instructions between it and the
02214 /// end of its block.
02215 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
02216   assert(I->hasOneUse() && "Invariants didn't hold!");
02217 
02218   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
02219   if (isa<PHINode>(I) || isa<LandingPadInst>(I) || I->mayHaveSideEffects() ||
02220       isa<TerminatorInst>(I))
02221     return false;
02222 
02223   // Do not sink alloca instructions out of the entry block.
02224   if (isa<AllocaInst>(I) && I->getParent() ==
02225         &DestBlock->getParent()->getEntryBlock())
02226     return false;
02227 
02228   // We can only sink load instructions if there is nothing between the load and
02229   // the end of block that could change the value.
02230   if (I->mayReadFromMemory()) {
02231     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
02232          Scan != E; ++Scan)
02233       if (Scan->mayWriteToMemory())
02234         return false;
02235   }
02236 
02237   BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
02238   I->moveBefore(InsertPos);
02239   ++NumSunkInst;
02240   return true;
02241 }
02242 
02243 
02244 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
02245 /// all reachable code to the worklist.
02246 ///
02247 /// This has a couple of tricks to make the code faster and more powerful.  In
02248 /// particular, we constant fold and DCE instructions as we go, to avoid adding
02249 /// them to the worklist (this significantly speeds up instcombine on code where
02250 /// many instructions are dead or constant).  Additionally, if we find a branch
02251 /// whose condition is a known constant, we only visit the reachable successors.
02252 ///
02253 static bool AddReachableCodeToWorklist(BasicBlock *BB,
02254                                        SmallPtrSet<BasicBlock*, 64> &Visited,
02255                                        InstCombiner &IC,
02256                                        const DataLayout *DL,
02257                                        const TargetLibraryInfo *TLI) {
02258   bool MadeIRChange = false;
02259   SmallVector<BasicBlock*, 256> Worklist;
02260   Worklist.push_back(BB);
02261 
02262   SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
02263   DenseMap<ConstantExpr*, Constant*> FoldedConstants;
02264 
02265   do {
02266     BB = Worklist.pop_back_val();
02267 
02268     // We have now visited this block!  If we've already been here, ignore it.
02269     if (!Visited.insert(BB)) continue;
02270 
02271     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
02272       Instruction *Inst = BBI++;
02273 
02274       // DCE instruction if trivially dead.
02275       if (isInstructionTriviallyDead(Inst, TLI)) {
02276         ++NumDeadInst;
02277         DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
02278         Inst->eraseFromParent();
02279         continue;
02280       }
02281 
02282       // ConstantProp instruction if trivially constant.
02283       if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
02284         if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
02285           DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: "
02286                        << *Inst << '\n');
02287           Inst->replaceAllUsesWith(C);
02288           ++NumConstProp;
02289           Inst->eraseFromParent();
02290           continue;
02291         }
02292 
02293       if (DL) {
02294         // See if we can constant fold its operands.
02295         for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
02296              i != e; ++i) {
02297           ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
02298           if (CE == 0) continue;
02299 
02300           Constant*& FoldRes = FoldedConstants[CE];
02301           if (!FoldRes)
02302             FoldRes = ConstantFoldConstantExpression(CE, DL, TLI);
02303           if (!FoldRes)
02304             FoldRes = CE;
02305 
02306           if (FoldRes != CE) {
02307             *i = FoldRes;
02308             MadeIRChange = true;
02309           }
02310         }
02311       }
02312 
02313       InstrsForInstCombineWorklist.push_back(Inst);
02314     }
02315 
02316     // Recursively visit successors.  If this is a branch or switch on a
02317     // constant, only visit the reachable successor.
02318     TerminatorInst *TI = BB->getTerminator();
02319     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
02320       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
02321         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
02322         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
02323         Worklist.push_back(ReachableBB);
02324         continue;
02325       }
02326     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
02327       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
02328         // See if this is an explicit destination.
02329         for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
02330              i != e; ++i)
02331           if (i.getCaseValue() == Cond) {
02332             BasicBlock *ReachableBB = i.getCaseSuccessor();
02333             Worklist.push_back(ReachableBB);
02334             continue;
02335           }
02336 
02337         // Otherwise it is the default destination.
02338         Worklist.push_back(SI->getDefaultDest());
02339         continue;
02340       }
02341     }
02342 
02343     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
02344       Worklist.push_back(TI->getSuccessor(i));
02345   } while (!Worklist.empty());
02346 
02347   // Once we've found all of the instructions to add to instcombine's worklist,
02348   // add them in reverse order.  This way instcombine will visit from the top
02349   // of the function down.  This jives well with the way that it adds all uses
02350   // of instructions to the worklist after doing a transformation, thus avoiding
02351   // some N^2 behavior in pathological cases.
02352   IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
02353                               InstrsForInstCombineWorklist.size());
02354 
02355   return MadeIRChange;
02356 }
02357 
02358 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
02359   MadeIRChange = false;
02360 
02361   DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
02362                << F.getName() << "\n");
02363 
02364   {
02365     // Do a depth-first traversal of the function, populate the worklist with
02366     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
02367     // track of which blocks we visit.
02368     SmallPtrSet<BasicBlock*, 64> Visited;
02369     MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, DL,
02370                                                TLI);
02371 
02372     // Do a quick scan over the function.  If we find any blocks that are
02373     // unreachable, remove any instructions inside of them.  This prevents
02374     // the instcombine code from having to deal with some bad special cases.
02375     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
02376       if (Visited.count(BB)) continue;
02377 
02378       // Delete the instructions backwards, as it has a reduced likelihood of
02379       // having to update as many def-use and use-def chains.
02380       Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
02381       while (EndInst != BB->begin()) {
02382         // Delete the next to last instruction.
02383         BasicBlock::iterator I = EndInst;
02384         Instruction *Inst = --I;
02385         if (!Inst->use_empty())
02386           Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
02387         if (isa<LandingPadInst>(Inst)) {
02388           EndInst = Inst;
02389           continue;
02390         }
02391         if (!isa<DbgInfoIntrinsic>(Inst)) {
02392           ++NumDeadInst;
02393           MadeIRChange = true;
02394         }
02395         Inst->eraseFromParent();
02396       }
02397     }
02398   }
02399 
02400   while (!Worklist.isEmpty()) {
02401     Instruction *I = Worklist.RemoveOne();
02402     if (I == 0) continue;  // skip null values.
02403 
02404     // Check to see if we can DCE the instruction.
02405     if (isInstructionTriviallyDead(I, TLI)) {
02406       DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
02407       EraseInstFromFunction(*I);
02408       ++NumDeadInst;
02409       MadeIRChange = true;
02410       continue;
02411     }
02412 
02413     // Instruction isn't dead, see if we can constant propagate it.
02414     if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
02415       if (Constant *C = ConstantFoldInstruction(I, DL, TLI)) {
02416         DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
02417 
02418         // Add operands to the worklist.
02419         ReplaceInstUsesWith(*I, C);
02420         ++NumConstProp;
02421         EraseInstFromFunction(*I);
02422         MadeIRChange = true;
02423         continue;
02424       }
02425 
02426     // See if we can trivially sink this instruction to a successor basic block.
02427     if (I->hasOneUse()) {
02428       BasicBlock *BB = I->getParent();
02429       Instruction *UserInst = cast<Instruction>(*I->user_begin());
02430       BasicBlock *UserParent;
02431 
02432       // Get the block the use occurs in.
02433       if (PHINode *PN = dyn_cast<PHINode>(UserInst))
02434         UserParent = PN->getIncomingBlock(*I->use_begin());
02435       else
02436         UserParent = UserInst->getParent();
02437 
02438       if (UserParent != BB) {
02439         bool UserIsSuccessor = false;
02440         // See if the user is one of our successors.
02441         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
02442           if (*SI == UserParent) {
02443             UserIsSuccessor = true;
02444             break;
02445           }
02446 
02447         // If the user is one of our immediate successors, and if that successor
02448         // only has us as a predecessors (we'd have to split the critical edge
02449         // otherwise), we can keep going.
02450         if (UserIsSuccessor && UserParent->getSinglePredecessor())
02451           // Okay, the CFG is simple enough, try to sink this instruction.
02452           MadeIRChange |= TryToSinkInstruction(I, UserParent);
02453       }
02454     }
02455 
02456     // Now that we have an instruction, try combining it to simplify it.
02457     Builder->SetInsertPoint(I->getParent(), I);
02458     Builder->SetCurrentDebugLocation(I->getDebugLoc());
02459 
02460 #ifndef NDEBUG
02461     std::string OrigI;
02462 #endif
02463     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
02464     DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
02465 
02466     if (Instruction *Result = visit(*I)) {
02467       ++NumCombined;
02468       // Should we replace the old instruction with a new one?
02469       if (Result != I) {
02470         DEBUG(dbgs() << "IC: Old = " << *I << '\n'
02471                      << "    New = " << *Result << '\n');
02472 
02473         if (!I->getDebugLoc().isUnknown())
02474           Result->setDebugLoc(I->getDebugLoc());
02475         // Everything uses the new instruction now.
02476         I->replaceAllUsesWith(Result);
02477 
02478         // Move the name to the new instruction first.
02479         Result->takeName(I);
02480 
02481         // Push the new instruction and any users onto the worklist.
02482         Worklist.Add(Result);
02483         Worklist.AddUsersToWorkList(*Result);
02484 
02485         // Insert the new instruction into the basic block...
02486         BasicBlock *InstParent = I->getParent();
02487         BasicBlock::iterator InsertPos = I;
02488 
02489         // If we replace a PHI with something that isn't a PHI, fix up the
02490         // insertion point.
02491         if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
02492           InsertPos = InstParent->getFirstInsertionPt();
02493 
02494         InstParent->getInstList().insert(InsertPos, Result);
02495 
02496         EraseInstFromFunction(*I);
02497       } else {
02498 #ifndef NDEBUG
02499         DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
02500                      << "    New = " << *I << '\n');
02501 #endif
02502 
02503         // If the instruction was modified, it's possible that it is now dead.
02504         // if so, remove it.
02505         if (isInstructionTriviallyDead(I, TLI)) {
02506           EraseInstFromFunction(*I);
02507         } else {
02508           Worklist.Add(I);
02509           Worklist.AddUsersToWorkList(*I);
02510         }
02511       }
02512       MadeIRChange = true;
02513     }
02514   }
02515 
02516   Worklist.Zap();
02517   return MadeIRChange;
02518 }
02519 
02520 namespace {
02521 class InstCombinerLibCallSimplifier : public LibCallSimplifier {
02522   InstCombiner *IC;
02523 public:
02524   InstCombinerLibCallSimplifier(const DataLayout *DL,
02525                                 const TargetLibraryInfo *TLI,
02526                                 InstCombiner *IC)
02527     : LibCallSimplifier(DL, TLI, UnsafeFPShrink) {
02528     this->IC = IC;
02529   }
02530 
02531   /// replaceAllUsesWith - override so that instruction replacement
02532   /// can be defined in terms of the instruction combiner framework.
02533   void replaceAllUsesWith(Instruction *I, Value *With) const override {
02534     IC->ReplaceInstUsesWith(*I, With);
02535   }
02536 };
02537 }
02538 
02539 bool InstCombiner::runOnFunction(Function &F) {
02540   if (skipOptnoneFunction(F))
02541     return false;
02542 
02543   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
02544   DL = DLP ? &DLP->getDataLayout() : 0;
02545   TLI = &getAnalysis<TargetLibraryInfo>();
02546   // Minimizing size?
02547   MinimizeSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
02548                                                 Attribute::MinSize);
02549 
02550   /// Builder - This is an IRBuilder that automatically inserts new
02551   /// instructions into the worklist when they are created.
02552   IRBuilder<true, TargetFolder, InstCombineIRInserter>
02553     TheBuilder(F.getContext(), TargetFolder(DL),
02554                InstCombineIRInserter(Worklist));
02555   Builder = &TheBuilder;
02556 
02557   InstCombinerLibCallSimplifier TheSimplifier(DL, TLI, this);
02558   Simplifier = &TheSimplifier;
02559 
02560   bool EverMadeChange = false;
02561 
02562   // Lower dbg.declare intrinsics otherwise their value may be clobbered
02563   // by instcombiner.
02564   EverMadeChange = LowerDbgDeclare(F);
02565 
02566   // Iterate while there is work to do.
02567   unsigned Iteration = 0;
02568   while (DoOneIteration(F, Iteration++))
02569     EverMadeChange = true;
02570 
02571   Builder = 0;
02572   return EverMadeChange;
02573 }
02574 
02575 FunctionPass *llvm::createInstructionCombiningPass() {
02576   return new InstCombiner();
02577 }