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