1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions.  This pass does not modify the CFG.  This pass is where
12 // algebraic simplification happens.
13 //
14 // This pass combines things like:
15 //    %Y = add i32 %X, 1
16 //    %Z = add i32 %Y, 1
17 // into:
18 //    %Z = add i32 %X, 2
19 //
20 // This is a simple worklist driven algorithm.
21 //
22 // This pass guarantees that the following canonicalizations are performed on
23 // the program:
24 //    1. If a binary operator has a constant operand, it is moved to the RHS
25 //    2. Bitwise operators with constant operands are always grouped so that
26 //       shifts are performed first, then or's, then and's, then xor's.
27 //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All cmp instructions on boolean values are replaced with logical ops
29 //    5. add X, X is represented as (X*2) => (X << 1)
30 //    6. Multiplies with a power-of-two constant argument are transformed into
31 //       shifts.
32 //   ... etc.
33 //
34 //===----------------------------------------------------------------------===//
35 
36 #include "InstCombineInternal.h"
37 #include "llvm-c/Initialization.h"
38 #include "llvm-c/Transforms/InstCombine.h"
39 #include "llvm/ADT/APInt.h"
40 #include "llvm/ADT/ArrayRef.h"
41 #include "llvm/ADT/DenseMap.h"
42 #include "llvm/ADT/None.h"
43 #include "llvm/ADT/SmallPtrSet.h"
44 #include "llvm/ADT/SmallVector.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/TinyPtrVector.h"
47 #include "llvm/Analysis/AliasAnalysis.h"
48 #include "llvm/Analysis/AssumptionCache.h"
49 #include "llvm/Analysis/BasicAliasAnalysis.h"
50 #include "llvm/Analysis/CFG.h"
51 #include "llvm/Analysis/ConstantFolding.h"
52 #include "llvm/Analysis/EHPersonalities.h"
53 #include "llvm/Analysis/GlobalsModRef.h"
54 #include "llvm/Analysis/InstructionSimplify.h"
55 #include "llvm/Analysis/LoopInfo.h"
56 #include "llvm/Analysis/MemoryBuiltins.h"
57 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
58 #include "llvm/Analysis/TargetFolder.h"
59 #include "llvm/Analysis/TargetLibraryInfo.h"
60 #include "llvm/Analysis/ValueTracking.h"
61 #include "llvm/IR/BasicBlock.h"
62 #include "llvm/IR/CFG.h"
63 #include "llvm/IR/Constant.h"
64 #include "llvm/IR/Constants.h"
65 #include "llvm/IR/DIBuilder.h"
66 #include "llvm/IR/DataLayout.h"
67 #include "llvm/IR/DerivedTypes.h"
68 #include "llvm/IR/Dominators.h"
69 #include "llvm/IR/Function.h"
70 #include "llvm/IR/GetElementPtrTypeIterator.h"
71 #include "llvm/IR/IRBuilder.h"
72 #include "llvm/IR/InstrTypes.h"
73 #include "llvm/IR/Instruction.h"
74 #include "llvm/IR/Instructions.h"
75 #include "llvm/IR/IntrinsicInst.h"
76 #include "llvm/IR/Intrinsics.h"
77 #include "llvm/IR/LegacyPassManager.h"
78 #include "llvm/IR/Metadata.h"
79 #include "llvm/IR/Operator.h"
80 #include "llvm/IR/PassManager.h"
81 #include "llvm/IR/PatternMatch.h"
82 #include "llvm/IR/Type.h"
83 #include "llvm/IR/Use.h"
84 #include "llvm/IR/User.h"
85 #include "llvm/IR/Value.h"
86 #include "llvm/IR/ValueHandle.h"
87 #include "llvm/Pass.h"
88 #include "llvm/Support/CBindingWrapping.h"
89 #include "llvm/Support/Casting.h"
90 #include "llvm/Support/CommandLine.h"
91 #include "llvm/Support/Compiler.h"
92 #include "llvm/Support/Debug.h"
93 #include "llvm/Support/DebugCounter.h"
94 #include "llvm/Support/ErrorHandling.h"
95 #include "llvm/Support/KnownBits.h"
96 #include "llvm/Support/raw_ostream.h"
97 #include "llvm/Transforms/InstCombine/InstCombine.h"
98 #include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
99 #include "llvm/Transforms/Utils/Local.h"
100 #include <algorithm>
101 #include <cassert>
102 #include <cstdint>
103 #include <memory>
104 #include <string>
105 #include <utility>
106 
107 using namespace llvm;
108 using namespace llvm::PatternMatch;
109 
110 #define DEBUG_TYPE "instcombine"
111 
112 STATISTIC(NumCombined , "Number of insts combined");
113 STATISTIC(NumConstProp, "Number of constant folds");
114 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
115 STATISTIC(NumSunkInst , "Number of instructions sunk");
116 STATISTIC(NumExpand,    "Number of expansions");
117 STATISTIC(NumFactor   , "Number of factorizations");
118 STATISTIC(NumReassoc  , "Number of reassociations");
119 DEBUG_COUNTER(VisitCounter, "instcombine-visit",
120               "Controls which instructions are visited");
121 
122 static cl::opt<bool>
123 EnableExpensiveCombines("expensive-combines",
124                         cl::desc("Enable expensive instruction combines"));
125 
126 static cl::opt<unsigned>
127 MaxArraySize("instcombine-maxarray-size", cl::init(1024),
128              cl::desc("Maximum array size considered when doing a combine"));
129 
130 // FIXME: Remove this flag when it is no longer necessary to convert
131 // llvm.dbg.declare to avoid inaccurate debug info. Setting this to false
132 // increases variable availability at the cost of accuracy. Variables that
133 // cannot be promoted by mem2reg or SROA will be described as living in memory
134 // for their entire lifetime. However, passes like DSE and instcombine can
135 // delete stores to the alloca, leading to misleading and inaccurate debug
136 // information. This flag can be removed when those passes are fixed.
137 static cl::opt<unsigned> ShouldLowerDbgDeclare("instcombine-lower-dbg-declare",
138                                                cl::Hidden, cl::init(true));
139 
140 Value *InstCombiner::EmitGEPOffset(User *GEP) {
141   return llvm::EmitGEPOffset(&Builder, DL, GEP);
142 }
143 
144 /// Return true if it is desirable to convert an integer computation from a
145 /// given bit width to a new bit width.
146 /// We don't want to convert from a legal to an illegal type or from a smaller
147 /// to a larger illegal type. A width of '1' is always treated as a legal type
148 /// because i1 is a fundamental type in IR, and there are many specialized
149 /// optimizations for i1 types. Widths of 8, 16 or 32 are equally treated as
150 /// legal to convert to, in order to open up more combining opportunities.
151 /// NOTE: this treats i8, i16 and i32 specially, due to them being so common
152 /// from frontend languages.
153 bool InstCombiner::shouldChangeType(unsigned FromWidth,
154                                     unsigned ToWidth) const {
155   bool FromLegal = FromWidth == 1 || DL.isLegalInteger(FromWidth);
156   bool ToLegal = ToWidth == 1 || DL.isLegalInteger(ToWidth);
157 
158   // Convert to widths of 8, 16 or 32 even if they are not legal types. Only
159   // shrink types, to prevent infinite loops.
160   if (ToWidth < FromWidth && (ToWidth == 8 || ToWidth == 16 || ToWidth == 32))
161     return true;
162 
163   // If this is a legal integer from type, and the result would be an illegal
164   // type, don't do the transformation.
165   if (FromLegal && !ToLegal)
166     return false;
167 
168   // Otherwise, if both are illegal, do not increase the size of the result. We
169   // do allow things like i160 -> i64, but not i64 -> i160.
170   if (!FromLegal && !ToLegal && ToWidth > FromWidth)
171     return false;
172 
173   return true;
174 }
175 
176 /// Return true if it is desirable to convert a computation from 'From' to 'To'.
177 /// We don't want to convert from a legal to an illegal type or from a smaller
178 /// to a larger illegal type. i1 is always treated as a legal type because it is
179 /// a fundamental type in IR, and there are many specialized optimizations for
180 /// i1 types.
181 bool InstCombiner::shouldChangeType(Type *From, Type *To) const {
182   assert(From->isIntegerTy() && To->isIntegerTy());
183 
184   unsigned FromWidth = From->getPrimitiveSizeInBits();
185   unsigned ToWidth = To->getPrimitiveSizeInBits();
186   return shouldChangeType(FromWidth, ToWidth);
187 }
188 
189 // Return true, if No Signed Wrap should be maintained for I.
190 // The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
191 // where both B and C should be ConstantInts, results in a constant that does
192 // not overflow. This function only handles the Add and Sub opcodes. For
193 // all other opcodes, the function conservatively returns false.
194 static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
195   OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
196   if (!OBO || !OBO->hasNoSignedWrap())
197     return false;
198 
199   // We reason about Add and Sub Only.
200   Instruction::BinaryOps Opcode = I.getOpcode();
201   if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
202     return false;
203 
204   const APInt *BVal, *CVal;
205   if (!match(B, m_APInt(BVal)) || !match(C, m_APInt(CVal)))
206     return false;
207 
208   bool Overflow = false;
209   if (Opcode == Instruction::Add)
210     (void)BVal->sadd_ov(*CVal, Overflow);
211   else
212     (void)BVal->ssub_ov(*CVal, Overflow);
213 
214   return !Overflow;
215 }
216 
217 /// Conservatively clears subclassOptionalData after a reassociation or
218 /// commutation. We preserve fast-math flags when applicable as they can be
219 /// preserved.
220 static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {
221   FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
222   if (!FPMO) {
223     I.clearSubclassOptionalData();
224     return;
225   }
226 
227   FastMathFlags FMF = I.getFastMathFlags();
228   I.clearSubclassOptionalData();
229   I.setFastMathFlags(FMF);
230 }
231 
232 /// Combine constant operands of associative operations either before or after a
233 /// cast to eliminate one of the associative operations:
234 /// (op (cast (op X, C2)), C1) --> (cast (op X, op (C1, C2)))
235 /// (op (cast (op X, C2)), C1) --> (op (cast X), op (C1, C2))
236 static bool simplifyAssocCastAssoc(BinaryOperator *BinOp1) {
237   auto *Cast = dyn_cast<CastInst>(BinOp1->getOperand(0));
238   if (!Cast || !Cast->hasOneUse())
239     return false;
240 
241   // TODO: Enhance logic for other casts and remove this check.
242   auto CastOpcode = Cast->getOpcode();
243   if (CastOpcode != Instruction::ZExt)
244     return false;
245 
246   // TODO: Enhance logic for other BinOps and remove this check.
247   if (!BinOp1->isBitwiseLogicOp())
248     return false;
249 
250   auto AssocOpcode = BinOp1->getOpcode();
251   auto *BinOp2 = dyn_cast<BinaryOperator>(Cast->getOperand(0));
252   if (!BinOp2 || !BinOp2->hasOneUse() || BinOp2->getOpcode() != AssocOpcode)
253     return false;
254 
255   Constant *C1, *C2;
256   if (!match(BinOp1->getOperand(1), m_Constant(C1)) ||
257       !match(BinOp2->getOperand(1), m_Constant(C2)))
258     return false;
259 
260   // TODO: This assumes a zext cast.
261   // Eg, if it was a trunc, we'd cast C1 to the source type because casting C2
262   // to the destination type might lose bits.
263 
264   // Fold the constants together in the destination type:
265   // (op (cast (op X, C2)), C1) --> (op (cast X), FoldedC)
266   Type *DestTy = C1->getType();
267   Constant *CastC2 = ConstantExpr::getCast(CastOpcode, C2, DestTy);
268   Constant *FoldedC = ConstantExpr::get(AssocOpcode, C1, CastC2);
269   Cast->setOperand(0, BinOp2->getOperand(0));
270   BinOp1->setOperand(1, FoldedC);
271   return true;
272 }
273 
274 /// This performs a few simplifications for operators that are associative or
275 /// commutative:
276 ///
277 ///  Commutative operators:
278 ///
279 ///  1. Order operands such that they are listed from right (least complex) to
280 ///     left (most complex).  This puts constants before unary operators before
281 ///     binary operators.
282 ///
283 ///  Associative operators:
284 ///
285 ///  2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
286 ///  3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
287 ///
288 ///  Associative and commutative operators:
289 ///
290 ///  4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
291 ///  5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
292 ///  6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
293 ///     if C1 and C2 are constants.
294 bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
295   Instruction::BinaryOps Opcode = I.getOpcode();
296   bool Changed = false;
297 
298   do {
299     // Order operands such that they are listed from right (least complex) to
300     // left (most complex).  This puts constants before unary operators before
301     // binary operators.
302     if (I.isCommutative() && getComplexity(I.getOperand(0)) <
303         getComplexity(I.getOperand(1)))
304       Changed = !I.swapOperands();
305 
306     BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
307     BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
308 
309     if (I.isAssociative()) {
310       // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
311       if (Op0 && Op0->getOpcode() == Opcode) {
312         Value *A = Op0->getOperand(0);
313         Value *B = Op0->getOperand(1);
314         Value *C = I.getOperand(1);
315 
316         // Does "B op C" simplify?
317         if (Value *V = SimplifyBinOp(Opcode, B, C, SQ.getWithInstruction(&I))) {
318           // It simplifies to V.  Form "A op V".
319           I.setOperand(0, A);
320           I.setOperand(1, V);
321           // Conservatively clear the optional flags, since they may not be
322           // preserved by the reassociation.
323           if (MaintainNoSignedWrap(I, B, C) &&
324               (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
325             // Note: this is only valid because SimplifyBinOp doesn't look at
326             // the operands to Op0.
327             I.clearSubclassOptionalData();
328             I.setHasNoSignedWrap(true);
329           } else {
330             ClearSubclassDataAfterReassociation(I);
331           }
332 
333           Changed = true;
334           ++NumReassoc;
335           continue;
336         }
337       }
338 
339       // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
340       if (Op1 && Op1->getOpcode() == Opcode) {
341         Value *A = I.getOperand(0);
342         Value *B = Op1->getOperand(0);
343         Value *C = Op1->getOperand(1);
344 
345         // Does "A op B" simplify?
346         if (Value *V = SimplifyBinOp(Opcode, A, B, SQ.getWithInstruction(&I))) {
347           // It simplifies to V.  Form "V op C".
348           I.setOperand(0, V);
349           I.setOperand(1, C);
350           // Conservatively clear the optional flags, since they may not be
351           // preserved by the reassociation.
352           ClearSubclassDataAfterReassociation(I);
353           Changed = true;
354           ++NumReassoc;
355           continue;
356         }
357       }
358     }
359 
360     if (I.isAssociative() && I.isCommutative()) {
361       if (simplifyAssocCastAssoc(&I)) {
362         Changed = true;
363         ++NumReassoc;
364         continue;
365       }
366 
367       // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
368       if (Op0 && Op0->getOpcode() == Opcode) {
369         Value *A = Op0->getOperand(0);
370         Value *B = Op0->getOperand(1);
371         Value *C = I.getOperand(1);
372 
373         // Does "C op A" simplify?
374         if (Value *V = SimplifyBinOp(Opcode, C, A, SQ.getWithInstruction(&I))) {
375           // It simplifies to V.  Form "V op B".
376           I.setOperand(0, V);
377           I.setOperand(1, B);
378           // Conservatively clear the optional flags, since they may not be
379           // preserved by the reassociation.
380           ClearSubclassDataAfterReassociation(I);
381           Changed = true;
382           ++NumReassoc;
383           continue;
384         }
385       }
386 
387       // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
388       if (Op1 && Op1->getOpcode() == Opcode) {
389         Value *A = I.getOperand(0);
390         Value *B = Op1->getOperand(0);
391         Value *C = Op1->getOperand(1);
392 
393         // Does "C op A" simplify?
394         if (Value *V = SimplifyBinOp(Opcode, C, A, SQ.getWithInstruction(&I))) {
395           // It simplifies to V.  Form "B op V".
396           I.setOperand(0, B);
397           I.setOperand(1, V);
398           // Conservatively clear the optional flags, since they may not be
399           // preserved by the reassociation.
400           ClearSubclassDataAfterReassociation(I);
401           Changed = true;
402           ++NumReassoc;
403           continue;
404         }
405       }
406 
407       // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
408       // if C1 and C2 are constants.
409       Value *A, *B;
410       Constant *C1, *C2;
411       if (Op0 && Op1 &&
412           Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
413           match(Op0, m_OneUse(m_BinOp(m_Value(A), m_Constant(C1)))) &&
414           match(Op1, m_OneUse(m_BinOp(m_Value(B), m_Constant(C2))))) {
415         BinaryOperator *NewBO = BinaryOperator::Create(Opcode, A, B);
416         if (isa<FPMathOperator>(NewBO)) {
417           FastMathFlags Flags = I.getFastMathFlags();
418           Flags &= Op0->getFastMathFlags();
419           Flags &= Op1->getFastMathFlags();
420           NewBO->setFastMathFlags(Flags);
421         }
422         InsertNewInstWith(NewBO, I);
423         NewBO->takeName(Op1);
424         I.setOperand(0, NewBO);
425         I.setOperand(1, ConstantExpr::get(Opcode, C1, C2));
426         // Conservatively clear the optional flags, since they may not be
427         // preserved by the reassociation.
428         ClearSubclassDataAfterReassociation(I);
429 
430         Changed = true;
431         continue;
432       }
433     }
434 
435     // No further simplifications.
436     return Changed;
437   } while (true);
438 }
439 
440 /// Return whether "X LOp (Y ROp Z)" is always equal to
441 /// "(X LOp Y) ROp (X LOp Z)".
442 static bool leftDistributesOverRight(Instruction::BinaryOps LOp,
443                                      Instruction::BinaryOps ROp) {
444   // X & (Y | Z) <--> (X & Y) | (X & Z)
445   // X & (Y ^ Z) <--> (X & Y) ^ (X & Z)
446   if (LOp == Instruction::And)
447     return ROp == Instruction::Or || ROp == Instruction::Xor;
448 
449   // X | (Y & Z) <--> (X | Y) & (X | Z)
450   if (LOp == Instruction::Or)
451     return ROp == Instruction::And;
452 
453   // X * (Y + Z) <--> (X * Y) + (X * Z)
454   // X * (Y - Z) <--> (X * Y) - (X * Z)
455   if (LOp == Instruction::Mul)
456     return ROp == Instruction::Add || ROp == Instruction::Sub;
457 
458   return false;
459 }
460 
461 /// Return whether "(X LOp Y) ROp Z" is always equal to
462 /// "(X ROp Z) LOp (Y ROp Z)".
463 static bool rightDistributesOverLeft(Instruction::BinaryOps LOp,
464                                      Instruction::BinaryOps ROp) {
465   if (Instruction::isCommutative(ROp))
466     return leftDistributesOverRight(ROp, LOp);
467 
468   // (X {&|^} Y) >> Z <--> (X >> Z) {&|^} (Y >> Z) for all shifts.
469   return Instruction::isBitwiseLogicOp(LOp) && Instruction::isShift(ROp);
470 
471   // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
472   // but this requires knowing that the addition does not overflow and other
473   // such subtleties.
474 }
475 
476 /// This function returns identity value for given opcode, which can be used to
477 /// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
478 static Value *getIdentityValue(Instruction::BinaryOps Opcode, Value *V) {
479   if (isa<Constant>(V))
480     return nullptr;
481 
482   return ConstantExpr::getBinOpIdentity(Opcode, V->getType());
483 }
484 
485 /// This function predicates factorization using distributive laws. By default,
486 /// it just returns the 'Op' inputs. But for special-cases like
487 /// 'add(shl(X, 5), ...)', this function will have TopOpcode == Instruction::Add
488 /// and Op = shl(X, 5). The 'shl' is treated as the more general 'mul X, 32' to
489 /// allow more factorization opportunities.
490 static Instruction::BinaryOps
491 getBinOpsForFactorization(Instruction::BinaryOps TopOpcode, BinaryOperator *Op,
492                           Value *&LHS, Value *&RHS) {
493   assert(Op && "Expected a binary operator");
494   LHS = Op->getOperand(0);
495   RHS = Op->getOperand(1);
496   if (TopOpcode == Instruction::Add || TopOpcode == Instruction::Sub) {
497     Constant *C;
498     if (match(Op, m_Shl(m_Value(), m_Constant(C)))) {
499       // X << C --> X * (1 << C)
500       RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), C);
501       return Instruction::Mul;
502     }
503     // TODO: We can add other conversions e.g. shr => div etc.
504   }
505   return Op->getOpcode();
506 }
507 
508 /// This tries to simplify binary operations by factorizing out common terms
509 /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
510 Value *InstCombiner::tryFactorization(BinaryOperator &I,
511                                       Instruction::BinaryOps InnerOpcode,
512                                       Value *A, Value *B, Value *C, Value *D) {
513   assert(A && B && C && D && "All values must be provided");
514 
515   Value *V = nullptr;
516   Value *SimplifiedInst = nullptr;
517   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
518   Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
519 
520   // Does "X op' Y" always equal "Y op' X"?
521   bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
522 
523   // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
524   if (leftDistributesOverRight(InnerOpcode, TopLevelOpcode))
525     // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
526     // commutative case, "(A op' B) op (C op' A)"?
527     if (A == C || (InnerCommutative && A == D)) {
528       if (A != C)
529         std::swap(C, D);
530       // Consider forming "A op' (B op D)".
531       // If "B op D" simplifies then it can be formed with no cost.
532       V = SimplifyBinOp(TopLevelOpcode, B, D, SQ.getWithInstruction(&I));
533       // If "B op D" doesn't simplify then only go on if both of the existing
534       // operations "A op' B" and "C op' D" will be zapped as no longer used.
535       if (!V && LHS->hasOneUse() && RHS->hasOneUse())
536         V = Builder.CreateBinOp(TopLevelOpcode, B, D, RHS->getName());
537       if (V) {
538         SimplifiedInst = Builder.CreateBinOp(InnerOpcode, A, V);
539       }
540     }
541 
542   // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
543   if (!SimplifiedInst && rightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
544     // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
545     // commutative case, "(A op' B) op (B op' D)"?
546     if (B == D || (InnerCommutative && B == C)) {
547       if (B != D)
548         std::swap(C, D);
549       // Consider forming "(A op C) op' B".
550       // If "A op C" simplifies then it can be formed with no cost.
551       V = SimplifyBinOp(TopLevelOpcode, A, C, SQ.getWithInstruction(&I));
552 
553       // If "A op C" doesn't simplify then only go on if both of the existing
554       // operations "A op' B" and "C op' D" will be zapped as no longer used.
555       if (!V && LHS->hasOneUse() && RHS->hasOneUse())
556         V = Builder.CreateBinOp(TopLevelOpcode, A, C, LHS->getName());
557       if (V) {
558         SimplifiedInst = Builder.CreateBinOp(InnerOpcode, V, B);
559       }
560     }
561 
562   if (SimplifiedInst) {
563     ++NumFactor;
564     SimplifiedInst->takeName(&I);
565 
566     // Check if we can add NSW flag to SimplifiedInst. If so, set NSW flag.
567     // TODO: Check for NUW.
568     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) {
569       if (isa<OverflowingBinaryOperator>(SimplifiedInst)) {
570         bool HasNSW = false;
571         if (isa<OverflowingBinaryOperator>(&I))
572           HasNSW = I.hasNoSignedWrap();
573 
574         if (auto *LOBO = dyn_cast<OverflowingBinaryOperator>(LHS))
575           HasNSW &= LOBO->hasNoSignedWrap();
576 
577         if (auto *ROBO = dyn_cast<OverflowingBinaryOperator>(RHS))
578           HasNSW &= ROBO->hasNoSignedWrap();
579 
580         // We can propagate 'nsw' if we know that
581         //  %Y = mul nsw i16 %X, C
582         //  %Z = add nsw i16 %Y, %X
583         // =>
584         //  %Z = mul nsw i16 %X, C+1
585         //
586         // iff C+1 isn't INT_MIN
587         const APInt *CInt;
588         if (TopLevelOpcode == Instruction::Add &&
589             InnerOpcode == Instruction::Mul)
590           if (match(V, m_APInt(CInt)) && !CInt->isMinSignedValue())
591             BO->setHasNoSignedWrap(HasNSW);
592       }
593     }
594   }
595   return SimplifiedInst;
596 }
597 
598 /// This tries to simplify binary operations which some other binary operation
599 /// distributes over either by factorizing out common terms
600 /// (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this results in
601 /// simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is a win).
602 /// Returns the simplified value, or null if it didn't simplify.
603 Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
604   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
605   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
606   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
607   Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
608 
609   {
610     // Factorization.
611     Value *A, *B, *C, *D;
612     Instruction::BinaryOps LHSOpcode, RHSOpcode;
613     if (Op0)
614       LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B);
615     if (Op1)
616       RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D);
617 
618     // The instruction has the form "(A op' B) op (C op' D)".  Try to factorize
619     // a common term.
620     if (Op0 && Op1 && LHSOpcode == RHSOpcode)
621       if (Value *V = tryFactorization(I, LHSOpcode, A, B, C, D))
622         return V;
623 
624     // The instruction has the form "(A op' B) op (C)".  Try to factorize common
625     // term.
626     if (Op0)
627       if (Value *Ident = getIdentityValue(LHSOpcode, RHS))
628         if (Value *V = tryFactorization(I, LHSOpcode, A, B, RHS, Ident))
629           return V;
630 
631     // The instruction has the form "(B) op (C op' D)".  Try to factorize common
632     // term.
633     if (Op1)
634       if (Value *Ident = getIdentityValue(RHSOpcode, LHS))
635         if (Value *V = tryFactorization(I, RHSOpcode, LHS, Ident, C, D))
636           return V;
637   }
638 
639   // Expansion.
640   if (Op0 && rightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
641     // The instruction has the form "(A op' B) op C".  See if expanding it out
642     // to "(A op C) op' (B op C)" results in simplifications.
643     Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
644     Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
645 
646     Value *L = SimplifyBinOp(TopLevelOpcode, A, C, SQ.getWithInstruction(&I));
647     Value *R = SimplifyBinOp(TopLevelOpcode, B, C, SQ.getWithInstruction(&I));
648 
649     // Do "A op C" and "B op C" both simplify?
650     if (L && R) {
651       // They do! Return "L op' R".
652       ++NumExpand;
653       C = Builder.CreateBinOp(InnerOpcode, L, R);
654       C->takeName(&I);
655       return C;
656     }
657 
658     // Does "A op C" simplify to the identity value for the inner opcode?
659     if (L && L == ConstantExpr::getBinOpIdentity(InnerOpcode, L->getType())) {
660       // They do! Return "B op C".
661       ++NumExpand;
662       C = Builder.CreateBinOp(TopLevelOpcode, B, C);
663       C->takeName(&I);
664       return C;
665     }
666 
667     // Does "B op C" simplify to the identity value for the inner opcode?
668     if (R && R == ConstantExpr::getBinOpIdentity(InnerOpcode, R->getType())) {
669       // They do! Return "A op C".
670       ++NumExpand;
671       C = Builder.CreateBinOp(TopLevelOpcode, A, C);
672       C->takeName(&I);
673       return C;
674     }
675   }
676 
677   if (Op1 && leftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
678     // The instruction has the form "A op (B op' C)".  See if expanding it out
679     // to "(A op B) op' (A op C)" results in simplifications.
680     Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
681     Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
682 
683     Value *L = SimplifyBinOp(TopLevelOpcode, A, B, SQ.getWithInstruction(&I));
684     Value *R = SimplifyBinOp(TopLevelOpcode, A, C, SQ.getWithInstruction(&I));
685 
686     // Do "A op B" and "A op C" both simplify?
687     if (L && R) {
688       // They do! Return "L op' R".
689       ++NumExpand;
690       A = Builder.CreateBinOp(InnerOpcode, L, R);
691       A->takeName(&I);
692       return A;
693     }
694 
695     // Does "A op B" simplify to the identity value for the inner opcode?
696     if (L && L == ConstantExpr::getBinOpIdentity(InnerOpcode, L->getType())) {
697       // They do! Return "A op C".
698       ++NumExpand;
699       A = Builder.CreateBinOp(TopLevelOpcode, A, C);
700       A->takeName(&I);
701       return A;
702     }
703 
704     // Does "A op C" simplify to the identity value for the inner opcode?
705     if (R && R == ConstantExpr::getBinOpIdentity(InnerOpcode, R->getType())) {
706       // They do! Return "A op B".
707       ++NumExpand;
708       A = Builder.CreateBinOp(TopLevelOpcode, A, B);
709       A->takeName(&I);
710       return A;
711     }
712   }
713 
714   return SimplifySelectsFeedingBinaryOp(I, LHS, RHS);
715 }
716 
717 Value *InstCombiner::SimplifySelectsFeedingBinaryOp(BinaryOperator &I,
718                                                     Value *LHS, Value *RHS) {
719   Instruction::BinaryOps Opcode = I.getOpcode();
720   // (op (select (a, b, c)), (select (a, d, e))) -> (select (a, (op b, d), (op
721   // c, e)))
722   Value *A, *B, *C, *D, *E;
723   Value *SI = nullptr;
724   if (match(LHS, m_Select(m_Value(A), m_Value(B), m_Value(C))) &&
725       match(RHS, m_Select(m_Specific(A), m_Value(D), m_Value(E)))) {
726     bool SelectsHaveOneUse = LHS->hasOneUse() && RHS->hasOneUse();
727     BuilderTy::FastMathFlagGuard Guard(Builder);
728     if (isa<FPMathOperator>(&I))
729       Builder.setFastMathFlags(I.getFastMathFlags());
730 
731     Value *V1 = SimplifyBinOp(Opcode, C, E, SQ.getWithInstruction(&I));
732     Value *V2 = SimplifyBinOp(Opcode, B, D, SQ.getWithInstruction(&I));
733     if (V1 && V2)
734       SI = Builder.CreateSelect(A, V2, V1);
735     else if (V2 && SelectsHaveOneUse)
736       SI = Builder.CreateSelect(A, V2, Builder.CreateBinOp(Opcode, C, E));
737     else if (V1 && SelectsHaveOneUse)
738       SI = Builder.CreateSelect(A, Builder.CreateBinOp(Opcode, B, D), V1);
739 
740     if (SI)
741       SI->takeName(&I);
742   }
743 
744   return SI;
745 }
746 
747 /// Given a 'sub' instruction, return the RHS of the instruction if the LHS is a
748 /// constant zero (which is the 'negate' form).
749 Value *InstCombiner::dyn_castNegVal(Value *V) const {
750   Value *NegV;
751   if (match(V, m_Neg(m_Value(NegV))))
752     return NegV;
753 
754   // Constants can be considered to be negated values if they can be folded.
755   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
756     return ConstantExpr::getNeg(C);
757 
758   if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
759     if (C->getType()->getElementType()->isIntegerTy())
760       return ConstantExpr::getNeg(C);
761 
762   if (ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
763     for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
764       Constant *Elt = CV->getAggregateElement(i);
765       if (!Elt)
766         return nullptr;
767 
768       if (isa<UndefValue>(Elt))
769         continue;
770 
771       if (!isa<ConstantInt>(Elt))
772         return nullptr;
773     }
774     return ConstantExpr::getNeg(CV);
775   }
776 
777   return nullptr;
778 }
779 
780 static Value *foldOperationIntoSelectOperand(Instruction &I, Value *SO,
781                                              InstCombiner::BuilderTy &Builder) {
782   if (auto *Cast = dyn_cast<CastInst>(&I))
783     return Builder.CreateCast(Cast->getOpcode(), SO, I.getType());
784 
785   assert(I.isBinaryOp() && "Unexpected opcode for select folding");
786 
787   // Figure out if the constant is the left or the right argument.
788   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
789   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
790 
791   if (auto *SOC = dyn_cast<Constant>(SO)) {
792     if (ConstIsRHS)
793       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
794     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
795   }
796 
797   Value *Op0 = SO, *Op1 = ConstOperand;
798   if (!ConstIsRHS)
799     std::swap(Op0, Op1);
800 
801   auto *BO = cast<BinaryOperator>(&I);
802   Value *RI = Builder.CreateBinOp(BO->getOpcode(), Op0, Op1,
803                                   SO->getName() + ".op");
804   auto *FPInst = dyn_cast<Instruction>(RI);
805   if (FPInst && isa<FPMathOperator>(FPInst))
806     FPInst->copyFastMathFlags(BO);
807   return RI;
808 }
809 
810 Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
811   // Don't modify shared select instructions.
812   if (!SI->hasOneUse())
813     return nullptr;
814 
815   Value *TV = SI->getTrueValue();
816   Value *FV = SI->getFalseValue();
817   if (!(isa<Constant>(TV) || isa<Constant>(FV)))
818     return nullptr;
819 
820   // Bool selects with constant operands can be folded to logical ops.
821   if (SI->getType()->isIntOrIntVectorTy(1))
822     return nullptr;
823 
824   // If it's a bitcast involving vectors, make sure it has the same number of
825   // elements on both sides.
826   if (auto *BC = dyn_cast<BitCastInst>(&Op)) {
827     VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
828     VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
829 
830     // Verify that either both or neither are vectors.
831     if ((SrcTy == nullptr) != (DestTy == nullptr))
832       return nullptr;
833 
834     // If vectors, verify that they have the same number of elements.
835     if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
836       return nullptr;
837   }
838 
839   // Test if a CmpInst instruction is used exclusively by a select as
840   // part of a minimum or maximum operation. If so, refrain from doing
841   // any other folding. This helps out other analyses which understand
842   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
843   // and CodeGen. And in this case, at least one of the comparison
844   // operands has at least one user besides the compare (the select),
845   // which would often largely negate the benefit of folding anyway.
846   if (auto *CI = dyn_cast<CmpInst>(SI->getCondition())) {
847     if (CI->hasOneUse()) {
848       Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
849       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
850           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
851         return nullptr;
852     }
853   }
854 
855   Value *NewTV = foldOperationIntoSelectOperand(Op, TV, Builder);
856   Value *NewFV = foldOperationIntoSelectOperand(Op, FV, Builder);
857   return SelectInst::Create(SI->getCondition(), NewTV, NewFV, "", nullptr, SI);
858 }
859 
860 static Value *foldOperationIntoPhiValue(BinaryOperator *I, Value *InV,
861                                         InstCombiner::BuilderTy &Builder) {
862   bool ConstIsRHS = isa<Constant>(I->getOperand(1));
863   Constant *C = cast<Constant>(I->getOperand(ConstIsRHS));
864 
865   if (auto *InC = dyn_cast<Constant>(InV)) {
866     if (ConstIsRHS)
867       return ConstantExpr::get(I->getOpcode(), InC, C);
868     return ConstantExpr::get(I->getOpcode(), C, InC);
869   }
870 
871   Value *Op0 = InV, *Op1 = C;
872   if (!ConstIsRHS)
873     std::swap(Op0, Op1);
874 
875   Value *RI = Builder.CreateBinOp(I->getOpcode(), Op0, Op1, "phitmp");
876   auto *FPInst = dyn_cast<Instruction>(RI);
877   if (FPInst && isa<FPMathOperator>(FPInst))
878     FPInst->copyFastMathFlags(I);
879   return RI;
880 }
881 
882 Instruction *InstCombiner::foldOpIntoPhi(Instruction &I, PHINode *PN) {
883   unsigned NumPHIValues = PN->getNumIncomingValues();
884   if (NumPHIValues == 0)
885     return nullptr;
886 
887   // We normally only transform phis with a single use.  However, if a PHI has
888   // multiple uses and they are all the same operation, we can fold *all* of the
889   // uses into the PHI.
890   if (!PN->hasOneUse()) {
891     // Walk the use list for the instruction, comparing them to I.
892     for (User *U : PN->users()) {
893       Instruction *UI = cast<Instruction>(U);
894       if (UI != &I && !I.isIdenticalTo(UI))
895         return nullptr;
896     }
897     // Otherwise, we can replace *all* users with the new PHI we form.
898   }
899 
900   // Check to see if all of the operands of the PHI are simple constants
901   // (constantint/constantfp/undef).  If there is one non-constant value,
902   // remember the BB it is in.  If there is more than one or if *it* is a PHI,
903   // bail out.  We don't do arbitrary constant expressions here because moving
904   // their computation can be expensive without a cost model.
905   BasicBlock *NonConstBB = nullptr;
906   for (unsigned i = 0; i != NumPHIValues; ++i) {
907     Value *InVal = PN->getIncomingValue(i);
908     if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
909       continue;
910 
911     if (isa<PHINode>(InVal)) return nullptr;  // Itself a phi.
912     if (NonConstBB) return nullptr;  // More than one non-const value.
913 
914     NonConstBB = PN->getIncomingBlock(i);
915 
916     // If the InVal is an invoke at the end of the pred block, then we can't
917     // insert a computation after it without breaking the edge.
918     if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
919       if (II->getParent() == NonConstBB)
920         return nullptr;
921 
922     // If the incoming non-constant value is in I's block, we will remove one
923     // instruction, but insert another equivalent one, leading to infinite
924     // instcombine.
925     if (isPotentiallyReachable(I.getParent(), NonConstBB, &DT, LI))
926       return nullptr;
927   }
928 
929   // If there is exactly one non-constant value, we can insert a copy of the
930   // operation in that block.  However, if this is a critical edge, we would be
931   // inserting the computation on some other paths (e.g. inside a loop).  Only
932   // do this if the pred block is unconditionally branching into the phi block.
933   if (NonConstBB != nullptr) {
934     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
935     if (!BI || !BI->isUnconditional()) return nullptr;
936   }
937 
938   // Okay, we can do the transformation: create the new PHI node.
939   PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
940   InsertNewInstBefore(NewPN, *PN);
941   NewPN->takeName(PN);
942 
943   // If we are going to have to insert a new computation, do so right before the
944   // predecessor's terminator.
945   if (NonConstBB)
946     Builder.SetInsertPoint(NonConstBB->getTerminator());
947 
948   // Next, add all of the operands to the PHI.
949   if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
950     // We only currently try to fold the condition of a select when it is a phi,
951     // not the true/false values.
952     Value *TrueV = SI->getTrueValue();
953     Value *FalseV = SI->getFalseValue();
954     BasicBlock *PhiTransBB = PN->getParent();
955     for (unsigned i = 0; i != NumPHIValues; ++i) {
956       BasicBlock *ThisBB = PN->getIncomingBlock(i);
957       Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
958       Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
959       Value *InV = nullptr;
960       // Beware of ConstantExpr:  it may eventually evaluate to getNullValue,
961       // even if currently isNullValue gives false.
962       Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i));
963       // For vector constants, we cannot use isNullValue to fold into
964       // FalseVInPred versus TrueVInPred. When we have individual nonzero
965       // elements in the vector, we will incorrectly fold InC to
966       // `TrueVInPred`.
967       if (InC && !isa<ConstantExpr>(InC) && isa<ConstantInt>(InC))
968         InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
969       else {
970         // Generate the select in the same block as PN's current incoming block.
971         // Note: ThisBB need not be the NonConstBB because vector constants
972         // which are constants by definition are handled here.
973         // FIXME: This can lead to an increase in IR generation because we might
974         // generate selects for vector constant phi operand, that could not be
975         // folded to TrueVInPred or FalseVInPred as done for ConstantInt. For
976         // non-vector phis, this transformation was always profitable because
977         // the select would be generated exactly once in the NonConstBB.
978         Builder.SetInsertPoint(ThisBB->getTerminator());
979         InV = Builder.CreateSelect(PN->getIncomingValue(i), TrueVInPred,
980                                    FalseVInPred, "phitmp");
981       }
982       NewPN->addIncoming(InV, ThisBB);
983     }
984   } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
985     Constant *C = cast<Constant>(I.getOperand(1));
986     for (unsigned i = 0; i != NumPHIValues; ++i) {
987       Value *InV = nullptr;
988       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
989         InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
990       else if (isa<ICmpInst>(CI))
991         InV = Builder.CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
992                                  C, "phitmp");
993       else
994         InV = Builder.CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
995                                  C, "phitmp");
996       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
997     }
998   } else if (auto *BO = dyn_cast<BinaryOperator>(&I)) {
999     for (unsigned i = 0; i != NumPHIValues; ++i) {
1000       Value *InV = foldOperationIntoPhiValue(BO, PN->getIncomingValue(i),
1001                                              Builder);
1002       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1003     }
1004   } else {
1005     CastInst *CI = cast<CastInst>(&I);
1006     Type *RetTy = CI->getType();
1007     for (unsigned i = 0; i != NumPHIValues; ++i) {
1008       Value *InV;
1009       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
1010         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1011       else
1012         InV = Builder.CreateCast(CI->getOpcode(), PN->getIncomingValue(i),
1013                                  I.getType(), "phitmp");
1014       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1015     }
1016   }
1017 
1018   for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
1019     Instruction *User = cast<Instruction>(*UI++);
1020     if (User == &I) continue;
1021     replaceInstUsesWith(*User, NewPN);
1022     eraseInstFromFunction(*User);
1023   }
1024   return replaceInstUsesWith(I, NewPN);
1025 }
1026 
1027 Instruction *InstCombiner::foldBinOpIntoSelectOrPhi(BinaryOperator &I) {
1028   if (!isa<Constant>(I.getOperand(1)))
1029     return nullptr;
1030 
1031   if (auto *Sel = dyn_cast<SelectInst>(I.getOperand(0))) {
1032     if (Instruction *NewSel = FoldOpIntoSelect(I, Sel))
1033       return NewSel;
1034   } else if (auto *PN = dyn_cast<PHINode>(I.getOperand(0))) {
1035     if (Instruction *NewPhi = foldOpIntoPhi(I, PN))
1036       return NewPhi;
1037   }
1038   return nullptr;
1039 }
1040 
1041 /// Given a pointer type and a constant offset, determine whether or not there
1042 /// is a sequence of GEP indices into the pointed type that will land us at the
1043 /// specified offset. If so, fill them into NewIndices and return the resultant
1044 /// element type, otherwise return null.
1045 Type *InstCombiner::FindElementAtOffset(PointerType *PtrTy, int64_t Offset,
1046                                         SmallVectorImpl<Value *> &NewIndices) {
1047   Type *Ty = PtrTy->getElementType();
1048   if (!Ty->isSized())
1049     return nullptr;
1050 
1051   // Start with the index over the outer type.  Note that the type size
1052   // might be zero (even if the offset isn't zero) if the indexed type
1053   // is something like [0 x {int, int}]
1054   Type *IndexTy = DL.getIndexType(PtrTy);
1055   int64_t FirstIdx = 0;
1056   if (int64_t TySize = DL.getTypeAllocSize(Ty)) {
1057     FirstIdx = Offset/TySize;
1058     Offset -= FirstIdx*TySize;
1059 
1060     // Handle hosts where % returns negative instead of values [0..TySize).
1061     if (Offset < 0) {
1062       --FirstIdx;
1063       Offset += TySize;
1064       assert(Offset >= 0);
1065     }
1066     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
1067   }
1068 
1069   NewIndices.push_back(ConstantInt::get(IndexTy, FirstIdx));
1070 
1071   // Index into the types.  If we fail, set OrigBase to null.
1072   while (Offset) {
1073     // Indexing into tail padding between struct/array elements.
1074     if (uint64_t(Offset * 8) >= DL.getTypeSizeInBits(Ty))
1075       return nullptr;
1076 
1077     if (StructType *STy = dyn_cast<StructType>(Ty)) {
1078       const StructLayout *SL = DL.getStructLayout(STy);
1079       assert(Offset < (int64_t)SL->getSizeInBytes() &&
1080              "Offset must stay within the indexed type");
1081 
1082       unsigned Elt = SL->getElementContainingOffset(Offset);
1083       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
1084                                             Elt));
1085 
1086       Offset -= SL->getElementOffset(Elt);
1087       Ty = STy->getElementType(Elt);
1088     } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
1089       uint64_t EltSize = DL.getTypeAllocSize(AT->getElementType());
1090       assert(EltSize && "Cannot index into a zero-sized array");
1091       NewIndices.push_back(ConstantInt::get(IndexTy,Offset/EltSize));
1092       Offset %= EltSize;
1093       Ty = AT->getElementType();
1094     } else {
1095       // Otherwise, we can't index into the middle of this atomic type, bail.
1096       return nullptr;
1097     }
1098   }
1099 
1100   return Ty;
1101 }
1102 
1103 static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
1104   // If this GEP has only 0 indices, it is the same pointer as
1105   // Src. If Src is not a trivial GEP too, don't combine
1106   // the indices.
1107   if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
1108       !Src.hasOneUse())
1109     return false;
1110   return true;
1111 }
1112 
1113 /// Return a value X such that Val = X * Scale, or null if none.
1114 /// If the multiplication is known not to overflow, then NoSignedWrap is set.
1115 Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
1116   assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
1117   assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
1118          Scale.getBitWidth() && "Scale not compatible with value!");
1119 
1120   // If Val is zero or Scale is one then Val = Val * Scale.
1121   if (match(Val, m_Zero()) || Scale == 1) {
1122     NoSignedWrap = true;
1123     return Val;
1124   }
1125 
1126   // If Scale is zero then it does not divide Val.
1127   if (Scale.isMinValue())
1128     return nullptr;
1129 
1130   // Look through chains of multiplications, searching for a constant that is
1131   // divisible by Scale.  For example, descaling X*(Y*(Z*4)) by a factor of 4
1132   // will find the constant factor 4 and produce X*(Y*Z).  Descaling X*(Y*8) by
1133   // a factor of 4 will produce X*(Y*2).  The principle of operation is to bore
1134   // down from Val:
1135   //
1136   //     Val = M1 * X          ||   Analysis starts here and works down
1137   //      M1 = M2 * Y          ||   Doesn't descend into terms with more
1138   //      M2 =  Z * 4          \/   than one use
1139   //
1140   // Then to modify a term at the bottom:
1141   //
1142   //     Val = M1 * X
1143   //      M1 =  Z * Y          ||   Replaced M2 with Z
1144   //
1145   // Then to work back up correcting nsw flags.
1146 
1147   // Op - the term we are currently analyzing.  Starts at Val then drills down.
1148   // Replaced with its descaled value before exiting from the drill down loop.
1149   Value *Op = Val;
1150 
1151   // Parent - initially null, but after drilling down notes where Op came from.
1152   // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
1153   // 0'th operand of Val.
1154   std::pair<Instruction *, unsigned> Parent;
1155 
1156   // Set if the transform requires a descaling at deeper levels that doesn't
1157   // overflow.
1158   bool RequireNoSignedWrap = false;
1159 
1160   // Log base 2 of the scale. Negative if not a power of 2.
1161   int32_t logScale = Scale.exactLogBase2();
1162 
1163   for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
1164     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1165       // If Op is a constant divisible by Scale then descale to the quotient.
1166       APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
1167       APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
1168       if (!Remainder.isMinValue())
1169         // Not divisible by Scale.
1170         return nullptr;
1171       // Replace with the quotient in the parent.
1172       Op = ConstantInt::get(CI->getType(), Quotient);
1173       NoSignedWrap = true;
1174       break;
1175     }
1176 
1177     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
1178       if (BO->getOpcode() == Instruction::Mul) {
1179         // Multiplication.
1180         NoSignedWrap = BO->hasNoSignedWrap();
1181         if (RequireNoSignedWrap && !NoSignedWrap)
1182           return nullptr;
1183 
1184         // There are three cases for multiplication: multiplication by exactly
1185         // the scale, multiplication by a constant different to the scale, and
1186         // multiplication by something else.
1187         Value *LHS = BO->getOperand(0);
1188         Value *RHS = BO->getOperand(1);
1189 
1190         if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1191           // Multiplication by a constant.
1192           if (CI->getValue() == Scale) {
1193             // Multiplication by exactly the scale, replace the multiplication
1194             // by its left-hand side in the parent.
1195             Op = LHS;
1196             break;
1197           }
1198 
1199           // Otherwise drill down into the constant.
1200           if (!Op->hasOneUse())
1201             return nullptr;
1202 
1203           Parent = std::make_pair(BO, 1);
1204           continue;
1205         }
1206 
1207         // Multiplication by something else. Drill down into the left-hand side
1208         // since that's where the reassociate pass puts the good stuff.
1209         if (!Op->hasOneUse())
1210           return nullptr;
1211 
1212         Parent = std::make_pair(BO, 0);
1213         continue;
1214       }
1215 
1216       if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
1217           isa<ConstantInt>(BO->getOperand(1))) {
1218         // Multiplication by a power of 2.
1219         NoSignedWrap = BO->hasNoSignedWrap();
1220         if (RequireNoSignedWrap && !NoSignedWrap)
1221           return nullptr;
1222 
1223         Value *LHS = BO->getOperand(0);
1224         int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
1225           getLimitedValue(Scale.getBitWidth());
1226         // Op = LHS << Amt.
1227 
1228         if (Amt == logScale) {
1229           // Multiplication by exactly the scale, replace the multiplication
1230           // by its left-hand side in the parent.
1231           Op = LHS;
1232           break;
1233         }
1234         if (Amt < logScale || !Op->hasOneUse())
1235           return nullptr;
1236 
1237         // Multiplication by more than the scale.  Reduce the multiplying amount
1238         // by the scale in the parent.
1239         Parent = std::make_pair(BO, 1);
1240         Op = ConstantInt::get(BO->getType(), Amt - logScale);
1241         break;
1242       }
1243     }
1244 
1245     if (!Op->hasOneUse())
1246       return nullptr;
1247 
1248     if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
1249       if (Cast->getOpcode() == Instruction::SExt) {
1250         // Op is sign-extended from a smaller type, descale in the smaller type.
1251         unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1252         APInt SmallScale = Scale.trunc(SmallSize);
1253         // Suppose Op = sext X, and we descale X as Y * SmallScale.  We want to
1254         // descale Op as (sext Y) * Scale.  In order to have
1255         //   sext (Y * SmallScale) = (sext Y) * Scale
1256         // some conditions need to hold however: SmallScale must sign-extend to
1257         // Scale and the multiplication Y * SmallScale should not overflow.
1258         if (SmallScale.sext(Scale.getBitWidth()) != Scale)
1259           // SmallScale does not sign-extend to Scale.
1260           return nullptr;
1261         assert(SmallScale.exactLogBase2() == logScale);
1262         // Require that Y * SmallScale must not overflow.
1263         RequireNoSignedWrap = true;
1264 
1265         // Drill down through the cast.
1266         Parent = std::make_pair(Cast, 0);
1267         Scale = SmallScale;
1268         continue;
1269       }
1270 
1271       if (Cast->getOpcode() == Instruction::Trunc) {
1272         // Op is truncated from a larger type, descale in the larger type.
1273         // Suppose Op = trunc X, and we descale X as Y * sext Scale.  Then
1274         //   trunc (Y * sext Scale) = (trunc Y) * Scale
1275         // always holds.  However (trunc Y) * Scale may overflow even if
1276         // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
1277         // from this point up in the expression (see later).
1278         if (RequireNoSignedWrap)
1279           return nullptr;
1280 
1281         // Drill down through the cast.
1282         unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1283         Parent = std::make_pair(Cast, 0);
1284         Scale = Scale.sext(LargeSize);
1285         if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1286           logScale = -1;
1287         assert(Scale.exactLogBase2() == logScale);
1288         continue;
1289       }
1290     }
1291 
1292     // Unsupported expression, bail out.
1293     return nullptr;
1294   }
1295 
1296   // If Op is zero then Val = Op * Scale.
1297   if (match(Op, m_Zero())) {
1298     NoSignedWrap = true;
1299     return Op;
1300   }
1301 
1302   // We know that we can successfully descale, so from here on we can safely
1303   // modify the IR.  Op holds the descaled version of the deepest term in the
1304   // expression.  NoSignedWrap is 'true' if multiplying Op by Scale is known
1305   // not to overflow.
1306 
1307   if (!Parent.first)
1308     // The expression only had one term.
1309     return Op;
1310 
1311   // Rewrite the parent using the descaled version of its operand.
1312   assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
1313   assert(Op != Parent.first->getOperand(Parent.second) &&
1314          "Descaling was a no-op?");
1315   Parent.first->setOperand(Parent.second, Op);
1316   Worklist.Add(Parent.first);
1317 
1318   // Now work back up the expression correcting nsw flags.  The logic is based
1319   // on the following observation: if X * Y is known not to overflow as a signed
1320   // multiplication, and Y is replaced by a value Z with smaller absolute value,
1321   // then X * Z will not overflow as a signed multiplication either.  As we work
1322   // our way up, having NoSignedWrap 'true' means that the descaled value at the
1323   // current level has strictly smaller absolute value than the original.
1324   Instruction *Ancestor = Parent.first;
1325   do {
1326     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
1327       // If the multiplication wasn't nsw then we can't say anything about the
1328       // value of the descaled multiplication, and we have to clear nsw flags
1329       // from this point on up.
1330       bool OpNoSignedWrap = BO->hasNoSignedWrap();
1331       NoSignedWrap &= OpNoSignedWrap;
1332       if (NoSignedWrap != OpNoSignedWrap) {
1333         BO->setHasNoSignedWrap(NoSignedWrap);
1334         Worklist.Add(Ancestor);
1335       }
1336     } else if (Ancestor->getOpcode() == Instruction::Trunc) {
1337       // The fact that the descaled input to the trunc has smaller absolute
1338       // value than the original input doesn't tell us anything useful about
1339       // the absolute values of the truncations.
1340       NoSignedWrap = false;
1341     }
1342     assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
1343            "Failed to keep proper track of nsw flags while drilling down?");
1344 
1345     if (Ancestor == Val)
1346       // Got to the top, all done!
1347       return Val;
1348 
1349     // Move up one level in the expression.
1350     assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
1351     Ancestor = Ancestor->user_back();
1352   } while (true);
1353 }
1354 
1355 Instruction *InstCombiner::foldVectorBinop(BinaryOperator &Inst) {
1356   if (!Inst.getType()->isVectorTy()) return nullptr;
1357 
1358   BinaryOperator::BinaryOps Opcode = Inst.getOpcode();
1359   unsigned NumElts = cast<VectorType>(Inst.getType())->getNumElements();
1360   Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
1361   assert(cast<VectorType>(LHS->getType())->getNumElements() == NumElts);
1362   assert(cast<VectorType>(RHS->getType())->getNumElements() == NumElts);
1363 
1364   // If both operands of the binop are vector concatenations, then perform the
1365   // narrow binop on each pair of the source operands followed by concatenation
1366   // of the results.
1367   Value *L0, *L1, *R0, *R1;
1368   Constant *Mask;
1369   if (match(LHS, m_ShuffleVector(m_Value(L0), m_Value(L1), m_Constant(Mask))) &&
1370       match(RHS, m_ShuffleVector(m_Value(R0), m_Value(R1), m_Specific(Mask))) &&
1371       LHS->hasOneUse() && RHS->hasOneUse() &&
1372       cast<ShuffleVectorInst>(LHS)->isConcat()) {
1373     // This transform does not have the speculative execution constraint as
1374     // below because the shuffle is a concatenation. The new binops are
1375     // operating on exactly the same elements as the existing binop.
1376     // TODO: We could ease the mask requirement to allow different undef lanes,
1377     //       but that requires an analysis of the binop-with-undef output value.
1378     Value *NewBO0 = Builder.CreateBinOp(Opcode, L0, R0);
1379     if (auto *BO = dyn_cast<BinaryOperator>(NewBO0))
1380       BO->copyIRFlags(&Inst);
1381     Value *NewBO1 = Builder.CreateBinOp(Opcode, L1, R1);
1382     if (auto *BO = dyn_cast<BinaryOperator>(NewBO1))
1383       BO->copyIRFlags(&Inst);
1384     return new ShuffleVectorInst(NewBO0, NewBO1, Mask);
1385   }
1386 
1387   // It may not be safe to reorder shuffles and things like div, urem, etc.
1388   // because we may trap when executing those ops on unknown vector elements.
1389   // See PR20059.
1390   if (!isSafeToSpeculativelyExecute(&Inst))
1391     return nullptr;
1392 
1393   auto createBinOpShuffle = [&](Value *X, Value *Y, Constant *M) {
1394     Value *XY = Builder.CreateBinOp(Opcode, X, Y);
1395     if (auto *BO = dyn_cast<BinaryOperator>(XY))
1396       BO->copyIRFlags(&Inst);
1397     return new ShuffleVectorInst(XY, UndefValue::get(XY->getType()), M);
1398   };
1399 
1400   // If both arguments of the binary operation are shuffles that use the same
1401   // mask and shuffle within a single vector, move the shuffle after the binop.
1402   Value *V1, *V2;
1403   if (match(LHS, m_ShuffleVector(m_Value(V1), m_Undef(), m_Constant(Mask))) &&
1404       match(RHS, m_ShuffleVector(m_Value(V2), m_Undef(), m_Specific(Mask))) &&
1405       V1->getType() == V2->getType() &&
1406       (LHS->hasOneUse() || RHS->hasOneUse() || LHS == RHS)) {
1407     // Op(shuffle(V1, Mask), shuffle(V2, Mask)) -> shuffle(Op(V1, V2), Mask)
1408     return createBinOpShuffle(V1, V2, Mask);
1409   }
1410 
1411   // If one argument is a shuffle within one vector and the other is a constant,
1412   // try moving the shuffle after the binary operation. This canonicalization
1413   // intends to move shuffles closer to other shuffles and binops closer to
1414   // other binops, so they can be folded. It may also enable demanded elements
1415   // transforms.
1416   Constant *C;
1417   if (match(&Inst, m_c_BinOp(
1418           m_OneUse(m_ShuffleVector(m_Value(V1), m_Undef(), m_Constant(Mask))),
1419           m_Constant(C))) &&
1420       V1->getType()->getVectorNumElements() <= NumElts) {
1421     assert(Inst.getType()->getScalarType() == V1->getType()->getScalarType() &&
1422            "Shuffle should not change scalar type");
1423     unsigned V1Width = V1->getType()->getVectorNumElements();
1424     // Find constant NewC that has property:
1425     //   shuffle(NewC, ShMask) = C
1426     // If such constant does not exist (example: ShMask=<0,0> and C=<1,2>)
1427     // reorder is not possible. A 1-to-1 mapping is not required. Example:
1428     // ShMask = <1,1,2,2> and C = <5,5,6,6> --> NewC = <undef,5,6,undef>
1429     SmallVector<int, 16> ShMask;
1430     ShuffleVectorInst::getShuffleMask(Mask, ShMask);
1431     SmallVector<Constant *, 16>
1432         NewVecC(V1Width, UndefValue::get(C->getType()->getScalarType()));
1433     bool MayChange = true;
1434     for (unsigned I = 0; I < NumElts; ++I) {
1435       if (ShMask[I] >= 0) {
1436         assert(ShMask[I] < (int)NumElts && "Not expecting narrowing shuffle");
1437         Constant *CElt = C->getAggregateElement(I);
1438         Constant *NewCElt = NewVecC[ShMask[I]];
1439         // Bail out if:
1440         // 1. The constant vector contains a constant expression.
1441         // 2. The shuffle needs an element of the constant vector that can't
1442         //    be mapped to a new constant vector.
1443         // 3. This is a widening shuffle that copies elements of V1 into the
1444         //    extended elements (extending with undef is allowed).
1445         if (!CElt || (!isa<UndefValue>(NewCElt) && NewCElt != CElt) ||
1446             I >= V1Width) {
1447           MayChange = false;
1448           break;
1449         }
1450         NewVecC[ShMask[I]] = CElt;
1451       }
1452     }
1453     if (MayChange) {
1454       Constant *NewC = ConstantVector::get(NewVecC);
1455       // It may not be safe to execute a binop on a vector with undef elements
1456       // because the entire instruction can be folded to undef or create poison
1457       // that did not exist in the original code.
1458       bool ConstOp1 = isa<Constant>(Inst.getOperand(1));
1459       if (Inst.isIntDivRem() || (Inst.isShift() && ConstOp1))
1460         NewC = getSafeVectorConstantForBinop(Opcode, NewC, ConstOp1);
1461 
1462       // Op(shuffle(V1, Mask), C) -> shuffle(Op(V1, NewC), Mask)
1463       // Op(C, shuffle(V1, Mask)) -> shuffle(Op(NewC, V1), Mask)
1464       Value *NewLHS = isa<Constant>(LHS) ? NewC : V1;
1465       Value *NewRHS = isa<Constant>(LHS) ? V1 : NewC;
1466       return createBinOpShuffle(NewLHS, NewRHS, Mask);
1467     }
1468   }
1469 
1470   return nullptr;
1471 }
1472 
1473 /// Try to narrow the width of a binop if at least 1 operand is an extend of
1474 /// of a value. This requires a potentially expensive known bits check to make
1475 /// sure the narrow op does not overflow.
1476 Instruction *InstCombiner::narrowMathIfNoOverflow(BinaryOperator &BO) {
1477   // We need at least one extended operand.
1478   Value *Op0 = BO.getOperand(0), *Op1 = BO.getOperand(1);
1479 
1480   // If this is a sub, we swap the operands since we always want an extension
1481   // on the RHS. The LHS can be an extension or a constant.
1482   if (BO.getOpcode() == Instruction::Sub)
1483     std::swap(Op0, Op1);
1484 
1485   Value *X;
1486   bool IsSext = match(Op0, m_SExt(m_Value(X)));
1487   if (!IsSext && !match(Op0, m_ZExt(m_Value(X))))
1488     return nullptr;
1489 
1490   // If both operands are the same extension from the same source type and we
1491   // can eliminate at least one (hasOneUse), this might work.
1492   CastInst::CastOps CastOpc = IsSext ? Instruction::SExt : Instruction::ZExt;
1493   Value *Y;
1494   if (!(match(Op1, m_ZExtOrSExt(m_Value(Y))) && X->getType() == Y->getType() &&
1495         cast<Operator>(Op1)->getOpcode() == CastOpc &&
1496         (Op0->hasOneUse() || Op1->hasOneUse()))) {
1497     // If that did not match, see if we have a suitable constant operand.
1498     // Truncating and extending must produce the same constant.
1499     Constant *WideC;
1500     if (!Op0->hasOneUse() || !match(Op1, m_Constant(WideC)))
1501       return nullptr;
1502     Constant *NarrowC = ConstantExpr::getTrunc(WideC, X->getType());
1503     if (ConstantExpr::getCast(CastOpc, NarrowC, BO.getType()) != WideC)
1504       return nullptr;
1505     Y = NarrowC;
1506   }
1507 
1508   // Swap back now that we found our operands.
1509   if (BO.getOpcode() == Instruction::Sub)
1510     std::swap(X, Y);
1511 
1512   // Both operands have narrow versions. Last step: the math must not overflow
1513   // in the narrow width.
1514   if (!willNotOverflow(BO.getOpcode(), X, Y, BO, IsSext))
1515     return nullptr;
1516 
1517   // bo (ext X), (ext Y) --> ext (bo X, Y)
1518   // bo (ext X), C       --> ext (bo X, C')
1519   Value *NarrowBO = Builder.CreateBinOp(BO.getOpcode(), X, Y, "narrow");
1520   if (auto *NewBinOp = dyn_cast<BinaryOperator>(NarrowBO)) {
1521     if (IsSext)
1522       NewBinOp->setHasNoSignedWrap();
1523     else
1524       NewBinOp->setHasNoUnsignedWrap();
1525   }
1526   return CastInst::Create(CastOpc, NarrowBO, BO.getType());
1527 }
1528 
1529 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1530   SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
1531   Type *GEPType = GEP.getType();
1532   Type *GEPEltType = GEP.getSourceElementType();
1533   if (Value *V = SimplifyGEPInst(GEPEltType, Ops, SQ.getWithInstruction(&GEP)))
1534     return replaceInstUsesWith(GEP, V);
1535 
1536   Value *PtrOp = GEP.getOperand(0);
1537 
1538   // Eliminate unneeded casts for indices, and replace indices which displace
1539   // by multiples of a zero size type with zero.
1540   bool MadeChange = false;
1541 
1542   // Index width may not be the same width as pointer width.
1543   // Data layout chooses the right type based on supported integer types.
1544   Type *NewScalarIndexTy =
1545       DL.getIndexType(GEP.getPointerOperandType()->getScalarType());
1546 
1547   gep_type_iterator GTI = gep_type_begin(GEP);
1548   for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
1549        ++I, ++GTI) {
1550     // Skip indices into struct types.
1551     if (GTI.isStruct())
1552       continue;
1553 
1554     Type *IndexTy = (*I)->getType();
1555     Type *NewIndexType =
1556         IndexTy->isVectorTy()
1557             ? VectorType::get(NewScalarIndexTy, IndexTy->getVectorNumElements())
1558             : NewScalarIndexTy;
1559 
1560     // If the element type has zero size then any index over it is equivalent
1561     // to an index of zero, so replace it with zero if it is not zero already.
1562     Type *EltTy = GTI.getIndexedType();
1563     if (EltTy->isSized() && DL.getTypeAllocSize(EltTy) == 0)
1564       if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
1565         *I = Constant::getNullValue(NewIndexType);
1566         MadeChange = true;
1567       }
1568 
1569     if (IndexTy != NewIndexType) {
1570       // If we are using a wider index than needed for this platform, shrink
1571       // it to what we need.  If narrower, sign-extend it to what we need.
1572       // This explicit cast can make subsequent optimizations more obvious.
1573       *I = Builder.CreateIntCast(*I, NewIndexType, true);
1574       MadeChange = true;
1575     }
1576   }
1577   if (MadeChange)
1578     return &GEP;
1579 
1580   // Check to see if the inputs to the PHI node are getelementptr instructions.
1581   if (auto *PN = dyn_cast<PHINode>(PtrOp)) {
1582     auto *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
1583     if (!Op1)
1584       return nullptr;
1585 
1586     // Don't fold a GEP into itself through a PHI node. This can only happen
1587     // through the back-edge of a loop. Folding a GEP into itself means that
1588     // the value of the previous iteration needs to be stored in the meantime,
1589     // thus requiring an additional register variable to be live, but not
1590     // actually achieving anything (the GEP still needs to be executed once per
1591     // loop iteration).
1592     if (Op1 == &GEP)
1593       return nullptr;
1594 
1595     int DI = -1;
1596 
1597     for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
1598       auto *Op2 = dyn_cast<GetElementPtrInst>(*I);
1599       if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
1600         return nullptr;
1601 
1602       // As for Op1 above, don't try to fold a GEP into itself.
1603       if (Op2 == &GEP)
1604         return nullptr;
1605 
1606       // Keep track of the type as we walk the GEP.
1607       Type *CurTy = nullptr;
1608 
1609       for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
1610         if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
1611           return nullptr;
1612 
1613         if (Op1->getOperand(J) != Op2->getOperand(J)) {
1614           if (DI == -1) {
1615             // We have not seen any differences yet in the GEPs feeding the
1616             // PHI yet, so we record this one if it is allowed to be a
1617             // variable.
1618 
1619             // The first two arguments can vary for any GEP, the rest have to be
1620             // static for struct slots
1621             if (J > 1 && CurTy->isStructTy())
1622               return nullptr;
1623 
1624             DI = J;
1625           } else {
1626             // The GEP is different by more than one input. While this could be
1627             // extended to support GEPs that vary by more than one variable it
1628             // doesn't make sense since it greatly increases the complexity and
1629             // would result in an R+R+R addressing mode which no backend
1630             // directly supports and would need to be broken into several
1631             // simpler instructions anyway.
1632             return nullptr;
1633           }
1634         }
1635 
1636         // Sink down a layer of the type for the next iteration.
1637         if (J > 0) {
1638           if (J == 1) {
1639             CurTy = Op1->getSourceElementType();
1640           } else if (auto *CT = dyn_cast<CompositeType>(CurTy)) {
1641             CurTy = CT->getTypeAtIndex(Op1->getOperand(J));
1642           } else {
1643             CurTy = nullptr;
1644           }
1645         }
1646       }
1647     }
1648 
1649     // If not all GEPs are identical we'll have to create a new PHI node.
1650     // Check that the old PHI node has only one use so that it will get
1651     // removed.
1652     if (DI != -1 && !PN->hasOneUse())
1653       return nullptr;
1654 
1655     auto *NewGEP = cast<GetElementPtrInst>(Op1->clone());
1656     if (DI == -1) {
1657       // All the GEPs feeding the PHI are identical. Clone one down into our
1658       // BB so that it can be merged with the current GEP.
1659       GEP.getParent()->getInstList().insert(
1660           GEP.getParent()->getFirstInsertionPt(), NewGEP);
1661     } else {
1662       // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
1663       // into the current block so it can be merged, and create a new PHI to
1664       // set that index.
1665       PHINode *NewPN;
1666       {
1667         IRBuilderBase::InsertPointGuard Guard(Builder);
1668         Builder.SetInsertPoint(PN);
1669         NewPN = Builder.CreatePHI(Op1->getOperand(DI)->getType(),
1670                                   PN->getNumOperands());
1671       }
1672 
1673       for (auto &I : PN->operands())
1674         NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1675                            PN->getIncomingBlock(I));
1676 
1677       NewGEP->setOperand(DI, NewPN);
1678       GEP.getParent()->getInstList().insert(
1679           GEP.getParent()->getFirstInsertionPt(), NewGEP);
1680       NewGEP->setOperand(DI, NewPN);
1681     }
1682 
1683     GEP.setOperand(0, NewGEP);
1684     PtrOp = NewGEP;
1685   }
1686 
1687   // Combine Indices - If the source pointer to this getelementptr instruction
1688   // is a getelementptr instruction, combine the indices of the two
1689   // getelementptr instructions into a single instruction.
1690   if (auto *Src = dyn_cast<GEPOperator>(PtrOp)) {
1691     if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
1692       return nullptr;
1693 
1694     // Try to reassociate loop invariant GEP chains to enable LICM.
1695     if (LI && Src->getNumOperands() == 2 && GEP.getNumOperands() == 2 &&
1696         Src->hasOneUse()) {
1697       if (Loop *L = LI->getLoopFor(GEP.getParent())) {
1698         Value *GO1 = GEP.getOperand(1);
1699         Value *SO1 = Src->getOperand(1);
1700         // Reassociate the two GEPs if SO1 is variant in the loop and GO1 is
1701         // invariant: this breaks the dependence between GEPs and allows LICM
1702         // to hoist the invariant part out of the loop.
1703         if (L->isLoopInvariant(GO1) && !L->isLoopInvariant(SO1)) {
1704           // We have to be careful here.
1705           // We have something like:
1706           //  %src = getelementptr <ty>, <ty>* %base, <ty> %idx
1707           //  %gep = getelementptr <ty>, <ty>* %src, <ty> %idx2
1708           // If we just swap idx & idx2 then we could inadvertantly
1709           // change %src from a vector to a scalar, or vice versa.
1710           // Cases:
1711           //  1) %base a scalar & idx a scalar & idx2 a vector
1712           //      => Swapping idx & idx2 turns %src into a vector type.
1713           //  2) %base a scalar & idx a vector & idx2 a scalar
1714           //      => Swapping idx & idx2 turns %src in a scalar type
1715           //  3) %base, %idx, and %idx2 are scalars
1716           //      => %src & %gep are scalars
1717           //      => swapping idx & idx2 is safe
1718           //  4) %base a vector
1719           //      => %src is a vector
1720           //      => swapping idx & idx2 is safe.
1721           auto *SO0 = Src->getOperand(0);
1722           auto *SO0Ty = SO0->getType();
1723           if (!isa<VectorType>(GEPType) || // case 3
1724               isa<VectorType>(SO0Ty)) {    // case 4
1725             Src->setOperand(1, GO1);
1726             GEP.setOperand(1, SO1);
1727             return &GEP;
1728           } else {
1729             // Case 1 or 2
1730             // -- have to recreate %src & %gep
1731             // put NewSrc at same location as %src
1732             Builder.SetInsertPoint(cast<Instruction>(PtrOp));
1733             auto *NewSrc = cast<GetElementPtrInst>(
1734                 Builder.CreateGEP(SO0, GO1, Src->getName()));
1735             NewSrc->setIsInBounds(Src->isInBounds());
1736             auto *NewGEP = GetElementPtrInst::Create(nullptr, NewSrc, {SO1});
1737             NewGEP->setIsInBounds(GEP.isInBounds());
1738             return NewGEP;
1739           }
1740         }
1741       }
1742     }
1743 
1744     // Note that if our source is a gep chain itself then we wait for that
1745     // chain to be resolved before we perform this transformation.  This
1746     // avoids us creating a TON of code in some cases.
1747     if (auto *SrcGEP = dyn_cast<GEPOperator>(Src->getOperand(0)))
1748       if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
1749         return nullptr;   // Wait until our source is folded to completion.
1750 
1751     SmallVector<Value*, 8> Indices;
1752 
1753     // Find out whether the last index in the source GEP is a sequential idx.
1754     bool EndsWithSequential = false;
1755     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
1756          I != E; ++I)
1757       EndsWithSequential = I.isSequential();
1758 
1759     // Can we combine the two pointer arithmetics offsets?
1760     if (EndsWithSequential) {
1761       // Replace: gep (gep %P, long B), long A, ...
1762       // With:    T = long A+B; gep %P, T, ...
1763       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1764       Value *GO1 = GEP.getOperand(1);
1765 
1766       // If they aren't the same type, then the input hasn't been processed
1767       // by the loop above yet (which canonicalizes sequential index types to
1768       // intptr_t).  Just avoid transforming this until the input has been
1769       // normalized.
1770       if (SO1->getType() != GO1->getType())
1771         return nullptr;
1772 
1773       Value *Sum =
1774           SimplifyAddInst(GO1, SO1, false, false, SQ.getWithInstruction(&GEP));
1775       // Only do the combine when we are sure the cost after the
1776       // merge is never more than that before the merge.
1777       if (Sum == nullptr)
1778         return nullptr;
1779 
1780       // Update the GEP in place if possible.
1781       if (Src->getNumOperands() == 2) {
1782         GEP.setOperand(0, Src->getOperand(0));
1783         GEP.setOperand(1, Sum);
1784         return &GEP;
1785       }
1786       Indices.append(Src->op_begin()+1, Src->op_end()-1);
1787       Indices.push_back(Sum);
1788       Indices.append(GEP.op_begin()+2, GEP.op_end());
1789     } else if (isa<Constant>(*GEP.idx_begin()) &&
1790                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
1791                Src->getNumOperands() != 1) {
1792       // Otherwise we can do the fold if the first index of the GEP is a zero
1793       Indices.append(Src->op_begin()+1, Src->op_end());
1794       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
1795     }
1796 
1797     if (!Indices.empty())
1798       return GEP.isInBounds() && Src->isInBounds()
1799                  ? GetElementPtrInst::CreateInBounds(
1800                        Src->getSourceElementType(), Src->getOperand(0), Indices,
1801                        GEP.getName())
1802                  : GetElementPtrInst::Create(Src->getSourceElementType(),
1803                                              Src->getOperand(0), Indices,
1804                                              GEP.getName());
1805   }
1806 
1807   if (GEP.getNumIndices() == 1) {
1808     unsigned AS = GEP.getPointerAddressSpace();
1809     if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
1810         DL.getIndexSizeInBits(AS)) {
1811       uint64_t TyAllocSize = DL.getTypeAllocSize(GEPEltType);
1812 
1813       bool Matched = false;
1814       uint64_t C;
1815       Value *V = nullptr;
1816       if (TyAllocSize == 1) {
1817         V = GEP.getOperand(1);
1818         Matched = true;
1819       } else if (match(GEP.getOperand(1),
1820                        m_AShr(m_Value(V), m_ConstantInt(C)))) {
1821         if (TyAllocSize == 1ULL << C)
1822           Matched = true;
1823       } else if (match(GEP.getOperand(1),
1824                        m_SDiv(m_Value(V), m_ConstantInt(C)))) {
1825         if (TyAllocSize == C)
1826           Matched = true;
1827       }
1828 
1829       if (Matched) {
1830         // Canonicalize (gep i8* X, -(ptrtoint Y))
1831         // to (inttoptr (sub (ptrtoint X), (ptrtoint Y)))
1832         // The GEP pattern is emitted by the SCEV expander for certain kinds of
1833         // pointer arithmetic.
1834         if (match(V, m_Neg(m_PtrToInt(m_Value())))) {
1835           Operator *Index = cast<Operator>(V);
1836           Value *PtrToInt = Builder.CreatePtrToInt(PtrOp, Index->getType());
1837           Value *NewSub = Builder.CreateSub(PtrToInt, Index->getOperand(1));
1838           return CastInst::Create(Instruction::IntToPtr, NewSub, GEPType);
1839         }
1840         // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X))
1841         // to (bitcast Y)
1842         Value *Y;
1843         if (match(V, m_Sub(m_PtrToInt(m_Value(Y)),
1844                            m_PtrToInt(m_Specific(GEP.getOperand(0))))))
1845           return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y, GEPType);
1846       }
1847     }
1848   }
1849 
1850   // We do not handle pointer-vector geps here.
1851   if (GEPType->isVectorTy())
1852     return nullptr;
1853 
1854   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
1855   Value *StrippedPtr = PtrOp->stripPointerCasts();
1856   PointerType *StrippedPtrTy = cast<PointerType>(StrippedPtr->getType());
1857 
1858   if (StrippedPtr != PtrOp) {
1859     bool HasZeroPointerIndex = false;
1860     if (auto *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
1861       HasZeroPointerIndex = C->isZero();
1862 
1863     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
1864     // into     : GEP [10 x i8]* X, i32 0, ...
1865     //
1866     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
1867     //           into     : GEP i8* X, ...
1868     //
1869     // This occurs when the program declares an array extern like "int X[];"
1870     if (HasZeroPointerIndex) {
1871       if (auto *CATy = dyn_cast<ArrayType>(GEPEltType)) {
1872         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
1873         if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
1874           // -> GEP i8* X, ...
1875           SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
1876           GetElementPtrInst *Res = GetElementPtrInst::Create(
1877               StrippedPtrTy->getElementType(), StrippedPtr, Idx, GEP.getName());
1878           Res->setIsInBounds(GEP.isInBounds());
1879           if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
1880             return Res;
1881           // Insert Res, and create an addrspacecast.
1882           // e.g.,
1883           // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
1884           // ->
1885           // %0 = GEP i8 addrspace(1)* X, ...
1886           // addrspacecast i8 addrspace(1)* %0 to i8*
1887           return new AddrSpaceCastInst(Builder.Insert(Res), GEPType);
1888         }
1889 
1890         if (auto *XATy = dyn_cast<ArrayType>(StrippedPtrTy->getElementType())) {
1891           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
1892           if (CATy->getElementType() == XATy->getElementType()) {
1893             // -> GEP [10 x i8]* X, i32 0, ...
1894             // At this point, we know that the cast source type is a pointer
1895             // to an array of the same type as the destination pointer
1896             // array.  Because the array type is never stepped over (there
1897             // is a leading zero) we can fold the cast into this GEP.
1898             if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
1899               GEP.setOperand(0, StrippedPtr);
1900               GEP.setSourceElementType(XATy);
1901               return &GEP;
1902             }
1903             // Cannot replace the base pointer directly because StrippedPtr's
1904             // address space is different. Instead, create a new GEP followed by
1905             // an addrspacecast.
1906             // e.g.,
1907             // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
1908             //   i32 0, ...
1909             // ->
1910             // %0 = GEP [10 x i8] addrspace(1)* X, ...
1911             // addrspacecast i8 addrspace(1)* %0 to i8*
1912             SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
1913             Value *NewGEP = GEP.isInBounds()
1914                                 ? Builder.CreateInBoundsGEP(
1915                                       nullptr, StrippedPtr, Idx, GEP.getName())
1916                                 : Builder.CreateGEP(nullptr, StrippedPtr, Idx,
1917                                                     GEP.getName());
1918             return new AddrSpaceCastInst(NewGEP, GEPType);
1919           }
1920         }
1921       }
1922     } else if (GEP.getNumOperands() == 2) {
1923       // Transform things like:
1924       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
1925       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
1926       Type *SrcEltTy = StrippedPtrTy->getElementType();
1927       if (SrcEltTy->isArrayTy() &&
1928           DL.getTypeAllocSize(SrcEltTy->getArrayElementType()) ==
1929               DL.getTypeAllocSize(GEPEltType)) {
1930         Type *IdxType = DL.getIndexType(GEPType);
1931         Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
1932         Value *NewGEP =
1933             GEP.isInBounds()
1934                 ? Builder.CreateInBoundsGEP(nullptr, StrippedPtr, Idx,
1935                                             GEP.getName())
1936                 : Builder.CreateGEP(nullptr, StrippedPtr, Idx, GEP.getName());
1937 
1938         // V and GEP are both pointer types --> BitCast
1939         return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP, GEPType);
1940       }
1941 
1942       // Transform things like:
1943       // %V = mul i64 %N, 4
1944       // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
1945       // into:  %t1 = getelementptr i32* %arr, i32 %N; bitcast
1946       if (GEPEltType->isSized() && SrcEltTy->isSized()) {
1947         // Check that changing the type amounts to dividing the index by a scale
1948         // factor.
1949         uint64_t ResSize = DL.getTypeAllocSize(GEPEltType);
1950         uint64_t SrcSize = DL.getTypeAllocSize(SrcEltTy);
1951         if (ResSize && SrcSize % ResSize == 0) {
1952           Value *Idx = GEP.getOperand(1);
1953           unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1954           uint64_t Scale = SrcSize / ResSize;
1955 
1956           // Earlier transforms ensure that the index has the right type
1957           // according to Data Layout, which considerably simplifies the
1958           // logic by eliminating implicit casts.
1959           assert(Idx->getType() == DL.getIndexType(GEPType) &&
1960                  "Index type does not match the Data Layout preferences");
1961 
1962           bool NSW;
1963           if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1964             // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1965             // If the multiplication NewIdx * Scale may overflow then the new
1966             // GEP may not be "inbounds".
1967             Value *NewGEP =
1968                 GEP.isInBounds() && NSW
1969                     ? Builder.CreateInBoundsGEP(nullptr, StrippedPtr, NewIdx,
1970                                                 GEP.getName())
1971                     : Builder.CreateGEP(nullptr, StrippedPtr, NewIdx,
1972                                         GEP.getName());
1973 
1974             // The NewGEP must be pointer typed, so must the old one -> BitCast
1975             return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1976                                                                  GEPType);
1977           }
1978         }
1979       }
1980 
1981       // Similarly, transform things like:
1982       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
1983       //   (where tmp = 8*tmp2) into:
1984       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
1985       if (GEPEltType->isSized() && SrcEltTy->isSized() &&
1986           SrcEltTy->isArrayTy()) {
1987         // Check that changing to the array element type amounts to dividing the
1988         // index by a scale factor.
1989         uint64_t ResSize = DL.getTypeAllocSize(GEPEltType);
1990         uint64_t ArrayEltSize =
1991             DL.getTypeAllocSize(SrcEltTy->getArrayElementType());
1992         if (ResSize && ArrayEltSize % ResSize == 0) {
1993           Value *Idx = GEP.getOperand(1);
1994           unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1995           uint64_t Scale = ArrayEltSize / ResSize;
1996 
1997           // Earlier transforms ensure that the index has the right type
1998           // according to the Data Layout, which considerably simplifies
1999           // the logic by eliminating implicit casts.
2000           assert(Idx->getType() == DL.getIndexType(GEPType) &&
2001                  "Index type does not match the Data Layout preferences");
2002 
2003           bool NSW;
2004           if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
2005             // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
2006             // If the multiplication NewIdx * Scale may overflow then the new
2007             // GEP may not be "inbounds".
2008             Type *IndTy = DL.getIndexType(GEPType);
2009             Value *Off[2] = {Constant::getNullValue(IndTy), NewIdx};
2010 
2011             Value *NewGEP = GEP.isInBounds() && NSW
2012                                 ? Builder.CreateInBoundsGEP(
2013                                       SrcEltTy, StrippedPtr, Off, GEP.getName())
2014                                 : Builder.CreateGEP(SrcEltTy, StrippedPtr, Off,
2015                                                     GEP.getName());
2016             // The NewGEP must be pointer typed, so must the old one -> BitCast
2017             return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
2018                                                                  GEPType);
2019           }
2020         }
2021       }
2022     }
2023   }
2024 
2025   // addrspacecast between types is canonicalized as a bitcast, then an
2026   // addrspacecast. To take advantage of the below bitcast + struct GEP, look
2027   // through the addrspacecast.
2028   Value *ASCStrippedPtrOp = PtrOp;
2029   if (auto *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
2030     //   X = bitcast A addrspace(1)* to B addrspace(1)*
2031     //   Y = addrspacecast A addrspace(1)* to B addrspace(2)*
2032     //   Z = gep Y, <...constant indices...>
2033     // Into an addrspacecasted GEP of the struct.
2034     if (auto *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
2035       ASCStrippedPtrOp = BC;
2036   }
2037 
2038   if (auto *BCI = dyn_cast<BitCastInst>(ASCStrippedPtrOp)) {
2039     Value *SrcOp = BCI->getOperand(0);
2040     PointerType *SrcType = cast<PointerType>(BCI->getSrcTy());
2041     Type *SrcEltType = SrcType->getElementType();
2042 
2043     // GEP directly using the source operand if this GEP is accessing an element
2044     // of a bitcasted pointer to vector or array of the same dimensions:
2045     // gep (bitcast <c x ty>* X to [c x ty]*), Y, Z --> gep X, Y, Z
2046     // gep (bitcast [c x ty]* X to <c x ty>*), Y, Z --> gep X, Y, Z
2047     auto areMatchingArrayAndVecTypes = [](Type *ArrTy, Type *VecTy) {
2048       return ArrTy->getArrayElementType() == VecTy->getVectorElementType() &&
2049              ArrTy->getArrayNumElements() == VecTy->getVectorNumElements();
2050     };
2051     if (GEP.getNumOperands() == 3 &&
2052         ((GEPEltType->isArrayTy() && SrcEltType->isVectorTy() &&
2053           areMatchingArrayAndVecTypes(GEPEltType, SrcEltType)) ||
2054          (GEPEltType->isVectorTy() && SrcEltType->isArrayTy() &&
2055           areMatchingArrayAndVecTypes(SrcEltType, GEPEltType)))) {
2056 
2057       // Create a new GEP here, as using `setOperand()` followed by
2058       // `setSourceElementType()` won't actually update the type of the
2059       // existing GEP Value. Causing issues if this Value is accessed when
2060       // constructing an AddrSpaceCastInst
2061       Value *NGEP =
2062           GEP.isInBounds()
2063               ? Builder.CreateInBoundsGEP(nullptr, SrcOp, {Ops[1], Ops[2]})
2064               : Builder.CreateGEP(nullptr, SrcOp, {Ops[1], Ops[2]});
2065       NGEP->takeName(&GEP);
2066 
2067       // Preserve GEP address space to satisfy users
2068       if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
2069         return new AddrSpaceCastInst(NGEP, GEPType);
2070 
2071       return replaceInstUsesWith(GEP, NGEP);
2072     }
2073 
2074     // See if we can simplify:
2075     //   X = bitcast A* to B*
2076     //   Y = gep X, <...constant indices...>
2077     // into a gep of the original struct. This is important for SROA and alias
2078     // analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
2079     unsigned OffsetBits = DL.getIndexTypeSizeInBits(GEPType);
2080     APInt Offset(OffsetBits, 0);
2081     if (!isa<BitCastInst>(SrcOp) && GEP.accumulateConstantOffset(DL, Offset)) {
2082       // If this GEP instruction doesn't move the pointer, just replace the GEP
2083       // with a bitcast of the real input to the dest type.
2084       if (!Offset) {
2085         // If the bitcast is of an allocation, and the allocation will be
2086         // converted to match the type of the cast, don't touch this.
2087         if (isa<AllocaInst>(SrcOp) || isAllocationFn(SrcOp, &TLI)) {
2088           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
2089           if (Instruction *I = visitBitCast(*BCI)) {
2090             if (I != BCI) {
2091               I->takeName(BCI);
2092               BCI->getParent()->getInstList().insert(BCI->getIterator(), I);
2093               replaceInstUsesWith(*BCI, I);
2094             }
2095             return &GEP;
2096           }
2097         }
2098 
2099         if (SrcType->getPointerAddressSpace() != GEP.getAddressSpace())
2100           return new AddrSpaceCastInst(SrcOp, GEPType);
2101         return new BitCastInst(SrcOp, GEPType);
2102       }
2103 
2104       // Otherwise, if the offset is non-zero, we need to find out if there is a
2105       // field at Offset in 'A's type.  If so, we can pull the cast through the
2106       // GEP.
2107       SmallVector<Value*, 8> NewIndices;
2108       if (FindElementAtOffset(SrcType, Offset.getSExtValue(), NewIndices)) {
2109         Value *NGEP =
2110             GEP.isInBounds()
2111                 ? Builder.CreateInBoundsGEP(nullptr, SrcOp, NewIndices)
2112                 : Builder.CreateGEP(nullptr, SrcOp, NewIndices);
2113 
2114         if (NGEP->getType() == GEPType)
2115           return replaceInstUsesWith(GEP, NGEP);
2116         NGEP->takeName(&GEP);
2117 
2118         if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
2119           return new AddrSpaceCastInst(NGEP, GEPType);
2120         return new BitCastInst(NGEP, GEPType);
2121       }
2122     }
2123   }
2124 
2125   if (!GEP.isInBounds()) {
2126     unsigned IdxWidth =
2127         DL.getIndexSizeInBits(PtrOp->getType()->getPointerAddressSpace());
2128     APInt BasePtrOffset(IdxWidth, 0);
2129     Value *UnderlyingPtrOp =
2130             PtrOp->stripAndAccumulateInBoundsConstantOffsets(DL,
2131                                                              BasePtrOffset);
2132     if (auto *AI = dyn_cast<AllocaInst>(UnderlyingPtrOp)) {
2133       if (GEP.accumulateConstantOffset(DL, BasePtrOffset) &&
2134           BasePtrOffset.isNonNegative()) {
2135         APInt AllocSize(IdxWidth, DL.getTypeAllocSize(AI->getAllocatedType()));
2136         if (BasePtrOffset.ule(AllocSize)) {
2137           return GetElementPtrInst::CreateInBounds(
2138               PtrOp, makeArrayRef(Ops).slice(1), GEP.getName());
2139         }
2140       }
2141     }
2142   }
2143 
2144   return nullptr;
2145 }
2146 
2147 static bool isNeverEqualToUnescapedAlloc(Value *V, const TargetLibraryInfo *TLI,
2148                                          Instruction *AI) {
2149   if (isa<ConstantPointerNull>(V))
2150     return true;
2151   if (auto *LI = dyn_cast<LoadInst>(V))
2152     return isa<GlobalVariable>(LI->getPointerOperand());
2153   // Two distinct allocations will never be equal.
2154   // We rely on LookThroughBitCast in isAllocLikeFn being false, since looking
2155   // through bitcasts of V can cause
2156   // the result statement below to be true, even when AI and V (ex:
2157   // i8* ->i32* ->i8* of AI) are the same allocations.
2158   return isAllocLikeFn(V, TLI) && V != AI;
2159 }
2160 
2161 static bool isAllocSiteRemovable(Instruction *AI,
2162                                  SmallVectorImpl<WeakTrackingVH> &Users,
2163                                  const TargetLibraryInfo *TLI) {
2164   SmallVector<Instruction*, 4> Worklist;
2165   Worklist.push_back(AI);
2166 
2167   do {
2168     Instruction *PI = Worklist.pop_back_val();
2169     for (User *U : PI->users()) {
2170       Instruction *I = cast<Instruction>(U);
2171       switch (I->getOpcode()) {
2172       default:
2173         // Give up the moment we see something we can't handle.
2174         return false;
2175 
2176       case Instruction::AddrSpaceCast:
2177       case Instruction::BitCast:
2178       case Instruction::GetElementPtr:
2179         Users.emplace_back(I);
2180         Worklist.push_back(I);
2181         continue;
2182 
2183       case Instruction::ICmp: {
2184         ICmpInst *ICI = cast<ICmpInst>(I);
2185         // We can fold eq/ne comparisons with null to false/true, respectively.
2186         // We also fold comparisons in some conditions provided the alloc has
2187         // not escaped (see isNeverEqualToUnescapedAlloc).
2188         if (!ICI->isEquality())
2189           return false;
2190         unsigned OtherIndex = (ICI->getOperand(0) == PI) ? 1 : 0;
2191         if (!isNeverEqualToUnescapedAlloc(ICI->getOperand(OtherIndex), TLI, AI))
2192           return false;
2193         Users.emplace_back(I);
2194         continue;
2195       }
2196 
2197       case Instruction::Call:
2198         // Ignore no-op and store intrinsics.
2199         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2200           switch (II->getIntrinsicID()) {
2201           default:
2202             return false;
2203 
2204           case Intrinsic::memmove:
2205           case Intrinsic::memcpy:
2206           case Intrinsic::memset: {
2207             MemIntrinsic *MI = cast<MemIntrinsic>(II);
2208             if (MI->isVolatile() || MI->getRawDest() != PI)
2209               return false;
2210             LLVM_FALLTHROUGH;
2211           }
2212           case Intrinsic::invariant_start:
2213           case Intrinsic::invariant_end:
2214           case Intrinsic::lifetime_start:
2215           case Intrinsic::lifetime_end:
2216           case Intrinsic::objectsize:
2217             Users.emplace_back(I);
2218             continue;
2219           }
2220         }
2221 
2222         if (isFreeCall(I, TLI)) {
2223           Users.emplace_back(I);
2224           continue;
2225         }
2226         return false;
2227 
2228       case Instruction::Store: {
2229         StoreInst *SI = cast<StoreInst>(I);
2230         if (SI->isVolatile() || SI->getPointerOperand() != PI)
2231           return false;
2232         Users.emplace_back(I);
2233         continue;
2234       }
2235       }
2236       llvm_unreachable("missing a return?");
2237     }
2238   } while (!Worklist.empty());
2239   return true;
2240 }
2241 
2242 Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
2243   // If we have a malloc call which is only used in any amount of comparisons
2244   // to null and free calls, delete the calls and replace the comparisons with
2245   // true or false as appropriate.
2246   SmallVector<WeakTrackingVH, 64> Users;
2247 
2248   // If we are removing an alloca with a dbg.declare, insert dbg.value calls
2249   // before each store.
2250   TinyPtrVector<DbgVariableIntrinsic *> DIIs;
2251   std::unique_ptr<DIBuilder> DIB;
2252   if (isa<AllocaInst>(MI)) {
2253     DIIs = FindDbgAddrUses(&MI);
2254     DIB.reset(new DIBuilder(*MI.getModule(), /*AllowUnresolved=*/false));
2255   }
2256 
2257   if (isAllocSiteRemovable(&MI, Users, &TLI)) {
2258     for (unsigned i = 0, e = Users.size(); i != e; ++i) {
2259       // Lowering all @llvm.objectsize calls first because they may
2260       // use a bitcast/GEP of the alloca we are removing.
2261       if (!Users[i])
2262        continue;
2263 
2264       Instruction *I = cast<Instruction>(&*Users[i]);
2265 
2266       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2267         if (II->getIntrinsicID() == Intrinsic::objectsize) {
2268           ConstantInt *Result = lowerObjectSizeCall(II, DL, &TLI,
2269                                                     /*MustSucceed=*/true);
2270           replaceInstUsesWith(*I, Result);
2271           eraseInstFromFunction(*I);
2272           Users[i] = nullptr; // Skip examining in the next loop.
2273         }
2274       }
2275     }
2276     for (unsigned i = 0, e = Users.size(); i != e; ++i) {
2277       if (!Users[i])
2278         continue;
2279 
2280       Instruction *I = cast<Instruction>(&*Users[i]);
2281 
2282       if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
2283         replaceInstUsesWith(*C,
2284                             ConstantInt::get(Type::getInt1Ty(C->getContext()),
2285                                              C->isFalseWhenEqual()));
2286       } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I) ||
2287                  isa<AddrSpaceCastInst>(I)) {
2288         replaceInstUsesWith(*I, UndefValue::get(I->getType()));
2289       } else if (auto *SI = dyn_cast<StoreInst>(I)) {
2290         for (auto *DII : DIIs)
2291           ConvertDebugDeclareToDebugValue(DII, SI, *DIB);
2292       }
2293       eraseInstFromFunction(*I);
2294     }
2295 
2296     if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
2297       // Replace invoke with a NOP intrinsic to maintain the original CFG
2298       Module *M = II->getModule();
2299       Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
2300       InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
2301                          None, "", II->getParent());
2302     }
2303 
2304     for (auto *DII : DIIs)
2305       eraseInstFromFunction(*DII);
2306 
2307     return eraseInstFromFunction(MI);
2308   }
2309   return nullptr;
2310 }
2311 
2312 /// Move the call to free before a NULL test.
2313 ///
2314 /// Check if this free is accessed after its argument has been test
2315 /// against NULL (property 0).
2316 /// If yes, it is legal to move this call in its predecessor block.
2317 ///
2318 /// The move is performed only if the block containing the call to free
2319 /// will be removed, i.e.:
2320 /// 1. it has only one predecessor P, and P has two successors
2321 /// 2. it contains the call and an unconditional branch
2322 /// 3. its successor is the same as its predecessor's successor
2323 ///
2324 /// The profitability is out-of concern here and this function should
2325 /// be called only if the caller knows this transformation would be
2326 /// profitable (e.g., for code size).
2327 static Instruction *
2328 tryToMoveFreeBeforeNullTest(CallInst &FI) {
2329   Value *Op = FI.getArgOperand(0);
2330   BasicBlock *FreeInstrBB = FI.getParent();
2331   BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
2332 
2333   // Validate part of constraint #1: Only one predecessor
2334   // FIXME: We can extend the number of predecessor, but in that case, we
2335   //        would duplicate the call to free in each predecessor and it may
2336   //        not be profitable even for code size.
2337   if (!PredBB)
2338     return nullptr;
2339 
2340   // Validate constraint #2: Does this block contains only the call to
2341   //                         free and an unconditional branch?
2342   // FIXME: We could check if we can speculate everything in the
2343   //        predecessor block
2344   if (FreeInstrBB->size() != 2)
2345     return nullptr;
2346   BasicBlock *SuccBB;
2347   if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
2348     return nullptr;
2349 
2350   // Validate the rest of constraint #1 by matching on the pred branch.
2351   Instruction *TI = PredBB->getTerminator();
2352   BasicBlock *TrueBB, *FalseBB;
2353   ICmpInst::Predicate Pred;
2354   if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
2355     return nullptr;
2356   if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2357     return nullptr;
2358 
2359   // Validate constraint #3: Ensure the null case just falls through.
2360   if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
2361     return nullptr;
2362   assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
2363          "Broken CFG: missing edge from predecessor to successor");
2364 
2365   FI.moveBefore(TI);
2366   return &FI;
2367 }
2368 
2369 Instruction *InstCombiner::visitFree(CallInst &FI) {
2370   Value *Op = FI.getArgOperand(0);
2371 
2372   // free undef -> unreachable.
2373   if (isa<UndefValue>(Op)) {
2374     // Insert a new store to null because we cannot modify the CFG here.
2375     Builder.CreateStore(ConstantInt::getTrue(FI.getContext()),
2376                         UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
2377     return eraseInstFromFunction(FI);
2378   }
2379 
2380   // If we have 'free null' delete the instruction.  This can happen in stl code
2381   // when lots of inlining happens.
2382   if (isa<ConstantPointerNull>(Op))
2383     return eraseInstFromFunction(FI);
2384 
2385   // If we optimize for code size, try to move the call to free before the null
2386   // test so that simplify cfg can remove the empty block and dead code
2387   // elimination the branch. I.e., helps to turn something like:
2388   // if (foo) free(foo);
2389   // into
2390   // free(foo);
2391   if (MinimizeSize)
2392     if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
2393       return I;
2394 
2395   return nullptr;
2396 }
2397 
2398 Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) {
2399   if (RI.getNumOperands() == 0) // ret void
2400     return nullptr;
2401 
2402   Value *ResultOp = RI.getOperand(0);
2403   Type *VTy = ResultOp->getType();
2404   if (!VTy->isIntegerTy())
2405     return nullptr;
2406 
2407   // There might be assume intrinsics dominating this return that completely
2408   // determine the value. If so, constant fold it.
2409   KnownBits Known = computeKnownBits(ResultOp, 0, &RI);
2410   if (Known.isConstant())
2411     RI.setOperand(0, Constant::getIntegerValue(VTy, Known.getConstant()));
2412 
2413   return nullptr;
2414 }
2415 
2416 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2417   // Change br (not X), label True, label False to: br X, label False, True
2418   Value *X = nullptr;
2419   BasicBlock *TrueDest;
2420   BasicBlock *FalseDest;
2421   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
2422       !isa<Constant>(X)) {
2423     // Swap Destinations and condition...
2424     BI.setCondition(X);
2425     BI.swapSuccessors();
2426     return &BI;
2427   }
2428 
2429   // If the condition is irrelevant, remove the use so that other
2430   // transforms on the condition become more effective.
2431   if (BI.isConditional() && !isa<ConstantInt>(BI.getCondition()) &&
2432       BI.getSuccessor(0) == BI.getSuccessor(1)) {
2433     BI.setCondition(ConstantInt::getFalse(BI.getCondition()->getType()));
2434     return &BI;
2435   }
2436 
2437   // Canonicalize, for example, icmp_ne -> icmp_eq or fcmp_one -> fcmp_oeq.
2438   CmpInst::Predicate Pred;
2439   if (match(&BI, m_Br(m_OneUse(m_Cmp(Pred, m_Value(), m_Value())), TrueDest,
2440                       FalseDest)) &&
2441       !isCanonicalPredicate(Pred)) {
2442     // Swap destinations and condition.
2443     CmpInst *Cond = cast<CmpInst>(BI.getCondition());
2444     Cond->setPredicate(CmpInst::getInversePredicate(Pred));
2445     BI.swapSuccessors();
2446     Worklist.Add(Cond);
2447     return &BI;
2448   }
2449 
2450   return nullptr;
2451 }
2452 
2453 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
2454   Value *Cond = SI.getCondition();
2455   Value *Op0;
2456   ConstantInt *AddRHS;
2457   if (match(Cond, m_Add(m_Value(Op0), m_ConstantInt(AddRHS)))) {
2458     // Change 'switch (X+4) case 1:' into 'switch (X) case -3'.
2459     for (auto Case : SI.cases()) {
2460       Constant *NewCase = ConstantExpr::getSub(Case.getCaseValue(), AddRHS);
2461       assert(isa<ConstantInt>(NewCase) &&
2462              "Result of expression should be constant");
2463       Case.setValue(cast<ConstantInt>(NewCase));
2464     }
2465     SI.setCondition(Op0);
2466     return &SI;
2467   }
2468 
2469   KnownBits Known = computeKnownBits(Cond, 0, &SI);
2470   unsigned LeadingKnownZeros = Known.countMinLeadingZeros();
2471   unsigned LeadingKnownOnes = Known.countMinLeadingOnes();
2472 
2473   // Compute the number of leading bits we can ignore.
2474   // TODO: A better way to determine this would use ComputeNumSignBits().
2475   for (auto &C : SI.cases()) {
2476     LeadingKnownZeros = std::min(
2477         LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
2478     LeadingKnownOnes = std::min(
2479         LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
2480   }
2481 
2482   unsigned NewWidth = Known.getBitWidth() - std::max(LeadingKnownZeros, LeadingKnownOnes);
2483 
2484   // Shrink the condition operand if the new type is smaller than the old type.
2485   // This may produce a non-standard type for the switch, but that's ok because
2486   // the backend should extend back to a legal type for the target.
2487   if (NewWidth > 0 && NewWidth < Known.getBitWidth()) {
2488     IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
2489     Builder.SetInsertPoint(&SI);
2490     Value *NewCond = Builder.CreateTrunc(Cond, Ty, "trunc");
2491     SI.setCondition(NewCond);
2492 
2493     for (auto Case : SI.cases()) {
2494       APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(NewWidth);
2495       Case.setValue(ConstantInt::get(SI.getContext(), TruncatedCase));
2496     }
2497     return &SI;
2498   }
2499 
2500   return nullptr;
2501 }
2502 
2503 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
2504   Value *Agg = EV.getAggregateOperand();
2505 
2506   if (!EV.hasIndices())
2507     return replaceInstUsesWith(EV, Agg);
2508 
2509   if (Value *V = SimplifyExtractValueInst(Agg, EV.getIndices(),
2510                                           SQ.getWithInstruction(&EV)))
2511     return replaceInstUsesWith(EV, V);
2512 
2513   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
2514     // We're extracting from an insertvalue instruction, compare the indices
2515     const unsigned *exti, *exte, *insi, *inse;
2516     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
2517          exte = EV.idx_end(), inse = IV->idx_end();
2518          exti != exte && insi != inse;
2519          ++exti, ++insi) {
2520       if (*insi != *exti)
2521         // The insert and extract both reference distinctly different elements.
2522         // This means the extract is not influenced by the insert, and we can
2523         // replace the aggregate operand of the extract with the aggregate
2524         // operand of the insert. i.e., replace
2525         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2526         // %E = extractvalue { i32, { i32 } } %I, 0
2527         // with
2528         // %E = extractvalue { i32, { i32 } } %A, 0
2529         return ExtractValueInst::Create(IV->getAggregateOperand(),
2530                                         EV.getIndices());
2531     }
2532     if (exti == exte && insi == inse)
2533       // Both iterators are at the end: Index lists are identical. Replace
2534       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2535       // %C = extractvalue { i32, { i32 } } %B, 1, 0
2536       // with "i32 42"
2537       return replaceInstUsesWith(EV, IV->getInsertedValueOperand());
2538     if (exti == exte) {
2539       // The extract list is a prefix of the insert list. i.e. replace
2540       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2541       // %E = extractvalue { i32, { i32 } } %I, 1
2542       // with
2543       // %X = extractvalue { i32, { i32 } } %A, 1
2544       // %E = insertvalue { i32 } %X, i32 42, 0
2545       // by switching the order of the insert and extract (though the
2546       // insertvalue should be left in, since it may have other uses).
2547       Value *NewEV = Builder.CreateExtractValue(IV->getAggregateOperand(),
2548                                                 EV.getIndices());
2549       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
2550                                      makeArrayRef(insi, inse));
2551     }
2552     if (insi == inse)
2553       // The insert list is a prefix of the extract list
2554       // We can simply remove the common indices from the extract and make it
2555       // operate on the inserted value instead of the insertvalue result.
2556       // i.e., replace
2557       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2558       // %E = extractvalue { i32, { i32 } } %I, 1, 0
2559       // with
2560       // %E extractvalue { i32 } { i32 42 }, 0
2561       return ExtractValueInst::Create(IV->getInsertedValueOperand(),
2562                                       makeArrayRef(exti, exte));
2563   }
2564   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
2565     // We're extracting from an intrinsic, see if we're the only user, which
2566     // allows us to simplify multiple result intrinsics to simpler things that
2567     // just get one value.
2568     if (II->hasOneUse()) {
2569       // Check if we're grabbing the overflow bit or the result of a 'with
2570       // overflow' intrinsic.  If it's the latter we can remove the intrinsic
2571       // and replace it with a traditional binary instruction.
2572       switch (II->getIntrinsicID()) {
2573       case Intrinsic::uadd_with_overflow:
2574       case Intrinsic::sadd_with_overflow:
2575         if (*EV.idx_begin() == 0) {  // Normal result.
2576           Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2577           replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2578           eraseInstFromFunction(*II);
2579           return BinaryOperator::CreateAdd(LHS, RHS);
2580         }
2581 
2582         // If the normal result of the add is dead, and the RHS is a constant,
2583         // we can transform this into a range comparison.
2584         // overflow = uadd a, -4  -->  overflow = icmp ugt a, 3
2585         if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2586           if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
2587             return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
2588                                 ConstantExpr::getNot(CI));
2589         break;
2590       case Intrinsic::usub_with_overflow:
2591       case Intrinsic::ssub_with_overflow:
2592         if (*EV.idx_begin() == 0) {  // Normal result.
2593           Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2594           replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2595           eraseInstFromFunction(*II);
2596           return BinaryOperator::CreateSub(LHS, RHS);
2597         }
2598         break;
2599       case Intrinsic::umul_with_overflow:
2600       case Intrinsic::smul_with_overflow:
2601         if (*EV.idx_begin() == 0) {  // Normal result.
2602           Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2603           replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2604           eraseInstFromFunction(*II);
2605           return BinaryOperator::CreateMul(LHS, RHS);
2606         }
2607         break;
2608       default:
2609         break;
2610       }
2611     }
2612   }
2613   if (LoadInst *L = dyn_cast<LoadInst>(Agg))
2614     // If the (non-volatile) load only has one use, we can rewrite this to a
2615     // load from a GEP. This reduces the size of the load. If a load is used
2616     // only by extractvalue instructions then this either must have been
2617     // optimized before, or it is a struct with padding, in which case we
2618     // don't want to do the transformation as it loses padding knowledge.
2619     if (L->isSimple() && L->hasOneUse()) {
2620       // extractvalue has integer indices, getelementptr has Value*s. Convert.
2621       SmallVector<Value*, 4> Indices;
2622       // Prefix an i32 0 since we need the first element.
2623       Indices.push_back(Builder.getInt32(0));
2624       for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
2625             I != E; ++I)
2626         Indices.push_back(Builder.getInt32(*I));
2627 
2628       // We need to insert these at the location of the old load, not at that of
2629       // the extractvalue.
2630       Builder.SetInsertPoint(L);
2631       Value *GEP = Builder.CreateInBoundsGEP(L->getType(),
2632                                              L->getPointerOperand(), Indices);
2633       Instruction *NL = Builder.CreateLoad(GEP);
2634       // Whatever aliasing information we had for the orignal load must also
2635       // hold for the smaller load, so propagate the annotations.
2636       AAMDNodes Nodes;
2637       L->getAAMetadata(Nodes);
2638       NL->setAAMetadata(Nodes);
2639       // Returning the load directly will cause the main loop to insert it in
2640       // the wrong spot, so use replaceInstUsesWith().
2641       return replaceInstUsesWith(EV, NL);
2642     }
2643   // We could simplify extracts from other values. Note that nested extracts may
2644   // already be simplified implicitly by the above: extract (extract (insert) )
2645   // will be translated into extract ( insert ( extract ) ) first and then just
2646   // the value inserted, if appropriate. Similarly for extracts from single-use
2647   // loads: extract (extract (load)) will be translated to extract (load (gep))
2648   // and if again single-use then via load (gep (gep)) to load (gep).
2649   // However, double extracts from e.g. function arguments or return values
2650   // aren't handled yet.
2651   return nullptr;
2652 }
2653 
2654 /// Return 'true' if the given typeinfo will match anything.
2655 static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
2656   switch (Personality) {
2657   case EHPersonality::GNU_C:
2658   case EHPersonality::GNU_C_SjLj:
2659   case EHPersonality::Rust:
2660     // The GCC C EH and Rust personality only exists to support cleanups, so
2661     // it's not clear what the semantics of catch clauses are.
2662     return false;
2663   case EHPersonality::Unknown:
2664     return false;
2665   case EHPersonality::GNU_Ada:
2666     // While __gnat_all_others_value will match any Ada exception, it doesn't
2667     // match foreign exceptions (or didn't, before gcc-4.7).
2668     return false;
2669   case EHPersonality::GNU_CXX:
2670   case EHPersonality::GNU_CXX_SjLj:
2671   case EHPersonality::GNU_ObjC:
2672   case EHPersonality::MSVC_X86SEH:
2673   case EHPersonality::MSVC_Win64SEH:
2674   case EHPersonality::MSVC_CXX:
2675   case EHPersonality::CoreCLR:
2676   case EHPersonality::Wasm_CXX:
2677     return TypeInfo->isNullValue();
2678   }
2679   llvm_unreachable("invalid enum");
2680 }
2681 
2682 static bool shorter_filter(const Value *LHS, const Value *RHS) {
2683   return
2684     cast<ArrayType>(LHS->getType())->getNumElements()
2685   <
2686     cast<ArrayType>(RHS->getType())->getNumElements();
2687 }
2688 
2689 Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
2690   // The logic here should be correct for any real-world personality function.
2691   // However if that turns out not to be true, the offending logic can always
2692   // be conditioned on the personality function, like the catch-all logic is.
2693   EHPersonality Personality =
2694       classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn());
2695 
2696   // Simplify the list of clauses, eg by removing repeated catch clauses
2697   // (these are often created by inlining).
2698   bool MakeNewInstruction = false; // If true, recreate using the following:
2699   SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
2700   bool CleanupFlag = LI.isCleanup();   // - The new instruction is a cleanup.
2701 
2702   SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
2703   for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
2704     bool isLastClause = i + 1 == e;
2705     if (LI.isCatch(i)) {
2706       // A catch clause.
2707       Constant *CatchClause = LI.getClause(i);
2708       Constant *TypeInfo = CatchClause->stripPointerCasts();
2709 
2710       // If we already saw this clause, there is no point in having a second
2711       // copy of it.
2712       if (AlreadyCaught.insert(TypeInfo).second) {
2713         // This catch clause was not already seen.
2714         NewClauses.push_back(CatchClause);
2715       } else {
2716         // Repeated catch clause - drop the redundant copy.
2717         MakeNewInstruction = true;
2718       }
2719 
2720       // If this is a catch-all then there is no point in keeping any following
2721       // clauses or marking the landingpad as having a cleanup.
2722       if (isCatchAll(Personality, TypeInfo)) {
2723         if (!isLastClause)
2724           MakeNewInstruction = true;
2725         CleanupFlag = false;
2726         break;
2727       }
2728     } else {
2729       // A filter clause.  If any of the filter elements were already caught
2730       // then they can be dropped from the filter.  It is tempting to try to
2731       // exploit the filter further by saying that any typeinfo that does not
2732       // occur in the filter can't be caught later (and thus can be dropped).
2733       // However this would be wrong, since typeinfos can match without being
2734       // equal (for example if one represents a C++ class, and the other some
2735       // class derived from it).
2736       assert(LI.isFilter(i) && "Unsupported landingpad clause!");
2737       Constant *FilterClause = LI.getClause(i);
2738       ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
2739       unsigned NumTypeInfos = FilterType->getNumElements();
2740 
2741       // An empty filter catches everything, so there is no point in keeping any
2742       // following clauses or marking the landingpad as having a cleanup.  By
2743       // dealing with this case here the following code is made a bit simpler.
2744       if (!NumTypeInfos) {
2745         NewClauses.push_back(FilterClause);
2746         if (!isLastClause)
2747           MakeNewInstruction = true;
2748         CleanupFlag = false;
2749         break;
2750       }
2751 
2752       bool MakeNewFilter = false; // If true, make a new filter.
2753       SmallVector<Constant *, 16> NewFilterElts; // New elements.
2754       if (isa<ConstantAggregateZero>(FilterClause)) {
2755         // Not an empty filter - it contains at least one null typeinfo.
2756         assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
2757         Constant *TypeInfo =
2758           Constant::getNullValue(FilterType->getElementType());
2759         // If this typeinfo is a catch-all then the filter can never match.
2760         if (isCatchAll(Personality, TypeInfo)) {
2761           // Throw the filter away.
2762           MakeNewInstruction = true;
2763           continue;
2764         }
2765 
2766         // There is no point in having multiple copies of this typeinfo, so
2767         // discard all but the first copy if there is more than one.
2768         NewFilterElts.push_back(TypeInfo);
2769         if (NumTypeInfos > 1)
2770           MakeNewFilter = true;
2771       } else {
2772         ConstantArray *Filter = cast<ConstantArray>(FilterClause);
2773         SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
2774         NewFilterElts.reserve(NumTypeInfos);
2775 
2776         // Remove any filter elements that were already caught or that already
2777         // occurred in the filter.  While there, see if any of the elements are
2778         // catch-alls.  If so, the filter can be discarded.
2779         bool SawCatchAll = false;
2780         for (unsigned j = 0; j != NumTypeInfos; ++j) {
2781           Constant *Elt = Filter->getOperand(j);
2782           Constant *TypeInfo = Elt->stripPointerCasts();
2783           if (isCatchAll(Personality, TypeInfo)) {
2784             // This element is a catch-all.  Bail out, noting this fact.
2785             SawCatchAll = true;
2786             break;
2787           }
2788 
2789           // Even if we've seen a type in a catch clause, we don't want to
2790           // remove it from the filter.  An unexpected type handler may be
2791           // set up for a call site which throws an exception of the same
2792           // type caught.  In order for the exception thrown by the unexpected
2793           // handler to propagate correctly, the filter must be correctly
2794           // described for the call site.
2795           //
2796           // Example:
2797           //
2798           // void unexpected() { throw 1;}
2799           // void foo() throw (int) {
2800           //   std::set_unexpected(unexpected);
2801           //   try {
2802           //     throw 2.0;
2803           //   } catch (int i) {}
2804           // }
2805 
2806           // There is no point in having multiple copies of the same typeinfo in
2807           // a filter, so only add it if we didn't already.
2808           if (SeenInFilter.insert(TypeInfo).second)
2809             NewFilterElts.push_back(cast<Constant>(Elt));
2810         }
2811         // A filter containing a catch-all cannot match anything by definition.
2812         if (SawCatchAll) {
2813           // Throw the filter away.
2814           MakeNewInstruction = true;
2815           continue;
2816         }
2817 
2818         // If we dropped something from the filter, make a new one.
2819         if (NewFilterElts.size() < NumTypeInfos)
2820           MakeNewFilter = true;
2821       }
2822       if (MakeNewFilter) {
2823         FilterType = ArrayType::get(FilterType->getElementType(),
2824                                     NewFilterElts.size());
2825         FilterClause = ConstantArray::get(FilterType, NewFilterElts);
2826         MakeNewInstruction = true;
2827       }
2828 
2829       NewClauses.push_back(FilterClause);
2830 
2831       // If the new filter is empty then it will catch everything so there is
2832       // no point in keeping any following clauses or marking the landingpad
2833       // as having a cleanup.  The case of the original filter being empty was
2834       // already handled above.
2835       if (MakeNewFilter && !NewFilterElts.size()) {
2836         assert(MakeNewInstruction && "New filter but not a new instruction!");
2837         CleanupFlag = false;
2838         break;
2839       }
2840     }
2841   }
2842 
2843   // If several filters occur in a row then reorder them so that the shortest
2844   // filters come first (those with the smallest number of elements).  This is
2845   // advantageous because shorter filters are more likely to match, speeding up
2846   // unwinding, but mostly because it increases the effectiveness of the other
2847   // filter optimizations below.
2848   for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
2849     unsigned j;
2850     // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
2851     for (j = i; j != e; ++j)
2852       if (!isa<ArrayType>(NewClauses[j]->getType()))
2853         break;
2854 
2855     // Check whether the filters are already sorted by length.  We need to know
2856     // if sorting them is actually going to do anything so that we only make a
2857     // new landingpad instruction if it does.
2858     for (unsigned k = i; k + 1 < j; ++k)
2859       if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
2860         // Not sorted, so sort the filters now.  Doing an unstable sort would be
2861         // correct too but reordering filters pointlessly might confuse users.
2862         std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
2863                          shorter_filter);
2864         MakeNewInstruction = true;
2865         break;
2866       }
2867 
2868     // Look for the next batch of filters.
2869     i = j + 1;
2870   }
2871 
2872   // If typeinfos matched if and only if equal, then the elements of a filter L
2873   // that occurs later than a filter F could be replaced by the intersection of
2874   // the elements of F and L.  In reality two typeinfos can match without being
2875   // equal (for example if one represents a C++ class, and the other some class
2876   // derived from it) so it would be wrong to perform this transform in general.
2877   // However the transform is correct and useful if F is a subset of L.  In that
2878   // case L can be replaced by F, and thus removed altogether since repeating a
2879   // filter is pointless.  So here we look at all pairs of filters F and L where
2880   // L follows F in the list of clauses, and remove L if every element of F is
2881   // an element of L.  This can occur when inlining C++ functions with exception
2882   // specifications.
2883   for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
2884     // Examine each filter in turn.
2885     Value *Filter = NewClauses[i];
2886     ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
2887     if (!FTy)
2888       // Not a filter - skip it.
2889       continue;
2890     unsigned FElts = FTy->getNumElements();
2891     // Examine each filter following this one.  Doing this backwards means that
2892     // we don't have to worry about filters disappearing under us when removed.
2893     for (unsigned j = NewClauses.size() - 1; j != i; --j) {
2894       Value *LFilter = NewClauses[j];
2895       ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
2896       if (!LTy)
2897         // Not a filter - skip it.
2898         continue;
2899       // If Filter is a subset of LFilter, i.e. every element of Filter is also
2900       // an element of LFilter, then discard LFilter.
2901       SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
2902       // If Filter is empty then it is a subset of LFilter.
2903       if (!FElts) {
2904         // Discard LFilter.
2905         NewClauses.erase(J);
2906         MakeNewInstruction = true;
2907         // Move on to the next filter.
2908         continue;
2909       }
2910       unsigned LElts = LTy->getNumElements();
2911       // If Filter is longer than LFilter then it cannot be a subset of it.
2912       if (FElts > LElts)
2913         // Move on to the next filter.
2914         continue;
2915       // At this point we know that LFilter has at least one element.
2916       if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
2917         // Filter is a subset of LFilter iff Filter contains only zeros (as we
2918         // already know that Filter is not longer than LFilter).
2919         if (isa<ConstantAggregateZero>(Filter)) {
2920           assert(FElts <= LElts && "Should have handled this case earlier!");
2921           // Discard LFilter.
2922           NewClauses.erase(J);
2923           MakeNewInstruction = true;
2924         }
2925         // Move on to the next filter.
2926         continue;
2927       }
2928       ConstantArray *LArray = cast<ConstantArray>(LFilter);
2929       if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
2930         // Since Filter is non-empty and contains only zeros, it is a subset of
2931         // LFilter iff LFilter contains a zero.
2932         assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
2933         for (unsigned l = 0; l != LElts; ++l)
2934           if (LArray->getOperand(l)->isNullValue()) {
2935             // LFilter contains a zero - discard it.
2936             NewClauses.erase(J);
2937             MakeNewInstruction = true;
2938             break;
2939           }
2940         // Move on to the next filter.
2941         continue;
2942       }
2943       // At this point we know that both filters are ConstantArrays.  Loop over
2944       // operands to see whether every element of Filter is also an element of
2945       // LFilter.  Since filters tend to be short this is probably faster than
2946       // using a method that scales nicely.
2947       ConstantArray *FArray = cast<ConstantArray>(Filter);
2948       bool AllFound = true;
2949       for (unsigned f = 0; f != FElts; ++f) {
2950         Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
2951         AllFound = false;
2952         for (unsigned l = 0; l != LElts; ++l) {
2953           Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
2954           if (LTypeInfo == FTypeInfo) {
2955             AllFound = true;
2956             break;
2957           }
2958         }
2959         if (!AllFound)
2960           break;
2961       }
2962       if (AllFound) {
2963         // Discard LFilter.
2964         NewClauses.erase(J);
2965         MakeNewInstruction = true;
2966       }
2967       // Move on to the next filter.
2968     }
2969   }
2970 
2971   // If we changed any of the clauses, replace the old landingpad instruction
2972   // with a new one.
2973   if (MakeNewInstruction) {
2974     LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
2975                                                  NewClauses.size());
2976     for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
2977       NLI->addClause(NewClauses[i]);
2978     // A landing pad with no clauses must have the cleanup flag set.  It is
2979     // theoretically possible, though highly unlikely, that we eliminated all
2980     // clauses.  If so, force the cleanup flag to true.
2981     if (NewClauses.empty())
2982       CleanupFlag = true;
2983     NLI->setCleanup(CleanupFlag);
2984     return NLI;
2985   }
2986 
2987   // Even if none of the clauses changed, we may nonetheless have understood
2988   // that the cleanup flag is pointless.  Clear it if so.
2989   if (LI.isCleanup() != CleanupFlag) {
2990     assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
2991     LI.setCleanup(CleanupFlag);
2992     return &LI;
2993   }
2994 
2995   return nullptr;
2996 }
2997 
2998 /// Try to move the specified instruction from its current block into the
2999 /// beginning of DestBlock, which can only happen if it's safe to move the
3000 /// instruction past all of the instructions between it and the end of its
3001 /// block.
3002 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
3003   assert(I->hasOneUse() && "Invariants didn't hold!");
3004   BasicBlock *SrcBlock = I->getParent();
3005 
3006   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
3007   if (isa<PHINode>(I) || I->isEHPad() || I->mayHaveSideEffects() ||
3008       I->isTerminator())
3009     return false;
3010 
3011   // Do not sink alloca instructions out of the entry block.
3012   if (isa<AllocaInst>(I) && I->getParent() ==
3013         &DestBlock->getParent()->getEntryBlock())
3014     return false;
3015 
3016   // Do not sink into catchswitch blocks.
3017   if (isa<CatchSwitchInst>(DestBlock->getTerminator()))
3018     return false;
3019 
3020   // Do not sink convergent call instructions.
3021   if (auto *CI = dyn_cast<CallInst>(I)) {
3022     if (CI->isConvergent())
3023       return false;
3024   }
3025   // We can only sink load instructions if there is nothing between the load and
3026   // the end of block that could change the value.
3027   if (I->mayReadFromMemory()) {
3028     for (BasicBlock::iterator Scan = I->getIterator(),
3029                               E = I->getParent()->end();
3030          Scan != E; ++Scan)
3031       if (Scan->mayWriteToMemory())
3032         return false;
3033   }
3034   BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
3035   I->moveBefore(&*InsertPos);
3036   ++NumSunkInst;
3037 
3038   // Also sink all related debug uses from the source basic block. Otherwise we
3039   // get debug use before the def.
3040   SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
3041   findDbgUsers(DbgUsers, I);
3042   for (auto *DII : DbgUsers) {
3043     if (DII->getParent() == SrcBlock) {
3044       DII->moveBefore(&*InsertPos);
3045       LLVM_DEBUG(dbgs() << "SINK: " << *DII << '\n');
3046     }
3047   }
3048   return true;
3049 }
3050 
3051 bool InstCombiner::run() {
3052   while (!Worklist.isEmpty()) {
3053     Instruction *I = Worklist.RemoveOne();
3054     if (I == nullptr) continue;  // skip null values.
3055 
3056     // Check to see if we can DCE the instruction.
3057     if (isInstructionTriviallyDead(I, &TLI)) {
3058       LLVM_DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
3059       eraseInstFromFunction(*I);
3060       ++NumDeadInst;
3061       MadeIRChange = true;
3062       continue;
3063     }
3064 
3065     if (!DebugCounter::shouldExecute(VisitCounter))
3066       continue;
3067 
3068     // Instruction isn't dead, see if we can constant propagate it.
3069     if (!I->use_empty() &&
3070         (I->getNumOperands() == 0 || isa<Constant>(I->getOperand(0)))) {
3071       if (Constant *C = ConstantFoldInstruction(I, DL, &TLI)) {
3072         LLVM_DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I
3073                           << '\n');
3074 
3075         // Add operands to the worklist.
3076         replaceInstUsesWith(*I, C);
3077         ++NumConstProp;
3078         if (isInstructionTriviallyDead(I, &TLI))
3079           eraseInstFromFunction(*I);
3080         MadeIRChange = true;
3081         continue;
3082       }
3083     }
3084 
3085     // In general, it is possible for computeKnownBits to determine all bits in
3086     // a value even when the operands are not all constants.
3087     Type *Ty = I->getType();
3088     if (ExpensiveCombines && !I->use_empty() && Ty->isIntOrIntVectorTy()) {
3089       KnownBits Known = computeKnownBits(I, /*Depth*/0, I);
3090       if (Known.isConstant()) {
3091         Constant *C = ConstantInt::get(Ty, Known.getConstant());
3092         LLVM_DEBUG(dbgs() << "IC: ConstFold (all bits known) to: " << *C
3093                           << " from: " << *I << '\n');
3094 
3095         // Add operands to the worklist.
3096         replaceInstUsesWith(*I, C);
3097         ++NumConstProp;
3098         if (isInstructionTriviallyDead(I, &TLI))
3099           eraseInstFromFunction(*I);
3100         MadeIRChange = true;
3101         continue;
3102       }
3103     }
3104 
3105     // See if we can trivially sink this instruction to a successor basic block.
3106     if (I->hasOneUse()) {
3107       BasicBlock *BB = I->getParent();
3108       Instruction *UserInst = cast<Instruction>(*I->user_begin());
3109       BasicBlock *UserParent;
3110 
3111       // Get the block the use occurs in.
3112       if (PHINode *PN = dyn_cast<PHINode>(UserInst))
3113         UserParent = PN->getIncomingBlock(*I->use_begin());
3114       else
3115         UserParent = UserInst->getParent();
3116 
3117       if (UserParent != BB) {
3118         bool UserIsSuccessor = false;
3119         // See if the user is one of our successors.
3120         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
3121           if (*SI == UserParent) {
3122             UserIsSuccessor = true;
3123             break;
3124           }
3125 
3126         // If the user is one of our immediate successors, and if that successor
3127         // only has us as a predecessors (we'd have to split the critical edge
3128         // otherwise), we can keep going.
3129         if (UserIsSuccessor && UserParent->getUniquePredecessor()) {
3130           // Okay, the CFG is simple enough, try to sink this instruction.
3131           if (TryToSinkInstruction(I, UserParent)) {
3132             LLVM_DEBUG(dbgs() << "IC: Sink: " << *I << '\n');
3133             MadeIRChange = true;
3134             // We'll add uses of the sunk instruction below, but since sinking
3135             // can expose opportunities for it's *operands* add them to the
3136             // worklist
3137             for (Use &U : I->operands())
3138               if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
3139                 Worklist.Add(OpI);
3140           }
3141         }
3142       }
3143     }
3144 
3145     // Now that we have an instruction, try combining it to simplify it.
3146     Builder.SetInsertPoint(I);
3147     Builder.SetCurrentDebugLocation(I->getDebugLoc());
3148 
3149 #ifndef NDEBUG
3150     std::string OrigI;
3151 #endif
3152     LLVM_DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
3153     LLVM_DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
3154 
3155     if (Instruction *Result = visit(*I)) {
3156       ++NumCombined;
3157       // Should we replace the old instruction with a new one?
3158       if (Result != I) {
3159         LLVM_DEBUG(dbgs() << "IC: Old = " << *I << '\n'
3160                           << "    New = " << *Result << '\n');
3161 
3162         if (I->getDebugLoc())
3163           Result->setDebugLoc(I->getDebugLoc());
3164         // Everything uses the new instruction now.
3165         I->replaceAllUsesWith(Result);
3166 
3167         // Move the name to the new instruction first.
3168         Result->takeName(I);
3169 
3170         // Push the new instruction and any users onto the worklist.
3171         Worklist.AddUsersToWorkList(*Result);
3172         Worklist.Add(Result);
3173 
3174         // Insert the new instruction into the basic block...
3175         BasicBlock *InstParent = I->getParent();
3176         BasicBlock::iterator InsertPos = I->getIterator();
3177 
3178         // If we replace a PHI with something that isn't a PHI, fix up the
3179         // insertion point.
3180         if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
3181           InsertPos = InstParent->getFirstInsertionPt();
3182 
3183         InstParent->getInstList().insert(InsertPos, Result);
3184 
3185         eraseInstFromFunction(*I);
3186       } else {
3187         LLVM_DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
3188                           << "    New = " << *I << '\n');
3189 
3190         // If the instruction was modified, it's possible that it is now dead.
3191         // if so, remove it.
3192         if (isInstructionTriviallyDead(I, &TLI)) {
3193           eraseInstFromFunction(*I);
3194         } else {
3195           Worklist.AddUsersToWorkList(*I);
3196           Worklist.Add(I);
3197         }
3198       }
3199       MadeIRChange = true;
3200     }
3201   }
3202 
3203   Worklist.Zap();
3204   return MadeIRChange;
3205 }
3206 
3207 /// Walk the function in depth-first order, adding all reachable code to the
3208 /// worklist.
3209 ///
3210 /// This has a couple of tricks to make the code faster and more powerful.  In
3211 /// particular, we constant fold and DCE instructions as we go, to avoid adding
3212 /// them to the worklist (this significantly speeds up instcombine on code where
3213 /// many instructions are dead or constant).  Additionally, if we find a branch
3214 /// whose condition is a known constant, we only visit the reachable successors.
3215 static bool AddReachableCodeToWorklist(BasicBlock *BB, const DataLayout &DL,
3216                                        SmallPtrSetImpl<BasicBlock *> &Visited,
3217                                        InstCombineWorklist &ICWorklist,
3218                                        const TargetLibraryInfo *TLI) {
3219   bool MadeIRChange = false;
3220   SmallVector<BasicBlock*, 256> Worklist;
3221   Worklist.push_back(BB);
3222 
3223   SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
3224   DenseMap<Constant *, Constant *> FoldedConstants;
3225 
3226   do {
3227     BB = Worklist.pop_back_val();
3228 
3229     // We have now visited this block!  If we've already been here, ignore it.
3230     if (!Visited.insert(BB).second)
3231       continue;
3232 
3233     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
3234       Instruction *Inst = &*BBI++;
3235 
3236       // DCE instruction if trivially dead.
3237       if (isInstructionTriviallyDead(Inst, TLI)) {
3238         ++NumDeadInst;
3239         LLVM_DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
3240         salvageDebugInfo(*Inst);
3241         Inst->eraseFromParent();
3242         MadeIRChange = true;
3243         continue;
3244       }
3245 
3246       // ConstantProp instruction if trivially constant.
3247       if (!Inst->use_empty() &&
3248           (Inst->getNumOperands() == 0 || isa<Constant>(Inst->getOperand(0))))
3249         if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
3250           LLVM_DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *Inst
3251                             << '\n');
3252           Inst->replaceAllUsesWith(C);
3253           ++NumConstProp;
3254           if (isInstructionTriviallyDead(Inst, TLI))
3255             Inst->eraseFromParent();
3256           MadeIRChange = true;
3257           continue;
3258         }
3259 
3260       // See if we can constant fold its operands.
3261       for (Use &U : Inst->operands()) {
3262         if (!isa<ConstantVector>(U) && !isa<ConstantExpr>(U))
3263           continue;
3264 
3265         auto *C = cast<Constant>(U);
3266         Constant *&FoldRes = FoldedConstants[C];
3267         if (!FoldRes)
3268           FoldRes = ConstantFoldConstant(C, DL, TLI);
3269         if (!FoldRes)
3270           FoldRes = C;
3271 
3272         if (FoldRes != C) {
3273           LLVM_DEBUG(dbgs() << "IC: ConstFold operand of: " << *Inst
3274                             << "\n    Old = " << *C
3275                             << "\n    New = " << *FoldRes << '\n');
3276           U = FoldRes;
3277           MadeIRChange = true;
3278         }
3279       }
3280 
3281       // Skip processing debug intrinsics in InstCombine. Processing these call instructions
3282       // consumes non-trivial amount of time and provides no value for the optimization.
3283       if (!isa<DbgInfoIntrinsic>(Inst))
3284         InstrsForInstCombineWorklist.push_back(Inst);
3285     }
3286 
3287     // Recursively visit successors.  If this is a branch or switch on a
3288     // constant, only visit the reachable successor.
3289     Instruction *TI = BB->getTerminator();
3290     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3291       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
3292         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
3293         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
3294         Worklist.push_back(ReachableBB);
3295         continue;
3296       }
3297     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3298       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
3299         Worklist.push_back(SI->findCaseValue(Cond)->getCaseSuccessor());
3300         continue;
3301       }
3302     }
3303 
3304     for (BasicBlock *SuccBB : successors(TI))
3305       Worklist.push_back(SuccBB);
3306   } while (!Worklist.empty());
3307 
3308   // Once we've found all of the instructions to add to instcombine's worklist,
3309   // add them in reverse order.  This way instcombine will visit from the top
3310   // of the function down.  This jives well with the way that it adds all uses
3311   // of instructions to the worklist after doing a transformation, thus avoiding
3312   // some N^2 behavior in pathological cases.
3313   ICWorklist.AddInitialGroup(InstrsForInstCombineWorklist);
3314 
3315   return MadeIRChange;
3316 }
3317 
3318 /// Populate the IC worklist from a function, and prune any dead basic
3319 /// blocks discovered in the process.
3320 ///
3321 /// This also does basic constant propagation and other forward fixing to make
3322 /// the combiner itself run much faster.
3323 static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL,
3324                                           TargetLibraryInfo *TLI,
3325                                           InstCombineWorklist &ICWorklist) {
3326   bool MadeIRChange = false;
3327 
3328   // Do a depth-first traversal of the function, populate the worklist with
3329   // the reachable instructions.  Ignore blocks that are not reachable.  Keep
3330   // track of which blocks we visit.
3331   SmallPtrSet<BasicBlock *, 32> Visited;
3332   MadeIRChange |=
3333       AddReachableCodeToWorklist(&F.front(), DL, Visited, ICWorklist, TLI);
3334 
3335   // Do a quick scan over the function.  If we find any blocks that are
3336   // unreachable, remove any instructions inside of them.  This prevents
3337   // the instcombine code from having to deal with some bad special cases.
3338   for (BasicBlock &BB : F) {
3339     if (Visited.count(&BB))
3340       continue;
3341 
3342     unsigned NumDeadInstInBB = removeAllNonTerminatorAndEHPadInstructions(&BB);
3343     MadeIRChange |= NumDeadInstInBB > 0;
3344     NumDeadInst += NumDeadInstInBB;
3345   }
3346 
3347   return MadeIRChange;
3348 }
3349 
3350 static bool combineInstructionsOverFunction(
3351     Function &F, InstCombineWorklist &Worklist, AliasAnalysis *AA,
3352     AssumptionCache &AC, TargetLibraryInfo &TLI, DominatorTree &DT,
3353     OptimizationRemarkEmitter &ORE, bool ExpensiveCombines = true,
3354     LoopInfo *LI = nullptr) {
3355   auto &DL = F.getParent()->getDataLayout();
3356   ExpensiveCombines |= EnableExpensiveCombines;
3357 
3358   /// Builder - This is an IRBuilder that automatically inserts new
3359   /// instructions into the worklist when they are created.
3360   IRBuilder<TargetFolder, IRBuilderCallbackInserter> Builder(
3361       F.getContext(), TargetFolder(DL),
3362       IRBuilderCallbackInserter([&Worklist, &AC](Instruction *I) {
3363         Worklist.Add(I);
3364         if (match(I, m_Intrinsic<Intrinsic::assume>()))
3365           AC.registerAssumption(cast<CallInst>(I));
3366       }));
3367 
3368   // Lower dbg.declare intrinsics otherwise their value may be clobbered
3369   // by instcombiner.
3370   bool MadeIRChange = false;
3371   if (ShouldLowerDbgDeclare)
3372     MadeIRChange = LowerDbgDeclare(F);
3373 
3374   // Iterate while there is work to do.
3375   int Iteration = 0;
3376   while (true) {
3377     ++Iteration;
3378     LLVM_DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
3379                       << F.getName() << "\n");
3380 
3381     MadeIRChange |= prepareICWorklistFromFunction(F, DL, &TLI, Worklist);
3382 
3383     InstCombiner IC(Worklist, Builder, F.optForMinSize(), ExpensiveCombines, AA,
3384                     AC, TLI, DT, ORE, DL, LI);
3385     IC.MaxArraySizeForCombine = MaxArraySize;
3386 
3387     if (!IC.run())
3388       break;
3389   }
3390 
3391   return MadeIRChange || Iteration > 1;
3392 }
3393 
3394 PreservedAnalyses InstCombinePass::run(Function &F,
3395                                        FunctionAnalysisManager &AM) {
3396   auto &AC = AM.getResult<AssumptionAnalysis>(F);
3397   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
3398   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
3399   auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
3400 
3401   auto *LI = AM.getCachedResult<LoopAnalysis>(F);
3402 
3403   auto *AA = &AM.getResult<AAManager>(F);
3404   if (!combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT, ORE,
3405                                        ExpensiveCombines, LI))
3406     // No changes, all analyses are preserved.
3407     return PreservedAnalyses::all();
3408 
3409   // Mark all the analyses that instcombine updates as preserved.
3410   PreservedAnalyses PA;
3411   PA.preserveSet<CFGAnalyses>();
3412   PA.preserve<AAManager>();
3413   PA.preserve<BasicAA>();
3414   PA.preserve<GlobalsAA>();
3415   return PA;
3416 }
3417 
3418 void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const {
3419   AU.setPreservesCFG();
3420   AU.addRequired<AAResultsWrapperPass>();
3421   AU.addRequired<AssumptionCacheTracker>();
3422   AU.addRequired<TargetLibraryInfoWrapperPass>();
3423   AU.addRequired<DominatorTreeWrapperPass>();
3424   AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
3425   AU.addPreserved<DominatorTreeWrapperPass>();
3426   AU.addPreserved<AAResultsWrapperPass>();
3427   AU.addPreserved<BasicAAWrapperPass>();
3428   AU.addPreserved<GlobalsAAWrapperPass>();
3429 }
3430 
3431 bool InstructionCombiningPass::runOnFunction(Function &F) {
3432   if (skipFunction(F))
3433     return false;
3434 
3435   // Required analyses.
3436   auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3437   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3438   auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
3439   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3440   auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
3441 
3442   // Optional analyses.
3443   auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
3444   auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
3445 
3446   return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT, ORE,
3447                                          ExpensiveCombines, LI);
3448 }
3449 
3450 char InstructionCombiningPass::ID = 0;
3451 
3452 INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine",
3453                       "Combine redundant instructions", false, false)
3454 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3455 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3456 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3457 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3458 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
3459 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
3460 INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine",
3461                     "Combine redundant instructions", false, false)
3462 
3463 // Initialization Routines
3464 void llvm::initializeInstCombine(PassRegistry &Registry) {
3465   initializeInstructionCombiningPassPass(Registry);
3466 }
3467 
3468 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
3469   initializeInstructionCombiningPassPass(*unwrap(R));
3470 }
3471 
3472 FunctionPass *llvm::createInstructionCombiningPass(bool ExpensiveCombines) {
3473   return new InstructionCombiningPass(ExpensiveCombines);
3474 }
3475 
3476 void LLVMAddInstructionCombiningPass(LLVMPassManagerRef PM) {
3477   unwrap(PM)->add(createInstructionCombiningPass());
3478 }
3479