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