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