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