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