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