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