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