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