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