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 //===----------------------------------------------------------------------===//
36 #include "llvm/Transforms/Scalar.h"
37 #include "InstCombine.h"
38 #include "llvm-c/Initialization.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/Statistic.h"
41 #include "llvm/ADT/StringSwitch.h"
42 #include "llvm/Analysis/AssumptionCache.h"
43 #include "llvm/Analysis/CFG.h"
44 #include "llvm/Analysis/ConstantFolding.h"
45 #include "llvm/Analysis/InstructionSimplify.h"
46 #include "llvm/Analysis/LoopInfo.h"
47 #include "llvm/Analysis/MemoryBuiltins.h"
48 #include "llvm/Analysis/ValueTracking.h"
49 #include "llvm/IR/CFG.h"
50 #include "llvm/IR/DataLayout.h"
51 #include "llvm/IR/Dominators.h"
52 #include "llvm/IR/GetElementPtrTypeIterator.h"
53 #include "llvm/IR/IntrinsicInst.h"
54 #include "llvm/IR/PatternMatch.h"
55 #include "llvm/IR/ValueHandle.h"
56 #include "llvm/Support/CommandLine.h"
57 #include "llvm/Support/Debug.h"
58 #include "llvm/Analysis/TargetLibraryInfo.h"
59 #include "llvm/Transforms/Utils/Local.h"
60 #include <algorithm>
61 #include <climits>
62 using namespace llvm;
63 using namespace llvm::PatternMatch;
65 #define DEBUG_TYPE "instcombine"
67 STATISTIC(NumCombined , "Number of insts combined");
68 STATISTIC(NumConstProp, "Number of constant folds");
69 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
70 STATISTIC(NumSunkInst , "Number of instructions sunk");
71 STATISTIC(NumExpand, "Number of expansions");
72 STATISTIC(NumFactor , "Number of factorizations");
73 STATISTIC(NumReassoc , "Number of reassociations");
75 // Initialization Routines
76 void llvm::initializeInstCombine(PassRegistry &Registry) {
77 initializeInstCombinerPass(Registry);
78 }
80 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
81 initializeInstCombine(*unwrap(R));
82 }
84 char InstCombiner::ID = 0;
85 INITIALIZE_PASS_BEGIN(InstCombiner, "instcombine",
86 "Combine redundant instructions", false, false)
87 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
88 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
89 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
90 INITIALIZE_PASS_END(InstCombiner, "instcombine",
91 "Combine redundant instructions", false, false)
93 void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
94 AU.setPreservesCFG();
95 AU.addRequired<AssumptionCacheTracker>();
96 AU.addRequired<TargetLibraryInfoWrapperPass>();
97 AU.addRequired<DominatorTreeWrapperPass>();
98 AU.addPreserved<DominatorTreeWrapperPass>();
99 }
102 Value *InstCombiner::EmitGEPOffset(User *GEP) {
103 return llvm::EmitGEPOffset(Builder, *getDataLayout(), GEP);
104 }
106 /// ShouldChangeType - Return true if it is desirable to convert a computation
107 /// from 'From' to 'To'. We don't want to convert from a legal to an illegal
108 /// type for example, or from a smaller to a larger illegal type.
109 bool InstCombiner::ShouldChangeType(Type *From, Type *To) const {
110 assert(From->isIntegerTy() && To->isIntegerTy());
112 // If we don't have DL, we don't know if the source/dest are legal.
113 if (!DL) return false;
115 unsigned FromWidth = From->getPrimitiveSizeInBits();
116 unsigned ToWidth = To->getPrimitiveSizeInBits();
117 bool FromLegal = DL->isLegalInteger(FromWidth);
118 bool ToLegal = DL->isLegalInteger(ToWidth);
120 // If this is a legal integer from type, and the result would be an illegal
121 // type, don't do the transformation.
122 if (FromLegal && !ToLegal)
123 return false;
125 // Otherwise, if both are illegal, do not increase the size of the result. We
126 // do allow things like i160 -> i64, but not i64 -> i160.
127 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
128 return false;
130 return true;
131 }
133 // Return true, if No Signed Wrap should be maintained for I.
134 // The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
135 // where both B and C should be ConstantInts, results in a constant that does
136 // not overflow. This function only handles the Add and Sub opcodes. For
137 // all other opcodes, the function conservatively returns false.
138 static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
139 OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
140 if (!OBO || !OBO->hasNoSignedWrap()) {
141 return false;
142 }
144 // We reason about Add and Sub Only.
145 Instruction::BinaryOps Opcode = I.getOpcode();
146 if (Opcode != Instruction::Add &&
147 Opcode != Instruction::Sub) {
148 return false;
149 }
151 ConstantInt *CB = dyn_cast<ConstantInt>(B);
152 ConstantInt *CC = dyn_cast<ConstantInt>(C);
154 if (!CB || !CC) {
155 return false;
156 }
158 const APInt &BVal = CB->getValue();
159 const APInt &CVal = CC->getValue();
160 bool Overflow = false;
162 if (Opcode == Instruction::Add) {
163 BVal.sadd_ov(CVal, Overflow);
164 } else {
165 BVal.ssub_ov(CVal, Overflow);
166 }
168 return !Overflow;
169 }
171 /// Conservatively clears subclassOptionalData after a reassociation or
172 /// commutation. We preserve fast-math flags when applicable as they can be
173 /// preserved.
174 static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {
175 FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
176 if (!FPMO) {
177 I.clearSubclassOptionalData();
178 return;
179 }
181 FastMathFlags FMF = I.getFastMathFlags();
182 I.clearSubclassOptionalData();
183 I.setFastMathFlags(FMF);
184 }
186 /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
187 /// operators which are associative or commutative:
188 //
189 // Commutative operators:
190 //
191 // 1. Order operands such that they are listed from right (least complex) to
192 // left (most complex). This puts constants before unary operators before
193 // binary operators.
194 //
195 // Associative operators:
196 //
197 // 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
198 // 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
199 //
200 // Associative and commutative operators:
201 //
202 // 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
203 // 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
204 // 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
205 // if C1 and C2 are constants.
206 //
207 bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
208 Instruction::BinaryOps Opcode = I.getOpcode();
209 bool Changed = false;
211 do {
212 // Order operands such that they are listed from right (least complex) to
213 // left (most complex). This puts constants before unary operators before
214 // binary operators.
215 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
216 getComplexity(I.getOperand(1)))
217 Changed = !I.swapOperands();
219 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
220 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
222 if (I.isAssociative()) {
223 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
224 if (Op0 && Op0->getOpcode() == Opcode) {
225 Value *A = Op0->getOperand(0);
226 Value *B = Op0->getOperand(1);
227 Value *C = I.getOperand(1);
229 // Does "B op C" simplify?
230 if (Value *V = SimplifyBinOp(Opcode, B, C, DL)) {
231 // It simplifies to V. Form "A op V".
232 I.setOperand(0, A);
233 I.setOperand(1, V);
234 // Conservatively clear the optional flags, since they may not be
235 // preserved by the reassociation.
236 if (MaintainNoSignedWrap(I, B, C) &&
237 (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
238 // Note: this is only valid because SimplifyBinOp doesn't look at
239 // the operands to Op0.
240 I.clearSubclassOptionalData();
241 I.setHasNoSignedWrap(true);
242 } else {
243 ClearSubclassDataAfterReassociation(I);
244 }
246 Changed = true;
247 ++NumReassoc;
248 continue;
249 }
250 }
252 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
253 if (Op1 && Op1->getOpcode() == Opcode) {
254 Value *A = I.getOperand(0);
255 Value *B = Op1->getOperand(0);
256 Value *C = Op1->getOperand(1);
258 // Does "A op B" simplify?
259 if (Value *V = SimplifyBinOp(Opcode, A, B, DL)) {
260 // It simplifies to V. Form "V op C".
261 I.setOperand(0, V);
262 I.setOperand(1, C);
263 // Conservatively clear the optional flags, since they may not be
264 // preserved by the reassociation.
265 ClearSubclassDataAfterReassociation(I);
266 Changed = true;
267 ++NumReassoc;
268 continue;
269 }
270 }
271 }
273 if (I.isAssociative() && I.isCommutative()) {
274 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
275 if (Op0 && Op0->getOpcode() == Opcode) {
276 Value *A = Op0->getOperand(0);
277 Value *B = Op0->getOperand(1);
278 Value *C = I.getOperand(1);
280 // Does "C op A" simplify?
281 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
282 // It simplifies to V. Form "V op B".
283 I.setOperand(0, V);
284 I.setOperand(1, B);
285 // Conservatively clear the optional flags, since they may not be
286 // preserved by the reassociation.
287 ClearSubclassDataAfterReassociation(I);
288 Changed = true;
289 ++NumReassoc;
290 continue;
291 }
292 }
294 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
295 if (Op1 && Op1->getOpcode() == Opcode) {
296 Value *A = I.getOperand(0);
297 Value *B = Op1->getOperand(0);
298 Value *C = Op1->getOperand(1);
300 // Does "C op A" simplify?
301 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
302 // It simplifies to V. Form "B op V".
303 I.setOperand(0, B);
304 I.setOperand(1, V);
305 // Conservatively clear the optional flags, since they may not be
306 // preserved by the reassociation.
307 ClearSubclassDataAfterReassociation(I);
308 Changed = true;
309 ++NumReassoc;
310 continue;
311 }
312 }
314 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
315 // if C1 and C2 are constants.
316 if (Op0 && Op1 &&
317 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
318 isa<Constant>(Op0->getOperand(1)) &&
319 isa<Constant>(Op1->getOperand(1)) &&
320 Op0->hasOneUse() && Op1->hasOneUse()) {
321 Value *A = Op0->getOperand(0);
322 Constant *C1 = cast<Constant>(Op0->getOperand(1));
323 Value *B = Op1->getOperand(0);
324 Constant *C2 = cast<Constant>(Op1->getOperand(1));
326 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
327 BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
328 if (isa<FPMathOperator>(New)) {
329 FastMathFlags Flags = I.getFastMathFlags();
330 Flags &= Op0->getFastMathFlags();
331 Flags &= Op1->getFastMathFlags();
332 New->setFastMathFlags(Flags);
333 }
334 InsertNewInstWith(New, I);
335 New->takeName(Op1);
336 I.setOperand(0, New);
337 I.setOperand(1, Folded);
338 // Conservatively clear the optional flags, since they may not be
339 // preserved by the reassociation.
340 ClearSubclassDataAfterReassociation(I);
342 Changed = true;
343 continue;
344 }
345 }
347 // No further simplifications.
348 return Changed;
349 } while (1);
350 }
352 /// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
353 /// "(X LOp Y) ROp (X LOp Z)".
354 static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
355 Instruction::BinaryOps ROp) {
356 switch (LOp) {
357 default:
358 return false;
360 case Instruction::And:
361 // And distributes over Or and Xor.
362 switch (ROp) {
363 default:
364 return false;
365 case Instruction::Or:
366 case Instruction::Xor:
367 return true;
368 }
370 case Instruction::Mul:
371 // Multiplication distributes over addition and subtraction.
372 switch (ROp) {
373 default:
374 return false;
375 case Instruction::Add:
376 case Instruction::Sub:
377 return true;
378 }
380 case Instruction::Or:
381 // Or distributes over And.
382 switch (ROp) {
383 default:
384 return false;
385 case Instruction::And:
386 return true;
387 }
388 }
389 }
391 /// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
392 /// "(X ROp Z) LOp (Y ROp Z)".
393 static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
394 Instruction::BinaryOps ROp) {
395 if (Instruction::isCommutative(ROp))
396 return LeftDistributesOverRight(ROp, LOp);
398 switch (LOp) {
399 default:
400 return false;
401 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
402 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
403 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
404 case Instruction::And:
405 case Instruction::Or:
406 case Instruction::Xor:
407 switch (ROp) {
408 default:
409 return false;
410 case Instruction::Shl:
411 case Instruction::LShr:
412 case Instruction::AShr:
413 return true;
414 }
415 }
416 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
417 // but this requires knowing that the addition does not overflow and other
418 // such subtleties.
419 return false;
420 }
422 /// This function returns identity value for given opcode, which can be used to
423 /// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
424 static Value *getIdentityValue(Instruction::BinaryOps OpCode, Value *V) {
425 if (isa<Constant>(V))
426 return nullptr;
428 if (OpCode == Instruction::Mul)
429 return ConstantInt::get(V->getType(), 1);
431 // TODO: We can handle other cases e.g. Instruction::And, Instruction::Or etc.
433 return nullptr;
434 }
436 /// This function factors binary ops which can be combined using distributive
437 /// laws. This function tries to transform 'Op' based TopLevelOpcode to enable
438 /// factorization e.g for ADD(SHL(X , 2), MUL(X, 5)), When this function called
439 /// with TopLevelOpcode == Instruction::Add and Op = SHL(X, 2), transforms
440 /// SHL(X, 2) to MUL(X, 4) i.e. returns Instruction::Mul with LHS set to 'X' and
441 /// RHS to 4.
442 static Instruction::BinaryOps
443 getBinOpsForFactorization(Instruction::BinaryOps TopLevelOpcode,
444 BinaryOperator *Op, Value *&LHS, Value *&RHS) {
445 if (!Op)
446 return Instruction::BinaryOpsEnd;
448 LHS = Op->getOperand(0);
449 RHS = Op->getOperand(1);
451 switch (TopLevelOpcode) {
452 default:
453 return Op->getOpcode();
455 case Instruction::Add:
456 case Instruction::Sub:
457 if (Op->getOpcode() == Instruction::Shl) {
458 if (Constant *CST = dyn_cast<Constant>(Op->getOperand(1))) {
459 // The multiplier is really 1 << CST.
460 RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), CST);
461 return Instruction::Mul;
462 }
463 }
464 return Op->getOpcode();
465 }
467 // TODO: We can add other conversions e.g. shr => div etc.
468 }
470 /// This tries to simplify binary operations by factorizing out common terms
471 /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
472 static Value *tryFactorization(InstCombiner::BuilderTy *Builder,
473 const DataLayout *DL, BinaryOperator &I,
474 Instruction::BinaryOps InnerOpcode, Value *A,
475 Value *B, Value *C, Value *D) {
477 // If any of A, B, C, D are null, we can not factor I, return early.
478 // Checking A and C should be enough.
479 if (!A || !C || !B || !D)
480 return nullptr;
482 Value *SimplifiedInst = nullptr;
483 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
484 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
486 // Does "X op' Y" always equal "Y op' X"?
487 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
489 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
490 if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
491 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
492 // commutative case, "(A op' B) op (C op' A)"?
493 if (A == C || (InnerCommutative && A == D)) {
494 if (A != C)
495 std::swap(C, D);
496 // Consider forming "A op' (B op D)".
497 // If "B op D" simplifies then it can be formed with no cost.
498 Value *V = SimplifyBinOp(TopLevelOpcode, B, D, DL);
499 // If "B op D" doesn't simplify then only go on if both of the existing
500 // operations "A op' B" and "C op' D" will be zapped as no longer used.
501 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
502 V = Builder->CreateBinOp(TopLevelOpcode, B, D, RHS->getName());
503 if (V) {
504 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, A, V);
505 }
506 }
508 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
509 if (!SimplifiedInst && RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
510 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
511 // commutative case, "(A op' B) op (B op' D)"?
512 if (B == D || (InnerCommutative && B == C)) {
513 if (B != D)
514 std::swap(C, D);
515 // Consider forming "(A op C) op' B".
516 // If "A op C" simplifies then it can be formed with no cost.
517 Value *V = SimplifyBinOp(TopLevelOpcode, A, C, DL);
519 // If "A op C" doesn't simplify then only go on if both of the existing
520 // operations "A op' B" and "C op' D" will be zapped as no longer used.
521 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
522 V = Builder->CreateBinOp(TopLevelOpcode, A, C, LHS->getName());
523 if (V) {
524 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, V, B);
525 }
526 }
528 if (SimplifiedInst) {
529 ++NumFactor;
530 SimplifiedInst->takeName(&I);
532 // Check if we can add NSW flag to SimplifiedInst. If so, set NSW flag.
533 // TODO: Check for NUW.
534 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) {
535 if (isa<OverflowingBinaryOperator>(SimplifiedInst)) {
536 bool HasNSW = false;
537 if (isa<OverflowingBinaryOperator>(&I))
538 HasNSW = I.hasNoSignedWrap();
540 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
541 if (isa<OverflowingBinaryOperator>(Op0))
542 HasNSW &= Op0->hasNoSignedWrap();
544 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
545 if (isa<OverflowingBinaryOperator>(Op1))
546 HasNSW &= Op1->hasNoSignedWrap();
547 BO->setHasNoSignedWrap(HasNSW);
548 }
549 }
550 }
551 return SimplifiedInst;
552 }
554 /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
555 /// which some other binary operation distributes over either by factorizing
556 /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
557 /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
558 /// a win). Returns the simplified value, or null if it didn't simplify.
559 Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
560 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
561 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
562 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
564 // Factorization.
565 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
566 auto TopLevelOpcode = I.getOpcode();
567 auto LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B);
568 auto RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D);
570 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
571 // a common term.
572 if (LHSOpcode == RHSOpcode) {
573 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, C, D))
574 return V;
575 }
577 // The instruction has the form "(A op' B) op (C)". Try to factorize common
578 // term.
579 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, RHS,
580 getIdentityValue(LHSOpcode, RHS)))
581 return V;
583 // The instruction has the form "(B) op (C op' D)". Try to factorize common
584 // term.
585 if (Value *V = tryFactorization(Builder, DL, I, RHSOpcode, LHS,
586 getIdentityValue(RHSOpcode, LHS), C, D))
587 return V;
589 // Expansion.
590 if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
591 // The instruction has the form "(A op' B) op C". See if expanding it out
592 // to "(A op C) op' (B op C)" results in simplifications.
593 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
594 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
596 // Do "A op C" and "B op C" both simplify?
597 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, DL))
598 if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, DL)) {
599 // They do! Return "L op' R".
600 ++NumExpand;
601 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
602 if ((L == A && R == B) ||
603 (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
604 return Op0;
605 // Otherwise return "L op' R" if it simplifies.
606 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
607 return V;
608 // Otherwise, create a new instruction.
609 C = Builder->CreateBinOp(InnerOpcode, L, R);
610 C->takeName(&I);
611 return C;
612 }
613 }
615 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
616 // The instruction has the form "A op (B op' C)". See if expanding it out
617 // to "(A op B) op' (A op C)" results in simplifications.
618 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
619 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
621 // Do "A op B" and "A op C" both simplify?
622 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, DL))
623 if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, DL)) {
624 // They do! Return "L op' R".
625 ++NumExpand;
626 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
627 if ((L == B && R == C) ||
628 (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
629 return Op1;
630 // Otherwise return "L op' R" if it simplifies.
631 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
632 return V;
633 // Otherwise, create a new instruction.
634 A = Builder->CreateBinOp(InnerOpcode, L, R);
635 A->takeName(&I);
636 return A;
637 }
638 }
640 return nullptr;
641 }
643 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
644 // if the LHS is a constant zero (which is the 'negate' form).
645 //
646 Value *InstCombiner::dyn_castNegVal(Value *V) const {
647 if (BinaryOperator::isNeg(V))
648 return BinaryOperator::getNegArgument(V);
650 // Constants can be considered to be negated values if they can be folded.
651 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
652 return ConstantExpr::getNeg(C);
654 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
655 if (C->getType()->getElementType()->isIntegerTy())
656 return ConstantExpr::getNeg(C);
658 return nullptr;
659 }
661 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
662 // instruction if the LHS is a constant negative zero (which is the 'negate'
663 // form).
664 //
665 Value *InstCombiner::dyn_castFNegVal(Value *V, bool IgnoreZeroSign) const {
666 if (BinaryOperator::isFNeg(V, IgnoreZeroSign))
667 return BinaryOperator::getFNegArgument(V);
669 // Constants can be considered to be negated values if they can be folded.
670 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
671 return ConstantExpr::getFNeg(C);
673 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
674 if (C->getType()->getElementType()->isFloatingPointTy())
675 return ConstantExpr::getFNeg(C);
677 return nullptr;
678 }
680 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
681 InstCombiner *IC) {
682 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
683 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
684 }
686 // Figure out if the constant is the left or the right argument.
687 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
688 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
690 if (Constant *SOC = dyn_cast<Constant>(SO)) {
691 if (ConstIsRHS)
692 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
693 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
694 }
696 Value *Op0 = SO, *Op1 = ConstOperand;
697 if (!ConstIsRHS)
698 std::swap(Op0, Op1);
700 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) {
701 Value *RI = IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
702 SO->getName()+".op");
703 Instruction *FPInst = dyn_cast<Instruction>(RI);
704 if (FPInst && isa<FPMathOperator>(FPInst))
705 FPInst->copyFastMathFlags(BO);
706 return RI;
707 }
708 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
709 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
710 SO->getName()+".cmp");
711 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
712 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
713 SO->getName()+".cmp");
714 llvm_unreachable("Unknown binary instruction type!");
715 }
717 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
718 // constant as the other operand, try to fold the binary operator into the
719 // select arguments. This also works for Cast instructions, which obviously do
720 // not have a second operand.
721 Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
722 // Don't modify shared select instructions
723 if (!SI->hasOneUse()) return nullptr;
724 Value *TV = SI->getOperand(1);
725 Value *FV = SI->getOperand(2);
727 if (isa<Constant>(TV) || isa<Constant>(FV)) {
728 // Bool selects with constant operands can be folded to logical ops.
729 if (SI->getType()->isIntegerTy(1)) return nullptr;
731 // If it's a bitcast involving vectors, make sure it has the same number of
732 // elements on both sides.
733 if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
734 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
735 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
737 // Verify that either both or neither are vectors.
738 if ((SrcTy == nullptr) != (DestTy == nullptr)) return nullptr;
739 // If vectors, verify that they have the same number of elements.
740 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
741 return nullptr;
742 }
744 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
745 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
747 return SelectInst::Create(SI->getCondition(),
748 SelectTrueVal, SelectFalseVal);
749 }
750 return nullptr;
751 }
754 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
755 /// has a PHI node as operand #0, see if we can fold the instruction into the
756 /// PHI (which is only possible if all operands to the PHI are constants).
757 ///
758 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
759 PHINode *PN = cast<PHINode>(I.getOperand(0));
760 unsigned NumPHIValues = PN->getNumIncomingValues();
761 if (NumPHIValues == 0)
762 return nullptr;
764 // We normally only transform phis with a single use. However, if a PHI has
765 // multiple uses and they are all the same operation, we can fold *all* of the
766 // uses into the PHI.
767 if (!PN->hasOneUse()) {
768 // Walk the use list for the instruction, comparing them to I.
769 for (User *U : PN->users()) {
770 Instruction *UI = cast<Instruction>(U);
771 if (UI != &I && !I.isIdenticalTo(UI))
772 return nullptr;
773 }
774 // Otherwise, we can replace *all* users with the new PHI we form.
775 }
777 // Check to see if all of the operands of the PHI are simple constants
778 // (constantint/constantfp/undef). If there is one non-constant value,
779 // remember the BB it is in. If there is more than one or if *it* is a PHI,
780 // bail out. We don't do arbitrary constant expressions here because moving
781 // their computation can be expensive without a cost model.
782 BasicBlock *NonConstBB = nullptr;
783 for (unsigned i = 0; i != NumPHIValues; ++i) {
784 Value *InVal = PN->getIncomingValue(i);
785 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
786 continue;
788 if (isa<PHINode>(InVal)) return nullptr; // Itself a phi.
789 if (NonConstBB) return nullptr; // More than one non-const value.
791 NonConstBB = PN->getIncomingBlock(i);
793 // If the InVal is an invoke at the end of the pred block, then we can't
794 // insert a computation after it without breaking the edge.
795 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
796 if (II->getParent() == NonConstBB)
797 return nullptr;
799 // If the incoming non-constant value is in I's block, we will remove one
800 // instruction, but insert another equivalent one, leading to infinite
801 // instcombine.
802 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
803 if (isPotentiallyReachable(I.getParent(), NonConstBB, DT,
804 LIWP ? &LIWP->getLoopInfo() : nullptr))
805 return nullptr;
806 }
808 // If there is exactly one non-constant value, we can insert a copy of the
809 // operation in that block. However, if this is a critical edge, we would be
810 // inserting the computation on some other paths (e.g. inside a loop). Only
811 // do this if the pred block is unconditionally branching into the phi block.
812 if (NonConstBB != nullptr) {
813 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
814 if (!BI || !BI->isUnconditional()) return nullptr;
815 }
817 // Okay, we can do the transformation: create the new PHI node.
818 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
819 InsertNewInstBefore(NewPN, *PN);
820 NewPN->takeName(PN);
822 // If we are going to have to insert a new computation, do so right before the
823 // predecessors terminator.
824 if (NonConstBB)
825 Builder->SetInsertPoint(NonConstBB->getTerminator());
827 // Next, add all of the operands to the PHI.
828 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
829 // We only currently try to fold the condition of a select when it is a phi,
830 // not the true/false values.
831 Value *TrueV = SI->getTrueValue();
832 Value *FalseV = SI->getFalseValue();
833 BasicBlock *PhiTransBB = PN->getParent();
834 for (unsigned i = 0; i != NumPHIValues; ++i) {
835 BasicBlock *ThisBB = PN->getIncomingBlock(i);
836 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
837 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
838 Value *InV = nullptr;
839 // Beware of ConstantExpr: it may eventually evaluate to getNullValue,
840 // even if currently isNullValue gives false.
841 Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i));
842 if (InC && !isa<ConstantExpr>(InC))
843 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
844 else
845 InV = Builder->CreateSelect(PN->getIncomingValue(i),
846 TrueVInPred, FalseVInPred, "phitmp");
847 NewPN->addIncoming(InV, ThisBB);
848 }
849 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
850 Constant *C = cast<Constant>(I.getOperand(1));
851 for (unsigned i = 0; i != NumPHIValues; ++i) {
852 Value *InV = nullptr;
853 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
854 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
855 else if (isa<ICmpInst>(CI))
856 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
857 C, "phitmp");
858 else
859 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
860 C, "phitmp");
861 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
862 }
863 } else if (I.getNumOperands() == 2) {
864 Constant *C = cast<Constant>(I.getOperand(1));
865 for (unsigned i = 0; i != NumPHIValues; ++i) {
866 Value *InV = nullptr;
867 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
868 InV = ConstantExpr::get(I.getOpcode(), InC, C);
869 else
870 InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
871 PN->getIncomingValue(i), C, "phitmp");
872 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
873 }
874 } else {
875 CastInst *CI = cast<CastInst>(&I);
876 Type *RetTy = CI->getType();
877 for (unsigned i = 0; i != NumPHIValues; ++i) {
878 Value *InV;
879 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
880 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
881 else
882 InV = Builder->CreateCast(CI->getOpcode(),
883 PN->getIncomingValue(i), I.getType(), "phitmp");
884 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
885 }
886 }
888 for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
889 Instruction *User = cast<Instruction>(*UI++);
890 if (User == &I) continue;
891 ReplaceInstUsesWith(*User, NewPN);
892 EraseInstFromFunction(*User);
893 }
894 return ReplaceInstUsesWith(I, NewPN);
895 }
897 /// FindElementAtOffset - Given a pointer type and a constant offset, determine
898 /// whether or not there is a sequence of GEP indices into the pointed type that
899 /// will land us at the specified offset. If so, fill them into NewIndices and
900 /// return the resultant element type, otherwise return null.
901 Type *InstCombiner::FindElementAtOffset(Type *PtrTy, int64_t Offset,
902 SmallVectorImpl<Value*> &NewIndices) {
903 assert(PtrTy->isPtrOrPtrVectorTy());
905 if (!DL)
906 return nullptr;
908 Type *Ty = PtrTy->getPointerElementType();
909 if (!Ty->isSized())
910 return nullptr;
912 // Start with the index over the outer type. Note that the type size
913 // might be zero (even if the offset isn't zero) if the indexed type
914 // is something like [0 x {int, int}]
915 Type *IntPtrTy = DL->getIntPtrType(PtrTy);
916 int64_t FirstIdx = 0;
917 if (int64_t TySize = DL->getTypeAllocSize(Ty)) {
918 FirstIdx = Offset/TySize;
919 Offset -= FirstIdx*TySize;
921 // Handle hosts where % returns negative instead of values [0..TySize).
922 if (Offset < 0) {
923 --FirstIdx;
924 Offset += TySize;
925 assert(Offset >= 0);
926 }
927 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
928 }
930 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
932 // Index into the types. If we fail, set OrigBase to null.
933 while (Offset) {
934 // Indexing into tail padding between struct/array elements.
935 if (uint64_t(Offset*8) >= DL->getTypeSizeInBits(Ty))
936 return nullptr;
938 if (StructType *STy = dyn_cast<StructType>(Ty)) {
939 const StructLayout *SL = DL->getStructLayout(STy);
940 assert(Offset < (int64_t)SL->getSizeInBytes() &&
941 "Offset must stay within the indexed type");
943 unsigned Elt = SL->getElementContainingOffset(Offset);
944 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
945 Elt));
947 Offset -= SL->getElementOffset(Elt);
948 Ty = STy->getElementType(Elt);
949 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
950 uint64_t EltSize = DL->getTypeAllocSize(AT->getElementType());
951 assert(EltSize && "Cannot index into a zero-sized array");
952 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
953 Offset %= EltSize;
954 Ty = AT->getElementType();
955 } else {
956 // Otherwise, we can't index into the middle of this atomic type, bail.
957 return nullptr;
958 }
959 }
961 return Ty;
962 }
964 static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
965 // If this GEP has only 0 indices, it is the same pointer as
966 // Src. If Src is not a trivial GEP too, don't combine
967 // the indices.
968 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
969 !Src.hasOneUse())
970 return false;
971 return true;
972 }
974 /// Descale - Return a value X such that Val = X * Scale, or null if none. If
975 /// the multiplication is known not to overflow then NoSignedWrap is set.
976 Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
977 assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
978 assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
979 Scale.getBitWidth() && "Scale not compatible with value!");
981 // If Val is zero or Scale is one then Val = Val * Scale.
982 if (match(Val, m_Zero()) || Scale == 1) {
983 NoSignedWrap = true;
984 return Val;
985 }
987 // If Scale is zero then it does not divide Val.
988 if (Scale.isMinValue())
989 return nullptr;
991 // Look through chains of multiplications, searching for a constant that is
992 // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4
993 // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by
994 // a factor of 4 will produce X*(Y*2). The principle of operation is to bore
995 // down from Val:
996 //
997 // Val = M1 * X || Analysis starts here and works down
998 // M1 = M2 * Y || Doesn't descend into terms with more
999 // M2 = Z * 4 \/ than one use
1000 //
1001 // Then to modify a term at the bottom:
1002 //
1003 // Val = M1 * X
1004 // M1 = Z * Y || Replaced M2 with Z
1005 //
1006 // Then to work back up correcting nsw flags.
1008 // Op - the term we are currently analyzing. Starts at Val then drills down.
1009 // Replaced with its descaled value before exiting from the drill down loop.
1010 Value *Op = Val;
1012 // Parent - initially null, but after drilling down notes where Op came from.
1013 // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
1014 // 0'th operand of Val.
1015 std::pair<Instruction*, unsigned> Parent;
1017 // RequireNoSignedWrap - Set if the transform requires a descaling at deeper
1018 // levels that doesn't overflow.
1019 bool RequireNoSignedWrap = false;
1021 // logScale - log base 2 of the scale. Negative if not a power of 2.
1022 int32_t logScale = Scale.exactLogBase2();
1024 for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
1026 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1027 // If Op is a constant divisible by Scale then descale to the quotient.
1028 APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
1029 APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
1030 if (!Remainder.isMinValue())
1031 // Not divisible by Scale.
1032 return nullptr;
1033 // Replace with the quotient in the parent.
1034 Op = ConstantInt::get(CI->getType(), Quotient);
1035 NoSignedWrap = true;
1036 break;
1037 }
1039 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
1041 if (BO->getOpcode() == Instruction::Mul) {
1042 // Multiplication.
1043 NoSignedWrap = BO->hasNoSignedWrap();
1044 if (RequireNoSignedWrap && !NoSignedWrap)
1045 return nullptr;
1047 // There are three cases for multiplication: multiplication by exactly
1048 // the scale, multiplication by a constant different to the scale, and
1049 // multiplication by something else.
1050 Value *LHS = BO->getOperand(0);
1051 Value *RHS = BO->getOperand(1);
1053 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1054 // Multiplication by a constant.
1055 if (CI->getValue() == Scale) {
1056 // Multiplication by exactly the scale, replace the multiplication
1057 // by its left-hand side in the parent.
1058 Op = LHS;
1059 break;
1060 }
1062 // Otherwise drill down into the constant.
1063 if (!Op->hasOneUse())
1064 return nullptr;
1066 Parent = std::make_pair(BO, 1);
1067 continue;
1068 }
1070 // Multiplication by something else. Drill down into the left-hand side
1071 // since that's where the reassociate pass puts the good stuff.
1072 if (!Op->hasOneUse())
1073 return nullptr;
1075 Parent = std::make_pair(BO, 0);
1076 continue;
1077 }
1079 if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
1080 isa<ConstantInt>(BO->getOperand(1))) {
1081 // Multiplication by a power of 2.
1082 NoSignedWrap = BO->hasNoSignedWrap();
1083 if (RequireNoSignedWrap && !NoSignedWrap)
1084 return nullptr;
1086 Value *LHS = BO->getOperand(0);
1087 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
1088 getLimitedValue(Scale.getBitWidth());
1089 // Op = LHS << Amt.
1091 if (Amt == logScale) {
1092 // Multiplication by exactly the scale, replace the multiplication
1093 // by its left-hand side in the parent.
1094 Op = LHS;
1095 break;
1096 }
1097 if (Amt < logScale || !Op->hasOneUse())
1098 return nullptr;
1100 // Multiplication by more than the scale. Reduce the multiplying amount
1101 // by the scale in the parent.
1102 Parent = std::make_pair(BO, 1);
1103 Op = ConstantInt::get(BO->getType(), Amt - logScale);
1104 break;
1105 }
1106 }
1108 if (!Op->hasOneUse())
1109 return nullptr;
1111 if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
1112 if (Cast->getOpcode() == Instruction::SExt) {
1113 // Op is sign-extended from a smaller type, descale in the smaller type.
1114 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1115 APInt SmallScale = Scale.trunc(SmallSize);
1116 // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to
1117 // descale Op as (sext Y) * Scale. In order to have
1118 // sext (Y * SmallScale) = (sext Y) * Scale
1119 // some conditions need to hold however: SmallScale must sign-extend to
1120 // Scale and the multiplication Y * SmallScale should not overflow.
1121 if (SmallScale.sext(Scale.getBitWidth()) != Scale)
1122 // SmallScale does not sign-extend to Scale.
1123 return nullptr;
1124 assert(SmallScale.exactLogBase2() == logScale);
1125 // Require that Y * SmallScale must not overflow.
1126 RequireNoSignedWrap = true;
1128 // Drill down through the cast.
1129 Parent = std::make_pair(Cast, 0);
1130 Scale = SmallScale;
1131 continue;
1132 }
1134 if (Cast->getOpcode() == Instruction::Trunc) {
1135 // Op is truncated from a larger type, descale in the larger type.
1136 // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then
1137 // trunc (Y * sext Scale) = (trunc Y) * Scale
1138 // always holds. However (trunc Y) * Scale may overflow even if
1139 // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
1140 // from this point up in the expression (see later).
1141 if (RequireNoSignedWrap)
1142 return nullptr;
1144 // Drill down through the cast.
1145 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1146 Parent = std::make_pair(Cast, 0);
1147 Scale = Scale.sext(LargeSize);
1148 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1149 logScale = -1;
1150 assert(Scale.exactLogBase2() == logScale);
1151 continue;
1152 }
1153 }
1155 // Unsupported expression, bail out.
1156 return nullptr;
1157 }
1159 // If Op is zero then Val = Op * Scale.
1160 if (match(Op, m_Zero())) {
1161 NoSignedWrap = true;
1162 return Op;
1163 }
1165 // We know that we can successfully descale, so from here on we can safely
1166 // modify the IR. Op holds the descaled version of the deepest term in the
1167 // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known
1168 // not to overflow.
1170 if (!Parent.first)
1171 // The expression only had one term.
1172 return Op;
1174 // Rewrite the parent using the descaled version of its operand.
1175 assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
1176 assert(Op != Parent.first->getOperand(Parent.second) &&
1177 "Descaling was a no-op?");
1178 Parent.first->setOperand(Parent.second, Op);
1179 Worklist.Add(Parent.first);
1181 // Now work back up the expression correcting nsw flags. The logic is based
1182 // on the following observation: if X * Y is known not to overflow as a signed
1183 // multiplication, and Y is replaced by a value Z with smaller absolute value,
1184 // then X * Z will not overflow as a signed multiplication either. As we work
1185 // our way up, having NoSignedWrap 'true' means that the descaled value at the
1186 // current level has strictly smaller absolute value than the original.
1187 Instruction *Ancestor = Parent.first;
1188 do {
1189 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
1190 // If the multiplication wasn't nsw then we can't say anything about the
1191 // value of the descaled multiplication, and we have to clear nsw flags
1192 // from this point on up.
1193 bool OpNoSignedWrap = BO->hasNoSignedWrap();
1194 NoSignedWrap &= OpNoSignedWrap;
1195 if (NoSignedWrap != OpNoSignedWrap) {
1196 BO->setHasNoSignedWrap(NoSignedWrap);
1197 Worklist.Add(Ancestor);
1198 }
1199 } else if (Ancestor->getOpcode() == Instruction::Trunc) {
1200 // The fact that the descaled input to the trunc has smaller absolute
1201 // value than the original input doesn't tell us anything useful about
1202 // the absolute values of the truncations.
1203 NoSignedWrap = false;
1204 }
1205 assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
1206 "Failed to keep proper track of nsw flags while drilling down?");
1208 if (Ancestor == Val)
1209 // Got to the top, all done!
1210 return Val;
1212 // Move up one level in the expression.
1213 assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
1214 Ancestor = Ancestor->user_back();
1215 } while (1);
1216 }
1218 /// \brief Creates node of binary operation with the same attributes as the
1219 /// specified one but with other operands.
1220 static Value *CreateBinOpAsGiven(BinaryOperator &Inst, Value *LHS, Value *RHS,
1221 InstCombiner::BuilderTy *B) {
1222 Value *BORes = B->CreateBinOp(Inst.getOpcode(), LHS, RHS);
1223 if (BinaryOperator *NewBO = dyn_cast<BinaryOperator>(BORes)) {
1224 if (isa<OverflowingBinaryOperator>(NewBO)) {
1225 NewBO->setHasNoSignedWrap(Inst.hasNoSignedWrap());
1226 NewBO->setHasNoUnsignedWrap(Inst.hasNoUnsignedWrap());
1227 }
1228 if (isa<PossiblyExactOperator>(NewBO))
1229 NewBO->setIsExact(Inst.isExact());
1230 }
1231 return BORes;
1232 }
1234 /// \brief Makes transformation of binary operation specific for vector types.
1235 /// \param Inst Binary operator to transform.
1236 /// \return Pointer to node that must replace the original binary operator, or
1237 /// null pointer if no transformation was made.
1238 Value *InstCombiner::SimplifyVectorOp(BinaryOperator &Inst) {
1239 if (!Inst.getType()->isVectorTy()) return nullptr;
1241 // It may not be safe to reorder shuffles and things like div, urem, etc.
1242 // because we may trap when executing those ops on unknown vector elements.
1243 // See PR20059.
1244 if (!isSafeToSpeculativelyExecute(&Inst, DL)) return nullptr;
1246 unsigned VWidth = cast<VectorType>(Inst.getType())->getNumElements();
1247 Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
1248 assert(cast<VectorType>(LHS->getType())->getNumElements() == VWidth);
1249 assert(cast<VectorType>(RHS->getType())->getNumElements() == VWidth);
1251 // If both arguments of binary operation are shuffles, which use the same
1252 // mask and shuffle within a single vector, it is worthwhile to move the
1253 // shuffle after binary operation:
1254 // Op(shuffle(v1, m), shuffle(v2, m)) -> shuffle(Op(v1, v2), m)
1255 if (isa<ShuffleVectorInst>(LHS) && isa<ShuffleVectorInst>(RHS)) {
1256 ShuffleVectorInst *LShuf = cast<ShuffleVectorInst>(LHS);
1257 ShuffleVectorInst *RShuf = cast<ShuffleVectorInst>(RHS);
1258 if (isa<UndefValue>(LShuf->getOperand(1)) &&
1259 isa<UndefValue>(RShuf->getOperand(1)) &&
1260 LShuf->getOperand(0)->getType() == RShuf->getOperand(0)->getType() &&
1261 LShuf->getMask() == RShuf->getMask()) {
1262 Value *NewBO = CreateBinOpAsGiven(Inst, LShuf->getOperand(0),
1263 RShuf->getOperand(0), Builder);
1264 Value *Res = Builder->CreateShuffleVector(NewBO,
1265 UndefValue::get(NewBO->getType()), LShuf->getMask());
1266 return Res;
1267 }
1268 }
1270 // If one argument is a shuffle within one vector, the other is a constant,
1271 // try moving the shuffle after the binary operation.
1272 ShuffleVectorInst *Shuffle = nullptr;
1273 Constant *C1 = nullptr;
1274 if (isa<ShuffleVectorInst>(LHS)) Shuffle = cast<ShuffleVectorInst>(LHS);
1275 if (isa<ShuffleVectorInst>(RHS)) Shuffle = cast<ShuffleVectorInst>(RHS);
1276 if (isa<Constant>(LHS)) C1 = cast<Constant>(LHS);
1277 if (isa<Constant>(RHS)) C1 = cast<Constant>(RHS);
1278 if (Shuffle && C1 &&
1279 (isa<ConstantVector>(C1) || isa<ConstantDataVector>(C1)) &&
1280 isa<UndefValue>(Shuffle->getOperand(1)) &&
1281 Shuffle->getType() == Shuffle->getOperand(0)->getType()) {
1282 SmallVector<int, 16> ShMask = Shuffle->getShuffleMask();
1283 // Find constant C2 that has property:
1284 // shuffle(C2, ShMask) = C1
1285 // If such constant does not exist (example: ShMask=<0,0> and C1=<1,2>)
1286 // reorder is not possible.
1287 SmallVector<Constant*, 16> C2M(VWidth,
1288 UndefValue::get(C1->getType()->getScalarType()));
1289 bool MayChange = true;
1290 for (unsigned I = 0; I < VWidth; ++I) {
1291 if (ShMask[I] >= 0) {
1292 assert(ShMask[I] < (int)VWidth);
1293 if (!isa<UndefValue>(C2M[ShMask[I]])) {
1294 MayChange = false;
1295 break;
1296 }
1297 C2M[ShMask[I]] = C1->getAggregateElement(I);
1298 }
1299 }
1300 if (MayChange) {
1301 Constant *C2 = ConstantVector::get(C2M);
1302 Value *NewLHS, *NewRHS;
1303 if (isa<Constant>(LHS)) {
1304 NewLHS = C2;
1305 NewRHS = Shuffle->getOperand(0);
1306 } else {
1307 NewLHS = Shuffle->getOperand(0);
1308 NewRHS = C2;
1309 }
1310 Value *NewBO = CreateBinOpAsGiven(Inst, NewLHS, NewRHS, Builder);
1311 Value *Res = Builder->CreateShuffleVector(NewBO,
1312 UndefValue::get(Inst.getType()), Shuffle->getMask());
1313 return Res;
1314 }
1315 }
1317 return nullptr;
1318 }
1320 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1321 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
1323 if (Value *V = SimplifyGEPInst(Ops, DL, TLI, DT, AC))
1324 return ReplaceInstUsesWith(GEP, V);
1326 Value *PtrOp = GEP.getOperand(0);
1328 // Eliminate unneeded casts for indices, and replace indices which displace
1329 // by multiples of a zero size type with zero.
1330 if (DL) {
1331 bool MadeChange = false;
1332 Type *IntPtrTy = DL->getIntPtrType(GEP.getPointerOperandType());
1334 gep_type_iterator GTI = gep_type_begin(GEP);
1335 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
1336 I != E; ++I, ++GTI) {
1337 // Skip indices into struct types.
1338 SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
1339 if (!SeqTy) continue;
1341 // If the element type has zero size then any index over it is equivalent
1342 // to an index of zero, so replace it with zero if it is not zero already.
1343 if (SeqTy->getElementType()->isSized() &&
1344 DL->getTypeAllocSize(SeqTy->getElementType()) == 0)
1345 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
1346 *I = Constant::getNullValue(IntPtrTy);
1347 MadeChange = true;
1348 }
1350 Type *IndexTy = (*I)->getType();
1351 if (IndexTy != IntPtrTy) {
1352 // If we are using a wider index than needed for this platform, shrink
1353 // it to what we need. If narrower, sign-extend it to what we need.
1354 // This explicit cast can make subsequent optimizations more obvious.
1355 *I = Builder->CreateIntCast(*I, IntPtrTy, true);
1356 MadeChange = true;
1357 }
1358 }
1359 if (MadeChange) return &GEP;
1360 }
1362 // Check to see if the inputs to the PHI node are getelementptr instructions.
1363 if (PHINode *PN = dyn_cast<PHINode>(PtrOp)) {
1364 GetElementPtrInst *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
1365 if (!Op1)
1366 return nullptr;
1368 signed DI = -1;
1370 for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
1371 GetElementPtrInst *Op2 = dyn_cast<GetElementPtrInst>(*I);
1372 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
1373 return nullptr;
1375 // Keep track of the type as we walk the GEP.
1376 Type *CurTy = Op1->getOperand(0)->getType()->getScalarType();
1378 for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
1379 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
1380 return nullptr;
1382 if (Op1->getOperand(J) != Op2->getOperand(J)) {
1383 if (DI == -1) {
1384 // We have not seen any differences yet in the GEPs feeding the
1385 // PHI yet, so we record this one if it is allowed to be a
1386 // variable.
1388 // The first two arguments can vary for any GEP, the rest have to be
1389 // static for struct slots
1390 if (J > 1 && CurTy->isStructTy())
1391 return nullptr;
1393 DI = J;
1394 } else {
1395 // The GEP is different by more than one input. While this could be
1396 // extended to support GEPs that vary by more than one variable it
1397 // doesn't make sense since it greatly increases the complexity and
1398 // would result in an R+R+R addressing mode which no backend
1399 // directly supports and would need to be broken into several
1400 // simpler instructions anyway.
1401 return nullptr;
1402 }
1403 }
1405 // Sink down a layer of the type for the next iteration.
1406 if (J > 0) {
1407 if (CompositeType *CT = dyn_cast<CompositeType>(CurTy)) {
1408 CurTy = CT->getTypeAtIndex(Op1->getOperand(J));
1409 } else {
1410 CurTy = nullptr;
1411 }
1412 }
1413 }
1414 }
1416 GetElementPtrInst *NewGEP = cast<GetElementPtrInst>(Op1->clone());
1418 if (DI == -1) {
1419 // All the GEPs feeding the PHI are identical. Clone one down into our
1420 // BB so that it can be merged with the current GEP.
1421 GEP.getParent()->getInstList().insert(GEP.getParent()->getFirstNonPHI(),
1422 NewGEP);
1423 } else {
1424 // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
1425 // into the current block so it can be merged, and create a new PHI to
1426 // set that index.
1427 Instruction *InsertPt = Builder->GetInsertPoint();
1428 Builder->SetInsertPoint(PN);
1429 PHINode *NewPN = Builder->CreatePHI(Op1->getOperand(DI)->getType(),
1430 PN->getNumOperands());
1431 Builder->SetInsertPoint(InsertPt);
1433 for (auto &I : PN->operands())
1434 NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1435 PN->getIncomingBlock(I));
1437 NewGEP->setOperand(DI, NewPN);
1438 GEP.getParent()->getInstList().insert(GEP.getParent()->getFirstNonPHI(),
1439 NewGEP);
1440 NewGEP->setOperand(DI, NewPN);
1441 }
1443 GEP.setOperand(0, NewGEP);
1444 PtrOp = NewGEP;
1445 }
1447 // Combine Indices - If the source pointer to this getelementptr instruction
1448 // is a getelementptr instruction, combine the indices of the two
1449 // getelementptr instructions into a single instruction.
1450 //
1451 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
1452 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
1453 return nullptr;
1455 // Note that if our source is a gep chain itself then we wait for that
1456 // chain to be resolved before we perform this transformation. This
1457 // avoids us creating a TON of code in some cases.
1458 if (GEPOperator *SrcGEP =
1459 dyn_cast<GEPOperator>(Src->getOperand(0)))
1460 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
1461 return nullptr; // Wait until our source is folded to completion.
1463 SmallVector<Value*, 8> Indices;
1465 // Find out whether the last index in the source GEP is a sequential idx.
1466 bool EndsWithSequential = false;
1467 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
1468 I != E; ++I)
1469 EndsWithSequential = !(*I)->isStructTy();
1471 // Can we combine the two pointer arithmetics offsets?
1472 if (EndsWithSequential) {
1473 // Replace: gep (gep %P, long B), long A, ...
1474 // With: T = long A+B; gep %P, T, ...
1475 //
1476 Value *Sum;
1477 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1478 Value *GO1 = GEP.getOperand(1);
1479 if (SO1 == Constant::getNullValue(SO1->getType())) {
1480 Sum = GO1;
1481 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
1482 Sum = SO1;
1483 } else {
1484 // If they aren't the same type, then the input hasn't been processed
1485 // by the loop above yet (which canonicalizes sequential index types to
1486 // intptr_t). Just avoid transforming this until the input has been
1487 // normalized.
1488 if (SO1->getType() != GO1->getType())
1489 return nullptr;
1490 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
1491 }
1493 // Update the GEP in place if possible.
1494 if (Src->getNumOperands() == 2) {
1495 GEP.setOperand(0, Src->getOperand(0));
1496 GEP.setOperand(1, Sum);
1497 return &GEP;
1498 }
1499 Indices.append(Src->op_begin()+1, Src->op_end()-1);
1500 Indices.push_back(Sum);
1501 Indices.append(GEP.op_begin()+2, GEP.op_end());
1502 } else if (isa<Constant>(*GEP.idx_begin()) &&
1503 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
1504 Src->getNumOperands() != 1) {
1505 // Otherwise we can do the fold if the first index of the GEP is a zero
1506 Indices.append(Src->op_begin()+1, Src->op_end());
1507 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
1508 }
1510 if (!Indices.empty())
1511 return (GEP.isInBounds() && Src->isInBounds()) ?
1512 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices,
1513 GEP.getName()) :
1514 GetElementPtrInst::Create(Src->getOperand(0), Indices, GEP.getName());
1515 }
1517 if (DL && GEP.getNumIndices() == 1) {
1518 unsigned AS = GEP.getPointerAddressSpace();
1519 if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
1520 DL->getPointerSizeInBits(AS)) {
1521 Type *PtrTy = GEP.getPointerOperandType();
1522 Type *Ty = PtrTy->getPointerElementType();
1523 uint64_t TyAllocSize = DL->getTypeAllocSize(Ty);
1525 bool Matched = false;
1526 uint64_t C;
1527 Value *V = nullptr;
1528 if (TyAllocSize == 1) {
1529 V = GEP.getOperand(1);
1530 Matched = true;
1531 } else if (match(GEP.getOperand(1),
1532 m_AShr(m_Value(V), m_ConstantInt(C)))) {
1533 if (TyAllocSize == 1ULL << C)
1534 Matched = true;
1535 } else if (match(GEP.getOperand(1),
1536 m_SDiv(m_Value(V), m_ConstantInt(C)))) {
1537 if (TyAllocSize == C)
1538 Matched = true;
1539 }
1541 if (Matched) {
1542 // Canonicalize (gep i8* X, -(ptrtoint Y))
1543 // to (inttoptr (sub (ptrtoint X), (ptrtoint Y)))
1544 // The GEP pattern is emitted by the SCEV expander for certain kinds of
1545 // pointer arithmetic.
1546 if (match(V, m_Neg(m_PtrToInt(m_Value())))) {
1547 Operator *Index = cast<Operator>(V);
1548 Value *PtrToInt = Builder->CreatePtrToInt(PtrOp, Index->getType());
1549 Value *NewSub = Builder->CreateSub(PtrToInt, Index->getOperand(1));
1550 return CastInst::Create(Instruction::IntToPtr, NewSub, GEP.getType());
1551 }
1552 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X))
1553 // to (bitcast Y)
1554 Value *Y;
1555 if (match(V, m_Sub(m_PtrToInt(m_Value(Y)),
1556 m_PtrToInt(m_Specific(GEP.getOperand(0)))))) {
1557 return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y,
1558 GEP.getType());
1559 }
1560 }
1561 }
1562 }
1564 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
1565 Value *StrippedPtr = PtrOp->stripPointerCasts();
1566 PointerType *StrippedPtrTy = dyn_cast<PointerType>(StrippedPtr->getType());
1568 // We do not handle pointer-vector geps here.
1569 if (!StrippedPtrTy)
1570 return nullptr;
1572 if (StrippedPtr != PtrOp) {
1573 bool HasZeroPointerIndex = false;
1574 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
1575 HasZeroPointerIndex = C->isZero();
1577 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
1578 // into : GEP [10 x i8]* X, i32 0, ...
1579 //
1580 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
1581 // into : GEP i8* X, ...
1582 //
1583 // This occurs when the program declares an array extern like "int X[];"
1584 if (HasZeroPointerIndex) {
1585 PointerType *CPTy = cast<PointerType>(PtrOp->getType());
1586 if (ArrayType *CATy =
1587 dyn_cast<ArrayType>(CPTy->getElementType())) {
1588 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
1589 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
1590 // -> GEP i8* X, ...
1591 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
1592 GetElementPtrInst *Res =
1593 GetElementPtrInst::Create(StrippedPtr, Idx, GEP.getName());
1594 Res->setIsInBounds(GEP.isInBounds());
1595 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
1596 return Res;
1597 // Insert Res, and create an addrspacecast.
1598 // e.g.,
1599 // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
1600 // ->
1601 // %0 = GEP i8 addrspace(1)* X, ...
1602 // addrspacecast i8 addrspace(1)* %0 to i8*
1603 return new AddrSpaceCastInst(Builder->Insert(Res), GEP.getType());
1604 }
1606 if (ArrayType *XATy =
1607 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
1608 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
1609 if (CATy->getElementType() == XATy->getElementType()) {
1610 // -> GEP [10 x i8]* X, i32 0, ...
1611 // At this point, we know that the cast source type is a pointer
1612 // to an array of the same type as the destination pointer
1613 // array. Because the array type is never stepped over (there
1614 // is a leading zero) we can fold the cast into this GEP.
1615 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
1616 GEP.setOperand(0, StrippedPtr);
1617 return &GEP;
1618 }
1619 // Cannot replace the base pointer directly because StrippedPtr's
1620 // address space is different. Instead, create a new GEP followed by
1621 // an addrspacecast.
1622 // e.g.,
1623 // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
1624 // i32 0, ...
1625 // ->
1626 // %0 = GEP [10 x i8] addrspace(1)* X, ...
1627 // addrspacecast i8 addrspace(1)* %0 to i8*
1628 SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
1629 Value *NewGEP = GEP.isInBounds() ?
1630 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()) :
1631 Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
1632 return new AddrSpaceCastInst(NewGEP, GEP.getType());
1633 }
1634 }
1635 }
1636 } else if (GEP.getNumOperands() == 2) {
1637 // Transform things like:
1638 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
1639 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
1640 Type *SrcElTy = StrippedPtrTy->getElementType();
1641 Type *ResElTy = PtrOp->getType()->getPointerElementType();
1642 if (DL && SrcElTy->isArrayTy() &&
1643 DL->getTypeAllocSize(SrcElTy->getArrayElementType()) ==
1644 DL->getTypeAllocSize(ResElTy)) {
1645 Type *IdxType = DL->getIntPtrType(GEP.getType());
1646 Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
1647 Value *NewGEP = GEP.isInBounds() ?
1648 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()) :
1649 Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
1651 // V and GEP are both pointer types --> BitCast
1652 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1653 GEP.getType());
1654 }
1656 // Transform things like:
1657 // %V = mul i64 %N, 4
1658 // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
1659 // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast
1660 if (DL && ResElTy->isSized() && SrcElTy->isSized()) {
1661 // Check that changing the type amounts to dividing the index by a scale
1662 // factor.
1663 uint64_t ResSize = DL->getTypeAllocSize(ResElTy);
1664 uint64_t SrcSize = DL->getTypeAllocSize(SrcElTy);
1665 if (ResSize && SrcSize % ResSize == 0) {
1666 Value *Idx = GEP.getOperand(1);
1667 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1668 uint64_t Scale = SrcSize / ResSize;
1670 // Earlier transforms ensure that the index has type IntPtrType, which
1671 // considerably simplifies the logic by eliminating implicit casts.
1672 assert(Idx->getType() == DL->getIntPtrType(GEP.getType()) &&
1673 "Index not cast to pointer width?");
1675 bool NSW;
1676 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1677 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1678 // If the multiplication NewIdx * Scale may overflow then the new
1679 // GEP may not be "inbounds".
1680 Value *NewGEP = GEP.isInBounds() && NSW ?
1681 Builder->CreateInBoundsGEP(StrippedPtr, NewIdx, GEP.getName()) :
1682 Builder->CreateGEP(StrippedPtr, NewIdx, GEP.getName());
1684 // The NewGEP must be pointer typed, so must the old one -> BitCast
1685 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1686 GEP.getType());
1687 }
1688 }
1689 }
1691 // Similarly, transform things like:
1692 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
1693 // (where tmp = 8*tmp2) into:
1694 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
1695 if (DL && ResElTy->isSized() && SrcElTy->isSized() &&
1696 SrcElTy->isArrayTy()) {
1697 // Check that changing to the array element type amounts to dividing the
1698 // index by a scale factor.
1699 uint64_t ResSize = DL->getTypeAllocSize(ResElTy);
1700 uint64_t ArrayEltSize
1701 = DL->getTypeAllocSize(SrcElTy->getArrayElementType());
1702 if (ResSize && ArrayEltSize % ResSize == 0) {
1703 Value *Idx = GEP.getOperand(1);
1704 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1705 uint64_t Scale = ArrayEltSize / ResSize;
1707 // Earlier transforms ensure that the index has type IntPtrType, which
1708 // considerably simplifies the logic by eliminating implicit casts.
1709 assert(Idx->getType() == DL->getIntPtrType(GEP.getType()) &&
1710 "Index not cast to pointer width?");
1712 bool NSW;
1713 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1714 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1715 // If the multiplication NewIdx * Scale may overflow then the new
1716 // GEP may not be "inbounds".
1717 Value *Off[2] = {
1718 Constant::getNullValue(DL->getIntPtrType(GEP.getType())),
1719 NewIdx
1720 };
1722 Value *NewGEP = GEP.isInBounds() && NSW ?
1723 Builder->CreateInBoundsGEP(StrippedPtr, Off, GEP.getName()) :
1724 Builder->CreateGEP(StrippedPtr, Off, GEP.getName());
1725 // The NewGEP must be pointer typed, so must the old one -> BitCast
1726 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1727 GEP.getType());
1728 }
1729 }
1730 }
1731 }
1732 }
1734 if (!DL)
1735 return nullptr;
1737 // addrspacecast between types is canonicalized as a bitcast, then an
1738 // addrspacecast. To take advantage of the below bitcast + struct GEP, look
1739 // through the addrspacecast.
1740 if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
1741 // X = bitcast A addrspace(1)* to B addrspace(1)*
1742 // Y = addrspacecast A addrspace(1)* to B addrspace(2)*
1743 // Z = gep Y, <...constant indices...>
1744 // Into an addrspacecasted GEP of the struct.
1745 if (BitCastInst *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
1746 PtrOp = BC;
1747 }
1749 /// See if we can simplify:
1750 /// X = bitcast A* to B*
1751 /// Y = gep X, <...constant indices...>
1752 /// into a gep of the original struct. This is important for SROA and alias
1753 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
1754 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
1755 Value *Operand = BCI->getOperand(0);
1756 PointerType *OpType = cast<PointerType>(Operand->getType());
1757 unsigned OffsetBits = DL->getPointerTypeSizeInBits(GEP.getType());
1758 APInt Offset(OffsetBits, 0);
1759 if (!isa<BitCastInst>(Operand) &&
1760 GEP.accumulateConstantOffset(*DL, Offset)) {
1762 // If this GEP instruction doesn't move the pointer, just replace the GEP
1763 // with a bitcast of the real input to the dest type.
1764 if (!Offset) {
1765 // If the bitcast is of an allocation, and the allocation will be
1766 // converted to match the type of the cast, don't touch this.
1767 if (isa<AllocaInst>(Operand) || isAllocationFn(Operand, TLI)) {
1768 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1769 if (Instruction *I = visitBitCast(*BCI)) {
1770 if (I != BCI) {
1771 I->takeName(BCI);
1772 BCI->getParent()->getInstList().insert(BCI, I);
1773 ReplaceInstUsesWith(*BCI, I);
1774 }
1775 return &GEP;
1776 }
1777 }
1779 if (Operand->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1780 return new AddrSpaceCastInst(Operand, GEP.getType());
1781 return new BitCastInst(Operand, GEP.getType());
1782 }
1784 // Otherwise, if the offset is non-zero, we need to find out if there is a
1785 // field at Offset in 'A's type. If so, we can pull the cast through the
1786 // GEP.
1787 SmallVector<Value*, 8> NewIndices;
1788 if (FindElementAtOffset(OpType, Offset.getSExtValue(), NewIndices)) {
1789 Value *NGEP = GEP.isInBounds() ?
1790 Builder->CreateInBoundsGEP(Operand, NewIndices) :
1791 Builder->CreateGEP(Operand, NewIndices);
1793 if (NGEP->getType() == GEP.getType())
1794 return ReplaceInstUsesWith(GEP, NGEP);
1795 NGEP->takeName(&GEP);
1797 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1798 return new AddrSpaceCastInst(NGEP, GEP.getType());
1799 return new BitCastInst(NGEP, GEP.getType());
1800 }
1801 }
1802 }
1804 return nullptr;
1805 }
1807 static bool
1808 isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users,
1809 const TargetLibraryInfo *TLI) {
1810 SmallVector<Instruction*, 4> Worklist;
1811 Worklist.push_back(AI);
1813 do {
1814 Instruction *PI = Worklist.pop_back_val();
1815 for (User *U : PI->users()) {
1816 Instruction *I = cast<Instruction>(U);
1817 switch (I->getOpcode()) {
1818 default:
1819 // Give up the moment we see something we can't handle.
1820 return false;
1822 case Instruction::BitCast:
1823 case Instruction::GetElementPtr:
1824 Users.push_back(I);
1825 Worklist.push_back(I);
1826 continue;
1828 case Instruction::ICmp: {
1829 ICmpInst *ICI = cast<ICmpInst>(I);
1830 // We can fold eq/ne comparisons with null to false/true, respectively.
1831 if (!ICI->isEquality() || !isa<ConstantPointerNull>(ICI->getOperand(1)))
1832 return false;
1833 Users.push_back(I);
1834 continue;
1835 }
1837 case Instruction::Call:
1838 // Ignore no-op and store intrinsics.
1839 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1840 switch (II->getIntrinsicID()) {
1841 default:
1842 return false;
1844 case Intrinsic::memmove:
1845 case Intrinsic::memcpy:
1846 case Intrinsic::memset: {
1847 MemIntrinsic *MI = cast<MemIntrinsic>(II);
1848 if (MI->isVolatile() || MI->getRawDest() != PI)
1849 return false;
1850 }
1851 // fall through
1852 case Intrinsic::dbg_declare:
1853 case Intrinsic::dbg_value:
1854 case Intrinsic::invariant_start:
1855 case Intrinsic::invariant_end:
1856 case Intrinsic::lifetime_start:
1857 case Intrinsic::lifetime_end:
1858 case Intrinsic::objectsize:
1859 Users.push_back(I);
1860 continue;
1861 }
1862 }
1864 if (isFreeCall(I, TLI)) {
1865 Users.push_back(I);
1866 continue;
1867 }
1868 return false;
1870 case Instruction::Store: {
1871 StoreInst *SI = cast<StoreInst>(I);
1872 if (SI->isVolatile() || SI->getPointerOperand() != PI)
1873 return false;
1874 Users.push_back(I);
1875 continue;
1876 }
1877 }
1878 llvm_unreachable("missing a return?");
1879 }
1880 } while (!Worklist.empty());
1881 return true;
1882 }
1884 Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
1885 // If we have a malloc call which is only used in any amount of comparisons
1886 // to null and free calls, delete the calls and replace the comparisons with
1887 // true or false as appropriate.
1888 SmallVector<WeakVH, 64> Users;
1889 if (isAllocSiteRemovable(&MI, Users, TLI)) {
1890 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
1891 Instruction *I = cast_or_null<Instruction>(&*Users[i]);
1892 if (!I) continue;
1894 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
1895 ReplaceInstUsesWith(*C,
1896 ConstantInt::get(Type::getInt1Ty(C->getContext()),
1897 C->isFalseWhenEqual()));
1898 } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
1899 ReplaceInstUsesWith(*I, UndefValue::get(I->getType()));
1900 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1901 if (II->getIntrinsicID() == Intrinsic::objectsize) {
1902 ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
1903 uint64_t DontKnow = CI->isZero() ? -1ULL : 0;
1904 ReplaceInstUsesWith(*I, ConstantInt::get(I->getType(), DontKnow));
1905 }
1906 }
1907 EraseInstFromFunction(*I);
1908 }
1910 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
1911 // Replace invoke with a NOP intrinsic to maintain the original CFG
1912 Module *M = II->getParent()->getParent()->getParent();
1913 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
1914 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
1915 None, "", II->getParent());
1916 }
1917 return EraseInstFromFunction(MI);
1918 }
1919 return nullptr;
1920 }
1922 /// \brief Move the call to free before a NULL test.
1923 ///
1924 /// Check if this free is accessed after its argument has been test
1925 /// against NULL (property 0).
1926 /// If yes, it is legal to move this call in its predecessor block.
1927 ///
1928 /// The move is performed only if the block containing the call to free
1929 /// will be removed, i.e.:
1930 /// 1. it has only one predecessor P, and P has two successors
1931 /// 2. it contains the call and an unconditional branch
1932 /// 3. its successor is the same as its predecessor's successor
1933 ///
1934 /// The profitability is out-of concern here and this function should
1935 /// be called only if the caller knows this transformation would be
1936 /// profitable (e.g., for code size).
1937 static Instruction *
1938 tryToMoveFreeBeforeNullTest(CallInst &FI) {
1939 Value *Op = FI.getArgOperand(0);
1940 BasicBlock *FreeInstrBB = FI.getParent();
1941 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
1943 // Validate part of constraint #1: Only one predecessor
1944 // FIXME: We can extend the number of predecessor, but in that case, we
1945 // would duplicate the call to free in each predecessor and it may
1946 // not be profitable even for code size.
1947 if (!PredBB)
1948 return nullptr;
1950 // Validate constraint #2: Does this block contains only the call to
1951 // free and an unconditional branch?
1952 // FIXME: We could check if we can speculate everything in the
1953 // predecessor block
1954 if (FreeInstrBB->size() != 2)
1955 return nullptr;
1956 BasicBlock *SuccBB;
1957 if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
1958 return nullptr;
1960 // Validate the rest of constraint #1 by matching on the pred branch.
1961 TerminatorInst *TI = PredBB->getTerminator();
1962 BasicBlock *TrueBB, *FalseBB;
1963 ICmpInst::Predicate Pred;
1964 if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
1965 return nullptr;
1966 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
1967 return nullptr;
1969 // Validate constraint #3: Ensure the null case just falls through.
1970 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
1971 return nullptr;
1972 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
1973 "Broken CFG: missing edge from predecessor to successor");
1975 FI.moveBefore(TI);
1976 return &FI;
1977 }
1980 Instruction *InstCombiner::visitFree(CallInst &FI) {
1981 Value *Op = FI.getArgOperand(0);
1983 // free undef -> unreachable.
1984 if (isa<UndefValue>(Op)) {
1985 // Insert a new store to null because we cannot modify the CFG here.
1986 Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
1987 UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
1988 return EraseInstFromFunction(FI);
1989 }
1991 // If we have 'free null' delete the instruction. This can happen in stl code
1992 // when lots of inlining happens.
1993 if (isa<ConstantPointerNull>(Op))
1994 return EraseInstFromFunction(FI);
1996 // If we optimize for code size, try to move the call to free before the null
1997 // test so that simplify cfg can remove the empty block and dead code
1998 // elimination the branch. I.e., helps to turn something like:
1999 // if (foo) free(foo);
2000 // into
2001 // free(foo);
2002 if (MinimizeSize)
2003 if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
2004 return I;
2006 return nullptr;
2007 }
2009 Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) {
2010 if (RI.getNumOperands() == 0) // ret void
2011 return nullptr;
2013 Value *ResultOp = RI.getOperand(0);
2014 Type *VTy = ResultOp->getType();
2015 if (!VTy->isIntegerTy())
2016 return nullptr;
2018 // There might be assume intrinsics dominating this return that completely
2019 // determine the value. If so, constant fold it.
2020 unsigned BitWidth = VTy->getPrimitiveSizeInBits();
2021 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2022 computeKnownBits(ResultOp, KnownZero, KnownOne, 0, &RI);
2023 if ((KnownZero|KnownOne).isAllOnesValue())
2024 RI.setOperand(0, Constant::getIntegerValue(VTy, KnownOne));
2026 return nullptr;
2027 }
2029 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2030 // Change br (not X), label True, label False to: br X, label False, True
2031 Value *X = nullptr;
2032 BasicBlock *TrueDest;
2033 BasicBlock *FalseDest;
2034 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
2035 !isa<Constant>(X)) {
2036 // Swap Destinations and condition...
2037 BI.setCondition(X);
2038 BI.swapSuccessors();
2039 return &BI;
2040 }
2042 // Canonicalize fcmp_one -> fcmp_oeq
2043 FCmpInst::Predicate FPred; Value *Y;
2044 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
2045 TrueDest, FalseDest)) &&
2046 BI.getCondition()->hasOneUse())
2047 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
2048 FPred == FCmpInst::FCMP_OGE) {
2049 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
2050 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
2052 // Swap Destinations and condition.
2053 BI.swapSuccessors();
2054 Worklist.Add(Cond);
2055 return &BI;
2056 }
2058 // Canonicalize icmp_ne -> icmp_eq
2059 ICmpInst::Predicate IPred;
2060 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
2061 TrueDest, FalseDest)) &&
2062 BI.getCondition()->hasOneUse())
2063 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
2064 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
2065 IPred == ICmpInst::ICMP_SGE) {
2066 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
2067 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
2068 // Swap Destinations and condition.
2069 BI.swapSuccessors();
2070 Worklist.Add(Cond);
2071 return &BI;
2072 }
2074 return nullptr;
2075 }
2077 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
2078 Value *Cond = SI.getCondition();
2079 unsigned BitWidth = cast<IntegerType>(Cond->getType())->getBitWidth();
2080 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2081 computeKnownBits(Cond, KnownZero, KnownOne);
2082 unsigned LeadingKnownZeros = KnownZero.countLeadingOnes();
2083 unsigned LeadingKnownOnes = KnownOne.countLeadingOnes();
2085 // Compute the number of leading bits we can ignore.
2086 for (auto &C : SI.cases()) {
2087 LeadingKnownZeros = std::min(
2088 LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
2089 LeadingKnownOnes = std::min(
2090 LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
2091 }
2093 unsigned NewWidth = BitWidth - std::max(LeadingKnownZeros, LeadingKnownOnes);
2095 // Truncate the condition operand if the new type is equal to or larger than
2096 // the largest legal integer type. We need to be conservative here since
2097 // x86 generates redundant zero-extenstion instructions if the operand is
2098 // truncated to i8 or i16.
2099 bool TruncCond = false;
2100 if (DL && BitWidth > NewWidth &&
2101 NewWidth >= DL->getLargestLegalIntTypeSize()) {
2102 TruncCond = true;
2103 IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
2104 Builder->SetInsertPoint(&SI);
2105 Value *NewCond = Builder->CreateTrunc(SI.getCondition(), Ty, "trunc");
2106 SI.setCondition(NewCond);
2108 for (auto &C : SI.cases())
2109 static_cast<SwitchInst::CaseIt *>(&C)->setValue(ConstantInt::get(
2110 SI.getContext(), C.getCaseValue()->getValue().trunc(NewWidth)));
2111 }
2113 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
2114 if (I->getOpcode() == Instruction::Add)
2115 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2116 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
2117 // Skip the first item since that's the default case.
2118 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
2119 i != e; ++i) {
2120 ConstantInt* CaseVal = i.getCaseValue();
2121 Constant *LHS = CaseVal;
2122 if (TruncCond)
2123 LHS = LeadingKnownZeros
2124 ? ConstantExpr::getZExt(CaseVal, Cond->getType())
2125 : ConstantExpr::getSExt(CaseVal, Cond->getType());
2126 Constant* NewCaseVal = ConstantExpr::getSub(LHS, AddRHS);
2127 assert(isa<ConstantInt>(NewCaseVal) &&
2128 "Result of expression should be constant");
2129 i.setValue(cast<ConstantInt>(NewCaseVal));
2130 }
2131 SI.setCondition(I->getOperand(0));
2132 Worklist.Add(I);
2133 return &SI;
2134 }
2135 }
2137 return TruncCond ? &SI : nullptr;
2138 }
2140 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
2141 Value *Agg = EV.getAggregateOperand();
2143 if (!EV.hasIndices())
2144 return ReplaceInstUsesWith(EV, Agg);
2146 if (Constant *C = dyn_cast<Constant>(Agg)) {
2147 if (Constant *C2 = C->getAggregateElement(*EV.idx_begin())) {
2148 if (EV.getNumIndices() == 0)
2149 return ReplaceInstUsesWith(EV, C2);
2150 // Extract the remaining indices out of the constant indexed by the
2151 // first index
2152 return ExtractValueInst::Create(C2, EV.getIndices().slice(1));
2153 }
2154 return nullptr; // Can't handle other constants
2155 }
2157 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
2158 // We're extracting from an insertvalue instruction, compare the indices
2159 const unsigned *exti, *exte, *insi, *inse;
2160 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
2161 exte = EV.idx_end(), inse = IV->idx_end();
2162 exti != exte && insi != inse;
2163 ++exti, ++insi) {
2164 if (*insi != *exti)
2165 // The insert and extract both reference distinctly different elements.
2166 // This means the extract is not influenced by the insert, and we can
2167 // replace the aggregate operand of the extract with the aggregate
2168 // operand of the insert. i.e., replace
2169 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2170 // %E = extractvalue { i32, { i32 } } %I, 0
2171 // with
2172 // %E = extractvalue { i32, { i32 } } %A, 0
2173 return ExtractValueInst::Create(IV->getAggregateOperand(),
2174 EV.getIndices());
2175 }
2176 if (exti == exte && insi == inse)
2177 // Both iterators are at the end: Index lists are identical. Replace
2178 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2179 // %C = extractvalue { i32, { i32 } } %B, 1, 0
2180 // with "i32 42"
2181 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
2182 if (exti == exte) {
2183 // The extract list is a prefix of the insert list. i.e. replace
2184 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2185 // %E = extractvalue { i32, { i32 } } %I, 1
2186 // with
2187 // %X = extractvalue { i32, { i32 } } %A, 1
2188 // %E = insertvalue { i32 } %X, i32 42, 0
2189 // by switching the order of the insert and extract (though the
2190 // insertvalue should be left in, since it may have other uses).
2191 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
2192 EV.getIndices());
2193 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
2194 makeArrayRef(insi, inse));
2195 }
2196 if (insi == inse)
2197 // The insert list is a prefix of the extract list
2198 // We can simply remove the common indices from the extract and make it
2199 // operate on the inserted value instead of the insertvalue result.
2200 // i.e., replace
2201 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2202 // %E = extractvalue { i32, { i32 } } %I, 1, 0
2203 // with
2204 // %E extractvalue { i32 } { i32 42 }, 0
2205 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
2206 makeArrayRef(exti, exte));
2207 }
2208 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
2209 // We're extracting from an intrinsic, see if we're the only user, which
2210 // allows us to simplify multiple result intrinsics to simpler things that
2211 // just get one value.
2212 if (II->hasOneUse()) {
2213 // Check if we're grabbing the overflow bit or the result of a 'with
2214 // overflow' intrinsic. If it's the latter we can remove the intrinsic
2215 // and replace it with a traditional binary instruction.
2216 switch (II->getIntrinsicID()) {
2217 case Intrinsic::uadd_with_overflow:
2218 case Intrinsic::sadd_with_overflow:
2219 if (*EV.idx_begin() == 0) { // Normal result.
2220 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2221 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
2222 EraseInstFromFunction(*II);
2223 return BinaryOperator::CreateAdd(LHS, RHS);
2224 }
2226 // If the normal result of the add is dead, and the RHS is a constant,
2227 // we can transform this into a range comparison.
2228 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
2229 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2230 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
2231 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
2232 ConstantExpr::getNot(CI));
2233 break;
2234 case Intrinsic::usub_with_overflow:
2235 case Intrinsic::ssub_with_overflow:
2236 if (*EV.idx_begin() == 0) { // Normal result.
2237 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2238 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
2239 EraseInstFromFunction(*II);
2240 return BinaryOperator::CreateSub(LHS, RHS);
2241 }
2242 break;
2243 case Intrinsic::umul_with_overflow:
2244 case Intrinsic::smul_with_overflow:
2245 if (*EV.idx_begin() == 0) { // Normal result.
2246 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2247 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
2248 EraseInstFromFunction(*II);
2249 return BinaryOperator::CreateMul(LHS, RHS);
2250 }
2251 break;
2252 default:
2253 break;
2254 }
2255 }
2256 }
2257 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
2258 // If the (non-volatile) load only has one use, we can rewrite this to a
2259 // load from a GEP. This reduces the size of the load.
2260 // FIXME: If a load is used only by extractvalue instructions then this
2261 // could be done regardless of having multiple uses.
2262 if (L->isSimple() && L->hasOneUse()) {
2263 // extractvalue has integer indices, getelementptr has Value*s. Convert.
2264 SmallVector<Value*, 4> Indices;
2265 // Prefix an i32 0 since we need the first element.
2266 Indices.push_back(Builder->getInt32(0));
2267 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
2268 I != E; ++I)
2269 Indices.push_back(Builder->getInt32(*I));
2271 // We need to insert these at the location of the old load, not at that of
2272 // the extractvalue.
2273 Builder->SetInsertPoint(L->getParent(), L);
2274 Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(), Indices);
2275 // Returning the load directly will cause the main loop to insert it in
2276 // the wrong spot, so use ReplaceInstUsesWith().
2277 return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
2278 }
2279 // We could simplify extracts from other values. Note that nested extracts may
2280 // already be simplified implicitly by the above: extract (extract (insert) )
2281 // will be translated into extract ( insert ( extract ) ) first and then just
2282 // the value inserted, if appropriate. Similarly for extracts from single-use
2283 // loads: extract (extract (load)) will be translated to extract (load (gep))
2284 // and if again single-use then via load (gep (gep)) to load (gep).
2285 // However, double extracts from e.g. function arguments or return values
2286 // aren't handled yet.
2287 return nullptr;
2288 }
2290 enum Personality_Type {
2291 Unknown_Personality,
2292 GNU_Ada_Personality,
2293 GNU_CXX_Personality,
2294 GNU_ObjC_Personality
2295 };
2297 /// RecognizePersonality - See if the given exception handling personality
2298 /// function is one that we understand. If so, return a description of it;
2299 /// otherwise return Unknown_Personality.
2300 static Personality_Type RecognizePersonality(Value *Pers) {
2301 Function *F = dyn_cast<Function>(Pers->stripPointerCasts());
2302 if (!F)
2303 return Unknown_Personality;
2304 return StringSwitch<Personality_Type>(F->getName())
2305 .Case("__gnat_eh_personality", GNU_Ada_Personality)
2306 .Case("__gxx_personality_v0", GNU_CXX_Personality)
2307 .Case("__objc_personality_v0", GNU_ObjC_Personality)
2308 .Default(Unknown_Personality);
2309 }
2311 /// isCatchAll - Return 'true' if the given typeinfo will match anything.
2312 static bool isCatchAll(Personality_Type Personality, Constant *TypeInfo) {
2313 switch (Personality) {
2314 case Unknown_Personality:
2315 return false;
2316 case GNU_Ada_Personality:
2317 // While __gnat_all_others_value will match any Ada exception, it doesn't
2318 // match foreign exceptions (or didn't, before gcc-4.7).
2319 return false;
2320 case GNU_CXX_Personality:
2321 case GNU_ObjC_Personality:
2322 return TypeInfo->isNullValue();
2323 }
2324 llvm_unreachable("Unknown personality!");
2325 }
2327 static bool shorter_filter(const Value *LHS, const Value *RHS) {
2328 return
2329 cast<ArrayType>(LHS->getType())->getNumElements()
2330 <
2331 cast<ArrayType>(RHS->getType())->getNumElements();
2332 }
2334 Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
2335 // The logic here should be correct for any real-world personality function.
2336 // However if that turns out not to be true, the offending logic can always
2337 // be conditioned on the personality function, like the catch-all logic is.
2338 Personality_Type Personality = RecognizePersonality(LI.getPersonalityFn());
2340 // Simplify the list of clauses, eg by removing repeated catch clauses
2341 // (these are often created by inlining).
2342 bool MakeNewInstruction = false; // If true, recreate using the following:
2343 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
2344 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
2346 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
2347 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
2348 bool isLastClause = i + 1 == e;
2349 if (LI.isCatch(i)) {
2350 // A catch clause.
2351 Constant *CatchClause = LI.getClause(i);
2352 Constant *TypeInfo = CatchClause->stripPointerCasts();
2354 // If we already saw this clause, there is no point in having a second
2355 // copy of it.
2356 if (AlreadyCaught.insert(TypeInfo).second) {
2357 // This catch clause was not already seen.
2358 NewClauses.push_back(CatchClause);
2359 } else {
2360 // Repeated catch clause - drop the redundant copy.
2361 MakeNewInstruction = true;
2362 }
2364 // If this is a catch-all then there is no point in keeping any following
2365 // clauses or marking the landingpad as having a cleanup.
2366 if (isCatchAll(Personality, TypeInfo)) {
2367 if (!isLastClause)
2368 MakeNewInstruction = true;
2369 CleanupFlag = false;
2370 break;
2371 }
2372 } else {
2373 // A filter clause. If any of the filter elements were already caught
2374 // then they can be dropped from the filter. It is tempting to try to
2375 // exploit the filter further by saying that any typeinfo that does not
2376 // occur in the filter can't be caught later (and thus can be dropped).
2377 // However this would be wrong, since typeinfos can match without being
2378 // equal (for example if one represents a C++ class, and the other some
2379 // class derived from it).
2380 assert(LI.isFilter(i) && "Unsupported landingpad clause!");
2381 Constant *FilterClause = LI.getClause(i);
2382 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
2383 unsigned NumTypeInfos = FilterType->getNumElements();
2385 // An empty filter catches everything, so there is no point in keeping any
2386 // following clauses or marking the landingpad as having a cleanup. By
2387 // dealing with this case here the following code is made a bit simpler.
2388 if (!NumTypeInfos) {
2389 NewClauses.push_back(FilterClause);
2390 if (!isLastClause)
2391 MakeNewInstruction = true;
2392 CleanupFlag = false;
2393 break;
2394 }
2396 bool MakeNewFilter = false; // If true, make a new filter.
2397 SmallVector<Constant *, 16> NewFilterElts; // New elements.
2398 if (isa<ConstantAggregateZero>(FilterClause)) {
2399 // Not an empty filter - it contains at least one null typeinfo.
2400 assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
2401 Constant *TypeInfo =
2402 Constant::getNullValue(FilterType->getElementType());
2403 // If this typeinfo is a catch-all then the filter can never match.
2404 if (isCatchAll(Personality, TypeInfo)) {
2405 // Throw the filter away.
2406 MakeNewInstruction = true;
2407 continue;
2408 }
2410 // There is no point in having multiple copies of this typeinfo, so
2411 // discard all but the first copy if there is more than one.
2412 NewFilterElts.push_back(TypeInfo);
2413 if (NumTypeInfos > 1)
2414 MakeNewFilter = true;
2415 } else {
2416 ConstantArray *Filter = cast<ConstantArray>(FilterClause);
2417 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
2418 NewFilterElts.reserve(NumTypeInfos);
2420 // Remove any filter elements that were already caught or that already
2421 // occurred in the filter. While there, see if any of the elements are
2422 // catch-alls. If so, the filter can be discarded.
2423 bool SawCatchAll = false;
2424 for (unsigned j = 0; j != NumTypeInfos; ++j) {
2425 Constant *Elt = Filter->getOperand(j);
2426 Constant *TypeInfo = Elt->stripPointerCasts();
2427 if (isCatchAll(Personality, TypeInfo)) {
2428 // This element is a catch-all. Bail out, noting this fact.
2429 SawCatchAll = true;
2430 break;
2431 }
2432 if (AlreadyCaught.count(TypeInfo))
2433 // Already caught by an earlier clause, so having it in the filter
2434 // is pointless.
2435 continue;
2436 // There is no point in having multiple copies of the same typeinfo in
2437 // a filter, so only add it if we didn't already.
2438 if (SeenInFilter.insert(TypeInfo).second)
2439 NewFilterElts.push_back(cast<Constant>(Elt));
2440 }
2441 // A filter containing a catch-all cannot match anything by definition.
2442 if (SawCatchAll) {
2443 // Throw the filter away.
2444 MakeNewInstruction = true;
2445 continue;
2446 }
2448 // If we dropped something from the filter, make a new one.
2449 if (NewFilterElts.size() < NumTypeInfos)
2450 MakeNewFilter = true;
2451 }
2452 if (MakeNewFilter) {
2453 FilterType = ArrayType::get(FilterType->getElementType(),
2454 NewFilterElts.size());
2455 FilterClause = ConstantArray::get(FilterType, NewFilterElts);
2456 MakeNewInstruction = true;
2457 }
2459 NewClauses.push_back(FilterClause);
2461 // If the new filter is empty then it will catch everything so there is
2462 // no point in keeping any following clauses or marking the landingpad
2463 // as having a cleanup. The case of the original filter being empty was
2464 // already handled above.
2465 if (MakeNewFilter && !NewFilterElts.size()) {
2466 assert(MakeNewInstruction && "New filter but not a new instruction!");
2467 CleanupFlag = false;
2468 break;
2469 }
2470 }
2471 }
2473 // If several filters occur in a row then reorder them so that the shortest
2474 // filters come first (those with the smallest number of elements). This is
2475 // advantageous because shorter filters are more likely to match, speeding up
2476 // unwinding, but mostly because it increases the effectiveness of the other
2477 // filter optimizations below.
2478 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
2479 unsigned j;
2480 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
2481 for (j = i; j != e; ++j)
2482 if (!isa<ArrayType>(NewClauses[j]->getType()))
2483 break;
2485 // Check whether the filters are already sorted by length. We need to know
2486 // if sorting them is actually going to do anything so that we only make a
2487 // new landingpad instruction if it does.
2488 for (unsigned k = i; k + 1 < j; ++k)
2489 if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
2490 // Not sorted, so sort the filters now. Doing an unstable sort would be
2491 // correct too but reordering filters pointlessly might confuse users.
2492 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
2493 shorter_filter);
2494 MakeNewInstruction = true;
2495 break;
2496 }
2498 // Look for the next batch of filters.
2499 i = j + 1;
2500 }
2502 // If typeinfos matched if and only if equal, then the elements of a filter L
2503 // that occurs later than a filter F could be replaced by the intersection of
2504 // the elements of F and L. In reality two typeinfos can match without being
2505 // equal (for example if one represents a C++ class, and the other some class
2506 // derived from it) so it would be wrong to perform this transform in general.
2507 // However the transform is correct and useful if F is a subset of L. In that
2508 // case L can be replaced by F, and thus removed altogether since repeating a
2509 // filter is pointless. So here we look at all pairs of filters F and L where
2510 // L follows F in the list of clauses, and remove L if every element of F is
2511 // an element of L. This can occur when inlining C++ functions with exception
2512 // specifications.
2513 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
2514 // Examine each filter in turn.
2515 Value *Filter = NewClauses[i];
2516 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
2517 if (!FTy)
2518 // Not a filter - skip it.
2519 continue;
2520 unsigned FElts = FTy->getNumElements();
2521 // Examine each filter following this one. Doing this backwards means that
2522 // we don't have to worry about filters disappearing under us when removed.
2523 for (unsigned j = NewClauses.size() - 1; j != i; --j) {
2524 Value *LFilter = NewClauses[j];
2525 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
2526 if (!LTy)
2527 // Not a filter - skip it.
2528 continue;
2529 // If Filter is a subset of LFilter, i.e. every element of Filter is also
2530 // an element of LFilter, then discard LFilter.
2531 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
2532 // If Filter is empty then it is a subset of LFilter.
2533 if (!FElts) {
2534 // Discard LFilter.
2535 NewClauses.erase(J);
2536 MakeNewInstruction = true;
2537 // Move on to the next filter.
2538 continue;
2539 }
2540 unsigned LElts = LTy->getNumElements();
2541 // If Filter is longer than LFilter then it cannot be a subset of it.
2542 if (FElts > LElts)
2543 // Move on to the next filter.
2544 continue;
2545 // At this point we know that LFilter has at least one element.
2546 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
2547 // Filter is a subset of LFilter iff Filter contains only zeros (as we
2548 // already know that Filter is not longer than LFilter).
2549 if (isa<ConstantAggregateZero>(Filter)) {
2550 assert(FElts <= LElts && "Should have handled this case earlier!");
2551 // Discard LFilter.
2552 NewClauses.erase(J);
2553 MakeNewInstruction = true;
2554 }
2555 // Move on to the next filter.
2556 continue;
2557 }
2558 ConstantArray *LArray = cast<ConstantArray>(LFilter);
2559 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
2560 // Since Filter is non-empty and contains only zeros, it is a subset of
2561 // LFilter iff LFilter contains a zero.
2562 assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
2563 for (unsigned l = 0; l != LElts; ++l)
2564 if (LArray->getOperand(l)->isNullValue()) {
2565 // LFilter contains a zero - discard it.
2566 NewClauses.erase(J);
2567 MakeNewInstruction = true;
2568 break;
2569 }
2570 // Move on to the next filter.
2571 continue;
2572 }
2573 // At this point we know that both filters are ConstantArrays. Loop over
2574 // operands to see whether every element of Filter is also an element of
2575 // LFilter. Since filters tend to be short this is probably faster than
2576 // using a method that scales nicely.
2577 ConstantArray *FArray = cast<ConstantArray>(Filter);
2578 bool AllFound = true;
2579 for (unsigned f = 0; f != FElts; ++f) {
2580 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
2581 AllFound = false;
2582 for (unsigned l = 0; l != LElts; ++l) {
2583 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
2584 if (LTypeInfo == FTypeInfo) {
2585 AllFound = true;
2586 break;
2587 }
2588 }
2589 if (!AllFound)
2590 break;
2591 }
2592 if (AllFound) {
2593 // Discard LFilter.
2594 NewClauses.erase(J);
2595 MakeNewInstruction = true;
2596 }
2597 // Move on to the next filter.
2598 }
2599 }
2601 // If we changed any of the clauses, replace the old landingpad instruction
2602 // with a new one.
2603 if (MakeNewInstruction) {
2604 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
2605 LI.getPersonalityFn(),
2606 NewClauses.size());
2607 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
2608 NLI->addClause(NewClauses[i]);
2609 // A landing pad with no clauses must have the cleanup flag set. It is
2610 // theoretically possible, though highly unlikely, that we eliminated all
2611 // clauses. If so, force the cleanup flag to true.
2612 if (NewClauses.empty())
2613 CleanupFlag = true;
2614 NLI->setCleanup(CleanupFlag);
2615 return NLI;
2616 }
2618 // Even if none of the clauses changed, we may nonetheless have understood
2619 // that the cleanup flag is pointless. Clear it if so.
2620 if (LI.isCleanup() != CleanupFlag) {
2621 assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
2622 LI.setCleanup(CleanupFlag);
2623 return &LI;
2624 }
2626 return nullptr;
2627 }
2632 /// TryToSinkInstruction - Try to move the specified instruction from its
2633 /// current block into the beginning of DestBlock, which can only happen if it's
2634 /// safe to move the instruction past all of the instructions between it and the
2635 /// end of its block.
2636 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
2637 assert(I->hasOneUse() && "Invariants didn't hold!");
2639 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
2640 if (isa<PHINode>(I) || isa<LandingPadInst>(I) || I->mayHaveSideEffects() ||
2641 isa<TerminatorInst>(I))
2642 return false;
2644 // Do not sink alloca instructions out of the entry block.
2645 if (isa<AllocaInst>(I) && I->getParent() ==
2646 &DestBlock->getParent()->getEntryBlock())
2647 return false;
2649 // We can only sink load instructions if there is nothing between the load and
2650 // the end of block that could change the value.
2651 if (I->mayReadFromMemory()) {
2652 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
2653 Scan != E; ++Scan)
2654 if (Scan->mayWriteToMemory())
2655 return false;
2656 }
2658 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
2659 I->moveBefore(InsertPos);
2660 ++NumSunkInst;
2661 return true;
2662 }
2665 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
2666 /// all reachable code to the worklist.
2667 ///
2668 /// This has a couple of tricks to make the code faster and more powerful. In
2669 /// particular, we constant fold and DCE instructions as we go, to avoid adding
2670 /// them to the worklist (this significantly speeds up instcombine on code where
2671 /// many instructions are dead or constant). Additionally, if we find a branch
2672 /// whose condition is a known constant, we only visit the reachable successors.
2673 ///
2674 static bool AddReachableCodeToWorklist(BasicBlock *BB,
2675 SmallPtrSetImpl<BasicBlock*> &Visited,
2676 InstCombiner &IC,
2677 const DataLayout *DL,
2678 const TargetLibraryInfo *TLI) {
2679 bool MadeIRChange = false;
2680 SmallVector<BasicBlock*, 256> Worklist;
2681 Worklist.push_back(BB);
2683 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
2684 DenseMap<ConstantExpr*, Constant*> FoldedConstants;
2686 do {
2687 BB = Worklist.pop_back_val();
2689 // We have now visited this block! If we've already been here, ignore it.
2690 if (!Visited.insert(BB).second)
2691 continue;
2693 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
2694 Instruction *Inst = BBI++;
2696 // DCE instruction if trivially dead.
2697 if (isInstructionTriviallyDead(Inst, TLI)) {
2698 ++NumDeadInst;
2699 DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
2700 Inst->eraseFromParent();
2701 continue;
2702 }
2704 // ConstantProp instruction if trivially constant.
2705 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
2706 if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
2707 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: "
2708 << *Inst << '\n');
2709 Inst->replaceAllUsesWith(C);
2710 ++NumConstProp;
2711 Inst->eraseFromParent();
2712 continue;
2713 }
2715 if (DL) {
2716 // See if we can constant fold its operands.
2717 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
2718 i != e; ++i) {
2719 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
2720 if (CE == nullptr) continue;
2722 Constant*& FoldRes = FoldedConstants[CE];
2723 if (!FoldRes)
2724 FoldRes = ConstantFoldConstantExpression(CE, DL, TLI);
2725 if (!FoldRes)
2726 FoldRes = CE;
2728 if (FoldRes != CE) {
2729 *i = FoldRes;
2730 MadeIRChange = true;
2731 }
2732 }
2733 }
2735 InstrsForInstCombineWorklist.push_back(Inst);
2736 }
2738 // Recursively visit successors. If this is a branch or switch on a
2739 // constant, only visit the reachable successor.
2740 TerminatorInst *TI = BB->getTerminator();
2741 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2742 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
2743 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
2744 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
2745 Worklist.push_back(ReachableBB);
2746 continue;
2747 }
2748 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2749 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
2750 // See if this is an explicit destination.
2751 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
2752 i != e; ++i)
2753 if (i.getCaseValue() == Cond) {
2754 BasicBlock *ReachableBB = i.getCaseSuccessor();
2755 Worklist.push_back(ReachableBB);
2756 continue;
2757 }
2759 // Otherwise it is the default destination.
2760 Worklist.push_back(SI->getDefaultDest());
2761 continue;
2762 }
2763 }
2765 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
2766 Worklist.push_back(TI->getSuccessor(i));
2767 } while (!Worklist.empty());
2769 // Once we've found all of the instructions to add to instcombine's worklist,
2770 // add them in reverse order. This way instcombine will visit from the top
2771 // of the function down. This jives well with the way that it adds all uses
2772 // of instructions to the worklist after doing a transformation, thus avoiding
2773 // some N^2 behavior in pathological cases.
2774 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
2775 InstrsForInstCombineWorklist.size());
2777 return MadeIRChange;
2778 }
2780 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
2781 MadeIRChange = false;
2783 DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
2784 << F.getName() << "\n");
2786 {
2787 // Do a depth-first traversal of the function, populate the worklist with
2788 // the reachable instructions. Ignore blocks that are not reachable. Keep
2789 // track of which blocks we visit.
2790 SmallPtrSet<BasicBlock*, 64> Visited;
2791 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, DL,
2792 TLI);
2794 // Do a quick scan over the function. If we find any blocks that are
2795 // unreachable, remove any instructions inside of them. This prevents
2796 // the instcombine code from having to deal with some bad special cases.
2797 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2798 if (Visited.count(BB)) continue;
2800 // Delete the instructions backwards, as it has a reduced likelihood of
2801 // having to update as many def-use and use-def chains.
2802 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
2803 while (EndInst != BB->begin()) {
2804 // Delete the next to last instruction.
2805 BasicBlock::iterator I = EndInst;
2806 Instruction *Inst = --I;
2807 if (!Inst->use_empty())
2808 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
2809 if (isa<LandingPadInst>(Inst)) {
2810 EndInst = Inst;
2811 continue;
2812 }
2813 if (!isa<DbgInfoIntrinsic>(Inst)) {
2814 ++NumDeadInst;
2815 MadeIRChange = true;
2816 }
2817 Inst->eraseFromParent();
2818 }
2819 }
2820 }
2822 while (!Worklist.isEmpty()) {
2823 Instruction *I = Worklist.RemoveOne();
2824 if (I == nullptr) continue; // skip null values.
2826 // Check to see if we can DCE the instruction.
2827 if (isInstructionTriviallyDead(I, TLI)) {
2828 DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
2829 EraseInstFromFunction(*I);
2830 ++NumDeadInst;
2831 MadeIRChange = true;
2832 continue;
2833 }
2835 // Instruction isn't dead, see if we can constant propagate it.
2836 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
2837 if (Constant *C = ConstantFoldInstruction(I, DL, TLI)) {
2838 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
2840 // Add operands to the worklist.
2841 ReplaceInstUsesWith(*I, C);
2842 ++NumConstProp;
2843 EraseInstFromFunction(*I);
2844 MadeIRChange = true;
2845 continue;
2846 }
2848 // See if we can trivially sink this instruction to a successor basic block.
2849 if (I->hasOneUse()) {
2850 BasicBlock *BB = I->getParent();
2851 Instruction *UserInst = cast<Instruction>(*I->user_begin());
2852 BasicBlock *UserParent;
2854 // Get the block the use occurs in.
2855 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
2856 UserParent = PN->getIncomingBlock(*I->use_begin());
2857 else
2858 UserParent = UserInst->getParent();
2860 if (UserParent != BB) {
2861 bool UserIsSuccessor = false;
2862 // See if the user is one of our successors.
2863 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
2864 if (*SI == UserParent) {
2865 UserIsSuccessor = true;
2866 break;
2867 }
2869 // If the user is one of our immediate successors, and if that successor
2870 // only has us as a predecessors (we'd have to split the critical edge
2871 // otherwise), we can keep going.
2872 if (UserIsSuccessor && UserParent->getSinglePredecessor()) {
2873 // Okay, the CFG is simple enough, try to sink this instruction.
2874 if (TryToSinkInstruction(I, UserParent)) {
2875 MadeIRChange = true;
2876 // We'll add uses of the sunk instruction below, but since sinking
2877 // can expose opportunities for it's *operands* add them to the
2878 // worklist
2879 for (Use &U : I->operands())
2880 if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
2881 Worklist.Add(OpI);
2882 }
2883 }
2884 }
2885 }
2887 // Now that we have an instruction, try combining it to simplify it.
2888 Builder->SetInsertPoint(I->getParent(), I);
2889 Builder->SetCurrentDebugLocation(I->getDebugLoc());
2891 #ifndef NDEBUG
2892 std::string OrigI;
2893 #endif
2894 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
2895 DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
2897 if (Instruction *Result = visit(*I)) {
2898 ++NumCombined;
2899 // Should we replace the old instruction with a new one?
2900 if (Result != I) {
2901 DEBUG(dbgs() << "IC: Old = " << *I << '\n'
2902 << " New = " << *Result << '\n');
2904 if (!I->getDebugLoc().isUnknown())
2905 Result->setDebugLoc(I->getDebugLoc());
2906 // Everything uses the new instruction now.
2907 I->replaceAllUsesWith(Result);
2909 // Move the name to the new instruction first.
2910 Result->takeName(I);
2912 // Push the new instruction and any users onto the worklist.
2913 Worklist.Add(Result);
2914 Worklist.AddUsersToWorkList(*Result);
2916 // Insert the new instruction into the basic block...
2917 BasicBlock *InstParent = I->getParent();
2918 BasicBlock::iterator InsertPos = I;
2920 // If we replace a PHI with something that isn't a PHI, fix up the
2921 // insertion point.
2922 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
2923 InsertPos = InstParent->getFirstInsertionPt();
2925 InstParent->getInstList().insert(InsertPos, Result);
2927 EraseInstFromFunction(*I);
2928 } else {
2929 #ifndef NDEBUG
2930 DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
2931 << " New = " << *I << '\n');
2932 #endif
2934 // If the instruction was modified, it's possible that it is now dead.
2935 // if so, remove it.
2936 if (isInstructionTriviallyDead(I, TLI)) {
2937 EraseInstFromFunction(*I);
2938 } else {
2939 Worklist.Add(I);
2940 Worklist.AddUsersToWorkList(*I);
2941 }
2942 }
2943 MadeIRChange = true;
2944 }
2945 }
2947 Worklist.Zap();
2948 return MadeIRChange;
2949 }
2951 namespace {
2952 class InstCombinerLibCallSimplifier final : public LibCallSimplifier {
2953 InstCombiner *IC;
2954 public:
2955 InstCombinerLibCallSimplifier(const DataLayout *DL,
2956 const TargetLibraryInfo *TLI,
2957 InstCombiner *IC)
2958 : LibCallSimplifier(DL, TLI) {
2959 this->IC = IC;
2960 }
2962 /// replaceAllUsesWith - override so that instruction replacement
2963 /// can be defined in terms of the instruction combiner framework.
2964 void replaceAllUsesWith(Instruction *I, Value *With) const override {
2965 IC->ReplaceInstUsesWith(*I, With);
2966 }
2967 };
2968 }
2970 bool InstCombiner::runOnFunction(Function &F) {
2971 if (skipOptnoneFunction(F))
2972 return false;
2974 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2975 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
2976 DL = DLP ? &DLP->getDataLayout() : nullptr;
2977 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2978 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
2980 // Minimizing size?
2981 MinimizeSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
2982 Attribute::MinSize);
2984 /// Builder - This is an IRBuilder that automatically inserts new
2985 /// instructions into the worklist when they are created.
2986 IRBuilder<true, TargetFolder, InstCombineIRInserter> TheBuilder(
2987 F.getContext(), TargetFolder(DL), InstCombineIRInserter(Worklist, AC));
2988 Builder = &TheBuilder;
2990 InstCombinerLibCallSimplifier TheSimplifier(DL, TLI, this);
2991 Simplifier = &TheSimplifier;
2993 bool EverMadeChange = false;
2995 // Lower dbg.declare intrinsics otherwise their value may be clobbered
2996 // by instcombiner.
2997 EverMadeChange = LowerDbgDeclare(F);
2999 // Iterate while there is work to do.
3000 unsigned Iteration = 0;
3001 while (DoOneIteration(F, Iteration++))
3002 EverMadeChange = true;
3004 Builder = nullptr;
3005 return EverMadeChange;
3006 }
3008 FunctionPass *llvm::createInstructionCombiningPass() {
3009 return new InstCombiner();
3010 }