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       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
926           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
927         return nullptr;
928     }
929   }
930 
931   Value *NewTV = foldOperationIntoSelectOperand(Op, TV, Builder);
932   Value *NewFV = foldOperationIntoSelectOperand(Op, FV, Builder);
933   return SelectInst::Create(SI->getCondition(), NewTV, NewFV, "", nullptr, SI);
934 }
935 
936 static Value *foldOperationIntoPhiValue(BinaryOperator *I, Value *InV,
937                                         InstCombiner::BuilderTy &Builder) {
938   bool ConstIsRHS = isa<Constant>(I->getOperand(1));
939   Constant *C = cast<Constant>(I->getOperand(ConstIsRHS));
940 
941   if (auto *InC = dyn_cast<Constant>(InV)) {
942     if (ConstIsRHS)
943       return ConstantExpr::get(I->getOpcode(), InC, C);
944     return ConstantExpr::get(I->getOpcode(), C, InC);
945   }
946 
947   Value *Op0 = InV, *Op1 = C;
948   if (!ConstIsRHS)
949     std::swap(Op0, Op1);
950 
951   Value *RI = Builder.CreateBinOp(I->getOpcode(), Op0, Op1, "phitmp");
952   auto *FPInst = dyn_cast<Instruction>(RI);
953   if (FPInst && isa<FPMathOperator>(FPInst))
954     FPInst->copyFastMathFlags(I);
955   return RI;
956 }
957 
958 Instruction *InstCombiner::foldOpIntoPhi(Instruction &I, PHINode *PN) {
959   unsigned NumPHIValues = PN->getNumIncomingValues();
960   if (NumPHIValues == 0)
961     return nullptr;
962 
963   // We normally only transform phis with a single use.  However, if a PHI has
964   // multiple uses and they are all the same operation, we can fold *all* of the
965   // uses into the PHI.
966   if (!PN->hasOneUse()) {
967     // Walk the use list for the instruction, comparing them to I.
968     for (User *U : PN->users()) {
969       Instruction *UI = cast<Instruction>(U);
970       if (UI != &I && !I.isIdenticalTo(UI))
971         return nullptr;
972     }
973     // Otherwise, we can replace *all* users with the new PHI we form.
974   }
975 
976   // Check to see if all of the operands of the PHI are simple constants
977   // (constantint/constantfp/undef).  If there is one non-constant value,
978   // remember the BB it is in.  If there is more than one or if *it* is a PHI,
979   // bail out.  We don't do arbitrary constant expressions here because moving
980   // their computation can be expensive without a cost model.
981   BasicBlock *NonConstBB = nullptr;
982   for (unsigned i = 0; i != NumPHIValues; ++i) {
983     Value *InVal = PN->getIncomingValue(i);
984     if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
985       continue;
986 
987     if (isa<PHINode>(InVal)) return nullptr;  // Itself a phi.
988     if (NonConstBB) return nullptr;  // More than one non-const value.
989 
990     NonConstBB = PN->getIncomingBlock(i);
991 
992     // If the InVal is an invoke at the end of the pred block, then we can't
993     // insert a computation after it without breaking the edge.
994     if (isa<InvokeInst>(InVal))
995       if (cast<Instruction>(InVal)->getParent() == NonConstBB)
996         return nullptr;
997 
998     // If the incoming non-constant value is in I's block, we will remove one
999     // instruction, but insert another equivalent one, leading to infinite
1000     // instcombine.
1001     if (isPotentiallyReachable(I.getParent(), NonConstBB, &DT, LI))
1002       return nullptr;
1003   }
1004 
1005   // If there is exactly one non-constant value, we can insert a copy of the
1006   // operation in that block.  However, if this is a critical edge, we would be
1007   // inserting the computation on some other paths (e.g. inside a loop).  Only
1008   // do this if the pred block is unconditionally branching into the phi block.
1009   if (NonConstBB != nullptr) {
1010     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1011     if (!BI || !BI->isUnconditional()) return nullptr;
1012   }
1013 
1014   // Okay, we can do the transformation: create the new PHI node.
1015   PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
1016   InsertNewInstBefore(NewPN, *PN);
1017   NewPN->takeName(PN);
1018 
1019   // If we are going to have to insert a new computation, do so right before the
1020   // predecessor's terminator.
1021   if (NonConstBB)
1022     Builder.SetInsertPoint(NonConstBB->getTerminator());
1023 
1024   // Next, add all of the operands to the PHI.
1025   if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
1026     // We only currently try to fold the condition of a select when it is a phi,
1027     // not the true/false values.
1028     Value *TrueV = SI->getTrueValue();
1029     Value *FalseV = SI->getFalseValue();
1030     BasicBlock *PhiTransBB = PN->getParent();
1031     for (unsigned i = 0; i != NumPHIValues; ++i) {
1032       BasicBlock *ThisBB = PN->getIncomingBlock(i);
1033       Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
1034       Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
1035       Value *InV = nullptr;
1036       // Beware of ConstantExpr:  it may eventually evaluate to getNullValue,
1037       // even if currently isNullValue gives false.
1038       Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i));
1039       // For vector constants, we cannot use isNullValue to fold into
1040       // FalseVInPred versus TrueVInPred. When we have individual nonzero
1041       // elements in the vector, we will incorrectly fold InC to
1042       // `TrueVInPred`.
1043       if (InC && !isa<ConstantExpr>(InC) && isa<ConstantInt>(InC))
1044         InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
1045       else {
1046         // Generate the select in the same block as PN's current incoming block.
1047         // Note: ThisBB need not be the NonConstBB because vector constants
1048         // which are constants by definition are handled here.
1049         // FIXME: This can lead to an increase in IR generation because we might
1050         // generate selects for vector constant phi operand, that could not be
1051         // folded to TrueVInPred or FalseVInPred as done for ConstantInt. For
1052         // non-vector phis, this transformation was always profitable because
1053         // the select would be generated exactly once in the NonConstBB.
1054         Builder.SetInsertPoint(ThisBB->getTerminator());
1055         InV = Builder.CreateSelect(PN->getIncomingValue(i), TrueVInPred,
1056                                    FalseVInPred, "phitmp");
1057       }
1058       NewPN->addIncoming(InV, ThisBB);
1059     }
1060   } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
1061     Constant *C = cast<Constant>(I.getOperand(1));
1062     for (unsigned i = 0; i != NumPHIValues; ++i) {
1063       Value *InV = nullptr;
1064       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
1065         InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1066       else if (isa<ICmpInst>(CI))
1067         InV = Builder.CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
1068                                  C, "phitmp");
1069       else
1070         InV = Builder.CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
1071                                  C, "phitmp");
1072       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1073     }
1074   } else if (auto *BO = dyn_cast<BinaryOperator>(&I)) {
1075     for (unsigned i = 0; i != NumPHIValues; ++i) {
1076       Value *InV = foldOperationIntoPhiValue(BO, PN->getIncomingValue(i),
1077                                              Builder);
1078       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1079     }
1080   } else {
1081     CastInst *CI = cast<CastInst>(&I);
1082     Type *RetTy = CI->getType();
1083     for (unsigned i = 0; i != NumPHIValues; ++i) {
1084       Value *InV;
1085       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
1086         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1087       else
1088         InV = Builder.CreateCast(CI->getOpcode(), PN->getIncomingValue(i),
1089                                  I.getType(), "phitmp");
1090       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1091     }
1092   }
1093 
1094   for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
1095     Instruction *User = cast<Instruction>(*UI++);
1096     if (User == &I) continue;
1097     replaceInstUsesWith(*User, NewPN);
1098     eraseInstFromFunction(*User);
1099   }
1100   return replaceInstUsesWith(I, NewPN);
1101 }
1102 
1103 Instruction *InstCombiner::foldBinOpIntoSelectOrPhi(BinaryOperator &I) {
1104   if (!isa<Constant>(I.getOperand(1)))
1105     return nullptr;
1106 
1107   if (auto *Sel = dyn_cast<SelectInst>(I.getOperand(0))) {
1108     if (Instruction *NewSel = FoldOpIntoSelect(I, Sel))
1109       return NewSel;
1110   } else if (auto *PN = dyn_cast<PHINode>(I.getOperand(0))) {
1111     if (Instruction *NewPhi = foldOpIntoPhi(I, PN))
1112       return NewPhi;
1113   }
1114   return nullptr;
1115 }
1116 
1117 /// Given a pointer type and a constant offset, determine whether or not there
1118 /// is a sequence of GEP indices into the pointed type that will land us at the
1119 /// specified offset. If so, fill them into NewIndices and return the resultant
1120 /// element type, otherwise return null.
1121 Type *InstCombiner::FindElementAtOffset(PointerType *PtrTy, int64_t Offset,
1122                                         SmallVectorImpl<Value *> &NewIndices) {
1123   Type *Ty = PtrTy->getElementType();
1124   if (!Ty->isSized())
1125     return nullptr;
1126 
1127   // Start with the index over the outer type.  Note that the type size
1128   // might be zero (even if the offset isn't zero) if the indexed type
1129   // is something like [0 x {int, int}]
1130   Type *IndexTy = DL.getIndexType(PtrTy);
1131   int64_t FirstIdx = 0;
1132   if (int64_t TySize = DL.getTypeAllocSize(Ty)) {
1133     FirstIdx = Offset/TySize;
1134     Offset -= FirstIdx*TySize;
1135 
1136     // Handle hosts where % returns negative instead of values [0..TySize).
1137     if (Offset < 0) {
1138       --FirstIdx;
1139       Offset += TySize;
1140       assert(Offset >= 0);
1141     }
1142     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
1143   }
1144 
1145   NewIndices.push_back(ConstantInt::get(IndexTy, FirstIdx));
1146 
1147   // Index into the types.  If we fail, set OrigBase to null.
1148   while (Offset) {
1149     // Indexing into tail padding between struct/array elements.
1150     if (uint64_t(Offset * 8) >= DL.getTypeSizeInBits(Ty))
1151       return nullptr;
1152 
1153     if (StructType *STy = dyn_cast<StructType>(Ty)) {
1154       const StructLayout *SL = DL.getStructLayout(STy);
1155       assert(Offset < (int64_t)SL->getSizeInBytes() &&
1156              "Offset must stay within the indexed type");
1157 
1158       unsigned Elt = SL->getElementContainingOffset(Offset);
1159       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
1160                                             Elt));
1161 
1162       Offset -= SL->getElementOffset(Elt);
1163       Ty = STy->getElementType(Elt);
1164     } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
1165       uint64_t EltSize = DL.getTypeAllocSize(AT->getElementType());
1166       assert(EltSize && "Cannot index into a zero-sized array");
1167       NewIndices.push_back(ConstantInt::get(IndexTy,Offset/EltSize));
1168       Offset %= EltSize;
1169       Ty = AT->getElementType();
1170     } else {
1171       // Otherwise, we can't index into the middle of this atomic type, bail.
1172       return nullptr;
1173     }
1174   }
1175 
1176   return Ty;
1177 }
1178 
1179 static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
1180   // If this GEP has only 0 indices, it is the same pointer as
1181   // Src. If Src is not a trivial GEP too, don't combine
1182   // the indices.
1183   if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
1184       !Src.hasOneUse())
1185     return false;
1186   return true;
1187 }
1188 
1189 /// Return a value X such that Val = X * Scale, or null if none.
1190 /// If the multiplication is known not to overflow, then NoSignedWrap is set.
1191 Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
1192   assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
1193   assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
1194          Scale.getBitWidth() && "Scale not compatible with value!");
1195 
1196   // If Val is zero or Scale is one then Val = Val * Scale.
1197   if (match(Val, m_Zero()) || Scale == 1) {
1198     NoSignedWrap = true;
1199     return Val;
1200   }
1201 
1202   // If Scale is zero then it does not divide Val.
1203   if (Scale.isMinValue())
1204     return nullptr;
1205 
1206   // Look through chains of multiplications, searching for a constant that is
1207   // divisible by Scale.  For example, descaling X*(Y*(Z*4)) by a factor of 4
1208   // will find the constant factor 4 and produce X*(Y*Z).  Descaling X*(Y*8) by
1209   // a factor of 4 will produce X*(Y*2).  The principle of operation is to bore
1210   // down from Val:
1211   //
1212   //     Val = M1 * X          ||   Analysis starts here and works down
1213   //      M1 = M2 * Y          ||   Doesn't descend into terms with more
1214   //      M2 =  Z * 4          \/   than one use
1215   //
1216   // Then to modify a term at the bottom:
1217   //
1218   //     Val = M1 * X
1219   //      M1 =  Z * Y          ||   Replaced M2 with Z
1220   //
1221   // Then to work back up correcting nsw flags.
1222 
1223   // Op - the term we are currently analyzing.  Starts at Val then drills down.
1224   // Replaced with its descaled value before exiting from the drill down loop.
1225   Value *Op = Val;
1226 
1227   // Parent - initially null, but after drilling down notes where Op came from.
1228   // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
1229   // 0'th operand of Val.
1230   std::pair<Instruction *, unsigned> Parent;
1231 
1232   // Set if the transform requires a descaling at deeper levels that doesn't
1233   // overflow.
1234   bool RequireNoSignedWrap = false;
1235 
1236   // Log base 2 of the scale. Negative if not a power of 2.
1237   int32_t logScale = Scale.exactLogBase2();
1238 
1239   for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
1240     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1241       // If Op is a constant divisible by Scale then descale to the quotient.
1242       APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
1243       APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
1244       if (!Remainder.isMinValue())
1245         // Not divisible by Scale.
1246         return nullptr;
1247       // Replace with the quotient in the parent.
1248       Op = ConstantInt::get(CI->getType(), Quotient);
1249       NoSignedWrap = true;
1250       break;
1251     }
1252 
1253     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
1254       if (BO->getOpcode() == Instruction::Mul) {
1255         // Multiplication.
1256         NoSignedWrap = BO->hasNoSignedWrap();
1257         if (RequireNoSignedWrap && !NoSignedWrap)
1258           return nullptr;
1259 
1260         // There are three cases for multiplication: multiplication by exactly
1261         // the scale, multiplication by a constant different to the scale, and
1262         // multiplication by something else.
1263         Value *LHS = BO->getOperand(0);
1264         Value *RHS = BO->getOperand(1);
1265 
1266         if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1267           // Multiplication by a constant.
1268           if (CI->getValue() == Scale) {
1269             // Multiplication by exactly the scale, replace the multiplication
1270             // by its left-hand side in the parent.
1271             Op = LHS;
1272             break;
1273           }
1274 
1275           // Otherwise drill down into the constant.
1276           if (!Op->hasOneUse())
1277             return nullptr;
1278 
1279           Parent = std::make_pair(BO, 1);
1280           continue;
1281         }
1282 
1283         // Multiplication by something else. Drill down into the left-hand side
1284         // since that's where the reassociate pass puts the good stuff.
1285         if (!Op->hasOneUse())
1286           return nullptr;
1287 
1288         Parent = std::make_pair(BO, 0);
1289         continue;
1290       }
1291 
1292       if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
1293           isa<ConstantInt>(BO->getOperand(1))) {
1294         // Multiplication by a power of 2.
1295         NoSignedWrap = BO->hasNoSignedWrap();
1296         if (RequireNoSignedWrap && !NoSignedWrap)
1297           return nullptr;
1298 
1299         Value *LHS = BO->getOperand(0);
1300         int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
1301           getLimitedValue(Scale.getBitWidth());
1302         // Op = LHS << Amt.
1303 
1304         if (Amt == logScale) {
1305           // Multiplication by exactly the scale, replace the multiplication
1306           // by its left-hand side in the parent.
1307           Op = LHS;
1308           break;
1309         }
1310         if (Amt < logScale || !Op->hasOneUse())
1311           return nullptr;
1312 
1313         // Multiplication by more than the scale.  Reduce the multiplying amount
1314         // by the scale in the parent.
1315         Parent = std::make_pair(BO, 1);
1316         Op = ConstantInt::get(BO->getType(), Amt - logScale);
1317         break;
1318       }
1319     }
1320 
1321     if (!Op->hasOneUse())
1322       return nullptr;
1323 
1324     if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
1325       if (Cast->getOpcode() == Instruction::SExt) {
1326         // Op is sign-extended from a smaller type, descale in the smaller type.
1327         unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1328         APInt SmallScale = Scale.trunc(SmallSize);
1329         // Suppose Op = sext X, and we descale X as Y * SmallScale.  We want to
1330         // descale Op as (sext Y) * Scale.  In order to have
1331         //   sext (Y * SmallScale) = (sext Y) * Scale
1332         // some conditions need to hold however: SmallScale must sign-extend to
1333         // Scale and the multiplication Y * SmallScale should not overflow.
1334         if (SmallScale.sext(Scale.getBitWidth()) != Scale)
1335           // SmallScale does not sign-extend to Scale.
1336           return nullptr;
1337         assert(SmallScale.exactLogBase2() == logScale);
1338         // Require that Y * SmallScale must not overflow.
1339         RequireNoSignedWrap = true;
1340 
1341         // Drill down through the cast.
1342         Parent = std::make_pair(Cast, 0);
1343         Scale = SmallScale;
1344         continue;
1345       }
1346 
1347       if (Cast->getOpcode() == Instruction::Trunc) {
1348         // Op is truncated from a larger type, descale in the larger type.
1349         // Suppose Op = trunc X, and we descale X as Y * sext Scale.  Then
1350         //   trunc (Y * sext Scale) = (trunc Y) * Scale
1351         // always holds.  However (trunc Y) * Scale may overflow even if
1352         // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
1353         // from this point up in the expression (see later).
1354         if (RequireNoSignedWrap)
1355           return nullptr;
1356 
1357         // Drill down through the cast.
1358         unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1359         Parent = std::make_pair(Cast, 0);
1360         Scale = Scale.sext(LargeSize);
1361         if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1362           logScale = -1;
1363         assert(Scale.exactLogBase2() == logScale);
1364         continue;
1365       }
1366     }
1367 
1368     // Unsupported expression, bail out.
1369     return nullptr;
1370   }
1371 
1372   // If Op is zero then Val = Op * Scale.
1373   if (match(Op, m_Zero())) {
1374     NoSignedWrap = true;
1375     return Op;
1376   }
1377 
1378   // We know that we can successfully descale, so from here on we can safely
1379   // modify the IR.  Op holds the descaled version of the deepest term in the
1380   // expression.  NoSignedWrap is 'true' if multiplying Op by Scale is known
1381   // not to overflow.
1382 
1383   if (!Parent.first)
1384     // The expression only had one term.
1385     return Op;
1386 
1387   // Rewrite the parent using the descaled version of its operand.
1388   assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
1389   assert(Op != Parent.first->getOperand(Parent.second) &&
1390          "Descaling was a no-op?");
1391   replaceOperand(*Parent.first, Parent.second, Op);
1392   Worklist.push(Parent.first);
1393 
1394   // Now work back up the expression correcting nsw flags.  The logic is based
1395   // on the following observation: if X * Y is known not to overflow as a signed
1396   // multiplication, and Y is replaced by a value Z with smaller absolute value,
1397   // then X * Z will not overflow as a signed multiplication either.  As we work
1398   // our way up, having NoSignedWrap 'true' means that the descaled value at the
1399   // current level has strictly smaller absolute value than the original.
1400   Instruction *Ancestor = Parent.first;
1401   do {
1402     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
1403       // If the multiplication wasn't nsw then we can't say anything about the
1404       // value of the descaled multiplication, and we have to clear nsw flags
1405       // from this point on up.
1406       bool OpNoSignedWrap = BO->hasNoSignedWrap();
1407       NoSignedWrap &= OpNoSignedWrap;
1408       if (NoSignedWrap != OpNoSignedWrap) {
1409         BO->setHasNoSignedWrap(NoSignedWrap);
1410         Worklist.push(Ancestor);
1411       }
1412     } else if (Ancestor->getOpcode() == Instruction::Trunc) {
1413       // The fact that the descaled input to the trunc has smaller absolute
1414       // value than the original input doesn't tell us anything useful about
1415       // the absolute values of the truncations.
1416       NoSignedWrap = false;
1417     }
1418     assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
1419            "Failed to keep proper track of nsw flags while drilling down?");
1420 
1421     if (Ancestor == Val)
1422       // Got to the top, all done!
1423       return Val;
1424 
1425     // Move up one level in the expression.
1426     assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
1427     Ancestor = Ancestor->user_back();
1428   } while (true);
1429 }
1430 
1431 Instruction *InstCombiner::foldVectorBinop(BinaryOperator &Inst) {
1432   if (!Inst.getType()->isVectorTy()) return nullptr;
1433 
1434   BinaryOperator::BinaryOps Opcode = Inst.getOpcode();
1435   unsigned NumElts = cast<VectorType>(Inst.getType())->getNumElements();
1436   Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
1437   assert(cast<VectorType>(LHS->getType())->getNumElements() == NumElts);
1438   assert(cast<VectorType>(RHS->getType())->getNumElements() == NumElts);
1439 
1440   // If both operands of the binop are vector concatenations, then perform the
1441   // narrow binop on each pair of the source operands followed by concatenation
1442   // of the results.
1443   Value *L0, *L1, *R0, *R1;
1444   ArrayRef<int> Mask;
1445   if (match(LHS, m_ShuffleVector(m_Value(L0), m_Value(L1), m_Mask(Mask))) &&
1446       match(RHS,
1447             m_ShuffleVector(m_Value(R0), m_Value(R1), m_SpecificMask(Mask))) &&
1448       LHS->hasOneUse() && RHS->hasOneUse() &&
1449       cast<ShuffleVectorInst>(LHS)->isConcat() &&
1450       cast<ShuffleVectorInst>(RHS)->isConcat()) {
1451     // This transform does not have the speculative execution constraint as
1452     // below because the shuffle is a concatenation. The new binops are
1453     // operating on exactly the same elements as the existing binop.
1454     // TODO: We could ease the mask requirement to allow different undef lanes,
1455     //       but that requires an analysis of the binop-with-undef output value.
1456     Value *NewBO0 = Builder.CreateBinOp(Opcode, L0, R0);
1457     if (auto *BO = dyn_cast<BinaryOperator>(NewBO0))
1458       BO->copyIRFlags(&Inst);
1459     Value *NewBO1 = Builder.CreateBinOp(Opcode, L1, R1);
1460     if (auto *BO = dyn_cast<BinaryOperator>(NewBO1))
1461       BO->copyIRFlags(&Inst);
1462     return new ShuffleVectorInst(NewBO0, NewBO1, Mask);
1463   }
1464 
1465   // It may not be safe to reorder shuffles and things like div, urem, etc.
1466   // because we may trap when executing those ops on unknown vector elements.
1467   // See PR20059.
1468   if (!isSafeToSpeculativelyExecute(&Inst))
1469     return nullptr;
1470 
1471   auto createBinOpShuffle = [&](Value *X, Value *Y, ArrayRef<int> M) {
1472     Value *XY = Builder.CreateBinOp(Opcode, X, Y);
1473     if (auto *BO = dyn_cast<BinaryOperator>(XY))
1474       BO->copyIRFlags(&Inst);
1475     return new ShuffleVectorInst(XY, UndefValue::get(XY->getType()), M);
1476   };
1477 
1478   // If both arguments of the binary operation are shuffles that use the same
1479   // mask and shuffle within a single vector, move the shuffle after the binop.
1480   Value *V1, *V2;
1481   if (match(LHS, m_ShuffleVector(m_Value(V1), m_Undef(), m_Mask(Mask))) &&
1482       match(RHS,
1483             m_ShuffleVector(m_Value(V2), m_Undef(), m_SpecificMask(Mask))) &&
1484       V1->getType() == V2->getType() &&
1485       (LHS->hasOneUse() || RHS->hasOneUse() || LHS == RHS)) {
1486     // Op(shuffle(V1, Mask), shuffle(V2, Mask)) -> shuffle(Op(V1, V2), Mask)
1487     return createBinOpShuffle(V1, V2, Mask);
1488   }
1489 
1490   // If both arguments of a commutative binop are select-shuffles that use the
1491   // same mask with commuted operands, the shuffles are unnecessary.
1492   if (Inst.isCommutative() &&
1493       match(LHS, m_ShuffleVector(m_Value(V1), m_Value(V2), m_Mask(Mask))) &&
1494       match(RHS, m_ShuffleVector(m_Specific(V2), m_Specific(V1),
1495                                  m_SpecificMask(Mask)))) {
1496     auto *LShuf = cast<ShuffleVectorInst>(LHS);
1497     auto *RShuf = cast<ShuffleVectorInst>(RHS);
1498     // TODO: Allow shuffles that contain undefs in the mask?
1499     //       That is legal, but it reduces undef knowledge.
1500     // TODO: Allow arbitrary shuffles by shuffling after binop?
1501     //       That might be legal, but we have to deal with poison.
1502     if (LShuf->isSelect() &&
1503         !is_contained(LShuf->getShuffleMask(), UndefMaskElem) &&
1504         RShuf->isSelect() &&
1505         !is_contained(RShuf->getShuffleMask(), UndefMaskElem)) {
1506       // Example:
1507       // LHS = shuffle V1, V2, <0, 5, 6, 3>
1508       // RHS = shuffle V2, V1, <0, 5, 6, 3>
1509       // LHS + RHS --> (V10+V20, V21+V11, V22+V12, V13+V23) --> V1 + V2
1510       Instruction *NewBO = BinaryOperator::Create(Opcode, V1, V2);
1511       NewBO->copyIRFlags(&Inst);
1512       return NewBO;
1513     }
1514   }
1515 
1516   // If one argument is a shuffle within one vector and the other is a constant,
1517   // try moving the shuffle after the binary operation. This canonicalization
1518   // intends to move shuffles closer to other shuffles and binops closer to
1519   // other binops, so they can be folded. It may also enable demanded elements
1520   // transforms.
1521   Constant *C;
1522   if (match(&Inst, m_c_BinOp(m_OneUse(m_ShuffleVector(m_Value(V1), m_Undef(),
1523                                                       m_Mask(Mask))),
1524                              m_Constant(C))) &&
1525       cast<VectorType>(V1->getType())->getNumElements() <= NumElts) {
1526     assert(Inst.getType()->getScalarType() == V1->getType()->getScalarType() &&
1527            "Shuffle should not change scalar type");
1528 
1529     // Find constant NewC that has property:
1530     //   shuffle(NewC, ShMask) = C
1531     // If such constant does not exist (example: ShMask=<0,0> and C=<1,2>)
1532     // reorder is not possible. A 1-to-1 mapping is not required. Example:
1533     // ShMask = <1,1,2,2> and C = <5,5,6,6> --> NewC = <undef,5,6,undef>
1534     bool ConstOp1 = isa<Constant>(RHS);
1535     ArrayRef<int> ShMask = Mask;
1536     unsigned SrcVecNumElts = cast<VectorType>(V1->getType())->getNumElements();
1537     UndefValue *UndefScalar = UndefValue::get(C->getType()->getScalarType());
1538     SmallVector<Constant *, 16> NewVecC(SrcVecNumElts, UndefScalar);
1539     bool MayChange = true;
1540     for (unsigned I = 0; I < NumElts; ++I) {
1541       Constant *CElt = C->getAggregateElement(I);
1542       if (ShMask[I] >= 0) {
1543         assert(ShMask[I] < (int)NumElts && "Not expecting narrowing shuffle");
1544         Constant *NewCElt = NewVecC[ShMask[I]];
1545         // Bail out if:
1546         // 1. The constant vector contains a constant expression.
1547         // 2. The shuffle needs an element of the constant vector that can't
1548         //    be mapped to a new constant vector.
1549         // 3. This is a widening shuffle that copies elements of V1 into the
1550         //    extended elements (extending with undef is allowed).
1551         if (!CElt || (!isa<UndefValue>(NewCElt) && NewCElt != CElt) ||
1552             I >= SrcVecNumElts) {
1553           MayChange = false;
1554           break;
1555         }
1556         NewVecC[ShMask[I]] = CElt;
1557       }
1558       // If this is a widening shuffle, we must be able to extend with undef
1559       // elements. If the original binop does not produce an undef in the high
1560       // lanes, then this transform is not safe.
1561       // Similarly for undef lanes due to the shuffle mask, we can only
1562       // transform binops that preserve undef.
1563       // TODO: We could shuffle those non-undef constant values into the
1564       //       result by using a constant vector (rather than an undef vector)
1565       //       as operand 1 of the new binop, but that might be too aggressive
1566       //       for target-independent shuffle creation.
1567       if (I >= SrcVecNumElts || ShMask[I] < 0) {
1568         Constant *MaybeUndef =
1569             ConstOp1 ? ConstantExpr::get(Opcode, UndefScalar, CElt)
1570                      : ConstantExpr::get(Opcode, CElt, UndefScalar);
1571         if (!isa<UndefValue>(MaybeUndef)) {
1572           MayChange = false;
1573           break;
1574         }
1575       }
1576     }
1577     if (MayChange) {
1578       Constant *NewC = ConstantVector::get(NewVecC);
1579       // It may not be safe to execute a binop on a vector with undef elements
1580       // because the entire instruction can be folded to undef or create poison
1581       // that did not exist in the original code.
1582       if (Inst.isIntDivRem() || (Inst.isShift() && ConstOp1))
1583         NewC = getSafeVectorConstantForBinop(Opcode, NewC, ConstOp1);
1584 
1585       // Op(shuffle(V1, Mask), C) -> shuffle(Op(V1, NewC), Mask)
1586       // Op(C, shuffle(V1, Mask)) -> shuffle(Op(NewC, V1), Mask)
1587       Value *NewLHS = ConstOp1 ? V1 : NewC;
1588       Value *NewRHS = ConstOp1 ? NewC : V1;
1589       return createBinOpShuffle(NewLHS, NewRHS, Mask);
1590     }
1591   }
1592 
1593   // Try to reassociate to sink a splat shuffle after a binary operation.
1594   if (Inst.isAssociative() && Inst.isCommutative()) {
1595     // Canonicalize shuffle operand as LHS.
1596     if (isa<ShuffleVectorInst>(RHS))
1597       std::swap(LHS, RHS);
1598 
1599     Value *X;
1600     ArrayRef<int> MaskC;
1601     int SplatIndex;
1602     BinaryOperator *BO;
1603     if (!match(LHS, m_OneUse(m_ShuffleVector(m_Value(X), m_Undef(),
1604                                              m_Mask(MaskC)))) ||
1605         !match(MaskC, m_SplatOrUndefMask(SplatIndex)) ||
1606         X->getType() != Inst.getType() || !match(RHS, m_OneUse(m_BinOp(BO))) ||
1607         BO->getOpcode() != Opcode)
1608       return nullptr;
1609 
1610     // FIXME: This may not be safe if the analysis allows undef elements. By
1611     //        moving 'Y' before the splat shuffle, we are implicitly assuming
1612     //        that it is not undef/poison at the splat index.
1613     Value *Y, *OtherOp;
1614     if (isSplatValue(BO->getOperand(0), SplatIndex)) {
1615       Y = BO->getOperand(0);
1616       OtherOp = BO->getOperand(1);
1617     } else if (isSplatValue(BO->getOperand(1), SplatIndex)) {
1618       Y = BO->getOperand(1);
1619       OtherOp = BO->getOperand(0);
1620     } else {
1621       return nullptr;
1622     }
1623 
1624     // X and Y are splatted values, so perform the binary operation on those
1625     // values followed by a splat followed by the 2nd binary operation:
1626     // bo (splat X), (bo Y, OtherOp) --> bo (splat (bo X, Y)), OtherOp
1627     Value *NewBO = Builder.CreateBinOp(Opcode, X, Y);
1628     UndefValue *Undef = UndefValue::get(Inst.getType());
1629     SmallVector<int, 8> NewMask(MaskC.size(), SplatIndex);
1630     Value *NewSplat = Builder.CreateShuffleVector(NewBO, Undef, NewMask);
1631     Instruction *R = BinaryOperator::Create(Opcode, NewSplat, OtherOp);
1632 
1633     // Intersect FMF on both new binops. Other (poison-generating) flags are
1634     // dropped to be safe.
1635     if (isa<FPMathOperator>(R)) {
1636       R->copyFastMathFlags(&Inst);
1637       R->andIRFlags(BO);
1638     }
1639     if (auto *NewInstBO = dyn_cast<BinaryOperator>(NewBO))
1640       NewInstBO->copyIRFlags(R);
1641     return R;
1642   }
1643 
1644   return nullptr;
1645 }
1646 
1647 /// Try to narrow the width of a binop if at least 1 operand is an extend of
1648 /// of a value. This requires a potentially expensive known bits check to make
1649 /// sure the narrow op does not overflow.
1650 Instruction *InstCombiner::narrowMathIfNoOverflow(BinaryOperator &BO) {
1651   // We need at least one extended operand.
1652   Value *Op0 = BO.getOperand(0), *Op1 = BO.getOperand(1);
1653 
1654   // If this is a sub, we swap the operands since we always want an extension
1655   // on the RHS. The LHS can be an extension or a constant.
1656   if (BO.getOpcode() == Instruction::Sub)
1657     std::swap(Op0, Op1);
1658 
1659   Value *X;
1660   bool IsSext = match(Op0, m_SExt(m_Value(X)));
1661   if (!IsSext && !match(Op0, m_ZExt(m_Value(X))))
1662     return nullptr;
1663 
1664   // If both operands are the same extension from the same source type and we
1665   // can eliminate at least one (hasOneUse), this might work.
1666   CastInst::CastOps CastOpc = IsSext ? Instruction::SExt : Instruction::ZExt;
1667   Value *Y;
1668   if (!(match(Op1, m_ZExtOrSExt(m_Value(Y))) && X->getType() == Y->getType() &&
1669         cast<Operator>(Op1)->getOpcode() == CastOpc &&
1670         (Op0->hasOneUse() || Op1->hasOneUse()))) {
1671     // If that did not match, see if we have a suitable constant operand.
1672     // Truncating and extending must produce the same constant.
1673     Constant *WideC;
1674     if (!Op0->hasOneUse() || !match(Op1, m_Constant(WideC)))
1675       return nullptr;
1676     Constant *NarrowC = ConstantExpr::getTrunc(WideC, X->getType());
1677     if (ConstantExpr::getCast(CastOpc, NarrowC, BO.getType()) != WideC)
1678       return nullptr;
1679     Y = NarrowC;
1680   }
1681 
1682   // Swap back now that we found our operands.
1683   if (BO.getOpcode() == Instruction::Sub)
1684     std::swap(X, Y);
1685 
1686   // Both operands have narrow versions. Last step: the math must not overflow
1687   // in the narrow width.
1688   if (!willNotOverflow(BO.getOpcode(), X, Y, BO, IsSext))
1689     return nullptr;
1690 
1691   // bo (ext X), (ext Y) --> ext (bo X, Y)
1692   // bo (ext X), C       --> ext (bo X, C')
1693   Value *NarrowBO = Builder.CreateBinOp(BO.getOpcode(), X, Y, "narrow");
1694   if (auto *NewBinOp = dyn_cast<BinaryOperator>(NarrowBO)) {
1695     if (IsSext)
1696       NewBinOp->setHasNoSignedWrap();
1697     else
1698       NewBinOp->setHasNoUnsignedWrap();
1699   }
1700   return CastInst::Create(CastOpc, NarrowBO, BO.getType());
1701 }
1702 
1703 static bool isMergedGEPInBounds(GEPOperator &GEP1, GEPOperator &GEP2) {
1704   // At least one GEP must be inbounds.
1705   if (!GEP1.isInBounds() && !GEP2.isInBounds())
1706     return false;
1707 
1708   return (GEP1.isInBounds() || GEP1.hasAllZeroIndices()) &&
1709          (GEP2.isInBounds() || GEP2.hasAllZeroIndices());
1710 }
1711 
1712 /// Thread a GEP operation with constant indices through the constant true/false
1713 /// arms of a select.
1714 static Instruction *foldSelectGEP(GetElementPtrInst &GEP,
1715                                   InstCombiner::BuilderTy &Builder) {
1716   if (!GEP.hasAllConstantIndices())
1717     return nullptr;
1718 
1719   Instruction *Sel;
1720   Value *Cond;
1721   Constant *TrueC, *FalseC;
1722   if (!match(GEP.getPointerOperand(), m_Instruction(Sel)) ||
1723       !match(Sel,
1724              m_Select(m_Value(Cond), m_Constant(TrueC), m_Constant(FalseC))))
1725     return nullptr;
1726 
1727   // gep (select Cond, TrueC, FalseC), IndexC --> select Cond, TrueC', FalseC'
1728   // Propagate 'inbounds' and metadata from existing instructions.
1729   // Note: using IRBuilder to create the constants for efficiency.
1730   SmallVector<Value *, 4> IndexC(GEP.idx_begin(), GEP.idx_end());
1731   bool IsInBounds = GEP.isInBounds();
1732   Value *NewTrueC = IsInBounds ? Builder.CreateInBoundsGEP(TrueC, IndexC)
1733                                : Builder.CreateGEP(TrueC, IndexC);
1734   Value *NewFalseC = IsInBounds ? Builder.CreateInBoundsGEP(FalseC, IndexC)
1735                                 : Builder.CreateGEP(FalseC, IndexC);
1736   return SelectInst::Create(Cond, NewTrueC, NewFalseC, "", nullptr, Sel);
1737 }
1738 
1739 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1740   SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
1741   Type *GEPType = GEP.getType();
1742   Type *GEPEltType = GEP.getSourceElementType();
1743   bool IsGEPSrcEleScalable = isa<ScalableVectorType>(GEPEltType);
1744   if (Value *V = SimplifyGEPInst(GEPEltType, Ops, SQ.getWithInstruction(&GEP)))
1745     return replaceInstUsesWith(GEP, V);
1746 
1747   // For vector geps, use the generic demanded vector support.
1748   // Skip if GEP return type is scalable. The number of elements is unknown at
1749   // compile-time.
1750   if (auto *GEPFVTy = dyn_cast<FixedVectorType>(GEPType)) {
1751     auto VWidth = GEPFVTy->getNumElements();
1752     APInt UndefElts(VWidth, 0);
1753     APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1754     if (Value *V = SimplifyDemandedVectorElts(&GEP, AllOnesEltMask,
1755                                               UndefElts)) {
1756       if (V != &GEP)
1757         return replaceInstUsesWith(GEP, V);
1758       return &GEP;
1759     }
1760 
1761     // TODO: 1) Scalarize splat operands, 2) scalarize entire instruction if
1762     // possible (decide on canonical form for pointer broadcast), 3) exploit
1763     // undef elements to decrease demanded bits
1764   }
1765 
1766   Value *PtrOp = GEP.getOperand(0);
1767 
1768   // Eliminate unneeded casts for indices, and replace indices which displace
1769   // by multiples of a zero size type with zero.
1770   bool MadeChange = false;
1771 
1772   // Index width may not be the same width as pointer width.
1773   // Data layout chooses the right type based on supported integer types.
1774   Type *NewScalarIndexTy =
1775       DL.getIndexType(GEP.getPointerOperandType()->getScalarType());
1776 
1777   gep_type_iterator GTI = gep_type_begin(GEP);
1778   for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
1779        ++I, ++GTI) {
1780     // Skip indices into struct types.
1781     if (GTI.isStruct())
1782       continue;
1783 
1784     Type *IndexTy = (*I)->getType();
1785     Type *NewIndexType =
1786         IndexTy->isVectorTy()
1787             ? VectorType::get(NewScalarIndexTy,
1788                               cast<VectorType>(IndexTy)->getElementCount())
1789             : NewScalarIndexTy;
1790 
1791     // If the element type has zero size then any index over it is equivalent
1792     // to an index of zero, so replace it with zero if it is not zero already.
1793     Type *EltTy = GTI.getIndexedType();
1794     if (EltTy->isSized() && DL.getTypeAllocSize(EltTy).isZero())
1795       if (!isa<Constant>(*I) || !match(I->get(), m_Zero())) {
1796         *I = Constant::getNullValue(NewIndexType);
1797         MadeChange = true;
1798       }
1799 
1800     if (IndexTy != NewIndexType) {
1801       // If we are using a wider index than needed for this platform, shrink
1802       // it to what we need.  If narrower, sign-extend it to what we need.
1803       // This explicit cast can make subsequent optimizations more obvious.
1804       *I = Builder.CreateIntCast(*I, NewIndexType, true);
1805       MadeChange = true;
1806     }
1807   }
1808   if (MadeChange)
1809     return &GEP;
1810 
1811   // Check to see if the inputs to the PHI node are getelementptr instructions.
1812   if (auto *PN = dyn_cast<PHINode>(PtrOp)) {
1813     auto *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
1814     if (!Op1)
1815       return nullptr;
1816 
1817     // Don't fold a GEP into itself through a PHI node. This can only happen
1818     // through the back-edge of a loop. Folding a GEP into itself means that
1819     // the value of the previous iteration needs to be stored in the meantime,
1820     // thus requiring an additional register variable to be live, but not
1821     // actually achieving anything (the GEP still needs to be executed once per
1822     // loop iteration).
1823     if (Op1 == &GEP)
1824       return nullptr;
1825 
1826     int DI = -1;
1827 
1828     for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
1829       auto *Op2 = dyn_cast<GetElementPtrInst>(*I);
1830       if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
1831         return nullptr;
1832 
1833       // As for Op1 above, don't try to fold a GEP into itself.
1834       if (Op2 == &GEP)
1835         return nullptr;
1836 
1837       // Keep track of the type as we walk the GEP.
1838       Type *CurTy = nullptr;
1839 
1840       for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
1841         if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
1842           return nullptr;
1843 
1844         if (Op1->getOperand(J) != Op2->getOperand(J)) {
1845           if (DI == -1) {
1846             // We have not seen any differences yet in the GEPs feeding the
1847             // PHI yet, so we record this one if it is allowed to be a
1848             // variable.
1849 
1850             // The first two arguments can vary for any GEP, the rest have to be
1851             // static for struct slots
1852             if (J > 1) {
1853               assert(CurTy && "No current type?");
1854               if (CurTy->isStructTy())
1855                 return nullptr;
1856             }
1857 
1858             DI = J;
1859           } else {
1860             // The GEP is different by more than one input. While this could be
1861             // extended to support GEPs that vary by more than one variable it
1862             // doesn't make sense since it greatly increases the complexity and
1863             // would result in an R+R+R addressing mode which no backend
1864             // directly supports and would need to be broken into several
1865             // simpler instructions anyway.
1866             return nullptr;
1867           }
1868         }
1869 
1870         // Sink down a layer of the type for the next iteration.
1871         if (J > 0) {
1872           if (J == 1) {
1873             CurTy = Op1->getSourceElementType();
1874           } else {
1875             CurTy =
1876                 GetElementPtrInst::getTypeAtIndex(CurTy, Op1->getOperand(J));
1877           }
1878         }
1879       }
1880     }
1881 
1882     // If not all GEPs are identical we'll have to create a new PHI node.
1883     // Check that the old PHI node has only one use so that it will get
1884     // removed.
1885     if (DI != -1 && !PN->hasOneUse())
1886       return nullptr;
1887 
1888     auto *NewGEP = cast<GetElementPtrInst>(Op1->clone());
1889     if (DI == -1) {
1890       // All the GEPs feeding the PHI are identical. Clone one down into our
1891       // BB so that it can be merged with the current GEP.
1892     } else {
1893       // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
1894       // into the current block so it can be merged, and create a new PHI to
1895       // set that index.
1896       PHINode *NewPN;
1897       {
1898         IRBuilderBase::InsertPointGuard Guard(Builder);
1899         Builder.SetInsertPoint(PN);
1900         NewPN = Builder.CreatePHI(Op1->getOperand(DI)->getType(),
1901                                   PN->getNumOperands());
1902       }
1903 
1904       for (auto &I : PN->operands())
1905         NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1906                            PN->getIncomingBlock(I));
1907 
1908       NewGEP->setOperand(DI, NewPN);
1909     }
1910 
1911     GEP.getParent()->getInstList().insert(
1912         GEP.getParent()->getFirstInsertionPt(), NewGEP);
1913     replaceOperand(GEP, 0, NewGEP);
1914     PtrOp = NewGEP;
1915   }
1916 
1917   // Combine Indices - If the source pointer to this getelementptr instruction
1918   // is a getelementptr instruction, combine the indices of the two
1919   // getelementptr instructions into a single instruction.
1920   if (auto *Src = dyn_cast<GEPOperator>(PtrOp)) {
1921     if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
1922       return nullptr;
1923 
1924     // Try to reassociate loop invariant GEP chains to enable LICM.
1925     if (LI && Src->getNumOperands() == 2 && GEP.getNumOperands() == 2 &&
1926         Src->hasOneUse()) {
1927       if (Loop *L = LI->getLoopFor(GEP.getParent())) {
1928         Value *GO1 = GEP.getOperand(1);
1929         Value *SO1 = Src->getOperand(1);
1930         // Reassociate the two GEPs if SO1 is variant in the loop and GO1 is
1931         // invariant: this breaks the dependence between GEPs and allows LICM
1932         // to hoist the invariant part out of the loop.
1933         if (L->isLoopInvariant(GO1) && !L->isLoopInvariant(SO1)) {
1934           // We have to be careful here.
1935           // We have something like:
1936           //  %src = getelementptr <ty>, <ty>* %base, <ty> %idx
1937           //  %gep = getelementptr <ty>, <ty>* %src, <ty> %idx2
1938           // If we just swap idx & idx2 then we could inadvertantly
1939           // change %src from a vector to a scalar, or vice versa.
1940           // Cases:
1941           //  1) %base a scalar & idx a scalar & idx2 a vector
1942           //      => Swapping idx & idx2 turns %src into a vector type.
1943           //  2) %base a scalar & idx a vector & idx2 a scalar
1944           //      => Swapping idx & idx2 turns %src in a scalar type
1945           //  3) %base, %idx, and %idx2 are scalars
1946           //      => %src & %gep are scalars
1947           //      => swapping idx & idx2 is safe
1948           //  4) %base a vector
1949           //      => %src is a vector
1950           //      => swapping idx & idx2 is safe.
1951           auto *SO0 = Src->getOperand(0);
1952           auto *SO0Ty = SO0->getType();
1953           if (!isa<VectorType>(GEPType) || // case 3
1954               isa<VectorType>(SO0Ty)) {    // case 4
1955             Src->setOperand(1, GO1);
1956             GEP.setOperand(1, SO1);
1957             return &GEP;
1958           } else {
1959             // Case 1 or 2
1960             // -- have to recreate %src & %gep
1961             // put NewSrc at same location as %src
1962             Builder.SetInsertPoint(cast<Instruction>(PtrOp));
1963             auto *NewSrc = cast<GetElementPtrInst>(
1964                 Builder.CreateGEP(GEPEltType, SO0, GO1, Src->getName()));
1965             NewSrc->setIsInBounds(Src->isInBounds());
1966             auto *NewGEP = GetElementPtrInst::Create(GEPEltType, NewSrc, {SO1});
1967             NewGEP->setIsInBounds(GEP.isInBounds());
1968             return NewGEP;
1969           }
1970         }
1971       }
1972     }
1973 
1974     // Note that if our source is a gep chain itself then we wait for that
1975     // chain to be resolved before we perform this transformation.  This
1976     // avoids us creating a TON of code in some cases.
1977     if (auto *SrcGEP = dyn_cast<GEPOperator>(Src->getOperand(0)))
1978       if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
1979         return nullptr;   // Wait until our source is folded to completion.
1980 
1981     SmallVector<Value*, 8> Indices;
1982 
1983     // Find out whether the last index in the source GEP is a sequential idx.
1984     bool EndsWithSequential = false;
1985     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
1986          I != E; ++I)
1987       EndsWithSequential = I.isSequential();
1988 
1989     // Can we combine the two pointer arithmetics offsets?
1990     if (EndsWithSequential) {
1991       // Replace: gep (gep %P, long B), long A, ...
1992       // With:    T = long A+B; gep %P, T, ...
1993       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1994       Value *GO1 = GEP.getOperand(1);
1995 
1996       // If they aren't the same type, then the input hasn't been processed
1997       // by the loop above yet (which canonicalizes sequential index types to
1998       // intptr_t).  Just avoid transforming this until the input has been
1999       // normalized.
2000       if (SO1->getType() != GO1->getType())
2001         return nullptr;
2002 
2003       Value *Sum =
2004           SimplifyAddInst(GO1, SO1, false, false, SQ.getWithInstruction(&GEP));
2005       // Only do the combine when we are sure the cost after the
2006       // merge is never more than that before the merge.
2007       if (Sum == nullptr)
2008         return nullptr;
2009 
2010       // Update the GEP in place if possible.
2011       if (Src->getNumOperands() == 2) {
2012         GEP.setIsInBounds(isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP)));
2013         replaceOperand(GEP, 0, Src->getOperand(0));
2014         replaceOperand(GEP, 1, Sum);
2015         return &GEP;
2016       }
2017       Indices.append(Src->op_begin()+1, Src->op_end()-1);
2018       Indices.push_back(Sum);
2019       Indices.append(GEP.op_begin()+2, GEP.op_end());
2020     } else if (isa<Constant>(*GEP.idx_begin()) &&
2021                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
2022                Src->getNumOperands() != 1) {
2023       // Otherwise we can do the fold if the first index of the GEP is a zero
2024       Indices.append(Src->op_begin()+1, Src->op_end());
2025       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
2026     }
2027 
2028     if (!Indices.empty())
2029       return isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP))
2030                  ? GetElementPtrInst::CreateInBounds(
2031                        Src->getSourceElementType(), Src->getOperand(0), Indices,
2032                        GEP.getName())
2033                  : GetElementPtrInst::Create(Src->getSourceElementType(),
2034                                              Src->getOperand(0), Indices,
2035                                              GEP.getName());
2036   }
2037 
2038   // Skip if GEP source element type is scalable. The type alloc size is unknown
2039   // at compile-time.
2040   if (GEP.getNumIndices() == 1 && !IsGEPSrcEleScalable) {
2041     unsigned AS = GEP.getPointerAddressSpace();
2042     if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
2043         DL.getIndexSizeInBits(AS)) {
2044       uint64_t TyAllocSize = DL.getTypeAllocSize(GEPEltType).getFixedSize();
2045 
2046       bool Matched = false;
2047       uint64_t C;
2048       Value *V = nullptr;
2049       if (TyAllocSize == 1) {
2050         V = GEP.getOperand(1);
2051         Matched = true;
2052       } else if (match(GEP.getOperand(1),
2053                        m_AShr(m_Value(V), m_ConstantInt(C)))) {
2054         if (TyAllocSize == 1ULL << C)
2055           Matched = true;
2056       } else if (match(GEP.getOperand(1),
2057                        m_SDiv(m_Value(V), m_ConstantInt(C)))) {
2058         if (TyAllocSize == C)
2059           Matched = true;
2060       }
2061 
2062       if (Matched) {
2063         // Canonicalize (gep i8* X, -(ptrtoint Y))
2064         // to (inttoptr (sub (ptrtoint X), (ptrtoint Y)))
2065         // The GEP pattern is emitted by the SCEV expander for certain kinds of
2066         // pointer arithmetic.
2067         if (match(V, m_Neg(m_PtrToInt(m_Value())))) {
2068           Operator *Index = cast<Operator>(V);
2069           Value *PtrToInt = Builder.CreatePtrToInt(PtrOp, Index->getType());
2070           Value *NewSub = Builder.CreateSub(PtrToInt, Index->getOperand(1));
2071           return CastInst::Create(Instruction::IntToPtr, NewSub, GEPType);
2072         }
2073         // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X))
2074         // to (bitcast Y)
2075         Value *Y;
2076         if (match(V, m_Sub(m_PtrToInt(m_Value(Y)),
2077                            m_PtrToInt(m_Specific(GEP.getOperand(0))))))
2078           return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y, GEPType);
2079       }
2080     }
2081   }
2082 
2083   // We do not handle pointer-vector geps here.
2084   if (GEPType->isVectorTy())
2085     return nullptr;
2086 
2087   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
2088   Value *StrippedPtr = PtrOp->stripPointerCasts();
2089   PointerType *StrippedPtrTy = cast<PointerType>(StrippedPtr->getType());
2090 
2091   if (StrippedPtr != PtrOp) {
2092     bool HasZeroPointerIndex = false;
2093     Type *StrippedPtrEltTy = StrippedPtrTy->getElementType();
2094 
2095     if (auto *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
2096       HasZeroPointerIndex = C->isZero();
2097 
2098     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
2099     // into     : GEP [10 x i8]* X, i32 0, ...
2100     //
2101     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
2102     //           into     : GEP i8* X, ...
2103     //
2104     // This occurs when the program declares an array extern like "int X[];"
2105     if (HasZeroPointerIndex) {
2106       if (auto *CATy = dyn_cast<ArrayType>(GEPEltType)) {
2107         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
2108         if (CATy->getElementType() == StrippedPtrEltTy) {
2109           // -> GEP i8* X, ...
2110           SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
2111           GetElementPtrInst *Res = GetElementPtrInst::Create(
2112               StrippedPtrEltTy, StrippedPtr, Idx, GEP.getName());
2113           Res->setIsInBounds(GEP.isInBounds());
2114           if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
2115             return Res;
2116           // Insert Res, and create an addrspacecast.
2117           // e.g.,
2118           // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
2119           // ->
2120           // %0 = GEP i8 addrspace(1)* X, ...
2121           // addrspacecast i8 addrspace(1)* %0 to i8*
2122           return new AddrSpaceCastInst(Builder.Insert(Res), GEPType);
2123         }
2124 
2125         if (auto *XATy = dyn_cast<ArrayType>(StrippedPtrEltTy)) {
2126           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
2127           if (CATy->getElementType() == XATy->getElementType()) {
2128             // -> GEP [10 x i8]* X, i32 0, ...
2129             // At this point, we know that the cast source type is a pointer
2130             // to an array of the same type as the destination pointer
2131             // array.  Because the array type is never stepped over (there
2132             // is a leading zero) we can fold the cast into this GEP.
2133             if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
2134               GEP.setSourceElementType(XATy);
2135               return replaceOperand(GEP, 0, StrippedPtr);
2136             }
2137             // Cannot replace the base pointer directly because StrippedPtr's
2138             // address space is different. Instead, create a new GEP followed by
2139             // an addrspacecast.
2140             // e.g.,
2141             // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
2142             //   i32 0, ...
2143             // ->
2144             // %0 = GEP [10 x i8] addrspace(1)* X, ...
2145             // addrspacecast i8 addrspace(1)* %0 to i8*
2146             SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
2147             Value *NewGEP =
2148                 GEP.isInBounds()
2149                     ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr,
2150                                                 Idx, GEP.getName())
2151                     : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Idx,
2152                                         GEP.getName());
2153             return new AddrSpaceCastInst(NewGEP, GEPType);
2154           }
2155         }
2156       }
2157     } else if (GEP.getNumOperands() == 2 && !IsGEPSrcEleScalable) {
2158       // Skip if GEP source element type is scalable. The type alloc size is
2159       // unknown at compile-time.
2160       // Transform things like: %t = getelementptr i32*
2161       // bitcast ([2 x i32]* %str to i32*), i32 %V into:  %t1 = getelementptr [2
2162       // x i32]* %str, i32 0, i32 %V; bitcast
2163       if (StrippedPtrEltTy->isArrayTy() &&
2164           DL.getTypeAllocSize(StrippedPtrEltTy->getArrayElementType()) ==
2165               DL.getTypeAllocSize(GEPEltType)) {
2166         Type *IdxType = DL.getIndexType(GEPType);
2167         Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
2168         Value *NewGEP =
2169             GEP.isInBounds()
2170                 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr, Idx,
2171                                             GEP.getName())
2172                 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Idx,
2173                                     GEP.getName());
2174 
2175         // V and GEP are both pointer types --> BitCast
2176         return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP, GEPType);
2177       }
2178 
2179       // Transform things like:
2180       // %V = mul i64 %N, 4
2181       // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
2182       // into:  %t1 = getelementptr i32* %arr, i32 %N; bitcast
2183       if (GEPEltType->isSized() && StrippedPtrEltTy->isSized()) {
2184         // Check that changing the type amounts to dividing the index by a scale
2185         // factor.
2186         uint64_t ResSize = DL.getTypeAllocSize(GEPEltType).getFixedSize();
2187         uint64_t SrcSize = DL.getTypeAllocSize(StrippedPtrEltTy).getFixedSize();
2188         if (ResSize && SrcSize % ResSize == 0) {
2189           Value *Idx = GEP.getOperand(1);
2190           unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
2191           uint64_t Scale = SrcSize / ResSize;
2192 
2193           // Earlier transforms ensure that the index has the right type
2194           // according to Data Layout, which considerably simplifies the
2195           // logic by eliminating implicit casts.
2196           assert(Idx->getType() == DL.getIndexType(GEPType) &&
2197                  "Index type does not match the Data Layout preferences");
2198 
2199           bool NSW;
2200           if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
2201             // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
2202             // If the multiplication NewIdx * Scale may overflow then the new
2203             // GEP may not be "inbounds".
2204             Value *NewGEP =
2205                 GEP.isInBounds() && NSW
2206                     ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr,
2207                                                 NewIdx, GEP.getName())
2208                     : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, NewIdx,
2209                                         GEP.getName());
2210 
2211             // The NewGEP must be pointer typed, so must the old one -> BitCast
2212             return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
2213                                                                  GEPType);
2214           }
2215         }
2216       }
2217 
2218       // Similarly, transform things like:
2219       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
2220       //   (where tmp = 8*tmp2) into:
2221       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
2222       if (GEPEltType->isSized() && StrippedPtrEltTy->isSized() &&
2223           StrippedPtrEltTy->isArrayTy()) {
2224         // Check that changing to the array element type amounts to dividing the
2225         // index by a scale factor.
2226         uint64_t ResSize = DL.getTypeAllocSize(GEPEltType).getFixedSize();
2227         uint64_t ArrayEltSize =
2228             DL.getTypeAllocSize(StrippedPtrEltTy->getArrayElementType())
2229                 .getFixedSize();
2230         if (ResSize && ArrayEltSize % ResSize == 0) {
2231           Value *Idx = GEP.getOperand(1);
2232           unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
2233           uint64_t Scale = ArrayEltSize / ResSize;
2234 
2235           // Earlier transforms ensure that the index has the right type
2236           // according to the Data Layout, which considerably simplifies
2237           // the logic by eliminating implicit casts.
2238           assert(Idx->getType() == DL.getIndexType(GEPType) &&
2239                  "Index type does not match the Data Layout preferences");
2240 
2241           bool NSW;
2242           if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
2243             // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
2244             // If the multiplication NewIdx * Scale may overflow then the new
2245             // GEP may not be "inbounds".
2246             Type *IndTy = DL.getIndexType(GEPType);
2247             Value *Off[2] = {Constant::getNullValue(IndTy), NewIdx};
2248 
2249             Value *NewGEP =
2250                 GEP.isInBounds() && NSW
2251                     ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr,
2252                                                 Off, GEP.getName())
2253                     : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Off,
2254                                         GEP.getName());
2255             // The NewGEP must be pointer typed, so must the old one -> BitCast
2256             return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
2257                                                                  GEPType);
2258           }
2259         }
2260       }
2261     }
2262   }
2263 
2264   // addrspacecast between types is canonicalized as a bitcast, then an
2265   // addrspacecast. To take advantage of the below bitcast + struct GEP, look
2266   // through the addrspacecast.
2267   Value *ASCStrippedPtrOp = PtrOp;
2268   if (auto *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
2269     //   X = bitcast A addrspace(1)* to B addrspace(1)*
2270     //   Y = addrspacecast A addrspace(1)* to B addrspace(2)*
2271     //   Z = gep Y, <...constant indices...>
2272     // Into an addrspacecasted GEP of the struct.
2273     if (auto *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
2274       ASCStrippedPtrOp = BC;
2275   }
2276 
2277   if (auto *BCI = dyn_cast<BitCastInst>(ASCStrippedPtrOp)) {
2278     Value *SrcOp = BCI->getOperand(0);
2279     PointerType *SrcType = cast<PointerType>(BCI->getSrcTy());
2280     Type *SrcEltType = SrcType->getElementType();
2281 
2282     // GEP directly using the source operand if this GEP is accessing an element
2283     // of a bitcasted pointer to vector or array of the same dimensions:
2284     // gep (bitcast <c x ty>* X to [c x ty]*), Y, Z --> gep X, Y, Z
2285     // gep (bitcast [c x ty]* X to <c x ty>*), Y, Z --> gep X, Y, Z
2286     auto areMatchingArrayAndVecTypes = [](Type *ArrTy, Type *VecTy,
2287                                           const DataLayout &DL) {
2288       auto *VecVTy = cast<VectorType>(VecTy);
2289       return ArrTy->getArrayElementType() == VecVTy->getElementType() &&
2290              ArrTy->getArrayNumElements() == VecVTy->getNumElements() &&
2291              DL.getTypeAllocSize(ArrTy) == DL.getTypeAllocSize(VecTy);
2292     };
2293     if (GEP.getNumOperands() == 3 &&
2294         ((GEPEltType->isArrayTy() && SrcEltType->isVectorTy() &&
2295           areMatchingArrayAndVecTypes(GEPEltType, SrcEltType, DL)) ||
2296          (GEPEltType->isVectorTy() && SrcEltType->isArrayTy() &&
2297           areMatchingArrayAndVecTypes(SrcEltType, GEPEltType, DL)))) {
2298 
2299       // Create a new GEP here, as using `setOperand()` followed by
2300       // `setSourceElementType()` won't actually update the type of the
2301       // existing GEP Value. Causing issues if this Value is accessed when
2302       // constructing an AddrSpaceCastInst
2303       Value *NGEP =
2304           GEP.isInBounds()
2305               ? Builder.CreateInBoundsGEP(SrcEltType, SrcOp, {Ops[1], Ops[2]})
2306               : Builder.CreateGEP(SrcEltType, SrcOp, {Ops[1], Ops[2]});
2307       NGEP->takeName(&GEP);
2308 
2309       // Preserve GEP address space to satisfy users
2310       if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
2311         return new AddrSpaceCastInst(NGEP, GEPType);
2312 
2313       return replaceInstUsesWith(GEP, NGEP);
2314     }
2315 
2316     // See if we can simplify:
2317     //   X = bitcast A* to B*
2318     //   Y = gep X, <...constant indices...>
2319     // into a gep of the original struct. This is important for SROA and alias
2320     // analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
2321     unsigned OffsetBits = DL.getIndexTypeSizeInBits(GEPType);
2322     APInt Offset(OffsetBits, 0);
2323     if (!isa<BitCastInst>(SrcOp) && GEP.accumulateConstantOffset(DL, Offset)) {
2324       // If this GEP instruction doesn't move the pointer, just replace the GEP
2325       // with a bitcast of the real input to the dest type.
2326       if (!Offset) {
2327         // If the bitcast is of an allocation, and the allocation will be
2328         // converted to match the type of the cast, don't touch this.
2329         if (isa<AllocaInst>(SrcOp) || isAllocationFn(SrcOp, &TLI)) {
2330           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
2331           if (Instruction *I = visitBitCast(*BCI)) {
2332             if (I != BCI) {
2333               I->takeName(BCI);
2334               BCI->getParent()->getInstList().insert(BCI->getIterator(), I);
2335               replaceInstUsesWith(*BCI, I);
2336             }
2337             return &GEP;
2338           }
2339         }
2340 
2341         if (SrcType->getPointerAddressSpace() != GEP.getAddressSpace())
2342           return new AddrSpaceCastInst(SrcOp, GEPType);
2343         return new BitCastInst(SrcOp, GEPType);
2344       }
2345 
2346       // Otherwise, if the offset is non-zero, we need to find out if there is a
2347       // field at Offset in 'A's type.  If so, we can pull the cast through the
2348       // GEP.
2349       SmallVector<Value*, 8> NewIndices;
2350       if (FindElementAtOffset(SrcType, Offset.getSExtValue(), NewIndices)) {
2351         Value *NGEP =
2352             GEP.isInBounds()
2353                 ? Builder.CreateInBoundsGEP(SrcEltType, SrcOp, NewIndices)
2354                 : Builder.CreateGEP(SrcEltType, SrcOp, NewIndices);
2355 
2356         if (NGEP->getType() == GEPType)
2357           return replaceInstUsesWith(GEP, NGEP);
2358         NGEP->takeName(&GEP);
2359 
2360         if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
2361           return new AddrSpaceCastInst(NGEP, GEPType);
2362         return new BitCastInst(NGEP, GEPType);
2363       }
2364     }
2365   }
2366 
2367   if (!GEP.isInBounds()) {
2368     unsigned IdxWidth =
2369         DL.getIndexSizeInBits(PtrOp->getType()->getPointerAddressSpace());
2370     APInt BasePtrOffset(IdxWidth, 0);
2371     Value *UnderlyingPtrOp =
2372             PtrOp->stripAndAccumulateInBoundsConstantOffsets(DL,
2373                                                              BasePtrOffset);
2374     if (auto *AI = dyn_cast<AllocaInst>(UnderlyingPtrOp)) {
2375       if (GEP.accumulateConstantOffset(DL, BasePtrOffset) &&
2376           BasePtrOffset.isNonNegative()) {
2377         APInt AllocSize(
2378             IdxWidth,
2379             DL.getTypeAllocSize(AI->getAllocatedType()).getKnownMinSize());
2380         if (BasePtrOffset.ule(AllocSize)) {
2381           return GetElementPtrInst::CreateInBounds(
2382               GEP.getSourceElementType(), PtrOp, makeArrayRef(Ops).slice(1),
2383               GEP.getName());
2384         }
2385       }
2386     }
2387   }
2388 
2389   if (Instruction *R = foldSelectGEP(GEP, Builder))
2390     return R;
2391 
2392   return nullptr;
2393 }
2394 
2395 static bool isNeverEqualToUnescapedAlloc(Value *V, const TargetLibraryInfo *TLI,
2396                                          Instruction *AI) {
2397   if (isa<ConstantPointerNull>(V))
2398     return true;
2399   if (auto *LI = dyn_cast<LoadInst>(V))
2400     return isa<GlobalVariable>(LI->getPointerOperand());
2401   // Two distinct allocations will never be equal.
2402   // We rely on LookThroughBitCast in isAllocLikeFn being false, since looking
2403   // through bitcasts of V can cause
2404   // the result statement below to be true, even when AI and V (ex:
2405   // i8* ->i32* ->i8* of AI) are the same allocations.
2406   return isAllocLikeFn(V, TLI) && V != AI;
2407 }
2408 
2409 static bool isAllocSiteRemovable(Instruction *AI,
2410                                  SmallVectorImpl<WeakTrackingVH> &Users,
2411                                  const TargetLibraryInfo *TLI) {
2412   SmallVector<Instruction*, 4> Worklist;
2413   Worklist.push_back(AI);
2414 
2415   do {
2416     Instruction *PI = Worklist.pop_back_val();
2417     for (User *U : PI->users()) {
2418       Instruction *I = cast<Instruction>(U);
2419       switch (I->getOpcode()) {
2420       default:
2421         // Give up the moment we see something we can't handle.
2422         return false;
2423 
2424       case Instruction::AddrSpaceCast:
2425       case Instruction::BitCast:
2426       case Instruction::GetElementPtr:
2427         Users.emplace_back(I);
2428         Worklist.push_back(I);
2429         continue;
2430 
2431       case Instruction::ICmp: {
2432         ICmpInst *ICI = cast<ICmpInst>(I);
2433         // We can fold eq/ne comparisons with null to false/true, respectively.
2434         // We also fold comparisons in some conditions provided the alloc has
2435         // not escaped (see isNeverEqualToUnescapedAlloc).
2436         if (!ICI->isEquality())
2437           return false;
2438         unsigned OtherIndex = (ICI->getOperand(0) == PI) ? 1 : 0;
2439         if (!isNeverEqualToUnescapedAlloc(ICI->getOperand(OtherIndex), TLI, AI))
2440           return false;
2441         Users.emplace_back(I);
2442         continue;
2443       }
2444 
2445       case Instruction::Call:
2446         // Ignore no-op and store intrinsics.
2447         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2448           switch (II->getIntrinsicID()) {
2449           default:
2450             return false;
2451 
2452           case Intrinsic::memmove:
2453           case Intrinsic::memcpy:
2454           case Intrinsic::memset: {
2455             MemIntrinsic *MI = cast<MemIntrinsic>(II);
2456             if (MI->isVolatile() || MI->getRawDest() != PI)
2457               return false;
2458             LLVM_FALLTHROUGH;
2459           }
2460           case Intrinsic::invariant_start:
2461           case Intrinsic::invariant_end:
2462           case Intrinsic::lifetime_start:
2463           case Intrinsic::lifetime_end:
2464           case Intrinsic::objectsize:
2465             Users.emplace_back(I);
2466             continue;
2467           }
2468         }
2469 
2470         if (isFreeCall(I, TLI)) {
2471           Users.emplace_back(I);
2472           continue;
2473         }
2474         return false;
2475 
2476       case Instruction::Store: {
2477         StoreInst *SI = cast<StoreInst>(I);
2478         if (SI->isVolatile() || SI->getPointerOperand() != PI)
2479           return false;
2480         Users.emplace_back(I);
2481         continue;
2482       }
2483       }
2484       llvm_unreachable("missing a return?");
2485     }
2486   } while (!Worklist.empty());
2487   return true;
2488 }
2489 
2490 Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
2491   // If we have a malloc call which is only used in any amount of comparisons to
2492   // null and free calls, delete the calls and replace the comparisons with true
2493   // or false as appropriate.
2494 
2495   // This is based on the principle that we can substitute our own allocation
2496   // function (which will never return null) rather than knowledge of the
2497   // specific function being called. In some sense this can change the permitted
2498   // outputs of a program (when we convert a malloc to an alloca, the fact that
2499   // the allocation is now on the stack is potentially visible, for example),
2500   // but we believe in a permissible manner.
2501   SmallVector<WeakTrackingVH, 64> Users;
2502 
2503   // If we are removing an alloca with a dbg.declare, insert dbg.value calls
2504   // before each store.
2505   TinyPtrVector<DbgVariableIntrinsic *> DIIs;
2506   std::unique_ptr<DIBuilder> DIB;
2507   if (isa<AllocaInst>(MI)) {
2508     DIIs = FindDbgAddrUses(&MI);
2509     DIB.reset(new DIBuilder(*MI.getModule(), /*AllowUnresolved=*/false));
2510   }
2511 
2512   if (isAllocSiteRemovable(&MI, Users, &TLI)) {
2513     for (unsigned i = 0, e = Users.size(); i != e; ++i) {
2514       // Lowering all @llvm.objectsize calls first because they may
2515       // use a bitcast/GEP of the alloca we are removing.
2516       if (!Users[i])
2517        continue;
2518 
2519       Instruction *I = cast<Instruction>(&*Users[i]);
2520 
2521       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2522         if (II->getIntrinsicID() == Intrinsic::objectsize) {
2523           Value *Result =
2524               lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/true);
2525           replaceInstUsesWith(*I, Result);
2526           eraseInstFromFunction(*I);
2527           Users[i] = nullptr; // Skip examining in the next loop.
2528         }
2529       }
2530     }
2531     for (unsigned i = 0, e = Users.size(); i != e; ++i) {
2532       if (!Users[i])
2533         continue;
2534 
2535       Instruction *I = cast<Instruction>(&*Users[i]);
2536 
2537       if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
2538         replaceInstUsesWith(*C,
2539                             ConstantInt::get(Type::getInt1Ty(C->getContext()),
2540                                              C->isFalseWhenEqual()));
2541       } else if (auto *SI = dyn_cast<StoreInst>(I)) {
2542         for (auto *DII : DIIs)
2543           ConvertDebugDeclareToDebugValue(DII, SI, *DIB);
2544       } else {
2545         // Casts, GEP, or anything else: we're about to delete this instruction,
2546         // so it can not have any valid uses.
2547         replaceInstUsesWith(*I, UndefValue::get(I->getType()));
2548       }
2549       eraseInstFromFunction(*I);
2550     }
2551 
2552     if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
2553       // Replace invoke with a NOP intrinsic to maintain the original CFG
2554       Module *M = II->getModule();
2555       Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
2556       InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
2557                          None, "", II->getParent());
2558     }
2559 
2560     for (auto *DII : DIIs)
2561       eraseInstFromFunction(*DII);
2562 
2563     return eraseInstFromFunction(MI);
2564   }
2565   return nullptr;
2566 }
2567 
2568 /// Move the call to free before a NULL test.
2569 ///
2570 /// Check if this free is accessed after its argument has been test
2571 /// against NULL (property 0).
2572 /// If yes, it is legal to move this call in its predecessor block.
2573 ///
2574 /// The move is performed only if the block containing the call to free
2575 /// will be removed, i.e.:
2576 /// 1. it has only one predecessor P, and P has two successors
2577 /// 2. it contains the call, noops, and an unconditional branch
2578 /// 3. its successor is the same as its predecessor's successor
2579 ///
2580 /// The profitability is out-of concern here and this function should
2581 /// be called only if the caller knows this transformation would be
2582 /// profitable (e.g., for code size).
2583 static Instruction *tryToMoveFreeBeforeNullTest(CallInst &FI,
2584                                                 const DataLayout &DL) {
2585   Value *Op = FI.getArgOperand(0);
2586   BasicBlock *FreeInstrBB = FI.getParent();
2587   BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
2588 
2589   // Validate part of constraint #1: Only one predecessor
2590   // FIXME: We can extend the number of predecessor, but in that case, we
2591   //        would duplicate the call to free in each predecessor and it may
2592   //        not be profitable even for code size.
2593   if (!PredBB)
2594     return nullptr;
2595 
2596   // Validate constraint #2: Does this block contains only the call to
2597   //                         free, noops, and an unconditional branch?
2598   BasicBlock *SuccBB;
2599   Instruction *FreeInstrBBTerminator = FreeInstrBB->getTerminator();
2600   if (!match(FreeInstrBBTerminator, m_UnconditionalBr(SuccBB)))
2601     return nullptr;
2602 
2603   // If there are only 2 instructions in the block, at this point,
2604   // this is the call to free and unconditional.
2605   // If there are more than 2 instructions, check that they are noops
2606   // i.e., they won't hurt the performance of the generated code.
2607   if (FreeInstrBB->size() != 2) {
2608     for (const Instruction &Inst : FreeInstrBB->instructionsWithoutDebug()) {
2609       if (&Inst == &FI || &Inst == FreeInstrBBTerminator)
2610         continue;
2611       auto *Cast = dyn_cast<CastInst>(&Inst);
2612       if (!Cast || !Cast->isNoopCast(DL))
2613         return nullptr;
2614     }
2615   }
2616   // Validate the rest of constraint #1 by matching on the pred branch.
2617   Instruction *TI = PredBB->getTerminator();
2618   BasicBlock *TrueBB, *FalseBB;
2619   ICmpInst::Predicate Pred;
2620   if (!match(TI, m_Br(m_ICmp(Pred,
2621                              m_CombineOr(m_Specific(Op),
2622                                          m_Specific(Op->stripPointerCasts())),
2623                              m_Zero()),
2624                       TrueBB, FalseBB)))
2625     return nullptr;
2626   if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2627     return nullptr;
2628 
2629   // Validate constraint #3: Ensure the null case just falls through.
2630   if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
2631     return nullptr;
2632   assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
2633          "Broken CFG: missing edge from predecessor to successor");
2634 
2635   // At this point, we know that everything in FreeInstrBB can be moved
2636   // before TI.
2637   for (BasicBlock::iterator It = FreeInstrBB->begin(), End = FreeInstrBB->end();
2638        It != End;) {
2639     Instruction &Instr = *It++;
2640     if (&Instr == FreeInstrBBTerminator)
2641       break;
2642     Instr.moveBefore(TI);
2643   }
2644   assert(FreeInstrBB->size() == 1 &&
2645          "Only the branch instruction should remain");
2646   return &FI;
2647 }
2648 
2649 Instruction *InstCombiner::visitFree(CallInst &FI) {
2650   Value *Op = FI.getArgOperand(0);
2651 
2652   // free undef -> unreachable.
2653   if (isa<UndefValue>(Op)) {
2654     // Leave a marker since we can't modify the CFG here.
2655     CreateNonTerminatorUnreachable(&FI);
2656     return eraseInstFromFunction(FI);
2657   }
2658 
2659   // If we have 'free null' delete the instruction.  This can happen in stl code
2660   // when lots of inlining happens.
2661   if (isa<ConstantPointerNull>(Op))
2662     return eraseInstFromFunction(FI);
2663 
2664   // If we optimize for code size, try to move the call to free before the null
2665   // test so that simplify cfg can remove the empty block and dead code
2666   // elimination the branch. I.e., helps to turn something like:
2667   // if (foo) free(foo);
2668   // into
2669   // free(foo);
2670   if (MinimizeSize)
2671     if (Instruction *I = tryToMoveFreeBeforeNullTest(FI, DL))
2672       return I;
2673 
2674   return nullptr;
2675 }
2676 
2677 static bool isMustTailCall(Value *V) {
2678   if (auto *CI = dyn_cast<CallInst>(V))
2679     return CI->isMustTailCall();
2680   return false;
2681 }
2682 
2683 Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) {
2684   if (RI.getNumOperands() == 0) // ret void
2685     return nullptr;
2686 
2687   Value *ResultOp = RI.getOperand(0);
2688   Type *VTy = ResultOp->getType();
2689   if (!VTy->isIntegerTy() || isa<Constant>(ResultOp))
2690     return nullptr;
2691 
2692   // Don't replace result of musttail calls.
2693   if (isMustTailCall(ResultOp))
2694     return nullptr;
2695 
2696   // There might be assume intrinsics dominating this return that completely
2697   // determine the value. If so, constant fold it.
2698   KnownBits Known = computeKnownBits(ResultOp, 0, &RI);
2699   if (Known.isConstant())
2700     return replaceOperand(RI, 0,
2701         Constant::getIntegerValue(VTy, Known.getConstant()));
2702 
2703   return nullptr;
2704 }
2705 
2706 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2707   // Change br (not X), label True, label False to: br X, label False, True
2708   Value *X = nullptr;
2709   if (match(&BI, m_Br(m_Not(m_Value(X)), m_BasicBlock(), m_BasicBlock())) &&
2710       !isa<Constant>(X)) {
2711     // Swap Destinations and condition...
2712     BI.swapSuccessors();
2713     return replaceOperand(BI, 0, X);
2714   }
2715 
2716   // If the condition is irrelevant, remove the use so that other
2717   // transforms on the condition become more effective.
2718   if (BI.isConditional() && !isa<ConstantInt>(BI.getCondition()) &&
2719       BI.getSuccessor(0) == BI.getSuccessor(1))
2720     return replaceOperand(
2721         BI, 0, ConstantInt::getFalse(BI.getCondition()->getType()));
2722 
2723   // Canonicalize, for example, icmp_ne -> icmp_eq or fcmp_one -> fcmp_oeq.
2724   CmpInst::Predicate Pred;
2725   if (match(&BI, m_Br(m_OneUse(m_Cmp(Pred, m_Value(), m_Value())),
2726                       m_BasicBlock(), m_BasicBlock())) &&
2727       !isCanonicalPredicate(Pred)) {
2728     // Swap destinations and condition.
2729     CmpInst *Cond = cast<CmpInst>(BI.getCondition());
2730     Cond->setPredicate(CmpInst::getInversePredicate(Pred));
2731     BI.swapSuccessors();
2732     Worklist.push(Cond);
2733     return &BI;
2734   }
2735 
2736   return nullptr;
2737 }
2738 
2739 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
2740   Value *Cond = SI.getCondition();
2741   Value *Op0;
2742   ConstantInt *AddRHS;
2743   if (match(Cond, m_Add(m_Value(Op0), m_ConstantInt(AddRHS)))) {
2744     // Change 'switch (X+4) case 1:' into 'switch (X) case -3'.
2745     for (auto Case : SI.cases()) {
2746       Constant *NewCase = ConstantExpr::getSub(Case.getCaseValue(), AddRHS);
2747       assert(isa<ConstantInt>(NewCase) &&
2748              "Result of expression should be constant");
2749       Case.setValue(cast<ConstantInt>(NewCase));
2750     }
2751     return replaceOperand(SI, 0, Op0);
2752   }
2753 
2754   KnownBits Known = computeKnownBits(Cond, 0, &SI);
2755   unsigned LeadingKnownZeros = Known.countMinLeadingZeros();
2756   unsigned LeadingKnownOnes = Known.countMinLeadingOnes();
2757 
2758   // Compute the number of leading bits we can ignore.
2759   // TODO: A better way to determine this would use ComputeNumSignBits().
2760   for (auto &C : SI.cases()) {
2761     LeadingKnownZeros = std::min(
2762         LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
2763     LeadingKnownOnes = std::min(
2764         LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
2765   }
2766 
2767   unsigned NewWidth = Known.getBitWidth() - std::max(LeadingKnownZeros, LeadingKnownOnes);
2768 
2769   // Shrink the condition operand if the new type is smaller than the old type.
2770   // But do not shrink to a non-standard type, because backend can't generate
2771   // good code for that yet.
2772   // TODO: We can make it aggressive again after fixing PR39569.
2773   if (NewWidth > 0 && NewWidth < Known.getBitWidth() &&
2774       shouldChangeType(Known.getBitWidth(), NewWidth)) {
2775     IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
2776     Builder.SetInsertPoint(&SI);
2777     Value *NewCond = Builder.CreateTrunc(Cond, Ty, "trunc");
2778 
2779     for (auto Case : SI.cases()) {
2780       APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(NewWidth);
2781       Case.setValue(ConstantInt::get(SI.getContext(), TruncatedCase));
2782     }
2783     return replaceOperand(SI, 0, NewCond);
2784   }
2785 
2786   return nullptr;
2787 }
2788 
2789 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
2790   Value *Agg = EV.getAggregateOperand();
2791 
2792   if (!EV.hasIndices())
2793     return replaceInstUsesWith(EV, Agg);
2794 
2795   if (Value *V = SimplifyExtractValueInst(Agg, EV.getIndices(),
2796                                           SQ.getWithInstruction(&EV)))
2797     return replaceInstUsesWith(EV, V);
2798 
2799   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
2800     // We're extracting from an insertvalue instruction, compare the indices
2801     const unsigned *exti, *exte, *insi, *inse;
2802     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
2803          exte = EV.idx_end(), inse = IV->idx_end();
2804          exti != exte && insi != inse;
2805          ++exti, ++insi) {
2806       if (*insi != *exti)
2807         // The insert and extract both reference distinctly different elements.
2808         // This means the extract is not influenced by the insert, and we can
2809         // replace the aggregate operand of the extract with the aggregate
2810         // operand of the insert. i.e., replace
2811         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2812         // %E = extractvalue { i32, { i32 } } %I, 0
2813         // with
2814         // %E = extractvalue { i32, { i32 } } %A, 0
2815         return ExtractValueInst::Create(IV->getAggregateOperand(),
2816                                         EV.getIndices());
2817     }
2818     if (exti == exte && insi == inse)
2819       // Both iterators are at the end: Index lists are identical. Replace
2820       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2821       // %C = extractvalue { i32, { i32 } } %B, 1, 0
2822       // with "i32 42"
2823       return replaceInstUsesWith(EV, IV->getInsertedValueOperand());
2824     if (exti == exte) {
2825       // The extract list is a prefix of the insert list. i.e. replace
2826       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2827       // %E = extractvalue { i32, { i32 } } %I, 1
2828       // with
2829       // %X = extractvalue { i32, { i32 } } %A, 1
2830       // %E = insertvalue { i32 } %X, i32 42, 0
2831       // by switching the order of the insert and extract (though the
2832       // insertvalue should be left in, since it may have other uses).
2833       Value *NewEV = Builder.CreateExtractValue(IV->getAggregateOperand(),
2834                                                 EV.getIndices());
2835       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
2836                                      makeArrayRef(insi, inse));
2837     }
2838     if (insi == inse)
2839       // The insert list is a prefix of the extract list
2840       // We can simply remove the common indices from the extract and make it
2841       // operate on the inserted value instead of the insertvalue result.
2842       // i.e., replace
2843       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2844       // %E = extractvalue { i32, { i32 } } %I, 1, 0
2845       // with
2846       // %E extractvalue { i32 } { i32 42 }, 0
2847       return ExtractValueInst::Create(IV->getInsertedValueOperand(),
2848                                       makeArrayRef(exti, exte));
2849   }
2850   if (WithOverflowInst *WO = dyn_cast<WithOverflowInst>(Agg)) {
2851     // We're extracting from an overflow intrinsic, see if we're the only user,
2852     // which allows us to simplify multiple result intrinsics to simpler
2853     // things that just get one value.
2854     if (WO->hasOneUse()) {
2855       // Check if we're grabbing only the result of a 'with overflow' intrinsic
2856       // and replace it with a traditional binary instruction.
2857       if (*EV.idx_begin() == 0) {
2858         Instruction::BinaryOps BinOp = WO->getBinaryOp();
2859         Value *LHS = WO->getLHS(), *RHS = WO->getRHS();
2860         replaceInstUsesWith(*WO, UndefValue::get(WO->getType()));
2861         eraseInstFromFunction(*WO);
2862         return BinaryOperator::Create(BinOp, LHS, RHS);
2863       }
2864 
2865       // If the normal result of the add is dead, and the RHS is a constant,
2866       // we can transform this into a range comparison.
2867       // overflow = uadd a, -4  -->  overflow = icmp ugt a, 3
2868       if (WO->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2869         if (ConstantInt *CI = dyn_cast<ConstantInt>(WO->getRHS()))
2870           return new ICmpInst(ICmpInst::ICMP_UGT, WO->getLHS(),
2871                               ConstantExpr::getNot(CI));
2872     }
2873   }
2874   if (LoadInst *L = dyn_cast<LoadInst>(Agg))
2875     // If the (non-volatile) load only has one use, we can rewrite this to a
2876     // load from a GEP. This reduces the size of the load. If a load is used
2877     // only by extractvalue instructions then this either must have been
2878     // optimized before, or it is a struct with padding, in which case we
2879     // don't want to do the transformation as it loses padding knowledge.
2880     if (L->isSimple() && L->hasOneUse()) {
2881       // extractvalue has integer indices, getelementptr has Value*s. Convert.
2882       SmallVector<Value*, 4> Indices;
2883       // Prefix an i32 0 since we need the first element.
2884       Indices.push_back(Builder.getInt32(0));
2885       for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
2886             I != E; ++I)
2887         Indices.push_back(Builder.getInt32(*I));
2888 
2889       // We need to insert these at the location of the old load, not at that of
2890       // the extractvalue.
2891       Builder.SetInsertPoint(L);
2892       Value *GEP = Builder.CreateInBoundsGEP(L->getType(),
2893                                              L->getPointerOperand(), Indices);
2894       Instruction *NL = Builder.CreateLoad(EV.getType(), GEP);
2895       // Whatever aliasing information we had for the orignal load must also
2896       // hold for the smaller load, so propagate the annotations.
2897       AAMDNodes Nodes;
2898       L->getAAMetadata(Nodes);
2899       NL->setAAMetadata(Nodes);
2900       // Returning the load directly will cause the main loop to insert it in
2901       // the wrong spot, so use replaceInstUsesWith().
2902       return replaceInstUsesWith(EV, NL);
2903     }
2904   // We could simplify extracts from other values. Note that nested extracts may
2905   // already be simplified implicitly by the above: extract (extract (insert) )
2906   // will be translated into extract ( insert ( extract ) ) first and then just
2907   // the value inserted, if appropriate. Similarly for extracts from single-use
2908   // loads: extract (extract (load)) will be translated to extract (load (gep))
2909   // and if again single-use then via load (gep (gep)) to load (gep).
2910   // However, double extracts from e.g. function arguments or return values
2911   // aren't handled yet.
2912   return nullptr;
2913 }
2914 
2915 /// Return 'true' if the given typeinfo will match anything.
2916 static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
2917   switch (Personality) {
2918   case EHPersonality::GNU_C:
2919   case EHPersonality::GNU_C_SjLj:
2920   case EHPersonality::Rust:
2921     // The GCC C EH and Rust personality only exists to support cleanups, so
2922     // it's not clear what the semantics of catch clauses are.
2923     return false;
2924   case EHPersonality::Unknown:
2925     return false;
2926   case EHPersonality::GNU_Ada:
2927     // While __gnat_all_others_value will match any Ada exception, it doesn't
2928     // match foreign exceptions (or didn't, before gcc-4.7).
2929     return false;
2930   case EHPersonality::GNU_CXX:
2931   case EHPersonality::GNU_CXX_SjLj:
2932   case EHPersonality::GNU_ObjC:
2933   case EHPersonality::MSVC_X86SEH:
2934   case EHPersonality::MSVC_Win64SEH:
2935   case EHPersonality::MSVC_CXX:
2936   case EHPersonality::CoreCLR:
2937   case EHPersonality::Wasm_CXX:
2938     return TypeInfo->isNullValue();
2939   }
2940   llvm_unreachable("invalid enum");
2941 }
2942 
2943 static bool shorter_filter(const Value *LHS, const Value *RHS) {
2944   return
2945     cast<ArrayType>(LHS->getType())->getNumElements()
2946   <
2947     cast<ArrayType>(RHS->getType())->getNumElements();
2948 }
2949 
2950 Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
2951   // The logic here should be correct for any real-world personality function.
2952   // However if that turns out not to be true, the offending logic can always
2953   // be conditioned on the personality function, like the catch-all logic is.
2954   EHPersonality Personality =
2955       classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn());
2956 
2957   // Simplify the list of clauses, eg by removing repeated catch clauses
2958   // (these are often created by inlining).
2959   bool MakeNewInstruction = false; // If true, recreate using the following:
2960   SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
2961   bool CleanupFlag = LI.isCleanup();   // - The new instruction is a cleanup.
2962 
2963   SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
2964   for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
2965     bool isLastClause = i + 1 == e;
2966     if (LI.isCatch(i)) {
2967       // A catch clause.
2968       Constant *CatchClause = LI.getClause(i);
2969       Constant *TypeInfo = CatchClause->stripPointerCasts();
2970 
2971       // If we already saw this clause, there is no point in having a second
2972       // copy of it.
2973       if (AlreadyCaught.insert(TypeInfo).second) {
2974         // This catch clause was not already seen.
2975         NewClauses.push_back(CatchClause);
2976       } else {
2977         // Repeated catch clause - drop the redundant copy.
2978         MakeNewInstruction = true;
2979       }
2980 
2981       // If this is a catch-all then there is no point in keeping any following
2982       // clauses or marking the landingpad as having a cleanup.
2983       if (isCatchAll(Personality, TypeInfo)) {
2984         if (!isLastClause)
2985           MakeNewInstruction = true;
2986         CleanupFlag = false;
2987         break;
2988       }
2989     } else {
2990       // A filter clause.  If any of the filter elements were already caught
2991       // then they can be dropped from the filter.  It is tempting to try to
2992       // exploit the filter further by saying that any typeinfo that does not
2993       // occur in the filter can't be caught later (and thus can be dropped).
2994       // However this would be wrong, since typeinfos can match without being
2995       // equal (for example if one represents a C++ class, and the other some
2996       // class derived from it).
2997       assert(LI.isFilter(i) && "Unsupported landingpad clause!");
2998       Constant *FilterClause = LI.getClause(i);
2999       ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
3000       unsigned NumTypeInfos = FilterType->getNumElements();
3001 
3002       // An empty filter catches everything, so there is no point in keeping any
3003       // following clauses or marking the landingpad as having a cleanup.  By
3004       // dealing with this case here the following code is made a bit simpler.
3005       if (!NumTypeInfos) {
3006         NewClauses.push_back(FilterClause);
3007         if (!isLastClause)
3008           MakeNewInstruction = true;
3009         CleanupFlag = false;
3010         break;
3011       }
3012 
3013       bool MakeNewFilter = false; // If true, make a new filter.
3014       SmallVector<Constant *, 16> NewFilterElts; // New elements.
3015       if (isa<ConstantAggregateZero>(FilterClause)) {
3016         // Not an empty filter - it contains at least one null typeinfo.
3017         assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
3018         Constant *TypeInfo =
3019           Constant::getNullValue(FilterType->getElementType());
3020         // If this typeinfo is a catch-all then the filter can never match.
3021         if (isCatchAll(Personality, TypeInfo)) {
3022           // Throw the filter away.
3023           MakeNewInstruction = true;
3024           continue;
3025         }
3026 
3027         // There is no point in having multiple copies of this typeinfo, so
3028         // discard all but the first copy if there is more than one.
3029         NewFilterElts.push_back(TypeInfo);
3030         if (NumTypeInfos > 1)
3031           MakeNewFilter = true;
3032       } else {
3033         ConstantArray *Filter = cast<ConstantArray>(FilterClause);
3034         SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
3035         NewFilterElts.reserve(NumTypeInfos);
3036 
3037         // Remove any filter elements that were already caught or that already
3038         // occurred in the filter.  While there, see if any of the elements are
3039         // catch-alls.  If so, the filter can be discarded.
3040         bool SawCatchAll = false;
3041         for (unsigned j = 0; j != NumTypeInfos; ++j) {
3042           Constant *Elt = Filter->getOperand(j);
3043           Constant *TypeInfo = Elt->stripPointerCasts();
3044           if (isCatchAll(Personality, TypeInfo)) {
3045             // This element is a catch-all.  Bail out, noting this fact.
3046             SawCatchAll = true;
3047             break;
3048           }
3049 
3050           // Even if we've seen a type in a catch clause, we don't want to
3051           // remove it from the filter.  An unexpected type handler may be
3052           // set up for a call site which throws an exception of the same
3053           // type caught.  In order for the exception thrown by the unexpected
3054           // handler to propagate correctly, the filter must be correctly
3055           // described for the call site.
3056           //
3057           // Example:
3058           //
3059           // void unexpected() { throw 1;}
3060           // void foo() throw (int) {
3061           //   std::set_unexpected(unexpected);
3062           //   try {
3063           //     throw 2.0;
3064           //   } catch (int i) {}
3065           // }
3066 
3067           // There is no point in having multiple copies of the same typeinfo in
3068           // a filter, so only add it if we didn't already.
3069           if (SeenInFilter.insert(TypeInfo).second)
3070             NewFilterElts.push_back(cast<Constant>(Elt));
3071         }
3072         // A filter containing a catch-all cannot match anything by definition.
3073         if (SawCatchAll) {
3074           // Throw the filter away.
3075           MakeNewInstruction = true;
3076           continue;
3077         }
3078 
3079         // If we dropped something from the filter, make a new one.
3080         if (NewFilterElts.size() < NumTypeInfos)
3081           MakeNewFilter = true;
3082       }
3083       if (MakeNewFilter) {
3084         FilterType = ArrayType::get(FilterType->getElementType(),
3085                                     NewFilterElts.size());
3086         FilterClause = ConstantArray::get(FilterType, NewFilterElts);
3087         MakeNewInstruction = true;
3088       }
3089 
3090       NewClauses.push_back(FilterClause);
3091 
3092       // If the new filter is empty then it will catch everything so there is
3093       // no point in keeping any following clauses or marking the landingpad
3094       // as having a cleanup.  The case of the original filter being empty was
3095       // already handled above.
3096       if (MakeNewFilter && !NewFilterElts.size()) {
3097         assert(MakeNewInstruction && "New filter but not a new instruction!");
3098         CleanupFlag = false;
3099         break;
3100       }
3101     }
3102   }
3103 
3104   // If several filters occur in a row then reorder them so that the shortest
3105   // filters come first (those with the smallest number of elements).  This is
3106   // advantageous because shorter filters are more likely to match, speeding up
3107   // unwinding, but mostly because it increases the effectiveness of the other
3108   // filter optimizations below.
3109   for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
3110     unsigned j;
3111     // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
3112     for (j = i; j != e; ++j)
3113       if (!isa<ArrayType>(NewClauses[j]->getType()))
3114         break;
3115 
3116     // Check whether the filters are already sorted by length.  We need to know
3117     // if sorting them is actually going to do anything so that we only make a
3118     // new landingpad instruction if it does.
3119     for (unsigned k = i; k + 1 < j; ++k)
3120       if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
3121         // Not sorted, so sort the filters now.  Doing an unstable sort would be
3122         // correct too but reordering filters pointlessly might confuse users.
3123         std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
3124                          shorter_filter);
3125         MakeNewInstruction = true;
3126         break;
3127       }
3128 
3129     // Look for the next batch of filters.
3130     i = j + 1;
3131   }
3132 
3133   // If typeinfos matched if and only if equal, then the elements of a filter L
3134   // that occurs later than a filter F could be replaced by the intersection of
3135   // the elements of F and L.  In reality two typeinfos can match without being
3136   // equal (for example if one represents a C++ class, and the other some class
3137   // derived from it) so it would be wrong to perform this transform in general.
3138   // However the transform is correct and useful if F is a subset of L.  In that
3139   // case L can be replaced by F, and thus removed altogether since repeating a
3140   // filter is pointless.  So here we look at all pairs of filters F and L where
3141   // L follows F in the list of clauses, and remove L if every element of F is
3142   // an element of L.  This can occur when inlining C++ functions with exception
3143   // specifications.
3144   for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
3145     // Examine each filter in turn.
3146     Value *Filter = NewClauses[i];
3147     ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
3148     if (!FTy)
3149       // Not a filter - skip it.
3150       continue;
3151     unsigned FElts = FTy->getNumElements();
3152     // Examine each filter following this one.  Doing this backwards means that
3153     // we don't have to worry about filters disappearing under us when removed.
3154     for (unsigned j = NewClauses.size() - 1; j != i; --j) {
3155       Value *LFilter = NewClauses[j];
3156       ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
3157       if (!LTy)
3158         // Not a filter - skip it.
3159         continue;
3160       // If Filter is a subset of LFilter, i.e. every element of Filter is also
3161       // an element of LFilter, then discard LFilter.
3162       SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
3163       // If Filter is empty then it is a subset of LFilter.
3164       if (!FElts) {
3165         // Discard LFilter.
3166         NewClauses.erase(J);
3167         MakeNewInstruction = true;
3168         // Move on to the next filter.
3169         continue;
3170       }
3171       unsigned LElts = LTy->getNumElements();
3172       // If Filter is longer than LFilter then it cannot be a subset of it.
3173       if (FElts > LElts)
3174         // Move on to the next filter.
3175         continue;
3176       // At this point we know that LFilter has at least one element.
3177       if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
3178         // Filter is a subset of LFilter iff Filter contains only zeros (as we
3179         // already know that Filter is not longer than LFilter).
3180         if (isa<ConstantAggregateZero>(Filter)) {
3181           assert(FElts <= LElts && "Should have handled this case earlier!");
3182           // Discard LFilter.
3183           NewClauses.erase(J);
3184           MakeNewInstruction = true;
3185         }
3186         // Move on to the next filter.
3187         continue;
3188       }
3189       ConstantArray *LArray = cast<ConstantArray>(LFilter);
3190       if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
3191         // Since Filter is non-empty and contains only zeros, it is a subset of
3192         // LFilter iff LFilter contains a zero.
3193         assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
3194         for (unsigned l = 0; l != LElts; ++l)
3195           if (LArray->getOperand(l)->isNullValue()) {
3196             // LFilter contains a zero - discard it.
3197             NewClauses.erase(J);
3198             MakeNewInstruction = true;
3199             break;
3200           }
3201         // Move on to the next filter.
3202         continue;
3203       }
3204       // At this point we know that both filters are ConstantArrays.  Loop over
3205       // operands to see whether every element of Filter is also an element of
3206       // LFilter.  Since filters tend to be short this is probably faster than
3207       // using a method that scales nicely.
3208       ConstantArray *FArray = cast<ConstantArray>(Filter);
3209       bool AllFound = true;
3210       for (unsigned f = 0; f != FElts; ++f) {
3211         Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
3212         AllFound = false;
3213         for (unsigned l = 0; l != LElts; ++l) {
3214           Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
3215           if (LTypeInfo == FTypeInfo) {
3216             AllFound = true;
3217             break;
3218           }
3219         }
3220         if (!AllFound)
3221           break;
3222       }
3223       if (AllFound) {
3224         // Discard LFilter.
3225         NewClauses.erase(J);
3226         MakeNewInstruction = true;
3227       }
3228       // Move on to the next filter.
3229     }
3230   }
3231 
3232   // If we changed any of the clauses, replace the old landingpad instruction
3233   // with a new one.
3234   if (MakeNewInstruction) {
3235     LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
3236                                                  NewClauses.size());
3237     for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
3238       NLI->addClause(NewClauses[i]);
3239     // A landing pad with no clauses must have the cleanup flag set.  It is
3240     // theoretically possible, though highly unlikely, that we eliminated all
3241     // clauses.  If so, force the cleanup flag to true.
3242     if (NewClauses.empty())
3243       CleanupFlag = true;
3244     NLI->setCleanup(CleanupFlag);
3245     return NLI;
3246   }
3247 
3248   // Even if none of the clauses changed, we may nonetheless have understood
3249   // that the cleanup flag is pointless.  Clear it if so.
3250   if (LI.isCleanup() != CleanupFlag) {
3251     assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
3252     LI.setCleanup(CleanupFlag);
3253     return &LI;
3254   }
3255 
3256   return nullptr;
3257 }
3258 
3259 Instruction *InstCombiner::visitFreeze(FreezeInst &I) {
3260   Value *Op0 = I.getOperand(0);
3261 
3262   if (Value *V = SimplifyFreezeInst(Op0, SQ.getWithInstruction(&I)))
3263     return replaceInstUsesWith(I, V);
3264 
3265   return nullptr;
3266 }
3267 
3268 /// Try to move the specified instruction from its current block into the
3269 /// beginning of DestBlock, which can only happen if it's safe to move the
3270 /// instruction past all of the instructions between it and the end of its
3271 /// block.
3272 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
3273   assert(I->getSingleUndroppableUse() && "Invariants didn't hold!");
3274   BasicBlock *SrcBlock = I->getParent();
3275 
3276   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
3277   if (isa<PHINode>(I) || I->isEHPad() || I->mayHaveSideEffects() ||
3278       I->isTerminator())
3279     return false;
3280 
3281   // Do not sink static or dynamic alloca instructions. Static allocas must
3282   // remain in the entry block, and dynamic allocas must not be sunk in between
3283   // a stacksave / stackrestore pair, which would incorrectly shorten its
3284   // lifetime.
3285   if (isa<AllocaInst>(I))
3286     return false;
3287 
3288   // Do not sink into catchswitch blocks.
3289   if (isa<CatchSwitchInst>(DestBlock->getTerminator()))
3290     return false;
3291 
3292   // Do not sink convergent call instructions.
3293   if (auto *CI = dyn_cast<CallInst>(I)) {
3294     if (CI->isConvergent())
3295       return false;
3296   }
3297   // We can only sink load instructions if there is nothing between the load and
3298   // the end of block that could change the value.
3299   if (I->mayReadFromMemory()) {
3300     for (BasicBlock::iterator Scan = I->getIterator(),
3301                               E = I->getParent()->end();
3302          Scan != E; ++Scan)
3303       if (Scan->mayWriteToMemory())
3304         return false;
3305   }
3306 
3307   I->dropDroppableUses([DestBlock](const Use *U) {
3308     if (auto *I = dyn_cast<Instruction>(U->getUser()))
3309       return I->getParent() != DestBlock;
3310     return true;
3311   });
3312   /// FIXME: We could remove droppable uses that are not dominated by
3313   /// the new position.
3314 
3315   BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
3316   I->moveBefore(&*InsertPos);
3317   ++NumSunkInst;
3318 
3319   // Also sink all related debug uses from the source basic block. Otherwise we
3320   // get debug use before the def. Attempt to salvage debug uses first, to
3321   // maximise the range variables have location for. If we cannot salvage, then
3322   // mark the location undef: we know it was supposed to receive a new location
3323   // here, but that computation has been sunk.
3324   SmallVector<DbgVariableIntrinsic *, 2> DbgUsers;
3325   findDbgUsers(DbgUsers, I);
3326   for (auto *DII : reverse(DbgUsers)) {
3327     if (DII->getParent() == SrcBlock) {
3328       if (isa<DbgDeclareInst>(DII)) {
3329         // A dbg.declare instruction should not be cloned, since there can only be
3330         // one per variable fragment. It should be left in the original place since
3331         // sunk instruction is not an alloca(otherwise we could not be here).
3332         // But we need to update arguments of dbg.declare instruction, so that it
3333         // would not point into sunk instruction.
3334         if (!isa<CastInst>(I))
3335           continue; // dbg.declare points at something it shouldn't
3336 
3337         DII->setOperand(
3338             0, MetadataAsValue::get(I->getContext(),
3339                                     ValueAsMetadata::get(I->getOperand(0))));
3340         continue;
3341       }
3342 
3343       // dbg.value is in the same basic block as the sunk inst, see if we can
3344       // salvage it. Clone a new copy of the instruction: on success we need
3345       // both salvaged and unsalvaged copies.
3346       SmallVector<DbgVariableIntrinsic *, 1> TmpUser{
3347           cast<DbgVariableIntrinsic>(DII->clone())};
3348 
3349       if (!salvageDebugInfoForDbgValues(*I, TmpUser)) {
3350         // We are unable to salvage: sink the cloned dbg.value, and mark the
3351         // original as undef, terminating any earlier variable location.
3352         LLVM_DEBUG(dbgs() << "SINK: " << *DII << '\n');
3353         TmpUser[0]->insertBefore(&*InsertPos);
3354         Value *Undef = UndefValue::get(I->getType());
3355         DII->setOperand(0, MetadataAsValue::get(DII->getContext(),
3356                                                 ValueAsMetadata::get(Undef)));
3357       } else {
3358         // We successfully salvaged: place the salvaged dbg.value in the
3359         // original location, and move the unmodified dbg.value to sink with
3360         // the sunk inst.
3361         TmpUser[0]->insertBefore(DII);
3362         DII->moveBefore(&*InsertPos);
3363       }
3364     }
3365   }
3366   return true;
3367 }
3368 
3369 bool InstCombiner::run() {
3370   while (!Worklist.isEmpty()) {
3371     // Walk deferred instructions in reverse order, and push them to the
3372     // worklist, which means they'll end up popped from the worklist in-order.
3373     while (Instruction *I = Worklist.popDeferred()) {
3374       // Check to see if we can DCE the instruction. We do this already here to
3375       // reduce the number of uses and thus allow other folds to trigger.
3376       // Note that eraseInstFromFunction() may push additional instructions on
3377       // the deferred worklist, so this will DCE whole instruction chains.
3378       if (isInstructionTriviallyDead(I, &TLI)) {
3379         eraseInstFromFunction(*I);
3380         ++NumDeadInst;
3381         continue;
3382       }
3383 
3384       Worklist.push(I);
3385     }
3386 
3387     Instruction *I = Worklist.removeOne();
3388     if (I == nullptr) continue;  // skip null values.
3389 
3390     // Check to see if we can DCE the instruction.
3391     if (isInstructionTriviallyDead(I, &TLI)) {
3392       eraseInstFromFunction(*I);
3393       ++NumDeadInst;
3394       continue;
3395     }
3396 
3397     if (!DebugCounter::shouldExecute(VisitCounter))
3398       continue;
3399 
3400     // Instruction isn't dead, see if we can constant propagate it.
3401     if (!I->use_empty() &&
3402         (I->getNumOperands() == 0 || isa<Constant>(I->getOperand(0)))) {
3403       if (Constant *C = ConstantFoldInstruction(I, DL, &TLI)) {
3404         LLVM_DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I
3405                           << '\n');
3406 
3407         // Add operands to the worklist.
3408         replaceInstUsesWith(*I, C);
3409         ++NumConstProp;
3410         if (isInstructionTriviallyDead(I, &TLI))
3411           eraseInstFromFunction(*I);
3412         MadeIRChange = true;
3413         continue;
3414       }
3415     }
3416 
3417     // See if we can trivially sink this instruction to a successor basic block.
3418     if (EnableCodeSinking)
3419       if (Use *SingleUse = I->getSingleUndroppableUse()) {
3420         BasicBlock *BB = I->getParent();
3421         Instruction *UserInst = cast<Instruction>(SingleUse->getUser());
3422         BasicBlock *UserParent;
3423 
3424         // Get the block the use occurs in.
3425         if (PHINode *PN = dyn_cast<PHINode>(UserInst))
3426           UserParent = PN->getIncomingBlock(*SingleUse);
3427         else
3428           UserParent = UserInst->getParent();
3429 
3430         if (UserParent != BB) {
3431           bool UserIsSuccessor = false;
3432           // See if the user is one of our successors.
3433           for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E;
3434                ++SI)
3435             if (*SI == UserParent) {
3436               UserIsSuccessor = true;
3437               break;
3438             }
3439 
3440           // If the user is one of our immediate successors, and if that
3441           // successor only has us as a predecessors (we'd have to split the
3442           // critical edge otherwise), we can keep going.
3443           if (UserIsSuccessor && UserParent->getUniquePredecessor()) {
3444             // Okay, the CFG is simple enough, try to sink this instruction.
3445             if (TryToSinkInstruction(I, UserParent)) {
3446               LLVM_DEBUG(dbgs() << "IC: Sink: " << *I << '\n');
3447               MadeIRChange = true;
3448               // We'll add uses of the sunk instruction below, but since sinking
3449               // can expose opportunities for it's *operands* add them to the
3450               // worklist
3451               for (Use &U : I->operands())
3452                 if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
3453                   Worklist.push(OpI);
3454             }
3455           }
3456         }
3457       }
3458 
3459     // Now that we have an instruction, try combining it to simplify it.
3460     Builder.SetInsertPoint(I);
3461     Builder.SetCurrentDebugLocation(I->getDebugLoc());
3462 
3463 #ifndef NDEBUG
3464     std::string OrigI;
3465 #endif
3466     LLVM_DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
3467     LLVM_DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
3468 
3469     if (Instruction *Result = visit(*I)) {
3470       ++NumCombined;
3471       // Should we replace the old instruction with a new one?
3472       if (Result != I) {
3473         LLVM_DEBUG(dbgs() << "IC: Old = " << *I << '\n'
3474                           << "    New = " << *Result << '\n');
3475 
3476         if (I->getDebugLoc())
3477           Result->setDebugLoc(I->getDebugLoc());
3478         // Everything uses the new instruction now.
3479         I->replaceAllUsesWith(Result);
3480 
3481         // Move the name to the new instruction first.
3482         Result->takeName(I);
3483 
3484         // Insert the new instruction into the basic block...
3485         BasicBlock *InstParent = I->getParent();
3486         BasicBlock::iterator InsertPos = I->getIterator();
3487 
3488         // If we replace a PHI with something that isn't a PHI, fix up the
3489         // insertion point.
3490         if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
3491           InsertPos = InstParent->getFirstInsertionPt();
3492 
3493         InstParent->getInstList().insert(InsertPos, Result);
3494 
3495         // Push the new instruction and any users onto the worklist.
3496         Worklist.pushUsersToWorkList(*Result);
3497         Worklist.push(Result);
3498 
3499         eraseInstFromFunction(*I);
3500       } else {
3501         LLVM_DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
3502                           << "    New = " << *I << '\n');
3503 
3504         // If the instruction was modified, it's possible that it is now dead.
3505         // if so, remove it.
3506         if (isInstructionTriviallyDead(I, &TLI)) {
3507           eraseInstFromFunction(*I);
3508         } else {
3509           Worklist.pushUsersToWorkList(*I);
3510           Worklist.push(I);
3511         }
3512       }
3513       MadeIRChange = true;
3514     }
3515   }
3516 
3517   Worklist.zap();
3518   return MadeIRChange;
3519 }
3520 
3521 /// Populate the IC worklist from a function, by walking it in depth-first
3522 /// order and adding all reachable code to the worklist.
3523 ///
3524 /// This has a couple of tricks to make the code faster and more powerful.  In
3525 /// particular, we constant fold and DCE instructions as we go, to avoid adding
3526 /// them to the worklist (this significantly speeds up instcombine on code where
3527 /// many instructions are dead or constant).  Additionally, if we find a branch
3528 /// whose condition is a known constant, we only visit the reachable successors.
3529 static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL,
3530                                           const TargetLibraryInfo *TLI,
3531                                           InstCombineWorklist &ICWorklist) {
3532   bool MadeIRChange = false;
3533   SmallPtrSet<BasicBlock *, 32> Visited;
3534   SmallVector<BasicBlock*, 256> Worklist;
3535   Worklist.push_back(&F.front());
3536 
3537   SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
3538   DenseMap<Constant *, Constant *> FoldedConstants;
3539 
3540   do {
3541     BasicBlock *BB = Worklist.pop_back_val();
3542 
3543     // We have now visited this block!  If we've already been here, ignore it.
3544     if (!Visited.insert(BB).second)
3545       continue;
3546 
3547     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
3548       Instruction *Inst = &*BBI++;
3549 
3550       // ConstantProp instruction if trivially constant.
3551       if (!Inst->use_empty() &&
3552           (Inst->getNumOperands() == 0 || isa<Constant>(Inst->getOperand(0))))
3553         if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
3554           LLVM_DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *Inst
3555                             << '\n');
3556           Inst->replaceAllUsesWith(C);
3557           ++NumConstProp;
3558           if (isInstructionTriviallyDead(Inst, TLI))
3559             Inst->eraseFromParent();
3560           MadeIRChange = true;
3561           continue;
3562         }
3563 
3564       // See if we can constant fold its operands.
3565       for (Use &U : Inst->operands()) {
3566         if (!isa<ConstantVector>(U) && !isa<ConstantExpr>(U))
3567           continue;
3568 
3569         auto *C = cast<Constant>(U);
3570         Constant *&FoldRes = FoldedConstants[C];
3571         if (!FoldRes)
3572           FoldRes = ConstantFoldConstant(C, DL, TLI);
3573 
3574         if (FoldRes != C) {
3575           LLVM_DEBUG(dbgs() << "IC: ConstFold operand of: " << *Inst
3576                             << "\n    Old = " << *C
3577                             << "\n    New = " << *FoldRes << '\n');
3578           U = FoldRes;
3579           MadeIRChange = true;
3580         }
3581       }
3582 
3583       // Skip processing debug intrinsics in InstCombine. Processing these call instructions
3584       // consumes non-trivial amount of time and provides no value for the optimization.
3585       if (!isa<DbgInfoIntrinsic>(Inst))
3586         InstrsForInstCombineWorklist.push_back(Inst);
3587     }
3588 
3589     // Recursively visit successors.  If this is a branch or switch on a
3590     // constant, only visit the reachable successor.
3591     Instruction *TI = BB->getTerminator();
3592     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3593       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
3594         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
3595         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
3596         Worklist.push_back(ReachableBB);
3597         continue;
3598       }
3599     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3600       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
3601         Worklist.push_back(SI->findCaseValue(Cond)->getCaseSuccessor());
3602         continue;
3603       }
3604     }
3605 
3606     for (BasicBlock *SuccBB : successors(TI))
3607       Worklist.push_back(SuccBB);
3608   } while (!Worklist.empty());
3609 
3610   // Remove instructions inside unreachable blocks. This prevents the
3611   // instcombine code from having to deal with some bad special cases, and
3612   // reduces use counts of instructions.
3613   for (BasicBlock &BB : F) {
3614     if (Visited.count(&BB))
3615       continue;
3616 
3617     unsigned NumDeadInstInBB = removeAllNonTerminatorAndEHPadInstructions(&BB);
3618     MadeIRChange |= NumDeadInstInBB > 0;
3619     NumDeadInst += NumDeadInstInBB;
3620   }
3621 
3622   // Once we've found all of the instructions to add to instcombine's worklist,
3623   // add them in reverse order.  This way instcombine will visit from the top
3624   // of the function down.  This jives well with the way that it adds all uses
3625   // of instructions to the worklist after doing a transformation, thus avoiding
3626   // some N^2 behavior in pathological cases.
3627   ICWorklist.reserve(InstrsForInstCombineWorklist.size());
3628   for (Instruction *Inst : reverse(InstrsForInstCombineWorklist)) {
3629     // DCE instruction if trivially dead. As we iterate in reverse program
3630     // order here, we will clean up whole chains of dead instructions.
3631     if (isInstructionTriviallyDead(Inst, TLI)) {
3632       ++NumDeadInst;
3633       LLVM_DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
3634       salvageDebugInfoOrMarkUndef(*Inst);
3635       Inst->eraseFromParent();
3636       MadeIRChange = true;
3637       continue;
3638     }
3639 
3640     ICWorklist.push(Inst);
3641   }
3642 
3643   return MadeIRChange;
3644 }
3645 
3646 static bool combineInstructionsOverFunction(
3647     Function &F, InstCombineWorklist &Worklist, AliasAnalysis *AA,
3648     AssumptionCache &AC, TargetLibraryInfo &TLI, DominatorTree &DT,
3649     OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI,
3650     ProfileSummaryInfo *PSI, unsigned MaxIterations, LoopInfo *LI) {
3651   auto &DL = F.getParent()->getDataLayout();
3652   MaxIterations = std::min(MaxIterations, LimitMaxIterations.getValue());
3653 
3654   /// Builder - This is an IRBuilder that automatically inserts new
3655   /// instructions into the worklist when they are created.
3656   IRBuilder<TargetFolder, IRBuilderCallbackInserter> Builder(
3657       F.getContext(), TargetFolder(DL),
3658       IRBuilderCallbackInserter([&Worklist, &AC](Instruction *I) {
3659         Worklist.add(I);
3660         if (match(I, m_Intrinsic<Intrinsic::assume>()))
3661           AC.registerAssumption(cast<CallInst>(I));
3662       }));
3663 
3664   // Lower dbg.declare intrinsics otherwise their value may be clobbered
3665   // by instcombiner.
3666   bool MadeIRChange = false;
3667   if (ShouldLowerDbgDeclare)
3668     MadeIRChange = LowerDbgDeclare(F);
3669 
3670   // Iterate while there is work to do.
3671   unsigned Iteration = 0;
3672   while (true) {
3673     ++Iteration;
3674 
3675     if (Iteration > InfiniteLoopDetectionThreshold) {
3676       report_fatal_error(
3677           "Instruction Combining seems stuck in an infinite loop after " +
3678           Twine(InfiniteLoopDetectionThreshold) + " iterations.");
3679     }
3680 
3681     if (Iteration > MaxIterations) {
3682       LLVM_DEBUG(dbgs() << "\n\n[IC] Iteration limit #" << MaxIterations
3683                         << " on " << F.getName()
3684                         << " reached; stopping before reaching a fixpoint\n");
3685       break;
3686     }
3687 
3688     LLVM_DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
3689                       << F.getName() << "\n");
3690 
3691     MadeIRChange |= prepareICWorklistFromFunction(F, DL, &TLI, Worklist);
3692 
3693     InstCombiner IC(Worklist, Builder, F.hasMinSize(), AA,
3694                     AC, TLI, DT, ORE, BFI, PSI, DL, LI);
3695     IC.MaxArraySizeForCombine = MaxArraySize;
3696 
3697     if (!IC.run())
3698       break;
3699 
3700     MadeIRChange = true;
3701   }
3702 
3703   return MadeIRChange;
3704 }
3705 
3706 InstCombinePass::InstCombinePass() : MaxIterations(LimitMaxIterations) {}
3707 
3708 InstCombinePass::InstCombinePass(unsigned MaxIterations)
3709     : MaxIterations(MaxIterations) {}
3710 
3711 PreservedAnalyses InstCombinePass::run(Function &F,
3712                                        FunctionAnalysisManager &AM) {
3713   auto &AC = AM.getResult<AssumptionAnalysis>(F);
3714   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
3715   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
3716   auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
3717 
3718   auto *LI = AM.getCachedResult<LoopAnalysis>(F);
3719 
3720   auto *AA = &AM.getResult<AAManager>(F);
3721   const ModuleAnalysisManager &MAM =
3722       AM.getResult<ModuleAnalysisManagerFunctionProxy>(F).getManager();
3723   ProfileSummaryInfo *PSI =
3724       MAM.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
3725   auto *BFI = (PSI && PSI->hasProfileSummary()) ?
3726       &AM.getResult<BlockFrequencyAnalysis>(F) : nullptr;
3727 
3728   if (!combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT, ORE, BFI,
3729                                        PSI, MaxIterations, LI))
3730     // No changes, all analyses are preserved.
3731     return PreservedAnalyses::all();
3732 
3733   // Mark all the analyses that instcombine updates as preserved.
3734   PreservedAnalyses PA;
3735   PA.preserveSet<CFGAnalyses>();
3736   PA.preserve<AAManager>();
3737   PA.preserve<BasicAA>();
3738   PA.preserve<GlobalsAA>();
3739   return PA;
3740 }
3741 
3742 void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const {
3743   AU.setPreservesCFG();
3744   AU.addRequired<AAResultsWrapperPass>();
3745   AU.addRequired<AssumptionCacheTracker>();
3746   AU.addRequired<TargetLibraryInfoWrapperPass>();
3747   AU.addRequired<DominatorTreeWrapperPass>();
3748   AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
3749   AU.addPreserved<DominatorTreeWrapperPass>();
3750   AU.addPreserved<AAResultsWrapperPass>();
3751   AU.addPreserved<BasicAAWrapperPass>();
3752   AU.addPreserved<GlobalsAAWrapperPass>();
3753   AU.addRequired<ProfileSummaryInfoWrapperPass>();
3754   LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU);
3755 }
3756 
3757 bool InstructionCombiningPass::runOnFunction(Function &F) {
3758   if (skipFunction(F))
3759     return false;
3760 
3761   // Required analyses.
3762   auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3763   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3764   auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
3765   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3766   auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
3767 
3768   // Optional analyses.
3769   auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
3770   auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
3771   ProfileSummaryInfo *PSI =
3772       &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
3773   BlockFrequencyInfo *BFI =
3774       (PSI && PSI->hasProfileSummary()) ?
3775       &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI() :
3776       nullptr;
3777 
3778   return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT, ORE, BFI,
3779                                          PSI, MaxIterations, LI);
3780 }
3781 
3782 char InstructionCombiningPass::ID = 0;
3783 
3784 InstructionCombiningPass::InstructionCombiningPass()
3785     : FunctionPass(ID), MaxIterations(InstCombineDefaultMaxIterations) {
3786   initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry());
3787 }
3788 
3789 InstructionCombiningPass::InstructionCombiningPass(unsigned MaxIterations)
3790     : FunctionPass(ID), MaxIterations(MaxIterations) {
3791   initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry());
3792 }
3793 
3794 INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine",
3795                       "Combine redundant instructions", false, false)
3796 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3797 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3798 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3799 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3800 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
3801 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
3802 INITIALIZE_PASS_DEPENDENCY(LazyBlockFrequencyInfoPass)
3803 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
3804 INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine",
3805                     "Combine redundant instructions", false, false)
3806 
3807 // Initialization Routines
3808 void llvm::initializeInstCombine(PassRegistry &Registry) {
3809   initializeInstructionCombiningPassPass(Registry);
3810 }
3811 
3812 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
3813   initializeInstructionCombiningPassPass(*unwrap(R));
3814 }
3815 
3816 FunctionPass *llvm::createInstructionCombiningPass() {
3817   return new InstructionCombiningPass();
3818 }
3819 
3820 FunctionPass *llvm::createInstructionCombiningPass(unsigned MaxIterations) {
3821   return new InstructionCombiningPass(MaxIterations);
3822 }
3823 
3824 void LLVMAddInstructionCombiningPass(LLVMPassManagerRef PM) {
3825   unwrap(PM)->add(createInstructionCombiningPass());
3826 }
3827