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