blob: 8e59c01da85de60a61e44b2bb7c7d595c5577ac9 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 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.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 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.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattnerac8f2fd2010-01-04 07:12:23 +000038#include "InstCombine.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000039#include "llvm/IntrinsicInst.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000040#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner9dbb4292009-11-09 23:28:39 +000041#include "llvm/Analysis/InstructionSimplify.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000042#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000043#include "llvm/Target/TargetData.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000044#include "llvm/Transforms/Utils/Local.h"
Chris Lattner804272c2010-01-05 07:54:43 +000045#include "llvm/Support/CFG.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000048#include "llvm/Support/PatternMatch.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000049#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000050#include "llvm/ADT/Statistic.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000051#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000052#include <climits>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000053using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000054using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000055
Chris Lattner0e5f4992006-12-19 21:40:18 +000056STATISTIC(NumCombined , "Number of insts combined");
57STATISTIC(NumConstProp, "Number of constant folds");
58STATISTIC(NumDeadInst , "Number of dead inst eliminated");
Chris Lattner0e5f4992006-12-19 21:40:18 +000059STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000060
Chris Lattnerdd841ae2002-04-18 17:39:14 +000061
Dan Gohman844731a2008-05-13 00:00:25 +000062char InstCombiner::ID = 0;
63static RegisterPass<InstCombiner>
64X("instcombine", "Combine redundant instructions");
65
Chris Lattnere0b4b722010-01-04 07:17:19 +000066void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
67 AU.addPreservedID(LCSSAID);
68 AU.setPreservesCFG();
69}
70
71
Chris Lattnerc22d4d12009-11-10 07:23:37 +000072/// ShouldChangeType - Return true if it is desirable to convert a computation
73/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
74/// type for example, or from a smaller to a larger illegal type.
Chris Lattner80f43d32010-01-04 07:53:58 +000075bool InstCombiner::ShouldChangeType(const Type *From, const Type *To) const {
Chris Lattnerc22d4d12009-11-10 07:23:37 +000076 assert(isa<IntegerType>(From) && isa<IntegerType>(To));
77
78 // If we don't have TD, we don't know if the source/dest are legal.
79 if (!TD) return false;
80
81 unsigned FromWidth = From->getPrimitiveSizeInBits();
82 unsigned ToWidth = To->getPrimitiveSizeInBits();
83 bool FromLegal = TD->isLegalInteger(FromWidth);
84 bool ToLegal = TD->isLegalInteger(ToWidth);
85
86 // If this is a legal integer from type, and the result would be an illegal
87 // type, don't do the transformation.
88 if (FromLegal && !ToLegal)
89 return false;
90
91 // Otherwise, if both are illegal, do not increase the size of the result. We
92 // do allow things like i160 -> i64, but not i64 -> i160.
93 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
94 return false;
95
96 return true;
97}
98
Chris Lattner33a61132006-05-06 09:00:16 +000099
Chris Lattner4f98c562003-03-10 21:43:22 +0000100// SimplifyCommutative - This performs a few simplifications for commutative
101// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000102//
Chris Lattner4f98c562003-03-10 21:43:22 +0000103// 1. Order operands such that they are listed from right (least complex) to
104// left (most complex). This puts constants before unary operators before
105// binary operators.
106//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000107// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
108// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000109//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000110bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000111 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000112 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000113 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000114
Chris Lattner4f98c562003-03-10 21:43:22 +0000115 if (!I.isAssociative()) return Changed;
Chris Lattner248a84b2010-01-05 07:04:23 +0000116
Chris Lattner4f98c562003-03-10 21:43:22 +0000117 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000118 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
119 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
120 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000121 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000122 cast<Constant>(I.getOperand(1)),
123 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000124 I.setOperand(0, Op->getOperand(0));
125 I.setOperand(1, Folded);
126 return true;
Chris Lattner248a84b2010-01-05 07:04:23 +0000127 }
128
129 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1)))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000130 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
Chris Lattner248a84b2010-01-05 07:04:23 +0000131 Op->hasOneUse() && Op1->hasOneUse()) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000132 Constant *C1 = cast<Constant>(Op->getOperand(1));
133 Constant *C2 = cast<Constant>(Op1->getOperand(1));
134
135 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000136 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000137 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000138 Op1->getOperand(0),
139 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000140 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000141 I.setOperand(0, New);
142 I.setOperand(1, Folded);
143 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000144 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000145 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000146 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000147}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000148
Chris Lattner8d969642003-03-10 23:06:50 +0000149// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
150// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000151//
Chris Lattner02446fc2010-01-04 07:37:31 +0000152Value *InstCombiner::dyn_castNegVal(Value *V) const {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000153 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000154 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000155
Chris Lattner0ce85802004-12-14 20:08:06 +0000156 // Constants can be considered to be negated values if they can be folded.
157 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000158 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000159
160 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
161 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000162 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000163
Chris Lattner8d969642003-03-10 23:06:50 +0000164 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000165}
166
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000167// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
168// instruction if the LHS is a constant negative zero (which is the 'negate'
169// form).
170//
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000171Value *InstCombiner::dyn_castFNegVal(Value *V) const {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000172 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000173 return BinaryOperator::getFNegArgument(V);
174
175 // Constants can be considered to be negated values if they can be folded.
176 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000177 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000178
179 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
180 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000181 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000182
183 return 0;
184}
185
Chris Lattner6e7ba452005-01-01 16:22:27 +0000186static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +0000187 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +0000188 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +0000189 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +0000190
Chris Lattner2eefe512004-04-09 19:05:30 +0000191 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +0000192 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
193 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +0000194
Chris Lattner2eefe512004-04-09 19:05:30 +0000195 if (Constant *SOC = dyn_cast<Constant>(SO)) {
196 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +0000197 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
198 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +0000199 }
200
201 Value *Op0 = SO, *Op1 = ConstOperand;
202 if (!ConstIsRHS)
203 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +0000204
Chris Lattner6e7ba452005-01-01 16:22:27 +0000205 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +0000206 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
207 SO->getName()+".op");
208 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
209 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
210 SO->getName()+".cmp");
211 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
212 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
213 SO->getName()+".cmp");
214 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +0000215}
216
217// FoldOpIntoSelect - Given an instruction with a select as one operand and a
218// constant as the other operand, try to fold the binary operator into the
219// select arguments. This also works for Cast instructions, which obviously do
220// not have a second operand.
Chris Lattner80f43d32010-01-04 07:53:58 +0000221Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
Chris Lattner6e7ba452005-01-01 16:22:27 +0000222 // Don't modify shared select instructions
223 if (!SI->hasOneUse()) return 0;
224 Value *TV = SI->getOperand(1);
225 Value *FV = SI->getOperand(2);
226
227 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +0000228 // Bool selects with constant operands can be folded to logical ops.
Chris Lattner4de84762010-01-04 07:02:48 +0000229 if (SI->getType() == Type::getInt1Ty(SI->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +0000230
Chris Lattner80f43d32010-01-04 07:53:58 +0000231 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
232 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000233
Gabor Greif051a9502008-04-06 20:25:17 +0000234 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
235 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000236 }
237 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +0000238}
239
Chris Lattner4e998b22004-09-29 05:07:12 +0000240
Chris Lattner5d1704d2009-09-27 19:57:57 +0000241/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
242/// has a PHI node as operand #0, see if we can fold the instruction into the
243/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000244///
245/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
246/// that would normally be unprofitable because they strongly encourage jump
247/// threading.
248Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
249 bool AllowAggressive) {
250 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +0000251 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +0000252 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +0000253 if (NumPHIValues == 0 ||
254 // We normally only transform phis with a single use, unless we're trying
255 // hard to make jump threading happen.
256 (!PN->hasOneUse() && !AllowAggressive))
257 return 0;
258
259
Chris Lattner5d1704d2009-09-27 19:57:57 +0000260 // Check to see if all of the operands of the PHI are simple constants
261 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000262 // remember the BB it is in. If there is more than one or if *it* is a PHI,
263 // bail out. We don't do arbitrary constant expressions here because moving
264 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000265 BasicBlock *NonConstBB = 0;
266 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +0000267 if (!isa<Constant>(PN->getIncomingValue(i)) ||
268 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000269 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +0000270 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000271 NonConstBB = PN->getIncomingBlock(i);
272
273 // If the incoming non-constant value is in I's block, we have an infinite
274 // loop.
275 if (NonConstBB == I.getParent())
276 return 0;
277 }
278
279 // If there is exactly one non-constant value, we can insert a copy of the
280 // operation in that block. However, if this is a critical edge, we would be
281 // inserting the computation one some other paths (e.g. inside a loop). Only
282 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +0000283 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000284 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
285 if (!BI || !BI->isUnconditional()) return 0;
286 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000287
288 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +0000289 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +0000290 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +0000291 InsertNewInstBefore(NewPN, *PN);
292 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +0000293
294 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +0000295 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
296 // We only currently try to fold the condition of a select when it is a phi,
297 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000298 Value *TrueV = SI->getTrueValue();
299 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +0000300 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +0000301 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000302 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +0000303 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
304 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000305 Value *InV = 0;
306 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000307 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +0000308 } else {
309 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000310 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
311 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +0000312 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +0000313 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +0000314 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000315 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000316 }
317 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000318 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +0000319 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000320 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000321 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000322 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000323 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000324 else
Owen Andersonbaf3c402009-07-29 18:55:55 +0000325 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000326 } else {
327 assert(PN->getIncomingBlock(i) == NonConstBB);
328 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000329 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000330 PN->getIncomingValue(i), C, "phitmp",
331 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +0000332 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000333 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +0000334 CI->getPredicate(),
335 PN->getIncomingValue(i), C, "phitmp",
336 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000337 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000338 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +0000339
340 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000341 }
342 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000343 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000344 } else {
345 CastInst *CI = cast<CastInst>(&I);
346 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +0000347 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000348 Value *InV;
349 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000350 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000351 } else {
352 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000353 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +0000354 I.getType(), "phitmp",
355 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +0000356 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000357 }
358 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000359 }
360 }
361 return ReplaceInstUsesWith(I, NewPN);
362}
363
Chris Lattner46cd5a12009-01-09 05:44:56 +0000364/// FindElementAtOffset - Given a type and a constant offset, determine whether
365/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +0000366/// the specified offset. If so, fill them into NewIndices and return the
367/// resultant element type, otherwise return null.
Chris Lattner80f43d32010-01-04 07:53:58 +0000368const Type *InstCombiner::FindElementAtOffset(const Type *Ty, int64_t Offset,
369 SmallVectorImpl<Value*> &NewIndices) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000370 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +0000371 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +0000372
373 // Start with the index over the outer type. Note that the type size
374 // might be zero (even if the offset isn't zero) if the indexed type
375 // is something like [0 x {int, int}]
Chris Lattner4de84762010-01-04 07:02:48 +0000376 const Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
Chris Lattner46cd5a12009-01-09 05:44:56 +0000377 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +0000378 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +0000379 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +0000380 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +0000381
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000382 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +0000383 if (Offset < 0) {
384 --FirstIdx;
385 Offset += TySize;
386 assert(Offset >= 0);
387 }
388 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
389 }
390
Owen Andersoneed707b2009-07-24 23:12:02 +0000391 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +0000392
393 // Index into the types. If we fail, set OrigBase to null.
394 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000395 // Indexing into tail padding between struct/array elements.
396 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +0000397 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000398
Chris Lattner46cd5a12009-01-09 05:44:56 +0000399 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
400 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000401 assert(Offset < (int64_t)SL->getSizeInBytes() &&
402 "Offset must stay within the indexed type");
403
Chris Lattner46cd5a12009-01-09 05:44:56 +0000404 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattner4de84762010-01-04 07:02:48 +0000405 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
406 Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +0000407
408 Offset -= SL->getElementOffset(Elt);
409 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +0000410 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000411 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000412 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +0000413 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000414 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +0000415 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +0000416 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000417 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +0000418 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +0000419 }
420 }
421
Chris Lattner3914f722009-01-24 01:00:13 +0000422 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +0000423}
424
Chris Lattner8a2a3112001-12-14 16:52:21 +0000425
Chris Lattner473945d2002-05-06 18:06:38 +0000426
Chris Lattner7e708292002-06-25 16:13:24 +0000427Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000428 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
429
430 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
431 return ReplaceInstUsesWith(GEP, V);
432
Chris Lattner620ce142004-05-07 22:09:22 +0000433 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc6bd1952004-02-22 05:25:17 +0000434
Chris Lattnere87597f2004-10-16 18:11:37 +0000435 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000436 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +0000437
Chris Lattner28977af2004-04-05 01:30:19 +0000438 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +0000439 if (TD) {
440 bool MadeChange = false;
441 unsigned PtrSize = TD->getPointerSizeInBits();
442
443 gep_type_iterator GTI = gep_type_begin(GEP);
444 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
445 I != E; ++I, ++GTI) {
446 if (!isa<SequentialType>(*GTI)) continue;
447
Chris Lattnercb69a4e2004-04-07 18:38:20 +0000448 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +0000449 // to what we need. If narrower, sign-extend it to what we need. This
450 // explicit cast can make subsequent optimizations more obvious.
451 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +0000452 if (OpBits == PtrSize)
453 continue;
454
Chris Lattner2345d1d2009-08-30 20:01:10 +0000455 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +0000456 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +0000457 }
Chris Lattnerccf4b342009-08-30 04:49:01 +0000458 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +0000459 }
Chris Lattner28977af2004-04-05 01:30:19 +0000460
Chris Lattner90ac28c2002-08-02 19:29:35 +0000461 // Combine Indices - If the source pointer to this getelementptr instruction
462 // is a getelementptr instruction, combine the indices of the two
463 // getelementptr instructions into a single instruction.
464 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000465 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +0000466 // Note that if our source is a gep chain itself that we wait for that
467 // chain to be resolved before we perform this transformation. This
468 // avoids us creating a TON of code in some cases.
469 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000470 if (GetElementPtrInst *SrcGEP =
471 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
472 if (SrcGEP->getNumOperands() == 2)
473 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +0000474
Chris Lattner72588fc2007-02-15 22:48:32 +0000475 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +0000476
477 // Find out whether the last index in the source GEP is a sequential idx.
478 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +0000479 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
480 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +0000481 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +0000482
Chris Lattner90ac28c2002-08-02 19:29:35 +0000483 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +0000484 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +0000485 // Replace: gep (gep %P, long B), long A, ...
486 // With: T = long A+B; gep %P, T, ...
487 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000488 Value *Sum;
489 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
490 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +0000491 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +0000492 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +0000493 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +0000494 Sum = SO1;
495 } else {
Chris Lattnerab984842009-08-30 05:30:55 +0000496 // If they aren't the same type, then the input hasn't been processed
497 // by the loop above yet (which canonicalizes sequential index types to
498 // intptr_t). Just avoid transforming this until the input has been
499 // normalized.
500 if (SO1->getType() != GO1->getType())
501 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000502 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +0000503 }
Chris Lattner620ce142004-05-07 22:09:22 +0000504
Chris Lattnerab984842009-08-30 05:30:55 +0000505 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000506 if (Src->getNumOperands() == 2) {
507 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +0000508 GEP.setOperand(1, Sum);
509 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +0000510 }
Chris Lattnerab984842009-08-30 05:30:55 +0000511 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +0000512 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +0000513 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +0000514 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +0000515 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000516 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +0000517 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +0000518 Indices.append(Src->op_begin()+1, Src->op_end());
519 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +0000520 }
521
Dan Gohmanf8dbee72009-09-07 23:54:19 +0000522 if (!Indices.empty())
Chris Lattner948cdeb2010-01-05 07:42:10 +0000523 return (GEP.isInBounds() && Src->isInBounds()) ?
Dan Gohmanf8dbee72009-09-07 23:54:19 +0000524 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
525 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000526 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +0000527 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +0000528 }
529
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000530 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
Chris Lattner948cdeb2010-01-05 07:42:10 +0000531 Value *StrippedPtr = PtrOp->stripPointerCasts();
532 if (StrippedPtr != PtrOp) {
533 const PointerType *StrippedPtrTy =cast<PointerType>(StrippedPtr->getType());
Chris Lattner963f4ba2009-08-30 20:36:46 +0000534
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000535 bool HasZeroPointerIndex = false;
536 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
537 HasZeroPointerIndex = C->isZero();
538
Chris Lattner963f4ba2009-08-30 20:36:46 +0000539 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
540 // into : GEP [10 x i8]* X, i32 0, ...
541 //
542 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
543 // into : GEP i8* X, ...
544 //
545 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +0000546 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +0000547 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000548 if (const ArrayType *CATy =
549 dyn_cast<ArrayType>(CPTy->getElementType())) {
550 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
Chris Lattner948cdeb2010-01-05 07:42:10 +0000551 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000552 // -> GEP i8* X, ...
Chris Lattner948cdeb2010-01-05 07:42:10 +0000553 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
554 GetElementPtrInst *Res =
555 GetElementPtrInst::Create(StrippedPtr, Idx.begin(),
556 Idx.end(), GEP.getName());
557 Res->setIsInBounds(GEP.isInBounds());
558 return Res;
Chris Lattner963f4ba2009-08-30 20:36:46 +0000559 }
560
Chris Lattner948cdeb2010-01-05 07:42:10 +0000561 if (const ArrayType *XATy =
562 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000563 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +0000564 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000565 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +0000566 // At this point, we know that the cast source type is a pointer
567 // to an array of the same type as the destination pointer
568 // array. Because the array type is never stepped over (there
569 // is a leading zero) we can fold the cast into this GEP.
Chris Lattner948cdeb2010-01-05 07:42:10 +0000570 GEP.setOperand(0, StrippedPtr);
Chris Lattnereed48272005-09-13 00:40:14 +0000571 return &GEP;
572 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000573 }
574 }
Chris Lattnereed48272005-09-13 00:40:14 +0000575 } else if (GEP.getNumOperands() == 2) {
576 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000577 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
578 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattner948cdeb2010-01-05 07:42:10 +0000579 const Type *SrcElTy = StrippedPtrTy->getElementType();
Chris Lattnereed48272005-09-13 00:40:14 +0000580 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000581 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +0000582 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
583 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +0000584 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +0000585 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +0000586 Idx[1] = GEP.getOperand(1);
Chris Lattner948cdeb2010-01-05 07:42:10 +0000587 Value *NewGEP = GEP.isInBounds() ?
588 Builder->CreateInBoundsGEP(StrippedPtr, Idx, Idx + 2, GEP.getName()) :
589 Builder->CreateGEP(StrippedPtr, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +0000590 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000591 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +0000592 }
Chris Lattner7835cdd2005-09-13 18:36:04 +0000593
594 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000595 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +0000596 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000597 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +0000598
Chris Lattner4de84762010-01-04 07:02:48 +0000599 if (TD && isa<ArrayType>(SrcElTy) &&
600 ResElTy == Type::getInt8Ty(GEP.getContext())) {
Chris Lattner7835cdd2005-09-13 18:36:04 +0000601 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +0000602 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +0000603
604 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
605 // allow either a mul, shift, or constant here.
606 Value *NewIdx = 0;
607 ConstantInt *Scale = 0;
608 if (ArrayEltSize == 1) {
609 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +0000610 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +0000611 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000612 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +0000613 Scale = CI;
614 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
615 if (Inst->getOpcode() == Instruction::Shl &&
616 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000617 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
618 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +0000619 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +0000620 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +0000621 NewIdx = Inst->getOperand(0);
622 } else if (Inst->getOpcode() == Instruction::Mul &&
623 isa<ConstantInt>(Inst->getOperand(1))) {
624 Scale = cast<ConstantInt>(Inst->getOperand(1));
625 NewIdx = Inst->getOperand(0);
626 }
627 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000628
Chris Lattner7835cdd2005-09-13 18:36:04 +0000629 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000630 // out, perform the transformation. Note, we don't know whether Scale is
631 // signed or not. We'll use unsigned version of division/modulo
632 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +0000633 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000634 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000635 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000636 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +0000637 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +0000638 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
639 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000640 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +0000641 }
642
643 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +0000644 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +0000645 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +0000646 Idx[1] = NewIdx;
Chris Lattner948cdeb2010-01-05 07:42:10 +0000647 Value *NewGEP = GEP.isInBounds() ?
648 Builder->CreateInBoundsGEP(StrippedPtr, Idx, Idx + 2,GEP.getName()):
649 Builder->CreateGEP(StrippedPtr, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +0000650 // The NewGEP must be pointer typed, so must the old one -> BitCast
651 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +0000652 }
653 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +0000654 }
Chris Lattner8a2a3112001-12-14 16:52:21 +0000655 }
Chris Lattner58407792009-01-09 04:53:57 +0000656
Chris Lattner46cd5a12009-01-09 05:44:56 +0000657 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +0000658 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +0000659 /// Y = gep X, <...constant indices...>
660 /// into a gep of the original struct. This is important for SROA and alias
661 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +0000662 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000663 if (TD &&
664 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +0000665 // Determine how much the GEP moves the pointer. We are guaranteed to get
666 // a constant back from EmitGEPOffset.
Chris Lattner02446fc2010-01-04 07:37:31 +0000667 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP));
Chris Lattner46cd5a12009-01-09 05:44:56 +0000668 int64_t Offset = OffsetV->getSExtValue();
669
670 // If this GEP instruction doesn't move the pointer, just replace the GEP
671 // with a bitcast of the real input to the dest type.
672 if (Offset == 0) {
673 // If the bitcast is of an allocation, and the allocation will be
674 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000675 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +0000676 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +0000677 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
678 if (Instruction *I = visitBitCast(*BCI)) {
679 if (I != BCI) {
680 I->takeName(BCI);
681 BCI->getParent()->getInstList().insert(BCI, I);
682 ReplaceInstUsesWith(*BCI, I);
683 }
684 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +0000685 }
Chris Lattner58407792009-01-09 04:53:57 +0000686 }
Chris Lattner46cd5a12009-01-09 05:44:56 +0000687 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +0000688 }
Chris Lattner46cd5a12009-01-09 05:44:56 +0000689
690 // Otherwise, if the offset is non-zero, we need to find out if there is a
691 // field at Offset in 'A's type. If so, we can pull the cast through the
692 // GEP.
693 SmallVector<Value*, 8> NewIndices;
694 const Type *InTy =
695 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Chris Lattner80f43d32010-01-04 07:53:58 +0000696 if (FindElementAtOffset(InTy, Offset, NewIndices)) {
Chris Lattner948cdeb2010-01-05 07:42:10 +0000697 Value *NGEP = GEP.isInBounds() ?
Dan Gohmanf8dbee72009-09-07 23:54:19 +0000698 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
699 NewIndices.end()) :
700 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
701 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000702
703 if (NGEP->getType() == GEP.getType())
704 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +0000705 NGEP->takeName(&GEP);
706 return new BitCastInst(NGEP, GEP.getType());
707 }
Chris Lattner58407792009-01-09 04:53:57 +0000708 }
709 }
710
Chris Lattner8a2a3112001-12-14 16:52:21 +0000711 return 0;
712}
713
Victor Hernandez66284e02009-10-24 04:23:03 +0000714Instruction *InstCombiner::visitFree(Instruction &FI) {
715 Value *Op = FI.getOperand(1);
716
717 // free undef -> unreachable.
718 if (isa<UndefValue>(Op)) {
719 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner4de84762010-01-04 07:02:48 +0000720 new StoreInst(ConstantInt::getTrue(FI.getContext()),
721 UndefValue::get(Type::getInt1PtrTy(FI.getContext())), &FI);
Victor Hernandez66284e02009-10-24 04:23:03 +0000722 return EraseInstFromFunction(FI);
723 }
724
725 // If we have 'free null' delete the instruction. This can happen in stl code
726 // when lots of inlining happens.
727 if (isa<ConstantPointerNull>(Op))
728 return EraseInstFromFunction(FI);
729
Victor Hernandez046e78c2009-10-26 23:43:48 +0000730 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman7f712a12009-10-27 00:11:02 +0000731 if (isMalloc(Op)) {
Victor Hernandez66284e02009-10-24 04:23:03 +0000732 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
733 if (Op->hasOneUse() && CI->hasOneUse()) {
734 EraseInstFromFunction(FI);
735 EraseInstFromFunction(*CI);
736 return EraseInstFromFunction(*cast<Instruction>(Op));
737 }
738 } else {
739 // Op is a call to malloc
740 if (Op->hasOneUse()) {
741 EraseInstFromFunction(FI);
742 return EraseInstFromFunction(*cast<Instruction>(Op));
743 }
744 }
Dan Gohman7f712a12009-10-27 00:11:02 +0000745 }
Victor Hernandez66284e02009-10-24 04:23:03 +0000746
747 return 0;
748}
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000749
Chris Lattner3284d1f2007-04-15 00:07:55 +0000750
Chris Lattner2f503e62005-01-31 05:36:43 +0000751
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000752Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
753 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +0000754 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000755 BasicBlock *TrueDest;
756 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +0000757 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000758 !isa<Constant>(X)) {
759 // Swap Destinations and condition...
760 BI.setCondition(X);
761 BI.setSuccessor(0, FalseDest);
762 BI.setSuccessor(1, TrueDest);
763 return &BI;
764 }
765
Reid Spencere4d87aa2006-12-23 06:05:41 +0000766 // Cannonicalize fcmp_one -> fcmp_oeq
767 FCmpInst::Predicate FPred; Value *Y;
768 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +0000769 TrueDest, FalseDest)) &&
770 BI.getCondition()->hasOneUse())
771 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
772 FPred == FCmpInst::FCMP_OGE) {
773 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
774 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
775
776 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000777 BI.setSuccessor(0, FalseDest);
778 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000779 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000780 return &BI;
781 }
782
783 // Cannonicalize icmp_ne -> icmp_eq
784 ICmpInst::Predicate IPred;
785 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +0000786 TrueDest, FalseDest)) &&
787 BI.getCondition()->hasOneUse())
788 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
789 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
790 IPred == ICmpInst::ICMP_SGE) {
791 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
792 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
793 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +0000794 BI.setSuccessor(0, FalseDest);
795 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000796 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +0000797 return &BI;
798 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000799
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000800 return 0;
801}
Chris Lattner0864acf2002-11-04 16:18:53 +0000802
Chris Lattner46238a62004-07-03 00:26:11 +0000803Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
804 Value *Cond = SI.getCondition();
805 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
806 if (I->getOpcode() == Instruction::Add)
807 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
808 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
809 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +0000810 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000811 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +0000812 AddRHS));
813 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +0000814 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +0000815 return &SI;
816 }
817 }
818 return 0;
819}
820
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000821Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +0000822 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000823
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +0000824 if (!EV.hasIndices())
825 return ReplaceInstUsesWith(EV, Agg);
826
827 if (Constant *C = dyn_cast<Constant>(Agg)) {
828 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000829 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +0000830
831 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +0000832 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +0000833
834 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
835 // Extract the element indexed by the first index out of the constant
836 Value *V = C->getOperand(*EV.idx_begin());
837 if (EV.getNumIndices() > 1)
838 // Extract the remaining indices out of the constant indexed by the
839 // first index
840 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
841 else
842 return ReplaceInstUsesWith(EV, V);
843 }
844 return 0; // Can't handle other constants
845 }
846 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
847 // We're extracting from an insertvalue instruction, compare the indices
848 const unsigned *exti, *exte, *insi, *inse;
849 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
850 exte = EV.idx_end(), inse = IV->idx_end();
851 exti != exte && insi != inse;
852 ++exti, ++insi) {
853 if (*insi != *exti)
854 // The insert and extract both reference distinctly different elements.
855 // This means the extract is not influenced by the insert, and we can
856 // replace the aggregate operand of the extract with the aggregate
857 // operand of the insert. i.e., replace
858 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
859 // %E = extractvalue { i32, { i32 } } %I, 0
860 // with
861 // %E = extractvalue { i32, { i32 } } %A, 0
862 return ExtractValueInst::Create(IV->getAggregateOperand(),
863 EV.idx_begin(), EV.idx_end());
864 }
865 if (exti == exte && insi == inse)
866 // Both iterators are at the end: Index lists are identical. Replace
867 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
868 // %C = extractvalue { i32, { i32 } } %B, 1, 0
869 // with "i32 42"
870 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
871 if (exti == exte) {
872 // The extract list is a prefix of the insert list. i.e. replace
873 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
874 // %E = extractvalue { i32, { i32 } } %I, 1
875 // with
876 // %X = extractvalue { i32, { i32 } } %A, 1
877 // %E = insertvalue { i32 } %X, i32 42, 0
878 // by switching the order of the insert and extract (though the
879 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000880 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
881 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +0000882 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
883 insi, inse);
884 }
885 if (insi == inse)
886 // The insert list is a prefix of the extract list
887 // We can simply remove the common indices from the extract and make it
888 // operate on the inserted value instead of the insertvalue result.
889 // i.e., replace
890 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
891 // %E = extractvalue { i32, { i32 } } %I, 1, 0
892 // with
893 // %E extractvalue { i32 } { i32 42 }, 0
894 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
895 exti, exte);
896 }
Chris Lattner7e606e22009-11-09 07:07:56 +0000897 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
898 // We're extracting from an intrinsic, see if we're the only user, which
899 // allows us to simplify multiple result intrinsics to simpler things that
900 // just get one value..
901 if (II->hasOneUse()) {
902 // Check if we're grabbing the overflow bit or the result of a 'with
903 // overflow' intrinsic. If it's the latter we can remove the intrinsic
904 // and replace it with a traditional binary instruction.
905 switch (II->getIntrinsicID()) {
906 case Intrinsic::uadd_with_overflow:
907 case Intrinsic::sadd_with_overflow:
908 if (*EV.idx_begin() == 0) { // Normal result.
909 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
910 II->replaceAllUsesWith(UndefValue::get(II->getType()));
911 EraseInstFromFunction(*II);
912 return BinaryOperator::CreateAdd(LHS, RHS);
913 }
914 break;
915 case Intrinsic::usub_with_overflow:
916 case Intrinsic::ssub_with_overflow:
917 if (*EV.idx_begin() == 0) { // Normal result.
918 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
919 II->replaceAllUsesWith(UndefValue::get(II->getType()));
920 EraseInstFromFunction(*II);
921 return BinaryOperator::CreateSub(LHS, RHS);
922 }
923 break;
924 case Intrinsic::umul_with_overflow:
925 case Intrinsic::smul_with_overflow:
926 if (*EV.idx_begin() == 0) { // Normal result.
927 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
928 II->replaceAllUsesWith(UndefValue::get(II->getType()));
929 EraseInstFromFunction(*II);
930 return BinaryOperator::CreateMul(LHS, RHS);
931 }
932 break;
933 default:
934 break;
935 }
936 }
937 }
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +0000938 // Can't simplify extracts from other values. Note that nested extracts are
939 // already simplified implicitely by the above (extract ( extract (insert) )
940 // will be translated into extract ( insert ( extract ) ) first and then just
941 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000942 return 0;
943}
944
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000945
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000946
Chris Lattnerea1c4542004-12-08 23:43:58 +0000947
948/// TryToSinkInstruction - Try to move the specified instruction from its
949/// current block into the beginning of DestBlock, which can only happen if it's
950/// safe to move the instruction past all of the instructions between it and the
951/// end of its block.
952static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
953 assert(I->hasOneUse() && "Invariants didn't hold!");
954
Chris Lattner108e9022005-10-27 17:13:11 +0000955 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +0000956 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +0000957 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000958
Chris Lattnerea1c4542004-12-08 23:43:58 +0000959 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +0000960 if (isa<AllocaInst>(I) && I->getParent() ==
961 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +0000962 return false;
963
Chris Lattner96a52a62004-12-09 07:14:34 +0000964 // We can only sink load instructions if there is nothing between the load and
965 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +0000966 if (I->mayReadFromMemory()) {
967 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +0000968 Scan != E; ++Scan)
969 if (Scan->mayWriteToMemory())
970 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +0000971 }
Chris Lattnerea1c4542004-12-08 23:43:58 +0000972
Dan Gohman02dea8b2008-05-23 21:05:58 +0000973 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +0000974
Chris Lattner4bc5f802005-08-08 19:11:57 +0000975 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +0000976 ++NumSunkInst;
977 return true;
978}
979
Chris Lattnerf4f5a772006-05-10 19:00:36 +0000980
981/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
982/// all reachable code to the worklist.
983///
984/// This has a couple of tricks to make the code faster and more powerful. In
985/// particular, we constant fold and DCE instructions as we go, to avoid adding
986/// them to the worklist (this significantly speeds up instcombine on code where
987/// many instructions are dead or constant). Additionally, if we find a branch
988/// whose condition is a known constant, we only visit the reachable successors.
989///
Chris Lattner2ee743b2009-10-15 04:59:28 +0000990static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +0000991 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +0000992 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +0000993 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +0000994 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +0000995 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +0000996 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +0000997
998 std::vector<Instruction*> InstrsForInstCombineWorklist;
999 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001000
Chris Lattner2ee743b2009-10-15 04:59:28 +00001001 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
1002
Dan Gohman321a8132010-01-05 16:27:25 +00001003 do {
1004 BB = Worklist.pop_back_val();
Chris Lattner2c7718a2007-03-23 19:17:18 +00001005
1006 // We have now visited this block! If we've already been here, ignore it.
1007 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +00001008
Chris Lattner2c7718a2007-03-23 19:17:18 +00001009 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
1010 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001011
Chris Lattner2c7718a2007-03-23 19:17:18 +00001012 // DCE instruction if trivially dead.
1013 if (isInstructionTriviallyDead(Inst)) {
1014 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00001015 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +00001016 Inst->eraseFromParent();
1017 continue;
1018 }
1019
1020 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001021 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001022 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001023 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
1024 << *Inst << '\n');
1025 Inst->replaceAllUsesWith(C);
1026 ++NumConstProp;
1027 Inst->eraseFromParent();
1028 continue;
1029 }
Chris Lattner2ee743b2009-10-15 04:59:28 +00001030
1031
1032
1033 if (TD) {
1034 // See if we can constant fold its operands.
1035 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
1036 i != e; ++i) {
1037 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
1038 if (CE == 0) continue;
1039
1040 // If we already folded this constant, don't try again.
1041 if (!FoldedConstants.insert(CE))
1042 continue;
1043
Chris Lattner7b550cc2009-11-06 04:27:31 +00001044 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattner2ee743b2009-10-15 04:59:28 +00001045 if (NewC && NewC != CE) {
1046 *i = NewC;
1047 MadeIRChange = true;
1048 }
1049 }
1050 }
1051
Devang Patel7fe1dec2008-11-19 18:56:50 +00001052
Chris Lattner67f7d542009-10-12 03:58:40 +00001053 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001054 }
Chris Lattner2c7718a2007-03-23 19:17:18 +00001055
1056 // Recursively visit successors. If this is a branch or switch on a
1057 // constant, only visit the reachable successor.
1058 TerminatorInst *TI = BB->getTerminator();
1059 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1060 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
1061 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +00001062 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +00001063 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00001064 continue;
1065 }
1066 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1067 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
1068 // See if this is an explicit destination.
1069 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
1070 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +00001071 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +00001072 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00001073 continue;
1074 }
1075
1076 // Otherwise it is the default destination.
1077 Worklist.push_back(SI->getSuccessor(0));
1078 continue;
1079 }
1080 }
1081
1082 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
1083 Worklist.push_back(TI->getSuccessor(i));
Dan Gohman321a8132010-01-05 16:27:25 +00001084 } while (!Worklist.empty());
Chris Lattner67f7d542009-10-12 03:58:40 +00001085
1086 // Once we've found all of the instructions to add to instcombine's worklist,
1087 // add them in reverse order. This way instcombine will visit from the top
1088 // of the function down. This jives well with the way that it adds all uses
1089 // of instructions to the worklist after doing a transformation, thus avoiding
1090 // some N^2 behavior in pathological cases.
1091 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
1092 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +00001093
1094 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001095}
1096
Chris Lattnerec9c3582007-03-03 02:04:50 +00001097bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001098 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +00001099
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001100 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
1101 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +00001102
Chris Lattnerb3d59702005-07-07 20:40:38 +00001103 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001104 // Do a depth-first traversal of the function, populate the worklist with
1105 // the reachable instructions. Ignore blocks that are not reachable. Keep
1106 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +00001107 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +00001108 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +00001109
Chris Lattnerb3d59702005-07-07 20:40:38 +00001110 // Do a quick scan over the function. If we find any blocks that are
1111 // unreachable, remove any instructions inside of them. This prevents
1112 // the instcombine code from having to deal with some bad special cases.
1113 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1114 if (!Visited.count(BB)) {
1115 Instruction *Term = BB->getTerminator();
1116 while (Term != BB->begin()) { // Remove instrs bottom-up
1117 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00001118
Chris Lattnerbdff5482009-08-23 04:37:46 +00001119 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +00001120 // A debug intrinsic shouldn't force another iteration if we weren't
1121 // going to do one without it.
1122 if (!isa<DbgInfoIntrinsic>(I)) {
1123 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001124 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +00001125 }
Devang Patel228ebd02009-10-13 22:56:32 +00001126
Devang Patel228ebd02009-10-13 22:56:32 +00001127 // If I is not void type then replaceAllUsesWith undef.
1128 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00001129 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00001130 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +00001131 I->eraseFromParent();
1132 }
1133 }
1134 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00001135
Chris Lattner873ff012009-08-30 05:55:36 +00001136 while (!Worklist.isEmpty()) {
1137 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +00001138 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +00001139
Chris Lattner8c8c66a2006-05-11 17:11:52 +00001140 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00001141 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00001142 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +00001143 EraseInstFromFunction(*I);
1144 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001145 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +00001146 continue;
1147 }
Chris Lattner62b14df2002-09-02 04:59:56 +00001148
Chris Lattner8c8c66a2006-05-11 17:11:52 +00001149 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001150 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001151 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001152 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +00001153
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001154 // Add operands to the worklist.
1155 ReplaceInstUsesWith(*I, C);
1156 ++NumConstProp;
1157 EraseInstFromFunction(*I);
1158 MadeIRChange = true;
1159 continue;
1160 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00001161
Chris Lattnerea1c4542004-12-08 23:43:58 +00001162 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001163 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +00001164 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +00001165 Instruction *UserInst = cast<Instruction>(I->use_back());
1166 BasicBlock *UserParent;
1167
1168 // Get the block the use occurs in.
1169 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
1170 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
1171 else
1172 UserParent = UserInst->getParent();
1173
Chris Lattnerea1c4542004-12-08 23:43:58 +00001174 if (UserParent != BB) {
1175 bool UserIsSuccessor = false;
1176 // See if the user is one of our successors.
1177 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
1178 if (*SI == UserParent) {
1179 UserIsSuccessor = true;
1180 break;
1181 }
1182
1183 // If the user is one of our immediate successors, and if that successor
1184 // only has us as a predecessors (we'd have to split the critical edge
1185 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +00001186 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +00001187 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001188 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +00001189 }
1190 }
1191
Chris Lattner74381062009-08-30 07:44:24 +00001192 // Now that we have an instruction, try combining it to simplify it.
1193 Builder->SetInsertPoint(I->getParent(), I);
1194
Reid Spencera9b81012007-03-26 17:44:01 +00001195#ifndef NDEBUG
1196 std::string OrigI;
1197#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +00001198 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +00001199 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
1200
Chris Lattner90ac28c2002-08-02 19:29:35 +00001201 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00001202 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001203 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00001204 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00001205 DEBUG(errs() << "IC: Old = " << *I << '\n'
1206 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +00001207
Chris Lattnerf523d062004-06-09 05:08:07 +00001208 // Everything uses the new instruction now.
1209 I->replaceAllUsesWith(Result);
1210
1211 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +00001212 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00001213 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00001214
Chris Lattner6934a042007-02-11 01:23:03 +00001215 // Move the name to the new instruction first.
1216 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00001217
1218 // Insert the new instruction into the basic block...
1219 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00001220 BasicBlock::iterator InsertPos = I;
1221
1222 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
1223 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
1224 ++InsertPos;
1225
1226 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00001227
Chris Lattner7a1e9242009-08-30 06:13:40 +00001228 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +00001229 } else {
Evan Chengc7baf682007-03-27 16:44:48 +00001230#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00001231 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
1232 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +00001233#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +00001234
Chris Lattner90ac28c2002-08-02 19:29:35 +00001235 // If the instruction was modified, it's possible that it is now dead.
1236 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00001237 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00001238 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +00001239 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +00001240 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00001241 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +00001242 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00001243 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001244 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00001245 }
1246 }
1247
Chris Lattner873ff012009-08-30 05:55:36 +00001248 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001249 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00001250}
1251
Chris Lattnerec9c3582007-03-03 02:04:50 +00001252
1253bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +00001254 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001255 TD = getAnalysisIfAvailable<TargetData>();
1256
Chris Lattner74381062009-08-30 07:44:24 +00001257
1258 /// Builder - This is an IRBuilder that automatically inserts new
1259 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001260 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +00001261 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +00001262 InstCombineIRInserter(Worklist));
1263 Builder = &TheBuilder;
1264
Chris Lattnerec9c3582007-03-03 02:04:50 +00001265 bool EverMadeChange = false;
1266
1267 // Iterate while there is work to do.
1268 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +00001269 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +00001270 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +00001271
1272 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +00001273 return EverMadeChange;
1274}
1275
Brian Gaeke96d4bf72004-07-27 17:43:21 +00001276FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001277 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00001278}