blob: 4971b7558c58b83aa732b65ce9fdbcf9e4983b7a [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-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 Lattnerdeaa0dd2003-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.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000027// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All SetCC instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-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 Lattner7515cab2004-11-14 19:13:23 +000032// ... etc.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000033//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner00648e12004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner69193f92004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattner22d00a82005-08-02 19:16:58 +000049#include "llvm/Support/MathExtras.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Chris Lattner4ed40f72005-07-07 20:40:38 +000051#include "llvm/ADT/DepthFirstIterator.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000052#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000053#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattnerc597b8a2006-01-22 23:32:06 +000055#include <iostream>
Chris Lattner8427bff2003-12-07 01:24:23 +000056using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000057using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000058
Chris Lattner260ab202002-04-18 17:39:14 +000059namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000060 Statistic<> NumCombined ("instcombine", "Number of insts combined");
61 Statistic<> NumConstProp("instcombine", "Number of constant folds");
62 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattner5997cf92006-02-08 03:25:32 +000063 Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
Chris Lattner39c98bb2004-12-08 23:43:58 +000064 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000065
Chris Lattnerc8e66542002-04-27 06:56:12 +000066 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000067 public InstVisitor<InstCombiner, Instruction*> {
68 // Worklist of all of the instructions that need to be simplified.
69 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000070 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000071
Chris Lattner51ea1272004-02-28 05:22:00 +000072 /// AddUsersToWorkList - When an instruction is simplified, add all users of
73 /// the instruction to the work lists because they might get more simplified
74 /// now.
75 ///
Chris Lattner2590e512006-02-07 06:56:34 +000076 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000077 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000078 UI != UE; ++UI)
79 WorkList.push_back(cast<Instruction>(*UI));
80 }
81
Chris Lattner51ea1272004-02-28 05:22:00 +000082 /// AddUsesToWorkList - When an instruction is simplified, add operands to
83 /// the work lists because they might get more simplified now.
84 ///
85 void AddUsesToWorkList(Instruction &I) {
86 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
87 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
88 WorkList.push_back(Op);
89 }
90
Chris Lattner99f48c62002-09-02 04:59:56 +000091 // removeFromWorkList - remove all instances of I from the worklist.
92 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000093 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000094 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000095
Chris Lattnerf12cc842002-04-28 21:27:06 +000096 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000097 AU.addRequired<TargetData>();
Chris Lattner820d9712002-10-21 20:00:28 +000098 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000099 }
100
Chris Lattner69193f92004-04-05 01:30:19 +0000101 TargetData &getTargetData() const { return *TD; }
102
Chris Lattner260ab202002-04-18 17:39:14 +0000103 // Visitation implementation - Implement instruction combining for different
104 // instruction types. The semantics are as follows:
105 // Return Value:
106 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000107 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000108 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000109 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000110 Instruction *visitAdd(BinaryOperator &I);
111 Instruction *visitSub(BinaryOperator &I);
112 Instruction *visitMul(BinaryOperator &I);
113 Instruction *visitDiv(BinaryOperator &I);
114 Instruction *visitRem(BinaryOperator &I);
115 Instruction *visitAnd(BinaryOperator &I);
116 Instruction *visitOr (BinaryOperator &I);
117 Instruction *visitXor(BinaryOperator &I);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000118 Instruction *visitSetCondInst(SetCondInst &I);
119 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
120
Chris Lattner0798af32005-01-13 20:14:25 +0000121 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
122 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000123 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner14553932006-01-06 07:12:35 +0000124 Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
125 ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000126 Instruction *visitCastInst(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000127 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
128 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000129 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000130 Instruction *visitCallInst(CallInst &CI);
131 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000132 Instruction *visitPHINode(PHINode &PN);
133 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000134 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000135 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000136 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000137 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000138 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000139 Instruction *visitSwitchInst(SwitchInst &SI);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000140 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattner260ab202002-04-18 17:39:14 +0000141
142 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000143 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000144
Chris Lattner970c33a2003-06-19 17:00:31 +0000145 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000146 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000147 bool transformConstExprCastCall(CallSite CS);
148
Chris Lattner69193f92004-04-05 01:30:19 +0000149 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000150 // InsertNewInstBefore - insert an instruction New before instruction Old
151 // in the program. Add the new instruction to the worklist.
152 //
Chris Lattner623826c2004-09-28 21:48:02 +0000153 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000154 assert(New && New->getParent() == 0 &&
155 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000156 BasicBlock *BB = Old.getParent();
157 BB->getInstList().insert(&Old, New); // Insert inst
158 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000159 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000160 }
161
Chris Lattner7e794272004-09-24 15:21:34 +0000162 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
163 /// This also adds the cast to the worklist. Finally, this returns the
164 /// cast.
165 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
166 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000167
Chris Lattner7e794272004-09-24 15:21:34 +0000168 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
169 WorkList.push_back(C);
170 return C;
171 }
172
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000173 // ReplaceInstUsesWith - This method is to be used when an instruction is
174 // found to be dead, replacable with another preexisting expression. Here
175 // we add all uses of I to the worklist, replace all uses of I with the new
176 // value, then return I, so that the inst combiner will know that I was
177 // modified.
178 //
179 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000180 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000181 if (&I != V) {
182 I.replaceAllUsesWith(V);
183 return &I;
184 } else {
185 // If we are replacing the instruction with itself, this must be in a
186 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000187 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000188 return &I;
189 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000190 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000191
Chris Lattner2590e512006-02-07 06:56:34 +0000192 // UpdateValueUsesWith - This method is to be used when an value is
193 // found to be replacable with another preexisting expression or was
194 // updated. Here we add all uses of I to the worklist, replace all uses of
195 // I with the new value (unless the instruction was just updated), then
196 // return true, so that the inst combiner will know that I was modified.
197 //
198 bool UpdateValueUsesWith(Value *Old, Value *New) {
199 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
200 if (Old != New)
201 Old->replaceAllUsesWith(New);
202 if (Instruction *I = dyn_cast<Instruction>(Old))
203 WorkList.push_back(I);
204 return true;
205 }
206
Chris Lattner51ea1272004-02-28 05:22:00 +0000207 // EraseInstFromFunction - When dealing with an instruction that has side
208 // effects or produces a void value, we can't rely on DCE to delete the
209 // instruction. Instead, visit methods should return the value returned by
210 // this function.
211 Instruction *EraseInstFromFunction(Instruction &I) {
212 assert(I.use_empty() && "Cannot erase instruction that is used!");
213 AddUsesToWorkList(I);
214 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000215 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000216 return 0; // Don't do anything with FI
217 }
218
Chris Lattner3ac7c262003-08-13 20:16:26 +0000219 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000220 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
221 /// InsertBefore instruction. This is specialized a bit to avoid inserting
222 /// casts that are known to not do anything...
223 ///
224 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
225 Instruction *InsertBefore);
226
Chris Lattner7fb29e12003-03-11 00:12:48 +0000227 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000228 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000229 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000230
Chris Lattner0157e7f2006-02-11 09:31:47 +0000231 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
232 uint64_t &KnownZero, uint64_t &KnownOne,
233 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000234
235 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
236 // PHI node as operand #0, see if we can fold the instruction into the PHI
237 // (which is only possible if all operands to the PHI are constants).
238 Instruction *FoldOpIntoPhi(Instruction &I);
239
Chris Lattner7515cab2004-11-14 19:13:23 +0000240 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
241 // operator and they all are only used by the PHI, PHI together their
242 // inputs, and do the operation once, to the result of the PHI.
243 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
244
Chris Lattnerba1cb382003-09-19 17:17:26 +0000245 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
246 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000247
248 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
249 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000250 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
251 bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000252 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattner260ab202002-04-18 17:39:14 +0000253 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000254
Chris Lattnerc8b70922002-07-26 21:12:46 +0000255 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000256}
257
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000258// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000259// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000260static unsigned getComplexity(Value *V) {
261 if (isa<Instruction>(V)) {
262 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000263 return 3;
264 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000265 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000266 if (isa<Argument>(V)) return 3;
267 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000268}
Chris Lattner260ab202002-04-18 17:39:14 +0000269
Chris Lattner7fb29e12003-03-11 00:12:48 +0000270// isOnlyUse - Return true if this instruction will be deleted if we stop using
271// it.
272static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000273 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000274}
275
Chris Lattnere79e8542004-02-23 06:38:22 +0000276// getPromotedType - Return the specified type promoted as it would be to pass
277// though a va_arg area...
278static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000279 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000280 case Type::SByteTyID:
281 case Type::ShortTyID: return Type::IntTy;
282 case Type::UByteTyID:
283 case Type::UShortTyID: return Type::UIntTy;
284 case Type::FloatTyID: return Type::DoubleTy;
285 default: return Ty;
286 }
287}
288
Chris Lattner567b81f2005-09-13 00:40:14 +0000289/// isCast - If the specified operand is a CastInst or a constant expr cast,
290/// return the operand value, otherwise return null.
291static Value *isCast(Value *V) {
292 if (CastInst *I = dyn_cast<CastInst>(V))
293 return I->getOperand(0);
294 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
295 if (CE->getOpcode() == Instruction::Cast)
296 return CE->getOperand(0);
297 return 0;
298}
299
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000300// SimplifyCommutative - This performs a few simplifications for commutative
301// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000302//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000303// 1. Order operands such that they are listed from right (least complex) to
304// left (most complex). This puts constants before unary operators before
305// binary operators.
306//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000307// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
308// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000309//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000310bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000311 bool Changed = false;
312 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
313 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000314
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000315 if (!I.isAssociative()) return Changed;
316 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000317 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
318 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
319 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000320 Constant *Folded = ConstantExpr::get(I.getOpcode(),
321 cast<Constant>(I.getOperand(1)),
322 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000323 I.setOperand(0, Op->getOperand(0));
324 I.setOperand(1, Folded);
325 return true;
326 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
327 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
328 isOnlyUse(Op) && isOnlyUse(Op1)) {
329 Constant *C1 = cast<Constant>(Op->getOperand(1));
330 Constant *C2 = cast<Constant>(Op1->getOperand(1));
331
332 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000333 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000334 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
335 Op1->getOperand(0),
336 Op1->getName(), &I);
337 WorkList.push_back(New);
338 I.setOperand(0, New);
339 I.setOperand(1, Folded);
340 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000341 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000342 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000343 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000344}
Chris Lattnerca081252001-12-14 16:52:21 +0000345
Chris Lattnerbb74e222003-03-10 23:06:50 +0000346// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
347// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000348//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000349static inline Value *dyn_castNegVal(Value *V) {
350 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000351 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000352
Chris Lattner9ad0d552004-12-14 20:08:06 +0000353 // Constants can be considered to be negated values if they can be folded.
354 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
355 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000356 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000357}
358
Chris Lattnerbb74e222003-03-10 23:06:50 +0000359static inline Value *dyn_castNotVal(Value *V) {
360 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000361 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000362
363 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000364 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000365 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000366 return 0;
367}
368
Chris Lattner7fb29e12003-03-11 00:12:48 +0000369// dyn_castFoldableMul - If this value is a multiply that can be folded into
370// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000371// non-constant operand of the multiply, and set CST to point to the multiplier.
372// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000373//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000374static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000375 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000376 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000377 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000378 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000379 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000380 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000381 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000382 // The multiplier is really 1 << CST.
383 Constant *One = ConstantInt::get(V->getType(), 1);
384 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
385 return I->getOperand(0);
386 }
387 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000388 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000389}
Chris Lattner31ae8632002-08-14 17:51:49 +0000390
Chris Lattner0798af32005-01-13 20:14:25 +0000391/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
392/// expression, return it.
393static User *dyn_castGetElementPtr(Value *V) {
394 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
395 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
396 if (CE->getOpcode() == Instruction::GetElementPtr)
397 return cast<User>(V);
398 return false;
399}
400
Chris Lattner623826c2004-09-28 21:48:02 +0000401// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000402static ConstantInt *AddOne(ConstantInt *C) {
403 return cast<ConstantInt>(ConstantExpr::getAdd(C,
404 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000405}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000406static ConstantInt *SubOne(ConstantInt *C) {
407 return cast<ConstantInt>(ConstantExpr::getSub(C,
408 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000409}
410
Chris Lattner0157e7f2006-02-11 09:31:47 +0000411/// GetConstantInType - Return a ConstantInt with the specified type and value.
412///
Chris Lattneree0f2802006-02-12 02:07:56 +0000413static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000414 if (Ty->isUnsigned())
415 return ConstantUInt::get(Ty, Val);
Chris Lattneree0f2802006-02-12 02:07:56 +0000416 else if (Ty->getTypeID() == Type::BoolTyID)
417 return ConstantBool::get(Val);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000418 int64_t SVal = Val;
419 SVal <<= 64-Ty->getPrimitiveSizeInBits();
420 SVal >>= 64-Ty->getPrimitiveSizeInBits();
421 return ConstantSInt::get(Ty, SVal);
422}
423
424
Chris Lattner4534dd592006-02-09 07:38:58 +0000425/// ComputeMaskedBits - Determine which of the bits specified in Mask are
426/// known to be either zero or one and return them in the KnownZero/KnownOne
427/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
428/// processing.
429static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
430 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000431 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
432 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000433 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000434 // optimized based on the contradictory assumption that it is non-zero.
435 // Because instcombine aggressively folds operations with undef args anyway,
436 // this won't lose us code quality.
Chris Lattner4534dd592006-02-09 07:38:58 +0000437 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
438 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000439 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000440 KnownZero = ~KnownOne & Mask;
441 return;
442 }
443
444 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000445 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000446 return; // Limit search depth.
447
448 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000449 Instruction *I = dyn_cast<Instruction>(V);
450 if (!I) return;
451
452 switch (I->getOpcode()) {
453 case Instruction::And:
454 // If either the LHS or the RHS are Zero, the result is zero.
455 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
456 Mask &= ~KnownZero;
457 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
458 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
459 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
460
461 // Output known-1 bits are only known if set in both the LHS & RHS.
462 KnownOne &= KnownOne2;
463 // Output known-0 are known to be clear if zero in either the LHS | RHS.
464 KnownZero |= KnownZero2;
465 return;
466 case Instruction::Or:
467 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
468 Mask &= ~KnownOne;
469 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
470 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
471 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
472
473 // Output known-0 bits are only known if clear in both the LHS & RHS.
474 KnownZero &= KnownZero2;
475 // Output known-1 are known to be set if set in either the LHS | RHS.
476 KnownOne |= KnownOne2;
477 return;
478 case Instruction::Xor: {
479 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
480 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
481 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
482 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
483
484 // Output known-0 bits are known if clear or set in both the LHS & RHS.
485 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
486 // Output known-1 are known to be set if set in only one of the LHS, RHS.
487 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
488 KnownZero = KnownZeroOut;
489 return;
490 }
491 case Instruction::Select:
492 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
493 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
494 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
495 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
496
497 // Only known if known in both the LHS and RHS.
498 KnownOne &= KnownOne2;
499 KnownZero &= KnownZero2;
500 return;
501 case Instruction::Cast: {
502 const Type *SrcTy = I->getOperand(0)->getType();
503 if (!SrcTy->isIntegral()) return;
504
505 // If this is an integer truncate or noop, just look in the input.
506 if (SrcTy->getPrimitiveSizeInBits() >=
507 I->getType()->getPrimitiveSizeInBits()) {
508 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000509 return;
510 }
Chris Lattner4534dd592006-02-09 07:38:58 +0000511
Chris Lattner0157e7f2006-02-11 09:31:47 +0000512 // Sign or Zero extension. Compute the bits in the result that are not
513 // present in the input.
514 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
515 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000516
Chris Lattner0157e7f2006-02-11 09:31:47 +0000517 // Handle zero extension.
518 if (!SrcTy->isSigned()) {
519 Mask &= SrcTy->getIntegralTypeMask();
520 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
521 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
522 // The top bits are known to be zero.
523 KnownZero |= NewBits;
524 } else {
525 // Sign extension.
526 Mask &= SrcTy->getIntegralTypeMask();
527 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
528 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000529
Chris Lattner0157e7f2006-02-11 09:31:47 +0000530 // If the sign bit of the input is known set or clear, then we know the
531 // top bits of the result.
532 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
533 if (KnownZero & InSignBit) { // Input sign bit known zero
Chris Lattner4534dd592006-02-09 07:38:58 +0000534 KnownZero |= NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000535 KnownOne &= ~NewBits;
536 } else if (KnownOne & InSignBit) { // Input sign bit known set
537 KnownOne |= NewBits;
538 KnownZero &= ~NewBits;
539 } else { // Input sign bit unknown
540 KnownZero &= ~NewBits;
541 KnownOne &= ~NewBits;
542 }
543 }
544 return;
545 }
546 case Instruction::Shl:
547 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
548 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
549 Mask >>= SA->getValue();
550 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
551 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
552 KnownZero <<= SA->getValue();
553 KnownOne <<= SA->getValue();
554 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
555 return;
556 }
557 break;
558 case Instruction::Shr:
559 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
560 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
561 // Compute the new bits that are at the top now.
562 uint64_t HighBits = (1ULL << SA->getValue())-1;
563 HighBits <<= I->getType()->getPrimitiveSizeInBits()-SA->getValue();
564
565 if (I->getType()->isUnsigned()) { // Unsigned shift right.
566 Mask <<= SA->getValue();
567 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
568 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
569 KnownZero >>= SA->getValue();
570 KnownOne >>= SA->getValue();
571 KnownZero |= HighBits; // high bits known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +0000572 } else {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000573 Mask <<= SA->getValue();
574 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
575 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
576 KnownZero >>= SA->getValue();
577 KnownOne >>= SA->getValue();
578
579 // Handle the sign bits.
580 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
581 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
582
583 if (KnownZero & SignBit) { // New bits are known zero.
584 KnownZero |= HighBits;
585 } else if (KnownOne & SignBit) { // New bits are known one.
586 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000587 }
588 }
589 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000590 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000591 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000592 }
Chris Lattner92a68652006-02-07 08:05:22 +0000593}
594
595/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
596/// this predicate to simplify operations downstream. Mask is known to be zero
597/// for bits that V cannot have.
598static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000599 uint64_t KnownZero, KnownOne;
600 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
601 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
602 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000603}
604
Chris Lattner0157e7f2006-02-11 09:31:47 +0000605/// ShrinkDemandedConstant - Check to see if the specified operand of the
606/// specified instruction is a constant integer. If so, check to see if there
607/// are any bits set in the constant that are not demanded. If so, shrink the
608/// constant and return true.
609static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
610 uint64_t Demanded) {
611 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
612 if (!OpC) return false;
613
614 // If there are no bits set that aren't demanded, nothing to do.
615 if ((~Demanded & OpC->getZExtValue()) == 0)
616 return false;
617
618 // This is producing any bits that are not needed, shrink the RHS.
619 uint64_t Val = Demanded & OpC->getZExtValue();
620 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
621 return true;
622}
623
Chris Lattneree0f2802006-02-12 02:07:56 +0000624// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
625// set of known zero and one bits, compute the maximum and minimum values that
626// could have the specified known zero and known one bits, returning them in
627// min/max.
628static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
629 uint64_t KnownZero,
630 uint64_t KnownOne,
631 int64_t &Min, int64_t &Max) {
632 uint64_t TypeBits = Ty->getIntegralTypeMask();
633 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
634
635 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
636
637 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
638 // bit if it is unknown.
639 Min = KnownOne;
640 Max = KnownOne|UnknownBits;
641
642 if (SignBit & UnknownBits) { // Sign bit is unknown
643 Min |= SignBit;
644 Max &= ~SignBit;
645 }
646
647 // Sign extend the min/max values.
648 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
649 Min = (Min << ShAmt) >> ShAmt;
650 Max = (Max << ShAmt) >> ShAmt;
651}
652
653// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
654// a set of known zero and one bits, compute the maximum and minimum values that
655// could have the specified known zero and known one bits, returning them in
656// min/max.
657static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
658 uint64_t KnownZero,
659 uint64_t KnownOne,
660 uint64_t &Min,
661 uint64_t &Max) {
662 uint64_t TypeBits = Ty->getIntegralTypeMask();
663 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
664
665 // The minimum value is when the unknown bits are all zeros.
666 Min = KnownOne;
667 // The maximum value is when the unknown bits are all ones.
668 Max = KnownOne|UnknownBits;
669}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000670
671
672/// SimplifyDemandedBits - Look at V. At this point, we know that only the
673/// DemandedMask bits of the result of V are ever used downstream. If we can
674/// use this information to simplify V, do so and return true. Otherwise,
675/// analyze the expression and return a mask of KnownOne and KnownZero bits for
676/// the expression (used to simplify the caller). The KnownZero/One bits may
677/// only be accurate for those bits in the DemandedMask.
678bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
679 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000680 unsigned Depth) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000681 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
682 // We know all of the bits for a constant!
683 KnownOne = CI->getZExtValue() & DemandedMask;
684 KnownZero = ~KnownOne & DemandedMask;
685 return false;
686 }
687
688 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000689 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000690 if (Depth != 0) { // Not at the root.
691 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
692 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000693 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000694 }
Chris Lattner2590e512006-02-07 06:56:34 +0000695 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000696 // just set the DemandedMask to all bits.
697 DemandedMask = V->getType()->getIntegralTypeMask();
698 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000699 if (V != UndefValue::get(V->getType()))
700 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
701 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000702 } else if (Depth == 6) { // Limit search depth.
703 return false;
704 }
705
706 Instruction *I = dyn_cast<Instruction>(V);
707 if (!I) return false; // Only analyze instructions.
708
Chris Lattner0157e7f2006-02-11 09:31:47 +0000709 uint64_t KnownZero2, KnownOne2;
Chris Lattner2590e512006-02-07 06:56:34 +0000710 switch (I->getOpcode()) {
711 default: break;
712 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000713 // If either the LHS or the RHS are Zero, the result is zero.
714 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
715 KnownZero, KnownOne, Depth+1))
716 return true;
717 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
718
719 // If something is known zero on the RHS, the bits aren't demanded on the
720 // LHS.
721 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
722 KnownZero2, KnownOne2, Depth+1))
723 return true;
724 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
725
726 // If all of the demanded bits are known one on one side, return the other.
727 // These bits cannot contribute to the result of the 'and'.
728 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
729 return UpdateValueUsesWith(I, I->getOperand(0));
730 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
731 return UpdateValueUsesWith(I, I->getOperand(1));
732
733 // If the RHS is a constant, see if we can simplify it.
734 if (ShrinkDemandedConstant(I, 1, DemandedMask))
735 return UpdateValueUsesWith(I, I);
736
737 // Output known-1 bits are only known if set in both the LHS & RHS.
738 KnownOne &= KnownOne2;
739 // Output known-0 are known to be clear if zero in either the LHS | RHS.
740 KnownZero |= KnownZero2;
741 break;
742 case Instruction::Or:
743 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
744 KnownZero, KnownOne, Depth+1))
745 return true;
746 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
747 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
748 KnownZero2, KnownOne2, Depth+1))
749 return true;
750 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
751
752 // If all of the demanded bits are known zero on one side, return the other.
753 // These bits cannot contribute to the result of the 'or'.
754 if ((DemandedMask & ~KnownOne2 & KnownZero) == DemandedMask & ~KnownOne2)
755 return UpdateValueUsesWith(I, I->getOperand(0));
756 if ((DemandedMask & ~KnownOne & KnownZero2) == DemandedMask & ~KnownOne)
757 return UpdateValueUsesWith(I, I->getOperand(1));
758
759 // If the RHS is a constant, see if we can simplify it.
760 if (ShrinkDemandedConstant(I, 1, DemandedMask))
761 return UpdateValueUsesWith(I, I);
762
763 // Output known-0 bits are only known if clear in both the LHS & RHS.
764 KnownZero &= KnownZero2;
765 // Output known-1 are known to be set if set in either the LHS | RHS.
766 KnownOne |= KnownOne2;
767 break;
768 case Instruction::Xor: {
769 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
770 KnownZero, KnownOne, Depth+1))
771 return true;
772 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
773 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
774 KnownZero2, KnownOne2, Depth+1))
775 return true;
776 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
777
778 // If all of the demanded bits are known zero on one side, return the other.
779 // These bits cannot contribute to the result of the 'xor'.
780 if ((DemandedMask & KnownZero) == DemandedMask)
781 return UpdateValueUsesWith(I, I->getOperand(0));
782 if ((DemandedMask & KnownZero2) == DemandedMask)
783 return UpdateValueUsesWith(I, I->getOperand(1));
784
785 // Output known-0 bits are known if clear or set in both the LHS & RHS.
786 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
787 // Output known-1 are known to be set if set in only one of the LHS, RHS.
788 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
789
790 // If all of the unknown bits are known to be zero on one side or the other
791 // (but not both) turn this into an *inclusive* or.
792 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
793 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
794 Instruction *Or =
795 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
796 I->getName());
797 InsertNewInstBefore(Or, *I);
798 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000799 }
800 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000801
802 // If the RHS is a constant, see if we can simplify it.
803 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
804 if (ShrinkDemandedConstant(I, 1, DemandedMask))
805 return UpdateValueUsesWith(I, I);
806
807 KnownZero = KnownZeroOut;
808 KnownOne = KnownOneOut;
809 break;
810 }
811 case Instruction::Select:
812 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
813 KnownZero, KnownOne, Depth+1))
814 return true;
815 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
816 KnownZero2, KnownOne2, Depth+1))
817 return true;
818 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
819 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
820
821 // If the operands are constants, see if we can simplify them.
822 if (ShrinkDemandedConstant(I, 1, DemandedMask))
823 return UpdateValueUsesWith(I, I);
824 if (ShrinkDemandedConstant(I, 2, DemandedMask))
825 return UpdateValueUsesWith(I, I);
826
827 // Only known if known in both the LHS and RHS.
828 KnownOne &= KnownOne2;
829 KnownZero &= KnownZero2;
830 break;
Chris Lattner2590e512006-02-07 06:56:34 +0000831 case Instruction::Cast: {
832 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +0000833 if (!SrcTy->isIntegral()) return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000834
Chris Lattner0157e7f2006-02-11 09:31:47 +0000835 // If this is an integer truncate or noop, just look in the input.
836 if (SrcTy->getPrimitiveSizeInBits() >=
837 I->getType()->getPrimitiveSizeInBits()) {
838 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
839 KnownZero, KnownOne, Depth+1))
840 return true;
841 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
842 break;
843 }
844
845 // Sign or Zero extension. Compute the bits in the result that are not
846 // present in the input.
847 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
848 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
849
850 // Handle zero extension.
851 if (!SrcTy->isSigned()) {
852 DemandedMask &= SrcTy->getIntegralTypeMask();
853 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
854 KnownZero, KnownOne, Depth+1))
855 return true;
856 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
857 // The top bits are known to be zero.
858 KnownZero |= NewBits;
859 } else {
860 // Sign extension.
861 if (SimplifyDemandedBits(I->getOperand(0),
862 DemandedMask & SrcTy->getIntegralTypeMask(),
863 KnownZero, KnownOne, Depth+1))
864 return true;
865 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
866
867 // If the sign bit of the input is known set or clear, then we know the
868 // top bits of the result.
869 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
Chris Lattner2590e512006-02-07 06:56:34 +0000870
Chris Lattner0157e7f2006-02-11 09:31:47 +0000871 // If the input sign bit is known zero, or if the NewBits are not demanded
872 // convert this into a zero extension.
873 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
Chris Lattner2590e512006-02-07 06:56:34 +0000874 // Convert to unsigned first.
Chris Lattner44314822006-02-07 19:07:40 +0000875 Instruction *NewVal;
Chris Lattner2590e512006-02-07 06:56:34 +0000876 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
Chris Lattner44314822006-02-07 19:07:40 +0000877 I->getOperand(0)->getName());
878 InsertNewInstBefore(NewVal, *I);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000879 // Then cast that to the destination type.
Chris Lattner44314822006-02-07 19:07:40 +0000880 NewVal = new CastInst(NewVal, I->getType(), I->getName());
881 InsertNewInstBefore(NewVal, *I);
Chris Lattner2590e512006-02-07 06:56:34 +0000882 return UpdateValueUsesWith(I, NewVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000883 } else if (KnownOne & InSignBit) { // Input sign bit known set
884 KnownOne |= NewBits;
885 KnownZero &= ~NewBits;
886 } else { // Input sign bit unknown
887 KnownZero &= ~NewBits;
888 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +0000889 }
Chris Lattner2590e512006-02-07 06:56:34 +0000890 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000891 break;
Chris Lattner2590e512006-02-07 06:56:34 +0000892 }
Chris Lattner2590e512006-02-07 06:56:34 +0000893 case Instruction::Shl:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000894 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
895 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> SA->getValue(),
896 KnownZero, KnownOne, Depth+1))
897 return true;
898 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
899 KnownZero <<= SA->getValue();
900 KnownOne <<= SA->getValue();
901 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
902 }
Chris Lattner2590e512006-02-07 06:56:34 +0000903 break;
904 case Instruction::Shr:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000905 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
906 unsigned ShAmt = SA->getValue();
907
908 // Compute the new bits that are at the top now.
909 uint64_t HighBits = (1ULL << ShAmt)-1;
910 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShAmt;
911
912 if (I->getType()->isUnsigned()) { // Unsigned shift right.
913 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask << ShAmt,
914 KnownZero, KnownOne, Depth+1))
915 return true;
916 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
917 KnownZero >>= ShAmt;
918 KnownOne >>= ShAmt;
919 KnownZero |= HighBits; // high bits known zero.
920 } else { // Signed shift right.
921 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask << ShAmt,
922 KnownZero, KnownOne, Depth+1))
923 return true;
924 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
925 KnownZero >>= SA->getValue();
926 KnownOne >>= SA->getValue();
927
928 // Handle the sign bits.
929 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
930 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
931
932 // If the input sign bit is known to be zero, or if none of the top bits
933 // are demanded, turn this into an unsigned shift right.
934 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
935 // Convert the input to unsigned.
936 Instruction *NewVal;
937 NewVal = new CastInst(I->getOperand(0),
938 I->getType()->getUnsignedVersion(),
939 I->getOperand(0)->getName());
940 InsertNewInstBefore(NewVal, *I);
941 // Perform the unsigned shift right.
942 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
943 InsertNewInstBefore(NewVal, *I);
944 // Then cast that to the destination type.
945 NewVal = new CastInst(NewVal, I->getType(), I->getName());
946 InsertNewInstBefore(NewVal, *I);
947 return UpdateValueUsesWith(I, NewVal);
948 } else if (KnownOne & SignBit) { // New bits are known one.
949 KnownOne |= HighBits;
950 }
Chris Lattner2590e512006-02-07 06:56:34 +0000951 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000952 }
Chris Lattner2590e512006-02-07 06:56:34 +0000953 break;
954 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000955
956 // If the client is only demanding bits that we know, return the known
957 // constant.
958 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
959 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +0000960 return false;
961}
962
Chris Lattner623826c2004-09-28 21:48:02 +0000963// isTrueWhenEqual - Return true if the specified setcondinst instruction is
964// true when both operands are equal...
965//
966static bool isTrueWhenEqual(Instruction &I) {
967 return I.getOpcode() == Instruction::SetEQ ||
968 I.getOpcode() == Instruction::SetGE ||
969 I.getOpcode() == Instruction::SetLE;
970}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000971
972/// AssociativeOpt - Perform an optimization on an associative operator. This
973/// function is designed to check a chain of associative operators for a
974/// potential to apply a certain optimization. Since the optimization may be
975/// applicable if the expression was reassociated, this checks the chain, then
976/// reassociates the expression as necessary to expose the optimization
977/// opportunity. This makes use of a special Functor, which must define
978/// 'shouldApply' and 'apply' methods.
979///
980template<typename Functor>
981Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
982 unsigned Opcode = Root.getOpcode();
983 Value *LHS = Root.getOperand(0);
984
985 // Quick check, see if the immediate LHS matches...
986 if (F.shouldApply(LHS))
987 return F.apply(Root);
988
989 // Otherwise, if the LHS is not of the same opcode as the root, return.
990 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000991 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000992 // Should we apply this transform to the RHS?
993 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
994
995 // If not to the RHS, check to see if we should apply to the LHS...
996 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
997 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
998 ShouldApply = true;
999 }
1000
1001 // If the functor wants to apply the optimization to the RHS of LHSI,
1002 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1003 if (ShouldApply) {
1004 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001005
Chris Lattnerb8b97502003-08-13 19:01:45 +00001006 // Now all of the instructions are in the current basic block, go ahead
1007 // and perform the reassociation.
1008 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1009
1010 // First move the selected RHS to the LHS of the root...
1011 Root.setOperand(0, LHSI->getOperand(1));
1012
1013 // Make what used to be the LHS of the root be the user of the root...
1014 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001015 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001016 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1017 return 0;
1018 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001019 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001020 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001021 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1022 BasicBlock::iterator ARI = &Root; ++ARI;
1023 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1024 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001025
1026 // Now propagate the ExtraOperand down the chain of instructions until we
1027 // get to LHSI.
1028 while (TmpLHSI != LHSI) {
1029 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001030 // Move the instruction to immediately before the chain we are
1031 // constructing to avoid breaking dominance properties.
1032 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1033 BB->getInstList().insert(ARI, NextLHSI);
1034 ARI = NextLHSI;
1035
Chris Lattnerb8b97502003-08-13 19:01:45 +00001036 Value *NextOp = NextLHSI->getOperand(1);
1037 NextLHSI->setOperand(1, ExtraOperand);
1038 TmpLHSI = NextLHSI;
1039 ExtraOperand = NextOp;
1040 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001041
Chris Lattnerb8b97502003-08-13 19:01:45 +00001042 // Now that the instructions are reassociated, have the functor perform
1043 // the transformation...
1044 return F.apply(Root);
1045 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001046
Chris Lattnerb8b97502003-08-13 19:01:45 +00001047 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1048 }
1049 return 0;
1050}
1051
1052
1053// AddRHS - Implements: X + X --> X << 1
1054struct AddRHS {
1055 Value *RHS;
1056 AddRHS(Value *rhs) : RHS(rhs) {}
1057 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1058 Instruction *apply(BinaryOperator &Add) const {
1059 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1060 ConstantInt::get(Type::UByteTy, 1));
1061 }
1062};
1063
1064// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1065// iff C1&C2 == 0
1066struct AddMaskingAnd {
1067 Constant *C2;
1068 AddMaskingAnd(Constant *c) : C2(c) {}
1069 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001070 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001071 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001072 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001073 }
1074 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001075 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001076 }
1077};
1078
Chris Lattner86102b82005-01-01 16:22:27 +00001079static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001080 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +00001081 if (isa<CastInst>(I)) {
1082 if (Constant *SOC = dyn_cast<Constant>(SO))
1083 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001084
Chris Lattner86102b82005-01-01 16:22:27 +00001085 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1086 SO->getName() + ".cast"), I);
1087 }
1088
Chris Lattner183b3362004-04-09 19:05:30 +00001089 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001090 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1091 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001092
Chris Lattner183b3362004-04-09 19:05:30 +00001093 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1094 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001095 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1096 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001097 }
1098
1099 Value *Op0 = SO, *Op1 = ConstOperand;
1100 if (!ConstIsRHS)
1101 std::swap(Op0, Op1);
1102 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001103 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1104 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1105 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1106 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001107 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001108 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001109 abort();
1110 }
Chris Lattner86102b82005-01-01 16:22:27 +00001111 return IC->InsertNewInstBefore(New, I);
1112}
1113
1114// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1115// constant as the other operand, try to fold the binary operator into the
1116// select arguments. This also works for Cast instructions, which obviously do
1117// not have a second operand.
1118static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1119 InstCombiner *IC) {
1120 // Don't modify shared select instructions
1121 if (!SI->hasOneUse()) return 0;
1122 Value *TV = SI->getOperand(1);
1123 Value *FV = SI->getOperand(2);
1124
1125 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001126 // Bool selects with constant operands can be folded to logical ops.
1127 if (SI->getType() == Type::BoolTy) return 0;
1128
Chris Lattner86102b82005-01-01 16:22:27 +00001129 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1130 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1131
1132 return new SelectInst(SI->getCondition(), SelectTrueVal,
1133 SelectFalseVal);
1134 }
1135 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001136}
1137
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001138
1139/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1140/// node as operand #0, see if we can fold the instruction into the PHI (which
1141/// is only possible if all operands to the PHI are constants).
1142Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1143 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001144 unsigned NumPHIValues = PN->getNumIncomingValues();
1145 if (!PN->hasOneUse() || NumPHIValues == 0 ||
1146 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001147
1148 // Check to see if all of the operands of the PHI are constants. If not, we
1149 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +00001150 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001151 if (!isa<Constant>(PN->getIncomingValue(i)))
1152 return 0;
1153
1154 // Okay, we can do the transformation: create the new PHI node.
1155 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1156 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001157 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001158 InsertNewInstBefore(NewPN, *PN);
1159
1160 // Next, add all of the operands to the PHI.
1161 if (I.getNumOperands() == 2) {
1162 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001163 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001164 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1165 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
1166 PN->getIncomingBlock(i));
1167 }
1168 } else {
1169 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1170 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001171 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001172 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1173 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
1174 PN->getIncomingBlock(i));
1175 }
1176 }
1177 return ReplaceInstUsesWith(I, NewPN);
1178}
1179
Chris Lattner113f4f42002-06-25 16:13:24 +00001180Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001181 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001182 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001183
Chris Lattnercf4a9962004-04-10 22:01:55 +00001184 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001185 // X + undef -> undef
1186 if (isa<UndefValue>(RHS))
1187 return ReplaceInstUsesWith(I, RHS);
1188
Chris Lattnercf4a9962004-04-10 22:01:55 +00001189 // X + 0 --> X
Chris Lattner7fde91e2005-10-17 17:56:38 +00001190 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1191 if (RHSC->isNullValue())
1192 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001193 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1194 if (CFP->isExactlyValue(-0.0))
1195 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001196 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001197
Chris Lattnercf4a9962004-04-10 22:01:55 +00001198 // X + (signbit) --> X ^ signbit
1199 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner92a68652006-02-07 08:05:22 +00001200 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001201 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001202 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +00001203 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001204
1205 if (isa<PHINode>(LHS))
1206 if (Instruction *NV = FoldOpIntoPhi(I))
1207 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001208
Chris Lattner330628a2006-01-06 17:59:59 +00001209 ConstantInt *XorRHS = 0;
1210 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001211 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1212 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1213 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1214 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1215
1216 uint64_t C0080Val = 1ULL << 31;
1217 int64_t CFF80Val = -C0080Val;
1218 unsigned Size = 32;
1219 do {
1220 if (TySizeBits > Size) {
1221 bool Found = false;
1222 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1223 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1224 if (RHSSExt == CFF80Val) {
1225 if (XorRHS->getZExtValue() == C0080Val)
1226 Found = true;
1227 } else if (RHSZExt == C0080Val) {
1228 if (XorRHS->getSExtValue() == CFF80Val)
1229 Found = true;
1230 }
1231 if (Found) {
1232 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001233 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001234 Mask <<= 64-(TySizeBits-Size);
Chris Lattner4534dd592006-02-09 07:38:58 +00001235 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001236 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001237 Size = 0; // Not a sign ext, but can't be any others either.
1238 goto FoundSExt;
1239 }
1240 }
1241 Size >>= 1;
1242 C0080Val >>= Size;
1243 CFF80Val >>= Size;
1244 } while (Size >= 8);
1245
1246FoundSExt:
1247 const Type *MiddleType = 0;
1248 switch (Size) {
1249 default: break;
1250 case 32: MiddleType = Type::IntTy; break;
1251 case 16: MiddleType = Type::ShortTy; break;
1252 case 8: MiddleType = Type::SByteTy; break;
1253 }
1254 if (MiddleType) {
1255 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1256 InsertNewInstBefore(NewTrunc, I);
1257 return new CastInst(NewTrunc, I.getType());
1258 }
1259 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001260 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001261
Chris Lattnerb8b97502003-08-13 19:01:45 +00001262 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001263 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001264 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001265
1266 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1267 if (RHSI->getOpcode() == Instruction::Sub)
1268 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1269 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1270 }
1271 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1272 if (LHSI->getOpcode() == Instruction::Sub)
1273 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1274 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1275 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001276 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001277
Chris Lattner147e9752002-05-08 22:46:53 +00001278 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001279 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001280 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001281
1282 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001283 if (!isa<Constant>(RHS))
1284 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001285 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001286
Misha Brukmanb1c93172005-04-21 23:48:37 +00001287
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001288 ConstantInt *C2;
1289 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1290 if (X == RHS) // X*C + X --> X * (C+1)
1291 return BinaryOperator::createMul(RHS, AddOne(C2));
1292
1293 // X*C1 + X*C2 --> X * (C1+C2)
1294 ConstantInt *C1;
1295 if (X == dyn_castFoldableMul(RHS, C1))
1296 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001297 }
1298
1299 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001300 if (dyn_castFoldableMul(RHS, C2) == LHS)
1301 return BinaryOperator::createMul(LHS, AddOne(C2));
1302
Chris Lattner57c8d992003-02-18 19:57:07 +00001303
Chris Lattnerb8b97502003-08-13 19:01:45 +00001304 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001305 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +00001306 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001307
Chris Lattnerb9cde762003-10-02 15:11:26 +00001308 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001309 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001310 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1311 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1312 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001313 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001314
Chris Lattnerbff91d92004-10-08 05:07:56 +00001315 // (X & FF00) + xx00 -> (X+xx00) & FF00
1316 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1317 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1318 if (Anded == CRHS) {
1319 // See if all bits from the first bit set in the Add RHS up are included
1320 // in the mask. First, get the rightmost bit.
1321 uint64_t AddRHSV = CRHS->getRawValue();
1322
1323 // Form a mask of all bits from the lowest bit added through the top.
1324 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001325 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001326
1327 // See if the and mask includes all of these bits.
1328 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001329
Chris Lattnerbff91d92004-10-08 05:07:56 +00001330 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1331 // Okay, the xform is safe. Insert the new add pronto.
1332 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1333 LHS->getName()), I);
1334 return BinaryOperator::createAnd(NewAdd, C2);
1335 }
1336 }
1337 }
1338
Chris Lattnerd4252a72004-07-30 07:50:03 +00001339 // Try to fold constant add into select arguments.
1340 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001341 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001342 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001343 }
1344
Chris Lattner113f4f42002-06-25 16:13:24 +00001345 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001346}
1347
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001348// isSignBit - Return true if the value represented by the constant only has the
1349// highest order bit set.
1350static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001351 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner2f1457f2005-04-24 17:46:05 +00001352 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001353}
1354
Chris Lattner022167f2004-03-13 00:11:49 +00001355/// RemoveNoopCast - Strip off nonconverting casts from the value.
1356///
1357static Value *RemoveNoopCast(Value *V) {
1358 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1359 const Type *CTy = CI->getType();
1360 const Type *OpTy = CI->getOperand(0)->getType();
1361 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001362 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001363 return RemoveNoopCast(CI->getOperand(0));
1364 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1365 return RemoveNoopCast(CI->getOperand(0));
1366 }
1367 return V;
1368}
1369
Chris Lattner113f4f42002-06-25 16:13:24 +00001370Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001371 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001372
Chris Lattnere6794492002-08-12 21:17:25 +00001373 if (Op0 == Op1) // sub X, X -> 0
1374 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001375
Chris Lattnere6794492002-08-12 21:17:25 +00001376 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001377 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001378 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001379
Chris Lattner81a7a232004-10-16 18:11:37 +00001380 if (isa<UndefValue>(Op0))
1381 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1382 if (isa<UndefValue>(Op1))
1383 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1384
Chris Lattner8f2f5982003-11-05 01:06:05 +00001385 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1386 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001387 if (C->isAllOnesValue())
1388 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001389
Chris Lattner8f2f5982003-11-05 01:06:05 +00001390 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001391 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001392 if (match(Op1, m_Not(m_Value(X))))
1393 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001394 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001395 // -((uint)X >> 31) -> ((int)X >> 31)
1396 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001397 if (C->isNullValue()) {
1398 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1399 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +00001400 if (SI->getOpcode() == Instruction::Shr)
1401 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1402 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +00001403 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +00001404 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001405 else
Chris Lattner97bfcea2004-06-17 18:16:02 +00001406 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001407 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001408 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +00001409 // Ok, the transformation is safe. Insert a cast of the incoming
1410 // value, then the new shift, then the new cast.
1411 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1412 SI->getOperand(0)->getName());
1413 Value *InV = InsertNewInstBefore(FirstCast, I);
1414 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1415 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +00001416 if (NewShift->getType() == I.getType())
1417 return NewShift;
1418 else {
1419 InV = InsertNewInstBefore(NewShift, I);
1420 return new CastInst(NewShift, I.getType());
1421 }
Chris Lattner92295c52004-03-12 23:53:13 +00001422 }
1423 }
Chris Lattner022167f2004-03-13 00:11:49 +00001424 }
Chris Lattner183b3362004-04-09 19:05:30 +00001425
1426 // Try to fold constant sub into select arguments.
1427 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001428 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001429 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001430
1431 if (isa<PHINode>(Op0))
1432 if (Instruction *NV = FoldOpIntoPhi(I))
1433 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001434 }
1435
Chris Lattnera9be4492005-04-07 16:15:25 +00001436 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1437 if (Op1I->getOpcode() == Instruction::Add &&
1438 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001439 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001440 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001441 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001442 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001443 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1444 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1445 // C1-(X+C2) --> (C1-C2)-X
1446 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1447 Op1I->getOperand(0));
1448 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001449 }
1450
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001451 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001452 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1453 // is not used by anyone else...
1454 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00001455 if (Op1I->getOpcode() == Instruction::Sub &&
1456 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001457 // Swap the two operands of the subexpr...
1458 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1459 Op1I->setOperand(0, IIOp1);
1460 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001461
Chris Lattner3082c5a2003-02-18 19:28:33 +00001462 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001463 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001464 }
1465
1466 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1467 //
1468 if (Op1I->getOpcode() == Instruction::And &&
1469 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1470 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1471
Chris Lattner396dbfe2004-06-09 05:08:07 +00001472 Value *NewNot =
1473 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001474 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001475 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001476
Chris Lattner0aee4b72004-10-06 15:08:25 +00001477 // -(X sdiv C) -> (X sdiv -C)
1478 if (Op1I->getOpcode() == Instruction::Div)
1479 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattnera9be4492005-04-07 16:15:25 +00001480 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00001481 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001482 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00001483 ConstantExpr::getNeg(DivRHS));
1484
Chris Lattner57c8d992003-02-18 19:57:07 +00001485 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001486 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001487 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001488 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001489 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001490 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00001491 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00001492 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001493 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001494
Chris Lattner47060462005-04-07 17:14:51 +00001495 if (!Op0->getType()->isFloatingPoint())
1496 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1497 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00001498 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1499 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1500 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1501 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00001502 } else if (Op0I->getOpcode() == Instruction::Sub) {
1503 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1504 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00001505 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001506
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001507 ConstantInt *C1;
1508 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1509 if (X == Op1) { // X*C - X --> X * (C-1)
1510 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1511 return BinaryOperator::createMul(Op1, CP1);
1512 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001513
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001514 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1515 if (X == dyn_castFoldableMul(Op1, C2))
1516 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1517 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001518 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001519}
1520
Chris Lattnere79e8542004-02-23 06:38:22 +00001521/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1522/// really just returns true if the most significant (sign) bit is set.
1523static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1524 if (RHS->getType()->isSigned()) {
1525 // True if source is LHS < 0 or LHS <= -1
1526 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1527 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1528 } else {
1529 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1530 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1531 // the size of the integer type.
1532 if (Opcode == Instruction::SetGE)
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001533 return RHSC->getValue() ==
1534 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001535 if (Opcode == Instruction::SetGT)
1536 return RHSC->getValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001537 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00001538 }
1539 return false;
1540}
1541
Chris Lattner113f4f42002-06-25 16:13:24 +00001542Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001543 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001544 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00001545
Chris Lattner81a7a232004-10-16 18:11:37 +00001546 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1547 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1548
Chris Lattnere6794492002-08-12 21:17:25 +00001549 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001550 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1551 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00001552
1553 // ((X << C1)*C2) == (X * (C2 << C1))
1554 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1555 if (SI->getOpcode() == Instruction::Shl)
1556 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001557 return BinaryOperator::createMul(SI->getOperand(0),
1558 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001559
Chris Lattnercce81be2003-09-11 22:24:54 +00001560 if (CI->isNullValue())
1561 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1562 if (CI->equalsInt(1)) // X * 1 == X
1563 return ReplaceInstUsesWith(I, Op0);
1564 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00001565 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00001566
Chris Lattnercce81be2003-09-11 22:24:54 +00001567 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001568 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1569 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001570 return new ShiftInst(Instruction::Shl, Op0,
1571 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001572 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001573 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001574 if (Op1F->isNullValue())
1575 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00001576
Chris Lattner3082c5a2003-02-18 19:28:33 +00001577 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1578 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1579 if (Op1F->getValue() == 1.0)
1580 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1581 }
Chris Lattner183b3362004-04-09 19:05:30 +00001582
1583 // Try to fold constant mul into select arguments.
1584 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001585 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001586 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001587
1588 if (isa<PHINode>(Op0))
1589 if (Instruction *NV = FoldOpIntoPhi(I))
1590 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00001591 }
1592
Chris Lattner934a64cf2003-03-10 23:23:04 +00001593 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1594 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001595 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00001596
Chris Lattner2635b522004-02-23 05:39:21 +00001597 // If one of the operands of the multiply is a cast from a boolean value, then
1598 // we know the bool is either zero or one, so this is a 'masking' multiply.
1599 // See if we can simplify things based on how the boolean was originally
1600 // formed.
1601 CastInst *BoolCast = 0;
1602 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1603 if (CI->getOperand(0)->getType() == Type::BoolTy)
1604 BoolCast = CI;
1605 if (!BoolCast)
1606 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1607 if (CI->getOperand(0)->getType() == Type::BoolTy)
1608 BoolCast = CI;
1609 if (BoolCast) {
1610 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1611 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1612 const Type *SCOpTy = SCIOp0->getType();
1613
Chris Lattnere79e8542004-02-23 06:38:22 +00001614 // If the setcc is true iff the sign bit of X is set, then convert this
1615 // multiply into a shift/and combination.
1616 if (isa<ConstantInt>(SCIOp1) &&
1617 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00001618 // Shift the X value right to turn it into "all signbits".
1619 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001620 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001621 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00001622 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +00001623 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1624 SCIOp0->getName()), I);
1625 }
1626
1627 Value *V =
1628 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1629 BoolCast->getOperand(0)->getName()+
1630 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00001631
1632 // If the multiply type is not the same as the source type, sign extend
1633 // or truncate to the multiply type.
1634 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +00001635 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001636
Chris Lattner2635b522004-02-23 05:39:21 +00001637 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001638 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00001639 }
1640 }
1641 }
1642
Chris Lattner113f4f42002-06-25 16:13:24 +00001643 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001644}
1645
Chris Lattner113f4f42002-06-25 16:13:24 +00001646Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001647 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00001648
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001649 if (isa<UndefValue>(Op0)) // undef / X -> 0
1650 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1651 if (isa<UndefValue>(Op1))
1652 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1653
1654 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00001655 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001656 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001657 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001658
Chris Lattnere20c3342004-04-26 14:01:59 +00001659 // div X, -1 == -X
1660 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001661 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00001662
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001663 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001664 if (LHS->getOpcode() == Instruction::Div)
1665 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001666 // (X / C1) / C2 -> X / (C1*C2)
1667 return BinaryOperator::createDiv(LHS->getOperand(0),
1668 ConstantExpr::getMul(RHS, LHSRHS));
1669 }
1670
Chris Lattner3082c5a2003-02-18 19:28:33 +00001671 // Check to see if this is an unsigned division with an exact power of 2,
1672 // if so, convert to a right shift.
1673 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1674 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattner22d00a82005-08-02 19:16:58 +00001675 if (isPowerOf2_64(Val)) {
1676 uint64_t C = Log2_64(Val);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001677 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001678 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001679 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001680
Chris Lattner4ad08352004-10-09 02:50:40 +00001681 // -X/C -> X/-C
1682 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001683 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001684 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1685
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001686 if (!RHS->isNullValue()) {
1687 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001688 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001689 return R;
1690 if (isa<PHINode>(Op0))
1691 if (Instruction *NV = FoldOpIntoPhi(I))
1692 return NV;
1693 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001694 }
1695
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001696 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1697 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1698 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1699 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1700 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1701 if (STO->getValue() == 0) { // Couldn't be this argument.
1702 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001703 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001704 } else if (SFO->getValue() == 0) {
Chris Lattner89dc4f12005-06-16 04:55:52 +00001705 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001706 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001707 }
1708
Chris Lattner42362612005-04-08 04:03:26 +00001709 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001710 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1711 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattner42362612005-04-08 04:03:26 +00001712 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1713 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1714 TC, SI->getName()+".t");
1715 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001716
Chris Lattner42362612005-04-08 04:03:26 +00001717 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1718 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1719 FC, SI->getName()+".f");
1720 FSI = InsertNewInstBefore(FSI, I);
1721 return new SelectInst(SI->getOperand(0), TSI, FSI);
1722 }
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001723 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001724
Chris Lattner3082c5a2003-02-18 19:28:33 +00001725 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001726 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001727 if (LHS->equalsInt(0))
1728 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1729
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001730 if (I.getType()->isSigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001731 // If the sign bits of both operands are zero (i.e. we can prove they are
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001732 // unsigned inputs), turn this into a udiv.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001733 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1734 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001735 const Type *NTy = Op0->getType()->getUnsignedVersion();
1736 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1737 InsertNewInstBefore(LHS, I);
1738 Value *RHS;
1739 if (Constant *R = dyn_cast<Constant>(Op1))
1740 RHS = ConstantExpr::getCast(R, NTy);
1741 else
1742 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1743 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1744 InsertNewInstBefore(Div, I);
1745 return new CastInst(Div, I.getType());
1746 }
Chris Lattner2e90b732006-02-05 07:54:04 +00001747 } else {
1748 // Known to be an unsigned division.
1749 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1750 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
1751 if (RHSI->getOpcode() == Instruction::Shl &&
1752 isa<ConstantUInt>(RHSI->getOperand(0))) {
1753 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1754 if (isPowerOf2_64(C1)) {
1755 unsigned C2 = Log2_64(C1);
1756 Value *Add = RHSI->getOperand(1);
1757 if (C2) {
1758 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
1759 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
1760 "tmp"), I);
1761 }
1762 return new ShiftInst(Instruction::Shr, Op0, Add);
1763 }
1764 }
1765 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001766 }
1767
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001768 return 0;
1769}
1770
1771
Chris Lattner113f4f42002-06-25 16:13:24 +00001772Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001773 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001774 if (I.getType()->isSigned()) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001775 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00001776 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00001777 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001778 // X % -Y -> X % Y
1779 AddUsesToWorkList(I);
1780 I.setOperand(1, RHSNeg);
1781 return &I;
1782 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001783
1784 // If the top bits of both operands are zero (i.e. we can prove they are
1785 // unsigned inputs), turn this into a urem.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001786 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1787 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001788 const Type *NTy = Op0->getType()->getUnsignedVersion();
1789 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1790 InsertNewInstBefore(LHS, I);
1791 Value *RHS;
1792 if (Constant *R = dyn_cast<Constant>(Op1))
1793 RHS = ConstantExpr::getCast(R, NTy);
1794 else
1795 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1796 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
1797 InsertNewInstBefore(Rem, I);
1798 return new CastInst(Rem, I.getType());
1799 }
1800 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00001801
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001802 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00001803 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001804 if (isa<UndefValue>(Op1))
1805 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattner81a7a232004-10-16 18:11:37 +00001806
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001807 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001808 if (RHS->equalsInt(1)) // X % 1 == 0
1809 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1810
1811 // Check to see if this is an unsigned remainder with an exact power of 2,
1812 // if so, convert to a bitwise and.
1813 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1814 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +00001815 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001816 return BinaryOperator::createAnd(Op0,
1817 ConstantUInt::get(I.getType(), Val-1));
1818
1819 if (!RHS->isNullValue()) {
1820 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001821 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001822 return R;
1823 if (isa<PHINode>(Op0))
1824 if (Instruction *NV = FoldOpIntoPhi(I))
1825 return NV;
1826 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001827 }
1828
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001829 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1830 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1831 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1832 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1833 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1834 if (STO->getValue() == 0) { // Couldn't be this argument.
1835 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001836 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001837 } else if (SFO->getValue() == 0) {
1838 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001839 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001840 }
1841
1842 if (!(STO->getValue() & (STO->getValue()-1)) &&
1843 !(SFO->getValue() & (SFO->getValue()-1))) {
1844 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1845 SubOne(STO), SI->getName()+".t"), I);
1846 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1847 SubOne(SFO), SI->getName()+".f"), I);
1848 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1849 }
1850 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001851
Chris Lattner3082c5a2003-02-18 19:28:33 +00001852 // 0 % X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001853 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001854 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +00001855 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1856
Chris Lattner2e90b732006-02-05 07:54:04 +00001857
1858 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1859 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
1860 if (I.getType()->isUnsigned() &&
1861 RHSI->getOpcode() == Instruction::Shl &&
1862 isa<ConstantUInt>(RHSI->getOperand(0))) {
1863 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1864 if (isPowerOf2_64(C1)) {
1865 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
1866 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
1867 "tmp"), I);
1868 return BinaryOperator::createAnd(Op0, Add);
1869 }
1870 }
1871 }
1872
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001873 return 0;
1874}
1875
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001876// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001877static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner77defba2006-02-07 07:00:41 +00001878 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1879 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001880
1881 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001882
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001883 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001884 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001885 int64_t Val = INT64_MAX; // All ones
1886 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1887 return CS->getValue() == Val-1;
1888}
1889
1890// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001891static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001892 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1893 return CU->getValue() == 1;
1894
1895 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001896
1897 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001898 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001899 int64_t Val = -1; // All ones
1900 Val <<= TypeBits-1; // Shift over to the right spot
1901 return CS->getValue() == Val+1;
1902}
1903
Chris Lattner35167c32004-06-09 07:59:58 +00001904// isOneBitSet - Return true if there is exactly one bit set in the specified
1905// constant.
1906static bool isOneBitSet(const ConstantInt *CI) {
1907 uint64_t V = CI->getRawValue();
1908 return V && (V & (V-1)) == 0;
1909}
1910
Chris Lattner8fc5af42004-09-23 21:46:38 +00001911#if 0 // Currently unused
1912// isLowOnes - Return true if the constant is of the form 0+1+.
1913static bool isLowOnes(const ConstantInt *CI) {
1914 uint64_t V = CI->getRawValue();
1915
1916 // There won't be bits set in parts that the type doesn't contain.
1917 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1918
1919 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1920 return U && V && (U & V) == 0;
1921}
1922#endif
1923
1924// isHighOnes - Return true if the constant is of the form 1+0+.
1925// This is the same as lowones(~X).
1926static bool isHighOnes(const ConstantInt *CI) {
1927 uint64_t V = ~CI->getRawValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00001928 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00001929
1930 // There won't be bits set in parts that the type doesn't contain.
1931 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1932
1933 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1934 return U && V && (U & V) == 0;
1935}
1936
1937
Chris Lattner3ac7c262003-08-13 20:16:26 +00001938/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1939/// are carefully arranged to allow folding of expressions such as:
1940///
1941/// (A < B) | (A > B) --> (A != B)
1942///
1943/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1944/// represents that the comparison is true if A == B, and bit value '1' is true
1945/// if A < B.
1946///
1947static unsigned getSetCondCode(const SetCondInst *SCI) {
1948 switch (SCI->getOpcode()) {
1949 // False -> 0
1950 case Instruction::SetGT: return 1;
1951 case Instruction::SetEQ: return 2;
1952 case Instruction::SetGE: return 3;
1953 case Instruction::SetLT: return 4;
1954 case Instruction::SetNE: return 5;
1955 case Instruction::SetLE: return 6;
1956 // True -> 7
1957 default:
1958 assert(0 && "Invalid SetCC opcode!");
1959 return 0;
1960 }
1961}
1962
1963/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1964/// opcode and two operands into either a constant true or false, or a brand new
1965/// SetCC instruction.
1966static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1967 switch (Opcode) {
1968 case 0: return ConstantBool::False;
1969 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1970 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1971 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1972 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1973 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1974 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1975 case 7: return ConstantBool::True;
1976 default: assert(0 && "Illegal SetCCCode!"); return 0;
1977 }
1978}
1979
1980// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1981struct FoldSetCCLogical {
1982 InstCombiner &IC;
1983 Value *LHS, *RHS;
1984 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1985 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1986 bool shouldApply(Value *V) const {
1987 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1988 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1989 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1990 return false;
1991 }
1992 Instruction *apply(BinaryOperator &Log) const {
1993 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1994 if (SCI->getOperand(0) != LHS) {
1995 assert(SCI->getOperand(1) == LHS);
1996 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1997 }
1998
1999 unsigned LHSCode = getSetCondCode(SCI);
2000 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2001 unsigned Code;
2002 switch (Log.getOpcode()) {
2003 case Instruction::And: Code = LHSCode & RHSCode; break;
2004 case Instruction::Or: Code = LHSCode | RHSCode; break;
2005 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002006 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002007 }
2008
2009 Value *RV = getSetCCValue(Code, LHS, RHS);
2010 if (Instruction *I = dyn_cast<Instruction>(RV))
2011 return I;
2012 // Otherwise, it's a constant boolean value...
2013 return IC.ReplaceInstUsesWith(Log, RV);
2014 }
2015};
2016
Chris Lattnerba1cb382003-09-19 17:17:26 +00002017// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2018// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2019// guaranteed to be either a shift instruction or a binary operator.
2020Instruction *InstCombiner::OptAndOp(Instruction *Op,
2021 ConstantIntegral *OpRHS,
2022 ConstantIntegral *AndRHS,
2023 BinaryOperator &TheAnd) {
2024 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002025 Constant *Together = 0;
2026 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002027 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002028
Chris Lattnerba1cb382003-09-19 17:17:26 +00002029 switch (Op->getOpcode()) {
2030 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002031 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002032 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2033 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002034 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002035 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002036 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002037 }
2038 break;
2039 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002040 if (Together == AndRHS) // (X | C) & C --> C
2041 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002042
Chris Lattner86102b82005-01-01 16:22:27 +00002043 if (Op->hasOneUse() && Together != OpRHS) {
2044 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2045 std::string Op0Name = Op->getName(); Op->setName("");
2046 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2047 InsertNewInstBefore(Or, TheAnd);
2048 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002049 }
2050 break;
2051 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002052 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002053 // Adding a one to a single bit bit-field should be turned into an XOR
2054 // of the bit. First thing to check is to see if this AND is with a
2055 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00002056 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002057
2058 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002059 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002060
2061 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002062 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002063 // Ok, at this point, we know that we are masking the result of the
2064 // ADD down to exactly one bit. If the constant we are adding has
2065 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00002066 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002067
Chris Lattnerba1cb382003-09-19 17:17:26 +00002068 // Check to see if any bits below the one bit set in AndRHSV are set.
2069 if ((AddRHS & (AndRHSV-1)) == 0) {
2070 // If not, the only thing that can effect the output of the AND is
2071 // the bit specified by AndRHSV. If that bit is set, the effect of
2072 // the XOR is to toggle the bit. If it is clear, then the ADD has
2073 // no effect.
2074 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2075 TheAnd.setOperand(0, X);
2076 return &TheAnd;
2077 } else {
2078 std::string Name = Op->getName(); Op->setName("");
2079 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002080 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002081 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002082 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002083 }
2084 }
2085 }
2086 }
2087 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002088
2089 case Instruction::Shl: {
2090 // We know that the AND will not produce any of the bits shifted in, so if
2091 // the anded constant includes them, clear them now!
2092 //
2093 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002094 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2095 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002096
Chris Lattner7e794272004-09-24 15:21:34 +00002097 if (CI == ShlMask) { // Masking out bits that the shift already masks
2098 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2099 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002100 TheAnd.setOperand(1, CI);
2101 return &TheAnd;
2102 }
2103 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002104 }
Chris Lattner2da29172003-09-19 19:05:02 +00002105 case Instruction::Shr:
2106 // We know that the AND will not produce any of the bits shifted in, so if
2107 // the anded constant includes them, clear them now! This only applies to
2108 // unsigned shifts, because a signed shr may bring in set bits!
2109 //
2110 if (AndRHS->getType()->isUnsigned()) {
2111 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002112 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2113 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2114
2115 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2116 return ReplaceInstUsesWith(TheAnd, Op);
2117 } else if (CI != AndRHS) {
2118 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00002119 return &TheAnd;
2120 }
Chris Lattner7e794272004-09-24 15:21:34 +00002121 } else { // Signed shr.
2122 // See if this is shifting in some sign extension, then masking it out
2123 // with an and.
2124 if (Op->hasOneUse()) {
2125 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2126 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2127 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00002128 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00002129 // Make the argument unsigned.
2130 Value *ShVal = Op->getOperand(0);
2131 ShVal = InsertCastBefore(ShVal,
2132 ShVal->getType()->getUnsignedVersion(),
2133 TheAnd);
2134 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2135 OpRHS, Op->getName()),
2136 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00002137 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2138 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2139 TheAnd.getName()),
2140 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00002141 return new CastInst(ShVal, Op->getType());
2142 }
2143 }
Chris Lattner2da29172003-09-19 19:05:02 +00002144 }
2145 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002146 }
2147 return 0;
2148}
2149
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002150
Chris Lattner6862fbd2004-09-29 17:40:11 +00002151/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2152/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2153/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2154/// insert new instructions.
2155Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2156 bool Inside, Instruction &IB) {
2157 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2158 "Lo is not <= Hi in range emission code!");
2159 if (Inside) {
2160 if (Lo == Hi) // Trivially false.
2161 return new SetCondInst(Instruction::SetNE, V, V);
2162 if (cast<ConstantIntegral>(Lo)->isMinValue())
2163 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002164
Chris Lattner6862fbd2004-09-29 17:40:11 +00002165 Constant *AddCST = ConstantExpr::getNeg(Lo);
2166 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2167 InsertNewInstBefore(Add, IB);
2168 // Convert to unsigned for the comparison.
2169 const Type *UnsType = Add->getType()->getUnsignedVersion();
2170 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2171 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2172 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2173 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2174 }
2175
2176 if (Lo == Hi) // Trivially true.
2177 return new SetCondInst(Instruction::SetEQ, V, V);
2178
2179 Hi = SubOne(cast<ConstantInt>(Hi));
2180 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
2181 return new SetCondInst(Instruction::SetGT, V, Hi);
2182
2183 // Emit X-Lo > Hi-Lo-1
2184 Constant *AddCST = ConstantExpr::getNeg(Lo);
2185 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2186 InsertNewInstBefore(Add, IB);
2187 // Convert to unsigned for the comparison.
2188 const Type *UnsType = Add->getType()->getUnsignedVersion();
2189 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2190 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2191 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2192 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2193}
2194
Chris Lattnerb4b25302005-09-18 07:22:02 +00002195// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2196// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2197// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2198// not, since all 1s are not contiguous.
2199static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2200 uint64_t V = Val->getRawValue();
2201 if (!isShiftedMask_64(V)) return false;
2202
2203 // look for the first zero bit after the run of ones
2204 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2205 // look for the first non-zero bit
2206 ME = 64-CountLeadingZeros_64(V);
2207 return true;
2208}
2209
2210
2211
2212/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2213/// where isSub determines whether the operator is a sub. If we can fold one of
2214/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00002215///
2216/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2217/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2218/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2219///
2220/// return (A +/- B).
2221///
2222Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2223 ConstantIntegral *Mask, bool isSub,
2224 Instruction &I) {
2225 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2226 if (!LHSI || LHSI->getNumOperands() != 2 ||
2227 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2228
2229 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2230
2231 switch (LHSI->getOpcode()) {
2232 default: return 0;
2233 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002234 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2235 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2236 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
2237 break;
2238
2239 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2240 // part, we don't need any explicit masks to take them out of A. If that
2241 // is all N is, ignore it.
2242 unsigned MB, ME;
2243 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002244 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2245 Mask >>= 64-MB+1;
2246 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00002247 break;
2248 }
2249 }
Chris Lattneraf517572005-09-18 04:24:45 +00002250 return 0;
2251 case Instruction::Or:
2252 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002253 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2254 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
2255 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00002256 break;
2257 return 0;
2258 }
2259
2260 Instruction *New;
2261 if (isSub)
2262 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2263 else
2264 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2265 return InsertNewInstBefore(New, I);
2266}
2267
Chris Lattner113f4f42002-06-25 16:13:24 +00002268Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002269 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002270 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002271
Chris Lattner81a7a232004-10-16 18:11:37 +00002272 if (isa<UndefValue>(Op1)) // X & undef -> 0
2273 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2274
Chris Lattner86102b82005-01-01 16:22:27 +00002275 // and X, X = X
2276 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00002277 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002278
Chris Lattner5997cf92006-02-08 03:25:32 +00002279 // See if we can simplify any instructions used by the LHS whose sole
2280 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00002281 uint64_t KnownZero, KnownOne;
2282 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2283 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00002284 return &I;
2285
Chris Lattner86102b82005-01-01 16:22:27 +00002286 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002287 uint64_t AndRHSMask = AndRHS->getZExtValue();
2288 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
2289
2290 if (AndRHSMask == TypeMask) // and X, -1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00002291 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002292 else if (AndRHSMask == 0) // and X, 0 == 0
2293 return ReplaceInstUsesWith(I, AndRHS);
Chris Lattner38a1b002005-10-26 17:18:16 +00002294
2295 // and (and X, c1), c2 -> and (x, c1&c2). Handle this case here, before
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002296 // calling ComputeMaskedNonZeroBits, to avoid inefficient cases where we
2297 // traipse through many levels of ands.
Chris Lattner38a1b002005-10-26 17:18:16 +00002298 {
Chris Lattner330628a2006-01-06 17:59:59 +00002299 Value *X = 0; ConstantInt *C1 = 0;
Chris Lattner38a1b002005-10-26 17:18:16 +00002300 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))))
2301 return BinaryOperator::createAnd(X, ConstantExpr::getAnd(C1, AndRHS));
2302 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002303
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002304 // Figure out which of the input bits are not known to be zero, and which
2305 // bits are known to be zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00002306 uint64_t KnownZeroBits, KnownOneBits;
2307 ComputeMaskedBits(Op0, TypeMask, KnownZeroBits, KnownOneBits);
Chris Lattner86102b82005-01-01 16:22:27 +00002308
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002309 // If the mask is not masking out any bits (i.e. all of the zeros in the
2310 // mask are already known to be zero), there is no reason to do the and in
2311 // the first place.
2312 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner4534dd592006-02-09 07:38:58 +00002313 if ((NotAndRHS & KnownZeroBits) == NotAndRHS)
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002314 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002315
Chris Lattner4534dd592006-02-09 07:38:58 +00002316 // If the AND'd bits are all known, turn this AND into a constant.
2317 if ((AndRHSMask & (KnownOneBits|KnownZeroBits)) == AndRHSMask) {
2318 Constant *NewRHS = ConstantUInt::get(Type::ULongTy,
2319 AndRHSMask & KnownOneBits);
2320 return ReplaceInstUsesWith(I, ConstantExpr::getCast(NewRHS, I.getType()));
2321 }
2322
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002323 // If the AND mask contains bits that are known zero, remove them. A
2324 // special case is when there are no bits in common, in which case we
2325 // implicitly turn this into an AND X, 0, which is later simplified into 0.
Chris Lattner4534dd592006-02-09 07:38:58 +00002326 if ((AndRHSMask & ~KnownZeroBits) != AndRHSMask) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002327 Constant *NewRHS =
Chris Lattner4534dd592006-02-09 07:38:58 +00002328 ConstantUInt::get(Type::ULongTy, AndRHSMask & ~KnownZeroBits);
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002329 I.setOperand(1, ConstantExpr::getCast(NewRHS, I.getType()));
2330 return &I;
2331 }
Chris Lattner86102b82005-01-01 16:22:27 +00002332
Chris Lattnerba1cb382003-09-19 17:17:26 +00002333 // Optimize a variety of ((val OP C1) & C2) combinations...
2334 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2335 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00002336 Value *Op0LHS = Op0I->getOperand(0);
2337 Value *Op0RHS = Op0I->getOperand(1);
2338 switch (Op0I->getOpcode()) {
2339 case Instruction::Xor:
2340 case Instruction::Or:
2341 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
2342 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002343 if (MaskedValueIsZero(Op0LHS, AndRHSMask))
Misha Brukmanb1c93172005-04-21 23:48:37 +00002344 return BinaryOperator::createAnd(Op0RHS, AndRHS);
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002345 if (MaskedValueIsZero(Op0RHS, AndRHSMask))
Misha Brukmanb1c93172005-04-21 23:48:37 +00002346 return BinaryOperator::createAnd(Op0LHS, AndRHS);
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002347
2348 // If the mask is only needed on one incoming arm, push it up.
2349 if (Op0I->hasOneUse()) {
2350 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2351 // Not masking anything out for the LHS, move to RHS.
2352 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2353 Op0RHS->getName()+".masked");
2354 InsertNewInstBefore(NewRHS, I);
2355 return BinaryOperator::create(
2356 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002357 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002358 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002359 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2360 // Not masking anything out for the RHS, move to LHS.
2361 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2362 Op0LHS->getName()+".masked");
2363 InsertNewInstBefore(NewLHS, I);
2364 return BinaryOperator::create(
2365 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2366 }
2367 }
2368
Chris Lattner86102b82005-01-01 16:22:27 +00002369 break;
2370 case Instruction::And:
2371 // (X & V) & C2 --> 0 iff (V & C2) == 0
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002372 if (MaskedValueIsZero(Op0LHS, AndRHSMask) ||
2373 MaskedValueIsZero(Op0RHS, AndRHSMask))
Chris Lattner86102b82005-01-01 16:22:27 +00002374 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2375 break;
Chris Lattneraf517572005-09-18 04:24:45 +00002376 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002377 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2378 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2379 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2380 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2381 return BinaryOperator::createAnd(V, AndRHS);
2382 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2383 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00002384 break;
2385
2386 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002387 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2388 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2389 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2390 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2391 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00002392 break;
Chris Lattner86102b82005-01-01 16:22:27 +00002393 }
2394
Chris Lattner16464b32003-07-23 19:25:52 +00002395 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00002396 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00002397 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00002398 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2399 const Type *SrcTy = CI->getOperand(0)->getType();
2400
Chris Lattner2c14cf72005-08-07 07:03:10 +00002401 // If this is an integer truncation or change from signed-to-unsigned, and
2402 // if the source is an and/or with immediate, transform it. This
2403 // frequently occurs for bitfield accesses.
2404 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2405 if (SrcTy->getPrimitiveSizeInBits() >=
2406 I.getType()->getPrimitiveSizeInBits() &&
2407 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002408 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00002409 if (CastOp->getOpcode() == Instruction::And) {
2410 // Change: and (cast (and X, C1) to T), C2
2411 // into : and (cast X to T), trunc(C1)&C2
2412 // This will folds the two ands together, which may allow other
2413 // simplifications.
2414 Instruction *NewCast =
2415 new CastInst(CastOp->getOperand(0), I.getType(),
2416 CastOp->getName()+".shrunk");
2417 NewCast = InsertNewInstBefore(NewCast, I);
2418
2419 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2420 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2421 return BinaryOperator::createAnd(NewCast, C3);
2422 } else if (CastOp->getOpcode() == Instruction::Or) {
2423 // Change: and (cast (or X, C1) to T), C2
2424 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2425 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2426 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2427 return ReplaceInstUsesWith(I, AndRHS);
2428 }
2429 }
2430
2431
Chris Lattner86102b82005-01-01 16:22:27 +00002432 // If this is an integer sign or zero extension instruction.
2433 if (SrcTy->isIntegral() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002434 SrcTy->getPrimitiveSizeInBits() <
2435 CI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner86102b82005-01-01 16:22:27 +00002436
2437 if (SrcTy->isUnsigned()) {
2438 // See if this and is clearing out bits that are known to be zero
2439 // anyway (due to the zero extension).
2440 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
2441 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
2442 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
2443 if (Result == Mask) // The "and" isn't doing anything, remove it.
2444 return ReplaceInstUsesWith(I, CI);
2445 if (Result != AndRHS) { // Reduce the and RHS constant.
2446 I.setOperand(1, Result);
2447 return &I;
2448 }
2449
2450 } else {
2451 if (CI->hasOneUse() && SrcTy->isInteger()) {
2452 // We can only do this if all of the sign bits brought in are masked
2453 // out. Compute this by first getting 0000011111, then inverting
2454 // it.
2455 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
2456 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
2457 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
2458 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
2459 // If the and is clearing all of the sign bits, change this to a
2460 // zero extension cast. To do this, cast the cast input to
2461 // unsigned, then to the requested size.
2462 Value *CastOp = CI->getOperand(0);
2463 Instruction *NC =
2464 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
2465 CI->getName()+".uns");
2466 NC = InsertNewInstBefore(NC, I);
2467 // Finally, insert a replacement for CI.
2468 NC = new CastInst(NC, CI->getType(), CI->getName());
2469 CI->setName("");
2470 NC = InsertNewInstBefore(NC, I);
2471 WorkList.push_back(CI); // Delete CI later.
2472 I.setOperand(0, NC);
2473 return &I; // The AND operand was modified.
2474 }
2475 }
2476 }
2477 }
Chris Lattner33217db2003-07-23 19:36:21 +00002478 }
Chris Lattner183b3362004-04-09 19:05:30 +00002479
2480 // Try to fold constant and into select arguments.
2481 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002482 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002483 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002484 if (isa<PHINode>(Op0))
2485 if (Instruction *NV = FoldOpIntoPhi(I))
2486 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00002487 }
2488
Chris Lattnerbb74e222003-03-10 23:06:50 +00002489 Value *Op0NotVal = dyn_castNotVal(Op0);
2490 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002491
Chris Lattner023a4832004-06-18 06:07:51 +00002492 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2493 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2494
Misha Brukman9c003d82004-07-30 12:50:08 +00002495 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00002496 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002497 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2498 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00002499 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002500 return BinaryOperator::createNot(Or);
2501 }
2502
Chris Lattner623826c2004-09-28 21:48:02 +00002503 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2504 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002505 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2506 return R;
2507
Chris Lattner623826c2004-09-28 21:48:02 +00002508 Value *LHSVal, *RHSVal;
2509 ConstantInt *LHSCst, *RHSCst;
2510 Instruction::BinaryOps LHSCC, RHSCC;
2511 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2512 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2513 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
2514 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002515 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00002516 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2517 // Ensure that the larger constant is on the RHS.
2518 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2519 SetCondInst *LHS = cast<SetCondInst>(Op0);
2520 if (cast<ConstantBool>(Cmp)->getValue()) {
2521 std::swap(LHS, RHS);
2522 std::swap(LHSCst, RHSCst);
2523 std::swap(LHSCC, RHSCC);
2524 }
2525
2526 // At this point, we know we have have two setcc instructions
2527 // comparing a value against two constants and and'ing the result
2528 // together. Because of the above check, we know that we only have
2529 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2530 // FoldSetCCLogical check above), that the two constants are not
2531 // equal.
2532 assert(LHSCst != RHSCst && "Compares not folded above?");
2533
2534 switch (LHSCC) {
2535 default: assert(0 && "Unknown integer condition code!");
2536 case Instruction::SetEQ:
2537 switch (RHSCC) {
2538 default: assert(0 && "Unknown integer condition code!");
2539 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
2540 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2541 return ReplaceInstUsesWith(I, ConstantBool::False);
2542 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2543 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2544 return ReplaceInstUsesWith(I, LHS);
2545 }
2546 case Instruction::SetNE:
2547 switch (RHSCC) {
2548 default: assert(0 && "Unknown integer condition code!");
2549 case Instruction::SetLT:
2550 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2551 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2552 break; // (X != 13 & X < 15) -> no change
2553 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2554 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2555 return ReplaceInstUsesWith(I, RHS);
2556 case Instruction::SetNE:
2557 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2558 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2559 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2560 LHSVal->getName()+".off");
2561 InsertNewInstBefore(Add, I);
2562 const Type *UnsType = Add->getType()->getUnsignedVersion();
2563 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2564 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2565 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2566 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2567 }
2568 break; // (X != 13 & X != 15) -> no change
2569 }
2570 break;
2571 case Instruction::SetLT:
2572 switch (RHSCC) {
2573 default: assert(0 && "Unknown integer condition code!");
2574 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2575 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2576 return ReplaceInstUsesWith(I, ConstantBool::False);
2577 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2578 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2579 return ReplaceInstUsesWith(I, LHS);
2580 }
2581 case Instruction::SetGT:
2582 switch (RHSCC) {
2583 default: assert(0 && "Unknown integer condition code!");
2584 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2585 return ReplaceInstUsesWith(I, LHS);
2586 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2587 return ReplaceInstUsesWith(I, RHS);
2588 case Instruction::SetNE:
2589 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2590 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2591 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00002592 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2593 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00002594 }
2595 }
2596 }
2597 }
2598
Chris Lattner113f4f42002-06-25 16:13:24 +00002599 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002600}
2601
Chris Lattner113f4f42002-06-25 16:13:24 +00002602Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002603 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002604 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002605
Chris Lattner81a7a232004-10-16 18:11:37 +00002606 if (isa<UndefValue>(Op1))
2607 return ReplaceInstUsesWith(I, // X | undef -> -1
2608 ConstantIntegral::getAllOnesValue(I.getType()));
2609
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002610 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00002611 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
2612 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002613
2614 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00002615 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner86102b82005-01-01 16:22:27 +00002616 // If X is known to only contain bits that already exist in RHS, just
2617 // replace this instruction with RHS directly.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002618 if (MaskedValueIsZero(Op0,
2619 RHS->getZExtValue()^RHS->getType()->getIntegralTypeMask()))
Chris Lattner86102b82005-01-01 16:22:27 +00002620 return ReplaceInstUsesWith(I, RHS);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002621
Chris Lattner330628a2006-01-06 17:59:59 +00002622 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002623 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2624 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002625 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2626 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00002627 InsertNewInstBefore(Or, I);
2628 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2629 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00002630
Chris Lattnerd4252a72004-07-30 07:50:03 +00002631 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2632 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2633 std::string Op0Name = Op0->getName(); Op0->setName("");
2634 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2635 InsertNewInstBefore(Or, I);
2636 return BinaryOperator::createXor(Or,
2637 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00002638 }
Chris Lattner183b3362004-04-09 19:05:30 +00002639
2640 // Try to fold constant and into select arguments.
2641 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002642 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002643 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002644 if (isa<PHINode>(Op0))
2645 if (Instruction *NV = FoldOpIntoPhi(I))
2646 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00002647 }
2648
Chris Lattner330628a2006-01-06 17:59:59 +00002649 Value *A = 0, *B = 0;
2650 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00002651
2652 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2653 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2654 return ReplaceInstUsesWith(I, Op1);
2655 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2656 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2657 return ReplaceInstUsesWith(I, Op0);
2658
Chris Lattnerb62f5082005-05-09 04:58:36 +00002659 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2660 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002661 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002662 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2663 Op0->setName("");
2664 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2665 }
2666
2667 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2668 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002669 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002670 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2671 Op0->setName("");
2672 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2673 }
2674
Chris Lattner15212982005-09-18 03:42:07 +00002675 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00002676 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00002677 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2678
2679 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2680 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2681
2682
Chris Lattner01f56c62005-09-18 06:02:59 +00002683 // If we have: ((V + N) & C1) | (V & C2)
2684 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2685 // replace with V+N.
2686 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002687 Value *V1 = 0, *V2 = 0;
Chris Lattner01f56c62005-09-18 06:02:59 +00002688 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2689 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2690 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002691 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002692 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002693 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002694 return ReplaceInstUsesWith(I, A);
2695 }
2696 // Or commutes, try both ways.
2697 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2698 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2699 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002700 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002701 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002702 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002703 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00002704 }
2705 }
2706 }
Chris Lattner812aab72003-08-12 19:11:07 +00002707
Chris Lattnerd4252a72004-07-30 07:50:03 +00002708 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2709 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00002710 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002711 ConstantIntegral::getAllOnesValue(I.getType()));
2712 } else {
2713 A = 0;
2714 }
Chris Lattner4294cec2005-05-07 23:49:08 +00002715 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00002716 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2717 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00002718 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002719 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00002720
Misha Brukman9c003d82004-07-30 12:50:08 +00002721 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00002722 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2723 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2724 I.getName()+".demorgan"), I);
2725 return BinaryOperator::createNot(And);
2726 }
Chris Lattner3e327a42003-03-10 23:13:59 +00002727 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002728
Chris Lattner3ac7c262003-08-13 20:16:26 +00002729 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002730 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002731 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2732 return R;
2733
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002734 Value *LHSVal, *RHSVal;
2735 ConstantInt *LHSCst, *RHSCst;
2736 Instruction::BinaryOps LHSCC, RHSCC;
2737 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2738 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2739 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2740 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002741 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002742 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2743 // Ensure that the larger constant is on the RHS.
2744 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2745 SetCondInst *LHS = cast<SetCondInst>(Op0);
2746 if (cast<ConstantBool>(Cmp)->getValue()) {
2747 std::swap(LHS, RHS);
2748 std::swap(LHSCst, RHSCst);
2749 std::swap(LHSCC, RHSCC);
2750 }
2751
2752 // At this point, we know we have have two setcc instructions
2753 // comparing a value against two constants and or'ing the result
2754 // together. Because of the above check, we know that we only have
2755 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2756 // FoldSetCCLogical check above), that the two constants are not
2757 // equal.
2758 assert(LHSCst != RHSCst && "Compares not folded above?");
2759
2760 switch (LHSCC) {
2761 default: assert(0 && "Unknown integer condition code!");
2762 case Instruction::SetEQ:
2763 switch (RHSCC) {
2764 default: assert(0 && "Unknown integer condition code!");
2765 case Instruction::SetEQ:
2766 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2767 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2768 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2769 LHSVal->getName()+".off");
2770 InsertNewInstBefore(Add, I);
2771 const Type *UnsType = Add->getType()->getUnsignedVersion();
2772 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2773 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2774 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2775 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2776 }
2777 break; // (X == 13 | X == 15) -> no change
2778
Chris Lattner5c219462005-04-19 06:04:18 +00002779 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2780 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002781 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2782 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2783 return ReplaceInstUsesWith(I, RHS);
2784 }
2785 break;
2786 case Instruction::SetNE:
2787 switch (RHSCC) {
2788 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002789 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2790 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2791 return ReplaceInstUsesWith(I, LHS);
2792 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00002793 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002794 return ReplaceInstUsesWith(I, ConstantBool::True);
2795 }
2796 break;
2797 case Instruction::SetLT:
2798 switch (RHSCC) {
2799 default: assert(0 && "Unknown integer condition code!");
2800 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2801 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00002802 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2803 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002804 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2805 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2806 return ReplaceInstUsesWith(I, RHS);
2807 }
2808 break;
2809 case Instruction::SetGT:
2810 switch (RHSCC) {
2811 default: assert(0 && "Unknown integer condition code!");
2812 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
2813 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
2814 return ReplaceInstUsesWith(I, LHS);
2815 case Instruction::SetNE: // (X > 13 | X != 15) -> true
2816 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2817 return ReplaceInstUsesWith(I, ConstantBool::True);
2818 }
2819 }
2820 }
2821 }
Chris Lattner15212982005-09-18 03:42:07 +00002822
Chris Lattner113f4f42002-06-25 16:13:24 +00002823 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002824}
2825
Chris Lattnerc2076352004-02-16 01:20:27 +00002826// XorSelf - Implements: X ^ X --> 0
2827struct XorSelf {
2828 Value *RHS;
2829 XorSelf(Value *rhs) : RHS(rhs) {}
2830 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2831 Instruction *apply(BinaryOperator &Xor) const {
2832 return &Xor;
2833 }
2834};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002835
2836
Chris Lattner113f4f42002-06-25 16:13:24 +00002837Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002838 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002839 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002840
Chris Lattner81a7a232004-10-16 18:11:37 +00002841 if (isa<UndefValue>(Op1))
2842 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2843
Chris Lattnerc2076352004-02-16 01:20:27 +00002844 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2845 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2846 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00002847 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00002848 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002849
Chris Lattner97638592003-07-23 21:37:07 +00002850 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002851 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00002852 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00002853 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002854
Chris Lattner97638592003-07-23 21:37:07 +00002855 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002856 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00002857 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002858 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002859 return new SetCondInst(SCI->getInverseCondition(),
2860 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00002861
Chris Lattner8f2f5982003-11-05 01:06:05 +00002862 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002863 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2864 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002865 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2866 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002867 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002868 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002869 }
Chris Lattner023a4832004-06-18 06:07:51 +00002870
2871 // ~(~X & Y) --> (X | ~Y)
2872 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2873 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2874 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2875 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00002876 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00002877 Op0I->getOperand(1)->getName()+".not");
2878 InsertNewInstBefore(NotY, I);
2879 return BinaryOperator::createOr(Op0NotVal, NotY);
2880 }
2881 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002882
Chris Lattner97638592003-07-23 21:37:07 +00002883 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00002884 switch (Op0I->getOpcode()) {
2885 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00002886 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002887 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002888 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2889 return BinaryOperator::createSub(
2890 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002891 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00002892 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002893 }
Chris Lattnere5806662003-11-04 23:50:51 +00002894 break;
2895 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00002896 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002897 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2898 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00002899 break;
2900 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00002901 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002902 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002903 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00002904 break;
2905 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00002906 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002907 }
Chris Lattner183b3362004-04-09 19:05:30 +00002908
2909 // Try to fold constant and into select arguments.
2910 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002911 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002912 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002913 if (isa<PHINode>(Op0))
2914 if (Instruction *NV = FoldOpIntoPhi(I))
2915 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002916 }
2917
Chris Lattnerbb74e222003-03-10 23:06:50 +00002918 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002919 if (X == Op1)
2920 return ReplaceInstUsesWith(I,
2921 ConstantIntegral::getAllOnesValue(I.getType()));
2922
Chris Lattnerbb74e222003-03-10 23:06:50 +00002923 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002924 if (X == Op0)
2925 return ReplaceInstUsesWith(I,
2926 ConstantIntegral::getAllOnesValue(I.getType()));
2927
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002928 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00002929 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002930 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2931 cast<BinaryOperator>(Op1I)->swapOperands();
2932 I.swapOperands();
2933 std::swap(Op0, Op1);
2934 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2935 I.swapOperands();
2936 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002937 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002938 } else if (Op1I->getOpcode() == Instruction::Xor) {
2939 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2940 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2941 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2942 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2943 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002944
2945 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002946 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002947 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2948 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002949 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00002950 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2951 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002952 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002953 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002954 } else if (Op0I->getOpcode() == Instruction::Xor) {
2955 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2956 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2957 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2958 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002959 }
2960
Chris Lattner7aa2d472004-08-01 19:42:59 +00002961 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner330628a2006-01-06 17:59:59 +00002962 ConstantInt *C1 = 0, *C2 = 0;
2963 if (match(Op0, m_And(m_Value(), m_ConstantInt(C1))) &&
2964 match(Op1, m_And(m_Value(), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00002965 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00002966 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00002967
Chris Lattner3ac7c262003-08-13 20:16:26 +00002968 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2969 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2970 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2971 return R;
2972
Chris Lattner113f4f42002-06-25 16:13:24 +00002973 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002974}
2975
Chris Lattner6862fbd2004-09-29 17:40:11 +00002976/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2977/// overflowed for this type.
2978static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2979 ConstantInt *In2) {
2980 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2981 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2982}
2983
2984static bool isPositive(ConstantInt *C) {
2985 return cast<ConstantSInt>(C)->getValue() >= 0;
2986}
2987
2988/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2989/// overflowed for this type.
2990static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2991 ConstantInt *In2) {
2992 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2993
2994 if (In1->getType()->isUnsigned())
2995 return cast<ConstantUInt>(Result)->getValue() <
2996 cast<ConstantUInt>(In1)->getValue();
2997 if (isPositive(In1) != isPositive(In2))
2998 return false;
2999 if (isPositive(In1))
3000 return cast<ConstantSInt>(Result)->getValue() <
3001 cast<ConstantSInt>(In1)->getValue();
3002 return cast<ConstantSInt>(Result)->getValue() >
3003 cast<ConstantSInt>(In1)->getValue();
3004}
3005
Chris Lattner0798af32005-01-13 20:14:25 +00003006/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3007/// code necessary to compute the offset from the base pointer (without adding
3008/// in the base pointer). Return the result as a signed integer of intptr size.
3009static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3010 TargetData &TD = IC.getTargetData();
3011 gep_type_iterator GTI = gep_type_begin(GEP);
3012 const Type *UIntPtrTy = TD.getIntPtrType();
3013 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3014 Value *Result = Constant::getNullValue(SIntPtrTy);
3015
3016 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00003017 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00003018
Chris Lattner0798af32005-01-13 20:14:25 +00003019 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3020 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00003021 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00003022 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
3023 SIntPtrTy);
3024 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3025 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003026 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00003027 Scale = ConstantExpr::getMul(OpC, Scale);
3028 if (Constant *RC = dyn_cast<Constant>(Result))
3029 Result = ConstantExpr::getAdd(RC, Scale);
3030 else {
3031 // Emit an add instruction.
3032 Result = IC.InsertNewInstBefore(
3033 BinaryOperator::createAdd(Result, Scale,
3034 GEP->getName()+".offs"), I);
3035 }
3036 }
3037 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00003038 // Convert to correct type.
3039 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3040 Op->getName()+".c"), I);
3041 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003042 // We'll let instcombine(mul) convert this to a shl if possible.
3043 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3044 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00003045
3046 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003047 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00003048 GEP->getName()+".offs"), I);
3049 }
3050 }
3051 return Result;
3052}
3053
3054/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3055/// else. At this point we know that the GEP is on the LHS of the comparison.
3056Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3057 Instruction::BinaryOps Cond,
3058 Instruction &I) {
3059 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00003060
3061 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3062 if (isa<PointerType>(CI->getOperand(0)->getType()))
3063 RHS = CI->getOperand(0);
3064
Chris Lattner0798af32005-01-13 20:14:25 +00003065 Value *PtrBase = GEPLHS->getOperand(0);
3066 if (PtrBase == RHS) {
3067 // As an optimization, we don't actually have to compute the actual value of
3068 // OFFSET if this is a seteq or setne comparison, just return whether each
3069 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00003070 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3071 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003072 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3073 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00003074 bool EmitIt = true;
3075 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3076 if (isa<UndefValue>(C)) // undef index -> undef.
3077 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3078 if (C->isNullValue())
3079 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003080 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3081 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00003082 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00003083 return ReplaceInstUsesWith(I, // No comparison is needed here.
3084 ConstantBool::get(Cond == Instruction::SetNE));
3085 }
3086
3087 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003088 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00003089 new SetCondInst(Cond, GEPLHS->getOperand(i),
3090 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3091 if (InVal == 0)
3092 InVal = Comp;
3093 else {
3094 InVal = InsertNewInstBefore(InVal, I);
3095 InsertNewInstBefore(Comp, I);
3096 if (Cond == Instruction::SetNE) // True if any are unequal
3097 InVal = BinaryOperator::createOr(InVal, Comp);
3098 else // True if all are equal
3099 InVal = BinaryOperator::createAnd(InVal, Comp);
3100 }
3101 }
3102 }
3103
3104 if (InVal)
3105 return InVal;
3106 else
3107 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3108 ConstantBool::get(Cond == Instruction::SetEQ));
3109 }
Chris Lattner0798af32005-01-13 20:14:25 +00003110
3111 // Only lower this if the setcc is the only user of the GEP or if we expect
3112 // the result to fold to a constant!
3113 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3114 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3115 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3116 return new SetCondInst(Cond, Offset,
3117 Constant::getNullValue(Offset->getType()));
3118 }
3119 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003120 // If the base pointers are different, but the indices are the same, just
3121 // compare the base pointer.
3122 if (PtrBase != GEPRHS->getOperand(0)) {
3123 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003124 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00003125 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003126 if (IndicesTheSame)
3127 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3128 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3129 IndicesTheSame = false;
3130 break;
3131 }
3132
3133 // If all indices are the same, just compare the base pointers.
3134 if (IndicesTheSame)
3135 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3136 GEPRHS->getOperand(0));
3137
3138 // Otherwise, the base pointers are different and the indices are
3139 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00003140 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003141 }
Chris Lattner0798af32005-01-13 20:14:25 +00003142
Chris Lattner81e84172005-01-13 22:25:21 +00003143 // If one of the GEPs has all zero indices, recurse.
3144 bool AllZeros = true;
3145 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3146 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3147 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3148 AllZeros = false;
3149 break;
3150 }
3151 if (AllZeros)
3152 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3153 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00003154
3155 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00003156 AllZeros = true;
3157 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3158 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3159 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3160 AllZeros = false;
3161 break;
3162 }
3163 if (AllZeros)
3164 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3165
Chris Lattner4fa89822005-01-14 00:20:05 +00003166 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3167 // If the GEPs only differ by one index, compare it.
3168 unsigned NumDifferences = 0; // Keep track of # differences.
3169 unsigned DiffOperand = 0; // The operand that differs.
3170 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3171 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003172 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3173 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003174 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00003175 NumDifferences = 2;
3176 break;
3177 } else {
3178 if (NumDifferences++) break;
3179 DiffOperand = i;
3180 }
3181 }
3182
3183 if (NumDifferences == 0) // SAME GEP?
3184 return ReplaceInstUsesWith(I, // No comparison is needed here.
3185 ConstantBool::get(Cond == Instruction::SetEQ));
3186 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003187 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3188 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00003189
3190 // Convert the operands to signed values to make sure to perform a
3191 // signed comparison.
3192 const Type *NewTy = LHSV->getType()->getSignedVersion();
3193 if (LHSV->getType() != NewTy)
3194 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3195 LHSV->getName()), I);
3196 if (RHSV->getType() != NewTy)
3197 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3198 RHSV->getName()), I);
3199 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00003200 }
3201 }
3202
Chris Lattner0798af32005-01-13 20:14:25 +00003203 // Only lower this if the setcc is the only user of the GEP or if we expect
3204 // the result to fold to a constant!
3205 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3206 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3207 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
3208 Value *L = EmitGEPOffset(GEPLHS, I, *this);
3209 Value *R = EmitGEPOffset(GEPRHS, I, *this);
3210 return new SetCondInst(Cond, L, R);
3211 }
3212 }
3213 return 0;
3214}
3215
3216
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003217Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003218 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003219 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3220 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003221
3222 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003223 if (Op0 == Op1)
3224 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00003225
Chris Lattner81a7a232004-10-16 18:11:37 +00003226 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
3227 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3228
Chris Lattner15ff1e12004-11-14 07:33:16 +00003229 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3230 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003231 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3232 isa<ConstantPointerNull>(Op0)) &&
3233 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00003234 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003235 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3236
3237 // setcc's with boolean values can always be turned into bitwise operations
3238 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00003239 switch (I.getOpcode()) {
3240 default: assert(0 && "Invalid setcc instruction!");
3241 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003242 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003243 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00003244 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003245 }
Chris Lattner4456da62004-08-11 00:50:51 +00003246 case Instruction::SetNE:
3247 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003248
Chris Lattner4456da62004-08-11 00:50:51 +00003249 case Instruction::SetGT:
3250 std::swap(Op0, Op1); // Change setgt -> setlt
3251 // FALL THROUGH
3252 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
3253 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3254 InsertNewInstBefore(Not, I);
3255 return BinaryOperator::createAnd(Not, Op1);
3256 }
3257 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003258 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00003259 // FALL THROUGH
3260 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
3261 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3262 InsertNewInstBefore(Not, I);
3263 return BinaryOperator::createOr(Not, Op1);
3264 }
3265 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003266 }
3267
Chris Lattner2dd01742004-06-09 04:24:29 +00003268 // See if we are doing a comparison between a constant and an instruction that
3269 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003270 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00003271 // Check to see if we are comparing against the minimum or maximum value...
3272 if (CI->isMinValue()) {
3273 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
3274 return ReplaceInstUsesWith(I, ConstantBool::False);
3275 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
3276 return ReplaceInstUsesWith(I, ConstantBool::True);
3277 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
3278 return BinaryOperator::createSetEQ(Op0, Op1);
3279 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
3280 return BinaryOperator::createSetNE(Op0, Op1);
3281
3282 } else if (CI->isMaxValue()) {
3283 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
3284 return ReplaceInstUsesWith(I, ConstantBool::False);
3285 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
3286 return ReplaceInstUsesWith(I, ConstantBool::True);
3287 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
3288 return BinaryOperator::createSetEQ(Op0, Op1);
3289 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
3290 return BinaryOperator::createSetNE(Op0, Op1);
3291
3292 // Comparing against a value really close to min or max?
3293 } else if (isMinValuePlusOne(CI)) {
3294 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
3295 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
3296 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
3297 return BinaryOperator::createSetNE(Op0, SubOne(CI));
3298
3299 } else if (isMaxValueMinusOne(CI)) {
3300 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
3301 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
3302 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
3303 return BinaryOperator::createSetNE(Op0, AddOne(CI));
3304 }
3305
3306 // If we still have a setle or setge instruction, turn it into the
3307 // appropriate setlt or setgt instruction. Since the border cases have
3308 // already been handled above, this requires little checking.
3309 //
3310 if (I.getOpcode() == Instruction::SetLE)
3311 return BinaryOperator::createSetLT(Op0, AddOne(CI));
3312 if (I.getOpcode() == Instruction::SetGE)
3313 return BinaryOperator::createSetGT(Op0, SubOne(CI));
3314
Chris Lattneree0f2802006-02-12 02:07:56 +00003315
3316 // See if we can fold the comparison based on bits known to be zero or one
3317 // in the input.
3318 uint64_t KnownZero, KnownOne;
3319 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
3320 KnownZero, KnownOne, 0))
3321 return &I;
3322
3323 // Given the known and unknown bits, compute a range that the LHS could be
3324 // in.
3325 if (KnownOne | KnownZero) {
3326 if (Ty->isUnsigned()) { // Unsigned comparison.
3327 uint64_t Min, Max;
3328 uint64_t RHSVal = CI->getZExtValue();
3329 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3330 Min, Max);
3331 switch (I.getOpcode()) { // LE/GE have been folded already.
3332 default: assert(0 && "Unknown setcc opcode!");
3333 case Instruction::SetEQ:
3334 if (Max < RHSVal || Min > RHSVal)
3335 return ReplaceInstUsesWith(I, ConstantBool::False);
3336 break;
3337 case Instruction::SetNE:
3338 if (Max < RHSVal || Min > RHSVal)
3339 return ReplaceInstUsesWith(I, ConstantBool::True);
3340 break;
3341 case Instruction::SetLT:
3342 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3343 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3344 break;
3345 case Instruction::SetGT:
3346 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3347 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3348 break;
3349 }
3350 } else { // Signed comparison.
3351 int64_t Min, Max;
3352 int64_t RHSVal = CI->getSExtValue();
3353 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3354 Min, Max);
3355 switch (I.getOpcode()) { // LE/GE have been folded already.
3356 default: assert(0 && "Unknown setcc opcode!");
3357 case Instruction::SetEQ:
3358 if (Max < RHSVal || Min > RHSVal)
3359 return ReplaceInstUsesWith(I, ConstantBool::False);
3360 break;
3361 case Instruction::SetNE:
3362 if (Max < RHSVal || Min > RHSVal)
3363 return ReplaceInstUsesWith(I, ConstantBool::True);
3364 break;
3365 case Instruction::SetLT:
3366 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3367 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3368 break;
3369 case Instruction::SetGT:
3370 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3371 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3372 break;
3373 }
3374 }
3375 }
3376
3377
Chris Lattnere1e10e12004-05-25 06:32:08 +00003378 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003379 switch (LHSI->getOpcode()) {
3380 case Instruction::And:
3381 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
3382 LHSI->getOperand(0)->hasOneUse()) {
3383 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
3384 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
3385 // happens a LOT in code produced by the C front-end, for bitfield
3386 // access.
3387 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00003388 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
3389
3390 // Check to see if there is a noop-cast between the shift and the and.
3391 if (!Shift) {
3392 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
3393 if (CI->getOperand(0)->getType()->isIntegral() &&
3394 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3395 CI->getType()->getPrimitiveSizeInBits())
3396 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
3397 }
3398
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003399 ConstantUInt *ShAmt;
3400 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00003401 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
3402 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003403
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003404 // We can fold this as long as we can't shift unknown bits
3405 // into the mask. This can only happen with signed shift
3406 // rights, as they sign-extend.
3407 if (ShAmt) {
3408 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattneree0f2802006-02-12 02:07:56 +00003409 Ty->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003410 if (!CanFold) {
3411 // To test for the bad case of the signed shr, see if any
3412 // of the bits shifted in could be tested after the mask.
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00003413 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
3414 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
3415
3416 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003417 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00003418 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
3419 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003420 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
3421 CanFold = true;
3422 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003423
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003424 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00003425 Constant *NewCst;
3426 if (Shift->getOpcode() == Instruction::Shl)
3427 NewCst = ConstantExpr::getUShr(CI, ShAmt);
3428 else
3429 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003430
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003431 // Check to see if we are shifting out any of the bits being
3432 // compared.
3433 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
3434 // If we shifted bits out, the fold is not going to work out.
3435 // As a special case, check to see if this means that the
3436 // result is always true or false now.
3437 if (I.getOpcode() == Instruction::SetEQ)
3438 return ReplaceInstUsesWith(I, ConstantBool::False);
3439 if (I.getOpcode() == Instruction::SetNE)
3440 return ReplaceInstUsesWith(I, ConstantBool::True);
3441 } else {
3442 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00003443 Constant *NewAndCST;
3444 if (Shift->getOpcode() == Instruction::Shl)
3445 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
3446 else
3447 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
3448 LHSI->setOperand(1, NewAndCST);
Chris Lattneree0f2802006-02-12 02:07:56 +00003449 if (AndTy == Ty)
3450 LHSI->setOperand(0, Shift->getOperand(0));
3451 else {
3452 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
3453 *Shift);
3454 LHSI->setOperand(0, NewCast);
3455 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003456 WorkList.push_back(Shift); // Shift is dead.
3457 AddUsesToWorkList(I);
3458 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00003459 }
3460 }
Chris Lattner35167c32004-06-09 07:59:58 +00003461 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003462 }
3463 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003464
Chris Lattner272d5ca2004-09-28 18:22:15 +00003465 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
3466 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3467 switch (I.getOpcode()) {
3468 default: break;
3469 case Instruction::SetEQ:
3470 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00003471 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3472
3473 // Check that the shift amount is in range. If not, don't perform
3474 // undefined shifts. When the shift is visited it will be
3475 // simplified.
3476 if (ShAmt->getValue() >= TypeBits)
3477 break;
3478
Chris Lattner272d5ca2004-09-28 18:22:15 +00003479 // If we are comparing against bits always shifted out, the
3480 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003481 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00003482 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
3483 if (Comp != CI) {// Comparing against a bit that we know is zero.
3484 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3485 Constant *Cst = ConstantBool::get(IsSetNE);
3486 return ReplaceInstUsesWith(I, Cst);
3487 }
3488
3489 if (LHSI->hasOneUse()) {
3490 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003491 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00003492 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
3493
3494 Constant *Mask;
3495 if (CI->getType()->isUnsigned()) {
3496 Mask = ConstantUInt::get(CI->getType(), Val);
3497 } else if (ShAmtVal != 0) {
3498 Mask = ConstantSInt::get(CI->getType(), Val);
3499 } else {
3500 Mask = ConstantInt::getAllOnesValue(CI->getType());
3501 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003502
Chris Lattner272d5ca2004-09-28 18:22:15 +00003503 Instruction *AndI =
3504 BinaryOperator::createAnd(LHSI->getOperand(0),
3505 Mask, LHSI->getName()+".mask");
3506 Value *And = InsertNewInstBefore(AndI, I);
3507 return new SetCondInst(I.getOpcode(), And,
3508 ConstantExpr::getUShr(CI, ShAmt));
3509 }
3510 }
3511 }
3512 }
3513 break;
3514
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003515 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00003516 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00003517 switch (I.getOpcode()) {
3518 default: break;
3519 case Instruction::SetEQ:
3520 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00003521
3522 // Check that the shift amount is in range. If not, don't perform
3523 // undefined shifts. When the shift is visited it will be
3524 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00003525 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner19b57f52005-06-15 20:53:31 +00003526 if (ShAmt->getValue() >= TypeBits)
3527 break;
3528
Chris Lattner1023b872004-09-27 16:18:50 +00003529 // If we are comparing against bits always shifted out, the
3530 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003531 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00003532 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003533
Chris Lattner1023b872004-09-27 16:18:50 +00003534 if (Comp != CI) {// Comparing against a bit that we know is zero.
3535 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3536 Constant *Cst = ConstantBool::get(IsSetNE);
3537 return ReplaceInstUsesWith(I, Cst);
3538 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003539
Chris Lattner1023b872004-09-27 16:18:50 +00003540 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003541 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00003542
Chris Lattner1023b872004-09-27 16:18:50 +00003543 // Otherwise strength reduce the shift into an and.
3544 uint64_t Val = ~0ULL; // All ones.
3545 Val <<= ShAmtVal; // Shift over to the right spot.
3546
3547 Constant *Mask;
3548 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00003549 Val &= ~0ULL >> (64-TypeBits);
Chris Lattner1023b872004-09-27 16:18:50 +00003550 Mask = ConstantUInt::get(CI->getType(), Val);
3551 } else {
3552 Mask = ConstantSInt::get(CI->getType(), Val);
3553 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003554
Chris Lattner1023b872004-09-27 16:18:50 +00003555 Instruction *AndI =
3556 BinaryOperator::createAnd(LHSI->getOperand(0),
3557 Mask, LHSI->getName()+".mask");
3558 Value *And = InsertNewInstBefore(AndI, I);
3559 return new SetCondInst(I.getOpcode(), And,
3560 ConstantExpr::getShl(CI, ShAmt));
3561 }
3562 break;
3563 }
3564 }
3565 }
3566 break;
Chris Lattner7e794272004-09-24 15:21:34 +00003567
Chris Lattner6862fbd2004-09-29 17:40:11 +00003568 case Instruction::Div:
3569 // Fold: (div X, C1) op C2 -> range check
3570 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
3571 // Fold this div into the comparison, producing a range check.
3572 // Determine, based on the divide type, what the range is being
3573 // checked. If there is an overflow on the low or high side, remember
3574 // it, otherwise compute the range [low, hi) bounding the new value.
3575 bool LoOverflow = false, HiOverflow = 0;
3576 ConstantInt *LoBound = 0, *HiBound = 0;
3577
3578 ConstantInt *Prod;
3579 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
3580
Chris Lattnera92af962004-10-11 19:40:04 +00003581 Instruction::BinaryOps Opcode = I.getOpcode();
3582
Chris Lattner6862fbd2004-09-29 17:40:11 +00003583 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
3584 } else if (LHSI->getType()->isUnsigned()) { // udiv
3585 LoBound = Prod;
3586 LoOverflow = ProdOV;
3587 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
3588 } else if (isPositive(DivRHS)) { // Divisor is > 0.
3589 if (CI->isNullValue()) { // (X / pos) op 0
3590 // Can't overflow.
3591 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
3592 HiBound = DivRHS;
3593 } else if (isPositive(CI)) { // (X / pos) op pos
3594 LoBound = Prod;
3595 LoOverflow = ProdOV;
3596 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
3597 } else { // (X / pos) op neg
3598 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
3599 LoOverflow = AddWithOverflow(LoBound, Prod,
3600 cast<ConstantInt>(DivRHSH));
3601 HiBound = Prod;
3602 HiOverflow = ProdOV;
3603 }
3604 } else { // Divisor is < 0.
3605 if (CI->isNullValue()) { // (X / neg) op 0
3606 LoBound = AddOne(DivRHS);
3607 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00003608 if (HiBound == DivRHS)
3609 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00003610 } else if (isPositive(CI)) { // (X / neg) op pos
3611 HiOverflow = LoOverflow = ProdOV;
3612 if (!LoOverflow)
3613 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
3614 HiBound = AddOne(Prod);
3615 } else { // (X / neg) op neg
3616 LoBound = Prod;
3617 LoOverflow = HiOverflow = ProdOV;
3618 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
3619 }
Chris Lattner0b41e862004-10-08 19:15:44 +00003620
Chris Lattnera92af962004-10-11 19:40:04 +00003621 // Dividing by a negate swaps the condition.
3622 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003623 }
3624
3625 if (LoBound) {
3626 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00003627 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00003628 default: assert(0 && "Unhandled setcc opcode!");
3629 case Instruction::SetEQ:
3630 if (LoOverflow && HiOverflow)
3631 return ReplaceInstUsesWith(I, ConstantBool::False);
3632 else if (HiOverflow)
3633 return new SetCondInst(Instruction::SetGE, X, LoBound);
3634 else if (LoOverflow)
3635 return new SetCondInst(Instruction::SetLT, X, HiBound);
3636 else
3637 return InsertRangeTest(X, LoBound, HiBound, true, I);
3638 case Instruction::SetNE:
3639 if (LoOverflow && HiOverflow)
3640 return ReplaceInstUsesWith(I, ConstantBool::True);
3641 else if (HiOverflow)
3642 return new SetCondInst(Instruction::SetLT, X, LoBound);
3643 else if (LoOverflow)
3644 return new SetCondInst(Instruction::SetGE, X, HiBound);
3645 else
3646 return InsertRangeTest(X, LoBound, HiBound, false, I);
3647 case Instruction::SetLT:
3648 if (LoOverflow)
3649 return ReplaceInstUsesWith(I, ConstantBool::False);
3650 return new SetCondInst(Instruction::SetLT, X, LoBound);
3651 case Instruction::SetGT:
3652 if (HiOverflow)
3653 return ReplaceInstUsesWith(I, ConstantBool::False);
3654 return new SetCondInst(Instruction::SetGE, X, HiBound);
3655 }
3656 }
3657 }
3658 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003659 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003660
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003661 // Simplify seteq and setne instructions...
3662 if (I.getOpcode() == Instruction::SetEQ ||
3663 I.getOpcode() == Instruction::SetNE) {
3664 bool isSetNE = I.getOpcode() == Instruction::SetNE;
3665
Chris Lattnercfbce7c2003-07-23 17:26:36 +00003666 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003667 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00003668 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3669 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00003670 case Instruction::Rem:
3671 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3672 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3673 BO->hasOneUse() &&
Chris Lattner22d00a82005-08-02 19:16:58 +00003674 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3675 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3676 if (isPowerOf2_64(V)) {
3677 unsigned L2 = Log2_64(V);
Chris Lattner23b47b62004-07-06 07:38:18 +00003678 const Type *UTy = BO->getType()->getUnsignedVersion();
3679 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3680 UTy, "tmp"), I);
3681 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3682 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3683 RHSCst, BO->getName()), I);
3684 return BinaryOperator::create(I.getOpcode(), NewRem,
3685 Constant::getNullValue(UTy));
3686 }
Chris Lattner22d00a82005-08-02 19:16:58 +00003687 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003688 break;
Chris Lattner23b47b62004-07-06 07:38:18 +00003689
Chris Lattnerc992add2003-08-13 05:33:12 +00003690 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00003691 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3692 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00003693 if (BO->hasOneUse())
3694 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3695 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00003696 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003697 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3698 // efficiently invertible, or if the add has just this one use.
3699 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003700
Chris Lattnerc992add2003-08-13 05:33:12 +00003701 if (Value *NegVal = dyn_castNegVal(BOp1))
3702 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3703 else if (Value *NegVal = dyn_castNegVal(BOp0))
3704 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003705 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003706 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3707 BO->setName("");
3708 InsertNewInstBefore(Neg, I);
3709 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3710 }
3711 }
3712 break;
3713 case Instruction::Xor:
3714 // For the xor case, we can xor two constants together, eliminating
3715 // the explicit xor.
3716 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3717 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003718 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00003719
3720 // FALLTHROUGH
3721 case Instruction::Sub:
3722 // Replace (([sub|xor] A, B) != 0) with (A != B)
3723 if (CI->isNullValue())
3724 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3725 BO->getOperand(1));
3726 break;
3727
3728 case Instruction::Or:
3729 // If bits are being or'd in that are not present in the constant we
3730 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003731 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003732 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003733 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003734 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003735 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003736 break;
3737
3738 case Instruction::And:
3739 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003740 // If bits are being compared against that are and'd out, then the
3741 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003742 if (!ConstantExpr::getAnd(CI,
3743 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003744 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00003745
Chris Lattner35167c32004-06-09 07:59:58 +00003746 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00003747 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00003748 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3749 Instruction::SetNE, Op0,
3750 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00003751
Chris Lattnerc992add2003-08-13 05:33:12 +00003752 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3753 // to be a signed value as appropriate.
3754 if (isSignBit(BOC)) {
3755 Value *X = BO->getOperand(0);
3756 // If 'X' is not signed, insert a cast now...
3757 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00003758 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003759 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00003760 }
3761 return new SetCondInst(isSetNE ? Instruction::SetLT :
3762 Instruction::SetGE, X,
3763 Constant::getNullValue(X->getType()));
3764 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003765
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003766 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00003767 if (CI->isNullValue() && isHighOnes(BOC)) {
3768 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003769 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003770
3771 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003772 if (NegX->getType()->isSigned()) {
3773 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3774 X = InsertCastBefore(X, DestTy, I);
3775 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003776 }
3777
3778 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003779 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003780 }
3781
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003782 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003783 default: break;
3784 }
3785 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00003786 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00003787 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00003788 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3789 Value *CastOp = Cast->getOperand(0);
3790 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003791 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00003792 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003793 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003794 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00003795 "Source and destination signednesses should differ!");
3796 if (Cast->getType()->isSigned()) {
3797 // If this is a signed comparison, check for comparisons in the
3798 // vicinity of zero.
3799 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3800 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003801 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003802 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003803 else if (I.getOpcode() == Instruction::SetGT &&
3804 cast<ConstantSInt>(CI)->getValue() == -1)
3805 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003806 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003807 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003808 } else {
3809 ConstantUInt *CUI = cast<ConstantUInt>(CI);
3810 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003811 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00003812 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003813 return BinaryOperator::createSetGT(CastOp,
3814 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003815 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003816 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00003817 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003818 return BinaryOperator::createSetLT(CastOp,
3819 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003820 }
3821 }
3822 }
Chris Lattnere967b342003-06-04 05:10:11 +00003823 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003824 }
3825
Chris Lattner77c32c32005-04-23 15:31:55 +00003826 // Handle setcc with constant RHS's that can be integer, FP or pointer.
3827 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3828 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3829 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00003830 case Instruction::GetElementPtr:
3831 if (RHSC->isNullValue()) {
3832 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3833 bool isAllZeros = true;
3834 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3835 if (!isa<Constant>(LHSI->getOperand(i)) ||
3836 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3837 isAllZeros = false;
3838 break;
3839 }
3840 if (isAllZeros)
3841 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3842 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3843 }
3844 break;
3845
Chris Lattner77c32c32005-04-23 15:31:55 +00003846 case Instruction::PHI:
3847 if (Instruction *NV = FoldOpIntoPhi(I))
3848 return NV;
3849 break;
3850 case Instruction::Select:
3851 // If either operand of the select is a constant, we can fold the
3852 // comparison into the select arms, which will cause one to be
3853 // constant folded and the select turned into a bitwise or.
3854 Value *Op1 = 0, *Op2 = 0;
3855 if (LHSI->hasOneUse()) {
3856 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3857 // Fold the known value into the constant operand.
3858 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3859 // Insert a new SetCC of the other select operand.
3860 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3861 LHSI->getOperand(2), RHSC,
3862 I.getName()), I);
3863 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3864 // Fold the known value into the constant operand.
3865 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3866 // Insert a new SetCC of the other select operand.
3867 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3868 LHSI->getOperand(1), RHSC,
3869 I.getName()), I);
3870 }
3871 }
Jeff Cohen82639852005-04-23 21:38:35 +00003872
Chris Lattner77c32c32005-04-23 15:31:55 +00003873 if (Op1)
3874 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3875 break;
3876 }
3877 }
3878
Chris Lattner0798af32005-01-13 20:14:25 +00003879 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3880 if (User *GEP = dyn_castGetElementPtr(Op0))
3881 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3882 return NI;
3883 if (User *GEP = dyn_castGetElementPtr(Op1))
3884 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3885 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3886 return NI;
3887
Chris Lattner16930792003-11-03 04:25:02 +00003888 // Test to see if the operands of the setcc are casted versions of other
3889 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00003890 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3891 Value *CastOp0 = CI->getOperand(0);
3892 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00003893 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00003894 (I.getOpcode() == Instruction::SetEQ ||
3895 I.getOpcode() == Instruction::SetNE)) {
3896 // We keep moving the cast from the left operand over to the right
3897 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00003898 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003899
Chris Lattner16930792003-11-03 04:25:02 +00003900 // If operand #1 is a cast instruction, see if we can eliminate it as
3901 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00003902 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3903 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00003904 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00003905 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003906
Chris Lattner16930792003-11-03 04:25:02 +00003907 // If Op1 is a constant, we can fold the cast into the constant.
3908 if (Op1->getType() != Op0->getType())
3909 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3910 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3911 } else {
3912 // Otherwise, cast the RHS right before the setcc
3913 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3914 InsertNewInstBefore(cast<Instruction>(Op1), I);
3915 }
3916 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3917 }
3918
Chris Lattner6444c372003-11-03 05:17:03 +00003919 // Handle the special case of: setcc (cast bool to X), <cst>
3920 // This comes up when you have code like
3921 // int X = A < B;
3922 // if (X) ...
3923 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003924 // with a constant or another cast from the same type.
3925 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3926 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3927 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00003928 }
Chris Lattner113f4f42002-06-25 16:13:24 +00003929 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003930}
3931
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003932// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
3933// We only handle extending casts so far.
3934//
3935Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
3936 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
3937 const Type *SrcTy = LHSCIOp->getType();
3938 const Type *DestTy = SCI.getOperand(0)->getType();
3939 Value *RHSCIOp;
3940
3941 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00003942 return 0;
3943
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003944 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
3945 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3946 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
3947
3948 // Is this a sign or zero extension?
3949 bool isSignSrc = SrcTy->isSigned();
3950 bool isSignDest = DestTy->isSigned();
3951
3952 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3953 // Not an extension from the same type?
3954 RHSCIOp = CI->getOperand(0);
3955 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3956 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3957 // Compute the constant that would happen if we truncated to SrcTy then
3958 // reextended to DestTy.
3959 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3960
3961 if (ConstantExpr::getCast(Res, DestTy) == CI) {
3962 RHSCIOp = Res;
3963 } else {
3964 // If the value cannot be represented in the shorter type, we cannot emit
3965 // a simple comparison.
3966 if (SCI.getOpcode() == Instruction::SetEQ)
3967 return ReplaceInstUsesWith(SCI, ConstantBool::False);
3968 if (SCI.getOpcode() == Instruction::SetNE)
3969 return ReplaceInstUsesWith(SCI, ConstantBool::True);
3970
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003971 // Evaluate the comparison for LT.
3972 Value *Result;
3973 if (DestTy->isSigned()) {
3974 // We're performing a signed comparison.
3975 if (isSignSrc) {
3976 // Signed extend and signed comparison.
3977 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
3978 Result = ConstantBool::False;
3979 else
3980 Result = ConstantBool::True; // X < (large) --> true
3981 } else {
3982 // Unsigned extend and signed comparison.
3983 if (cast<ConstantSInt>(CI)->getValue() < 0)
3984 Result = ConstantBool::False;
3985 else
3986 Result = ConstantBool::True;
3987 }
3988 } else {
3989 // We're performing an unsigned comparison.
3990 if (!isSignSrc) {
3991 // Unsigned extend & compare -> always true.
3992 Result = ConstantBool::True;
3993 } else {
3994 // We're performing an unsigned comp with a sign extended value.
3995 // This is true if the input is >= 0. [aka >s -1]
3996 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
3997 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
3998 NegOne, SCI.getName()), SCI);
3999 }
Reid Spencer279fa252004-11-28 21:31:15 +00004000 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004001
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004002 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004003 if (SCI.getOpcode() == Instruction::SetLT) {
4004 return ReplaceInstUsesWith(SCI, Result);
4005 } else {
4006 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4007 if (Constant *CI = dyn_cast<Constant>(Result))
4008 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4009 else
4010 return BinaryOperator::createNot(Result);
4011 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004012 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004013 } else {
4014 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00004015 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004016
Chris Lattner252a8452005-06-16 03:00:08 +00004017 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004018 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4019}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004020
Chris Lattnere8d6c602003-03-10 19:16:08 +00004021Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00004022 assert(I.getOperand(1)->getType() == Type::UByteTy);
4023 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004024 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004025
4026 // shl X, 0 == X and shr X, 0 == X
4027 // shl 0, X == 0 and shr 0, X == 0
4028 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00004029 Op0 == Constant::getNullValue(Op0->getType()))
4030 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004031
Chris Lattner81a7a232004-10-16 18:11:37 +00004032 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4033 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00004034 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00004035 else // undef << X -> 0 AND undef >>u X -> 0
4036 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4037 }
4038 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00004039 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00004040 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4041 else
4042 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
4043 }
4044
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004045 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
4046 if (!isLeftShift)
4047 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
4048 if (CSI->isAllOnesValue())
4049 return ReplaceInstUsesWith(I, CSI);
4050
Chris Lattner183b3362004-04-09 19:05:30 +00004051 // Try to fold constant and into select arguments.
4052 if (isa<Constant>(Op0))
4053 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00004054 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004055 return R;
4056
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00004057 // See if we can turn a signed shr into an unsigned shr.
4058 if (!isLeftShift && I.getType()->isSigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004059 if (MaskedValueIsZero(Op0,
4060 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00004061 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
4062 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
4063 I.getName()), I);
4064 return new CastInst(V, I.getType());
4065 }
4066 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004067
Chris Lattner14553932006-01-06 07:12:35 +00004068 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
4069 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4070 return Res;
4071 return 0;
4072}
4073
4074Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
4075 ShiftInst &I) {
4076 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerb3309392006-01-06 07:22:22 +00004077 bool isSignedShift = Op0->getType()->isSigned();
4078 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00004079
4080 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
4081 // of a signed value.
4082 //
4083 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
4084 if (Op1->getValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00004085 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00004086 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
4087 else {
4088 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
4089 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00004090 }
Chris Lattner14553932006-01-06 07:12:35 +00004091 }
4092
4093 // ((X*C1) << C2) == (X * (C1 << C2))
4094 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4095 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4096 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4097 return BinaryOperator::createMul(BO->getOperand(0),
4098 ConstantExpr::getShl(BOOp, Op1));
4099
4100 // Try to fold constant and into select arguments.
4101 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4102 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4103 return R;
4104 if (isa<PHINode>(Op0))
4105 if (Instruction *NV = FoldOpIntoPhi(I))
4106 return NV;
4107
4108 if (Op0->hasOneUse()) {
4109 // If this is a SHL of a sign-extending cast, see if we can turn the input
4110 // into a zero extending cast (a simple strength reduction).
4111 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4112 const Type *SrcTy = CI->getOperand(0)->getType();
4113 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
4114 SrcTy->getPrimitiveSizeInBits() <
4115 CI->getType()->getPrimitiveSizeInBits()) {
4116 // We can change it to a zero extension if we are shifting out all of
4117 // the sign extended bits. To check this, form a mask of all of the
4118 // sign extend bits, then shift them left and see if we have anything
4119 // left.
4120 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
4121 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
4122 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
4123 if (ConstantExpr::getShl(Mask, Op1)->isNullValue()) {
4124 // If the shift is nuking all of the sign bits, change this to a
4125 // zero extension cast. To do this, cast the cast input to
4126 // unsigned, then to the requested size.
4127 Value *CastOp = CI->getOperand(0);
4128 Instruction *NC =
4129 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
4130 CI->getName()+".uns");
4131 NC = InsertNewInstBefore(NC, I);
4132 // Finally, insert a replacement for CI.
4133 NC = new CastInst(NC, CI->getType(), CI->getName());
4134 CI->setName("");
4135 NC = InsertNewInstBefore(NC, I);
4136 WorkList.push_back(CI); // Delete CI later.
4137 I.setOperand(0, NC);
4138 return &I; // The SHL operand was modified.
Chris Lattner86102b82005-01-01 16:22:27 +00004139 }
4140 }
Chris Lattner14553932006-01-06 07:12:35 +00004141 }
4142
4143 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4144 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4145 Value *V1, *V2;
4146 ConstantInt *CC;
4147 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00004148 default: break;
4149 case Instruction::Add:
4150 case Instruction::And:
4151 case Instruction::Or:
4152 case Instruction::Xor:
4153 // These operators commute.
4154 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004155 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4156 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00004157 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004158 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004159 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004160 Op0BO->getName());
4161 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004162 Instruction *X =
4163 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4164 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00004165 InsertNewInstBefore(X, I); // (X + (Y << C))
4166 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00004167 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00004168 return BinaryOperator::createAnd(X, C2);
4169 }
Chris Lattner14553932006-01-06 07:12:35 +00004170
Chris Lattner797dee72005-09-18 06:30:59 +00004171 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
4172 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4173 match(Op0BO->getOperand(1),
4174 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00004175 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004176 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00004177 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004178 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004179 Op0BO->getName());
4180 InsertNewInstBefore(YS, I); // (Y << C)
4181 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00004182 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00004183 V1->getName()+".mask");
4184 InsertNewInstBefore(XM, I); // X & (CC << C)
4185
4186 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4187 }
Chris Lattner14553932006-01-06 07:12:35 +00004188
Chris Lattner797dee72005-09-18 06:30:59 +00004189 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00004190 case Instruction::Sub:
4191 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004192 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4193 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00004194 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004195 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004196 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004197 Op0BO->getName());
4198 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004199 Instruction *X =
4200 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4201 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00004202 InsertNewInstBefore(X, I); // (X + (Y << C))
4203 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00004204 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00004205 return BinaryOperator::createAnd(X, C2);
4206 }
Chris Lattner14553932006-01-06 07:12:35 +00004207
Chris Lattner797dee72005-09-18 06:30:59 +00004208 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4209 match(Op0BO->getOperand(0),
4210 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00004211 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004212 cast<BinaryOperator>(Op0BO->getOperand(0))
4213 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00004214 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004215 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004216 Op0BO->getName());
4217 InsertNewInstBefore(YS, I); // (Y << C)
4218 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00004219 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00004220 V1->getName()+".mask");
4221 InsertNewInstBefore(XM, I); // X & (CC << C)
4222
4223 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4224 }
Chris Lattner14553932006-01-06 07:12:35 +00004225
Chris Lattner27cb9db2005-09-18 05:12:10 +00004226 break;
Chris Lattner14553932006-01-06 07:12:35 +00004227 }
4228
4229
4230 // If the operand is an bitwise operator with a constant RHS, and the
4231 // shift is the only use, we can pull it out of the shift.
4232 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4233 bool isValid = true; // Valid only for And, Or, Xor
4234 bool highBitSet = false; // Transform if high bit of constant set?
4235
4236 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004237 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00004238 case Instruction::Add:
4239 isValid = isLeftShift;
4240 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004241 case Instruction::Or:
4242 case Instruction::Xor:
4243 highBitSet = false;
4244 break;
4245 case Instruction::And:
4246 highBitSet = true;
4247 break;
Chris Lattner14553932006-01-06 07:12:35 +00004248 }
4249
4250 // If this is a signed shift right, and the high bit is modified
4251 // by the logical operation, do not perform the transformation.
4252 // The highBitSet boolean indicates the value of the high bit of
4253 // the constant which would cause it to be modified for this
4254 // operation.
4255 //
Chris Lattnerb3309392006-01-06 07:22:22 +00004256 if (isValid && !isLeftShift && isSignedShift) {
Chris Lattner14553932006-01-06 07:12:35 +00004257 uint64_t Val = Op0C->getRawValue();
4258 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
4259 }
4260
4261 if (isValid) {
4262 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
4263
4264 Instruction *NewShift =
4265 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
4266 Op0BO->getName());
4267 Op0BO->setName("");
4268 InsertNewInstBefore(NewShift, I);
4269
4270 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
4271 NewRHS);
4272 }
4273 }
4274 }
4275 }
4276
Chris Lattnereb372a02006-01-06 07:52:12 +00004277 // Find out if this is a shift of a shift by a constant.
4278 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00004279 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00004280 ShiftOp = Op0SI;
4281 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4282 // If this is a noop-integer case of a shift instruction, use the shift.
4283 if (CI->getOperand(0)->getType()->isInteger() &&
4284 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4285 CI->getType()->getPrimitiveSizeInBits() &&
4286 isa<ShiftInst>(CI->getOperand(0))) {
4287 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
4288 }
4289 }
4290
4291 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
4292 // Find the operands and properties of the input shift. Note that the
4293 // signedness of the input shift may differ from the current shift if there
4294 // is a noop cast between the two.
4295 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
4296 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004297 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00004298
4299 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
4300
4301 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
4302 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
4303
4304 // Check for (A << c1) << c2 and (A >> c1) >> c2.
4305 if (isLeftShift == isShiftOfLeftShift) {
4306 // Do not fold these shifts if the first one is signed and the second one
4307 // is unsigned and this is a right shift. Further, don't do any folding
4308 // on them.
4309 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
4310 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00004311
Chris Lattnereb372a02006-01-06 07:52:12 +00004312 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
4313 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
4314 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00004315
Chris Lattnereb372a02006-01-06 07:52:12 +00004316 Value *Op = ShiftOp->getOperand(0);
4317 if (isShiftOfSignedShift != isSignedShift)
4318 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
4319 return new ShiftInst(I.getOpcode(), Op,
4320 ConstantUInt::get(Type::UByteTy, Amt));
4321 }
4322
4323 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
4324 // signed types, we can only support the (A >> c1) << c2 configuration,
4325 // because it can not turn an arbitrary bit of A into a sign bit.
4326 if (isUnsignedShift || isLeftShift) {
4327 // Calculate bitmask for what gets shifted off the edge.
4328 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
4329 if (isLeftShift)
4330 C = ConstantExpr::getShl(C, ShiftAmt1C);
4331 else
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004332 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00004333
4334 Value *Op = ShiftOp->getOperand(0);
4335 if (isShiftOfSignedShift != isSignedShift)
4336 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
4337
4338 Instruction *Mask =
4339 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
4340 InsertNewInstBefore(Mask, I);
4341
4342 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004343 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004344 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004345 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004346 return new ShiftInst(I.getOpcode(), Mask,
4347 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004348 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
4349 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
4350 // Make sure to emit an unsigned shift right, not a signed one.
4351 Mask = InsertNewInstBefore(new CastInst(Mask,
4352 Mask->getType()->getUnsignedVersion(),
4353 Op->getName()), I);
4354 Mask = new ShiftInst(Instruction::Shr, Mask,
Chris Lattnereb372a02006-01-06 07:52:12 +00004355 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004356 InsertNewInstBefore(Mask, I);
4357 return new CastInst(Mask, I.getType());
4358 } else {
4359 return new ShiftInst(ShiftOp->getOpcode(), Mask,
4360 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4361 }
4362 } else {
4363 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
4364 Op = InsertNewInstBefore(new CastInst(Mask,
4365 I.getType()->getSignedVersion(),
4366 Mask->getName()), I);
4367 Instruction *Shift =
4368 new ShiftInst(ShiftOp->getOpcode(), Op,
4369 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4370 InsertNewInstBefore(Shift, I);
4371
4372 C = ConstantIntegral::getAllOnesValue(Shift->getType());
4373 C = ConstantExpr::getShl(C, Op1);
4374 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
4375 InsertNewInstBefore(Mask, I);
4376 return new CastInst(Mask, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00004377 }
4378 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004379 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00004380 // this case, C1 == C2 and C1 is 8, 16, or 32.
4381 if (ShiftAmt1 == ShiftAmt2) {
4382 const Type *SExtType = 0;
4383 switch (ShiftAmt1) {
4384 case 8 : SExtType = Type::SByteTy; break;
4385 case 16: SExtType = Type::ShortTy; break;
4386 case 32: SExtType = Type::IntTy; break;
4387 }
4388
4389 if (SExtType) {
4390 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
4391 SExtType, "sext");
4392 InsertNewInstBefore(NewTrunc, I);
4393 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004394 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00004395 }
Chris Lattner86102b82005-01-01 16:22:27 +00004396 }
Chris Lattnereb372a02006-01-06 07:52:12 +00004397 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004398 return 0;
4399}
4400
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004401enum CastType {
4402 Noop = 0,
4403 Truncate = 1,
4404 Signext = 2,
4405 Zeroext = 3
4406};
4407
4408/// getCastType - In the future, we will split the cast instruction into these
4409/// various types. Until then, we have to do the analysis here.
4410static CastType getCastType(const Type *Src, const Type *Dest) {
4411 assert(Src->isIntegral() && Dest->isIntegral() &&
4412 "Only works on integral types!");
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004413 unsigned SrcSize = Src->getPrimitiveSizeInBits();
4414 unsigned DestSize = Dest->getPrimitiveSizeInBits();
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004415
4416 if (SrcSize == DestSize) return Noop;
4417 if (SrcSize > DestSize) return Truncate;
4418 if (Src->isSigned()) return Signext;
4419 return Zeroext;
4420}
4421
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004422
Chris Lattner48a44f72002-05-02 17:06:02 +00004423// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
4424// instruction.
4425//
Chris Lattnere154abf2006-01-19 07:40:22 +00004426static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
4427 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00004428
Chris Lattner650b6da2002-08-02 20:00:25 +00004429 // It is legal to eliminate the instruction if casting A->B->A if the sizes
Misha Brukmanb1c93172005-04-21 23:48:37 +00004430 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00004431 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00004432 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00004433 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00004434
Chris Lattner4fbad962004-07-21 04:27:24 +00004435 // If we are casting between pointer and integer types, treat pointers as
4436 // integers of the appropriate size for the code below.
4437 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
4438 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
4439 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00004440
Chris Lattner48a44f72002-05-02 17:06:02 +00004441 // Allow free casting and conversion of sizes as long as the sign doesn't
4442 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00004443 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004444 CastType FirstCast = getCastType(SrcTy, MidTy);
4445 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00004446
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004447 // Capture the effect of these two casts. If the result is a legal cast,
4448 // the CastType is stored here, otherwise a special code is used.
4449 static const unsigned CastResult[] = {
4450 // First cast is noop
4451 0, 1, 2, 3,
4452 // First cast is a truncate
4453 1, 1, 4, 4, // trunc->extend is not safe to eliminate
4454 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00004455 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004456 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00004457 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004458 };
4459
4460 unsigned Result = CastResult[FirstCast*4+SecondCast];
4461 switch (Result) {
4462 default: assert(0 && "Illegal table value!");
4463 case 0:
4464 case 1:
4465 case 2:
4466 case 3:
4467 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
4468 // truncates, we could eliminate more casts.
4469 return (unsigned)getCastType(SrcTy, DstTy) == Result;
4470 case 4:
4471 return false; // Not possible to eliminate this here.
4472 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00004473 // Sign or zero extend followed by truncate is always ok if the result
4474 // is a truncate or noop.
4475 CastType ResultCast = getCastType(SrcTy, DstTy);
4476 if (ResultCast == Noop || ResultCast == Truncate)
4477 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004478 // Otherwise we are still growing the value, we are only safe if the
Chris Lattner1638de42004-07-21 19:50:44 +00004479 // result will match the sign/zeroextendness of the result.
4480 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00004481 }
Chris Lattner650b6da2002-08-02 20:00:25 +00004482 }
Chris Lattnere154abf2006-01-19 07:40:22 +00004483
4484 // If this is a cast from 'float -> double -> integer', cast from
4485 // 'float -> integer' directly, as the value isn't changed by the
4486 // float->double conversion.
4487 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
4488 DstTy->isIntegral() &&
4489 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
4490 return true;
4491
Chris Lattner48a44f72002-05-02 17:06:02 +00004492 return false;
4493}
4494
Chris Lattner11ffd592004-07-20 05:21:00 +00004495static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004496 if (V->getType() == Ty || isa<Constant>(V)) return false;
4497 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00004498 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
4499 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004500 return false;
4501 return true;
4502}
4503
4504/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
4505/// InsertBefore instruction. This is specialized a bit to avoid inserting
4506/// casts that are known to not do anything...
4507///
4508Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
4509 Instruction *InsertBefore) {
4510 if (V->getType() == DestTy) return V;
4511 if (Constant *C = dyn_cast<Constant>(V))
4512 return ConstantExpr::getCast(C, DestTy);
4513
4514 CastInst *CI = new CastInst(V, DestTy, V->getName());
4515 InsertNewInstBefore(CI, *InsertBefore);
4516 return CI;
4517}
Chris Lattner48a44f72002-05-02 17:06:02 +00004518
Chris Lattner8f663e82005-10-29 04:36:15 +00004519/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4520/// expression. If so, decompose it, returning some value X, such that Val is
4521/// X*Scale+Offset.
4522///
4523static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4524 unsigned &Offset) {
4525 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4526 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4527 Offset = CI->getValue();
4528 Scale = 1;
4529 return ConstantUInt::get(Type::UIntTy, 0);
4530 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4531 if (I->getNumOperands() == 2) {
4532 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4533 if (I->getOpcode() == Instruction::Shl) {
4534 // This is a value scaled by '1 << the shift amt'.
4535 Scale = 1U << CUI->getValue();
4536 Offset = 0;
4537 return I->getOperand(0);
4538 } else if (I->getOpcode() == Instruction::Mul) {
4539 // This value is scaled by 'CUI'.
4540 Scale = CUI->getValue();
4541 Offset = 0;
4542 return I->getOperand(0);
4543 } else if (I->getOpcode() == Instruction::Add) {
4544 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
4545 // divisible by C2.
4546 unsigned SubScale;
4547 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
4548 Offset);
4549 Offset += CUI->getValue();
4550 if (SubScale > 1 && (Offset % SubScale == 0)) {
4551 Scale = SubScale;
4552 return SubVal;
4553 }
4554 }
4555 }
4556 }
4557 }
4558
4559 // Otherwise, we can't look past this.
4560 Scale = 1;
4561 Offset = 0;
4562 return Val;
4563}
4564
4565
Chris Lattner216be912005-10-24 06:03:58 +00004566/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4567/// try to eliminate the cast by moving the type information into the alloc.
4568Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
4569 AllocationInst &AI) {
4570 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00004571 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00004572
Chris Lattnerac87beb2005-10-24 06:22:12 +00004573 // Remove any uses of AI that are dead.
4574 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
4575 std::vector<Instruction*> DeadUsers;
4576 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4577 Instruction *User = cast<Instruction>(*UI++);
4578 if (isInstructionTriviallyDead(User)) {
4579 while (UI != E && *UI == User)
4580 ++UI; // If this instruction uses AI more than once, don't break UI.
4581
4582 // Add operands to the worklist.
4583 AddUsesToWorkList(*User);
4584 ++NumDeadInst;
4585 DEBUG(std::cerr << "IC: DCE: " << *User);
4586
4587 User->eraseFromParent();
4588 removeFromWorkList(User);
4589 }
4590 }
4591
Chris Lattner216be912005-10-24 06:03:58 +00004592 // Get the type really allocated and the type casted to.
4593 const Type *AllocElTy = AI.getAllocatedType();
4594 const Type *CastElTy = PTy->getElementType();
4595 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00004596
4597 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
4598 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
4599 if (CastElTyAlign < AllocElTyAlign) return 0;
4600
Chris Lattner46705b22005-10-24 06:35:18 +00004601 // If the allocation has multiple uses, only promote it if we are strictly
4602 // increasing the alignment of the resultant allocation. If we keep it the
4603 // same, we open the door to infinite loops of various kinds.
4604 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
4605
Chris Lattner216be912005-10-24 06:03:58 +00004606 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
4607 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00004608 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00004609
Chris Lattner8270c332005-10-29 03:19:53 +00004610 // See if we can satisfy the modulus by pulling a scale out of the array
4611 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00004612 unsigned ArraySizeScale, ArrayOffset;
4613 Value *NumElements = // See if the array size is a decomposable linear expr.
4614 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
4615
Chris Lattner8270c332005-10-29 03:19:53 +00004616 // If we can now satisfy the modulus, by using a non-1 scale, we really can
4617 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00004618 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4619 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00004620
Chris Lattner8270c332005-10-29 03:19:53 +00004621 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4622 Value *Amt = 0;
4623 if (Scale == 1) {
4624 Amt = NumElements;
4625 } else {
4626 Amt = ConstantUInt::get(Type::UIntTy, Scale);
4627 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4628 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4629 else if (Scale != 1) {
4630 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4631 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00004632 }
Chris Lattnerbb171802005-10-27 05:53:56 +00004633 }
4634
Chris Lattner8f663e82005-10-29 04:36:15 +00004635 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4636 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4637 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4638 Amt = InsertNewInstBefore(Tmp, AI);
4639 }
4640
Chris Lattner216be912005-10-24 06:03:58 +00004641 std::string Name = AI.getName(); AI.setName("");
4642 AllocationInst *New;
4643 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00004644 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00004645 else
Nate Begeman848622f2005-11-05 09:21:28 +00004646 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00004647 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00004648
4649 // If the allocation has multiple uses, insert a cast and change all things
4650 // that used it to use the new cast. This will also hack on CI, but it will
4651 // die soon.
4652 if (!AI.hasOneUse()) {
4653 AddUsesToWorkList(AI);
4654 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4655 InsertNewInstBefore(NewCast, AI);
4656 AI.replaceAllUsesWith(NewCast);
4657 }
Chris Lattner216be912005-10-24 06:03:58 +00004658 return ReplaceInstUsesWith(CI, New);
4659}
4660
4661
Chris Lattner48a44f72002-05-02 17:06:02 +00004662// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00004663//
Chris Lattner113f4f42002-06-25 16:13:24 +00004664Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00004665 Value *Src = CI.getOperand(0);
4666
Chris Lattner48a44f72002-05-02 17:06:02 +00004667 // If the user is casting a value to the same type, eliminate this cast
4668 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00004669 if (CI.getType() == Src->getType())
4670 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00004671
Chris Lattner81a7a232004-10-16 18:11:37 +00004672 if (isa<UndefValue>(Src)) // cast undef -> undef
4673 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
4674
Chris Lattner48a44f72002-05-02 17:06:02 +00004675 // If casting the result of another cast instruction, try to eliminate this
4676 // one!
4677 //
Chris Lattner86102b82005-01-01 16:22:27 +00004678 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
4679 Value *A = CSrc->getOperand(0);
4680 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
4681 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00004682 // This instruction now refers directly to the cast's src operand. This
4683 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00004684 CI.setOperand(0, CSrc->getOperand(0));
4685 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00004686 }
4687
Chris Lattner650b6da2002-08-02 20:00:25 +00004688 // If this is an A->B->A cast, and we are dealing with integral types, try
4689 // to convert this into a logical 'and' instruction.
4690 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00004691 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00004692 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00004693 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004694 CSrc->getType()->getPrimitiveSizeInBits() <
4695 CI.getType()->getPrimitiveSizeInBits()&&
4696 A->getType()->getPrimitiveSizeInBits() ==
4697 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00004698 assert(CSrc->getType() != Type::ULongTy &&
4699 "Cannot have type bigger than ulong!");
Chris Lattner77defba2006-02-07 07:00:41 +00004700 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Chris Lattner86102b82005-01-01 16:22:27 +00004701 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
4702 AndValue);
4703 AndOp = ConstantExpr::getCast(AndOp, A->getType());
4704 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
4705 if (And->getType() != CI.getType()) {
4706 And->setName(CSrc->getName()+".mask");
4707 InsertNewInstBefore(And, CI);
4708 And = new CastInst(And, CI.getType());
4709 }
4710 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00004711 }
4712 }
Chris Lattner2590e512006-02-07 06:56:34 +00004713
Chris Lattner03841652004-05-25 04:29:21 +00004714 // If this is a cast to bool, turn it into the appropriate setne instruction.
4715 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004716 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00004717 Constant::getNullValue(CI.getOperand(0)->getType()));
4718
Chris Lattner2590e512006-02-07 06:56:34 +00004719 // See if we can simplify any instructions used by the LHS whose sole
4720 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00004721 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
4722 uint64_t KnownZero, KnownOne;
4723 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
4724 KnownZero, KnownOne))
4725 return &CI;
4726 }
Chris Lattner2590e512006-02-07 06:56:34 +00004727
Chris Lattnerd0d51602003-06-21 23:12:02 +00004728 // If casting the result of a getelementptr instruction with no offset, turn
4729 // this into a cast of the original pointer!
4730 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00004731 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00004732 bool AllZeroOperands = true;
4733 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
4734 if (!isa<Constant>(GEP->getOperand(i)) ||
4735 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
4736 AllZeroOperands = false;
4737 break;
4738 }
4739 if (AllZeroOperands) {
4740 CI.setOperand(0, GEP->getOperand(0));
4741 return &CI;
4742 }
4743 }
4744
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004745 // If we are casting a malloc or alloca to a pointer to a type of the same
4746 // size, rewrite the allocation instruction to allocate the "right" type.
4747 //
4748 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00004749 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4750 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004751
Chris Lattner86102b82005-01-01 16:22:27 +00004752 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4753 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4754 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004755 if (isa<PHINode>(Src))
4756 if (Instruction *NV = FoldOpIntoPhi(CI))
4757 return NV;
4758
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004759 // If the source value is an instruction with only this use, we can attempt to
4760 // propagate the cast into the instruction. Also, only handle integral types
4761 // for now.
4762 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004763 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004764 CI.getType()->isInteger()) { // Don't mess with casts to bool here
4765 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004766 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
4767 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004768
4769 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
4770 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
4771
4772 switch (SrcI->getOpcode()) {
4773 case Instruction::Add:
4774 case Instruction::Mul:
4775 case Instruction::And:
4776 case Instruction::Or:
4777 case Instruction::Xor:
4778 // If we are discarding information, or just changing the sign, rewrite.
4779 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
4780 // Don't insert two casts if they cannot be eliminated. We allow two
4781 // casts to be inserted if the sizes are the same. This could only be
4782 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00004783 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
4784 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004785 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4786 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
4787 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
4788 ->getOpcode(), Op0c, Op1c);
4789 }
4790 }
Chris Lattner72086162005-05-06 02:07:39 +00004791
4792 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
4793 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
4794 Op1 == ConstantBool::True &&
4795 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
4796 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
4797 return BinaryOperator::createXor(New,
4798 ConstantInt::get(CI.getType(), 1));
4799 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004800 break;
4801 case Instruction::Shl:
4802 // Allow changing the sign of the source operand. Do not allow changing
4803 // the size of the shift, UNLESS the shift amount is a constant. We
4804 // mush not change variable sized shifts to a smaller size, because it
4805 // is undefined to shift more bits out than exist in the value.
4806 if (DestBitSize == SrcBitSize ||
4807 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
4808 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4809 return new ShiftInst(Instruction::Shl, Op0c, Op1);
4810 }
4811 break;
Chris Lattner87380412005-05-06 04:18:52 +00004812 case Instruction::Shr:
4813 // If this is a signed shr, and if all bits shifted in are about to be
4814 // truncated off, turn it into an unsigned shr to allow greater
4815 // simplifications.
4816 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
4817 isa<ConstantInt>(Op1)) {
4818 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
4819 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
4820 // Convert to unsigned.
4821 Value *N1 = InsertOperandCastBefore(Op0,
4822 Op0->getType()->getUnsignedVersion(), &CI);
4823 // Insert the new shift, which is now unsigned.
4824 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
4825 Op1, Src->getName()), CI);
4826 return new CastInst(N1, CI.getType());
4827 }
4828 }
4829 break;
4830
Chris Lattner809dfac2005-05-04 19:10:26 +00004831 case Instruction::SetNE:
Chris Lattner809dfac2005-05-04 19:10:26 +00004832 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00004833 if (Op1C->getRawValue() == 0) {
4834 // If the input only has the low bit set, simplify directly.
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004835 Constant *Not1 =
Chris Lattner809dfac2005-05-04 19:10:26 +00004836 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
Chris Lattner4c2d3782005-05-06 01:53:19 +00004837 // cast (X != 0) to int --> X if X&~1 == 0
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004838 if (MaskedValueIsZero(Op0,
4839 cast<ConstantIntegral>(Not1)->getZExtValue())) {
Chris Lattner809dfac2005-05-04 19:10:26 +00004840 if (CI.getType() == Op0->getType())
4841 return ReplaceInstUsesWith(CI, Op0);
4842 else
4843 return new CastInst(Op0, CI.getType());
4844 }
Chris Lattner4c2d3782005-05-06 01:53:19 +00004845
4846 // If the input is an and with a single bit, shift then simplify.
4847 ConstantInt *AndRHS;
4848 if (match(Op0, m_And(m_Value(), m_ConstantInt(AndRHS))))
4849 if (AndRHS->getRawValue() &&
4850 (AndRHS->getRawValue() & (AndRHS->getRawValue()-1)) == 0) {
Chris Lattner22d00a82005-08-02 19:16:58 +00004851 unsigned ShiftAmt = Log2_64(AndRHS->getRawValue());
Chris Lattner4c2d3782005-05-06 01:53:19 +00004852 // Perform an unsigned shr by shiftamt. Convert input to
4853 // unsigned if it is signed.
4854 Value *In = Op0;
4855 if (In->getType()->isSigned())
4856 In = InsertNewInstBefore(new CastInst(In,
4857 In->getType()->getUnsignedVersion(), In->getName()),CI);
4858 // Insert the shift to put the result in the low bit.
4859 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
4860 ConstantInt::get(Type::UByteTy, ShiftAmt),
4861 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00004862 if (CI.getType() == In->getType())
4863 return ReplaceInstUsesWith(CI, In);
4864 else
4865 return new CastInst(In, CI.getType());
4866 }
4867 }
4868 }
4869 break;
4870 case Instruction::SetEQ:
4871 // We if we are just checking for a seteq of a single bit and casting it
4872 // to an integer. If so, shift the bit to the appropriate place then
4873 // cast to integer to avoid the comparison.
4874 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
4875 // Is Op1C a power of two or zero?
4876 if ((Op1C->getRawValue() & Op1C->getRawValue()-1) == 0) {
4877 // cast (X == 1) to int -> X iff X has only the low bit set.
4878 if (Op1C->getRawValue() == 1) {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004879 Constant *Not1 =
Chris Lattner4c2d3782005-05-06 01:53:19 +00004880 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004881 if (MaskedValueIsZero(Op0,
4882 cast<ConstantIntegral>(Not1)->getZExtValue())) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00004883 if (CI.getType() == Op0->getType())
4884 return ReplaceInstUsesWith(CI, Op0);
4885 else
4886 return new CastInst(Op0, CI.getType());
4887 }
4888 }
Chris Lattner809dfac2005-05-04 19:10:26 +00004889 }
4890 }
4891 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004892 }
4893 }
Chris Lattnerbb171802005-10-27 05:53:56 +00004894
Chris Lattner260ab202002-04-18 17:39:14 +00004895 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00004896}
4897
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004898/// GetSelectFoldableOperands - We want to turn code that looks like this:
4899/// %C = or %A, %B
4900/// %D = select %cond, %C, %A
4901/// into:
4902/// %C = select %cond, %B, 0
4903/// %D = or %A, %C
4904///
4905/// Assuming that the specified instruction is an operand to the select, return
4906/// a bitmask indicating which operands of this instruction are foldable if they
4907/// equal the other incoming value of the select.
4908///
4909static unsigned GetSelectFoldableOperands(Instruction *I) {
4910 switch (I->getOpcode()) {
4911 case Instruction::Add:
4912 case Instruction::Mul:
4913 case Instruction::And:
4914 case Instruction::Or:
4915 case Instruction::Xor:
4916 return 3; // Can fold through either operand.
4917 case Instruction::Sub: // Can only fold on the amount subtracted.
4918 case Instruction::Shl: // Can only fold on the shift amount.
4919 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00004920 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004921 default:
4922 return 0; // Cannot fold
4923 }
4924}
4925
4926/// GetSelectFoldableConstant - For the same transformation as the previous
4927/// function, return the identity constant that goes into the select.
4928static Constant *GetSelectFoldableConstant(Instruction *I) {
4929 switch (I->getOpcode()) {
4930 default: assert(0 && "This cannot happen!"); abort();
4931 case Instruction::Add:
4932 case Instruction::Sub:
4933 case Instruction::Or:
4934 case Instruction::Xor:
4935 return Constant::getNullValue(I->getType());
4936 case Instruction::Shl:
4937 case Instruction::Shr:
4938 return Constant::getNullValue(Type::UByteTy);
4939 case Instruction::And:
4940 return ConstantInt::getAllOnesValue(I->getType());
4941 case Instruction::Mul:
4942 return ConstantInt::get(I->getType(), 1);
4943 }
4944}
4945
Chris Lattner411336f2005-01-19 21:50:18 +00004946/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
4947/// have the same opcode and only one use each. Try to simplify this.
4948Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
4949 Instruction *FI) {
4950 if (TI->getNumOperands() == 1) {
4951 // If this is a non-volatile load or a cast from the same type,
4952 // merge.
4953 if (TI->getOpcode() == Instruction::Cast) {
4954 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
4955 return 0;
4956 } else {
4957 return 0; // unknown unary op.
4958 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004959
Chris Lattner411336f2005-01-19 21:50:18 +00004960 // Fold this by inserting a select from the input values.
4961 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
4962 FI->getOperand(0), SI.getName()+".v");
4963 InsertNewInstBefore(NewSI, SI);
4964 return new CastInst(NewSI, TI->getType());
4965 }
4966
4967 // Only handle binary operators here.
4968 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
4969 return 0;
4970
4971 // Figure out if the operations have any operands in common.
4972 Value *MatchOp, *OtherOpT, *OtherOpF;
4973 bool MatchIsOpZero;
4974 if (TI->getOperand(0) == FI->getOperand(0)) {
4975 MatchOp = TI->getOperand(0);
4976 OtherOpT = TI->getOperand(1);
4977 OtherOpF = FI->getOperand(1);
4978 MatchIsOpZero = true;
4979 } else if (TI->getOperand(1) == FI->getOperand(1)) {
4980 MatchOp = TI->getOperand(1);
4981 OtherOpT = TI->getOperand(0);
4982 OtherOpF = FI->getOperand(0);
4983 MatchIsOpZero = false;
4984 } else if (!TI->isCommutative()) {
4985 return 0;
4986 } else if (TI->getOperand(0) == FI->getOperand(1)) {
4987 MatchOp = TI->getOperand(0);
4988 OtherOpT = TI->getOperand(1);
4989 OtherOpF = FI->getOperand(0);
4990 MatchIsOpZero = true;
4991 } else if (TI->getOperand(1) == FI->getOperand(0)) {
4992 MatchOp = TI->getOperand(1);
4993 OtherOpT = TI->getOperand(0);
4994 OtherOpF = FI->getOperand(1);
4995 MatchIsOpZero = true;
4996 } else {
4997 return 0;
4998 }
4999
5000 // If we reach here, they do have operations in common.
5001 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
5002 OtherOpF, SI.getName()+".v");
5003 InsertNewInstBefore(NewSI, SI);
5004
5005 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
5006 if (MatchIsOpZero)
5007 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
5008 else
5009 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
5010 } else {
5011 if (MatchIsOpZero)
5012 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
5013 else
5014 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
5015 }
5016}
5017
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005018Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00005019 Value *CondVal = SI.getCondition();
5020 Value *TrueVal = SI.getTrueValue();
5021 Value *FalseVal = SI.getFalseValue();
5022
5023 // select true, X, Y -> X
5024 // select false, X, Y -> Y
5025 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005026 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00005027 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005028 else {
5029 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00005030 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005031 }
Chris Lattner533bc492004-03-30 19:37:13 +00005032
5033 // select C, X, X -> X
5034 if (TrueVal == FalseVal)
5035 return ReplaceInstUsesWith(SI, TrueVal);
5036
Chris Lattner81a7a232004-10-16 18:11:37 +00005037 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
5038 return ReplaceInstUsesWith(SI, FalseVal);
5039 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
5040 return ReplaceInstUsesWith(SI, TrueVal);
5041 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
5042 if (isa<Constant>(TrueVal))
5043 return ReplaceInstUsesWith(SI, TrueVal);
5044 else
5045 return ReplaceInstUsesWith(SI, FalseVal);
5046 }
5047
Chris Lattner1c631e82004-04-08 04:43:23 +00005048 if (SI.getType() == Type::BoolTy)
5049 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
5050 if (C == ConstantBool::True) {
5051 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005052 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005053 } else {
5054 // Change: A = select B, false, C --> A = and !B, C
5055 Value *NotCond =
5056 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5057 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005058 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005059 }
5060 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
5061 if (C == ConstantBool::False) {
5062 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005063 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005064 } else {
5065 // Change: A = select B, C, true --> A = or !B, C
5066 Value *NotCond =
5067 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5068 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005069 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005070 }
5071 }
5072
Chris Lattner183b3362004-04-09 19:05:30 +00005073 // Selecting between two integer constants?
5074 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5075 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
5076 // select C, 1, 0 -> cast C to int
5077 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
5078 return new CastInst(CondVal, SI.getType());
5079 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
5080 // select C, 0, 1 -> cast !C to int
5081 Value *NotCond =
5082 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00005083 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00005084 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00005085 }
Chris Lattner35167c32004-06-09 07:59:58 +00005086
5087 // If one of the constants is zero (we know they can't both be) and we
5088 // have a setcc instruction with zero, and we have an 'and' with the
5089 // non-constant value, eliminate this whole mess. This corresponds to
5090 // cases like this: ((X & 27) ? 27 : 0)
5091 if (TrueValC->isNullValue() || FalseValC->isNullValue())
5092 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
5093 if ((IC->getOpcode() == Instruction::SetEQ ||
5094 IC->getOpcode() == Instruction::SetNE) &&
5095 isa<ConstantInt>(IC->getOperand(1)) &&
5096 cast<Constant>(IC->getOperand(1))->isNullValue())
5097 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
5098 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005099 isa<ConstantInt>(ICA->getOperand(1)) &&
5100 (ICA->getOperand(1) == TrueValC ||
5101 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00005102 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
5103 // Okay, now we know that everything is set up, we just don't
5104 // know whether we have a setne or seteq and whether the true or
5105 // false val is the zero.
5106 bool ShouldNotVal = !TrueValC->isNullValue();
5107 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
5108 Value *V = ICA;
5109 if (ShouldNotVal)
5110 V = InsertNewInstBefore(BinaryOperator::create(
5111 Instruction::Xor, V, ICA->getOperand(1)), SI);
5112 return ReplaceInstUsesWith(SI, V);
5113 }
Chris Lattner533bc492004-03-30 19:37:13 +00005114 }
Chris Lattner623fba12004-04-10 22:21:27 +00005115
5116 // See if we are selecting two values based on a comparison of the two values.
5117 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
5118 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
5119 // Transform (X == Y) ? X : Y -> Y
5120 if (SCI->getOpcode() == Instruction::SetEQ)
5121 return ReplaceInstUsesWith(SI, FalseVal);
5122 // Transform (X != Y) ? X : Y -> X
5123 if (SCI->getOpcode() == Instruction::SetNE)
5124 return ReplaceInstUsesWith(SI, TrueVal);
5125 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5126
5127 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
5128 // Transform (X == Y) ? Y : X -> X
5129 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00005130 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00005131 // Transform (X != Y) ? Y : X -> Y
5132 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00005133 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00005134 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5135 }
5136 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005137
Chris Lattnera04c9042005-01-13 22:52:24 +00005138 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
5139 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
5140 if (TI->hasOneUse() && FI->hasOneUse()) {
5141 bool isInverse = false;
5142 Instruction *AddOp = 0, *SubOp = 0;
5143
Chris Lattner411336f2005-01-19 21:50:18 +00005144 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
5145 if (TI->getOpcode() == FI->getOpcode())
5146 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
5147 return IV;
5148
5149 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
5150 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00005151 if (TI->getOpcode() == Instruction::Sub &&
5152 FI->getOpcode() == Instruction::Add) {
5153 AddOp = FI; SubOp = TI;
5154 } else if (FI->getOpcode() == Instruction::Sub &&
5155 TI->getOpcode() == Instruction::Add) {
5156 AddOp = TI; SubOp = FI;
5157 }
5158
5159 if (AddOp) {
5160 Value *OtherAddOp = 0;
5161 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
5162 OtherAddOp = AddOp->getOperand(1);
5163 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
5164 OtherAddOp = AddOp->getOperand(0);
5165 }
5166
5167 if (OtherAddOp) {
5168 // So at this point we know we have:
5169 // select C, (add X, Y), (sub X, ?)
5170 // We can do the transform profitably if either 'Y' = '?' or '?' is
5171 // a constant.
5172 if (SubOp->getOperand(1) == AddOp ||
5173 isa<Constant>(SubOp->getOperand(1))) {
5174 Value *NegVal;
5175 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
5176 NegVal = ConstantExpr::getNeg(C);
5177 } else {
5178 NegVal = InsertNewInstBefore(
5179 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
5180 }
5181
Chris Lattner51726c42005-01-14 17:35:12 +00005182 Value *NewTrueOp = OtherAddOp;
Chris Lattnera04c9042005-01-13 22:52:24 +00005183 Value *NewFalseOp = NegVal;
5184 if (AddOp != TI)
5185 std::swap(NewTrueOp, NewFalseOp);
5186 Instruction *NewSel =
5187 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
Misha Brukmanb1c93172005-04-21 23:48:37 +00005188
Chris Lattnera04c9042005-01-13 22:52:24 +00005189 NewSel = InsertNewInstBefore(NewSel, SI);
Chris Lattner51726c42005-01-14 17:35:12 +00005190 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00005191 }
5192 }
5193 }
5194 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005195
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005196 // See if we can fold the select into one of our operands.
5197 if (SI.getType()->isInteger()) {
5198 // See the comment above GetSelectFoldableOperands for a description of the
5199 // transformation we are doing here.
5200 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
5201 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
5202 !isa<Constant>(FalseVal))
5203 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
5204 unsigned OpToFold = 0;
5205 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
5206 OpToFold = 1;
5207 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
5208 OpToFold = 2;
5209 }
5210
5211 if (OpToFold) {
5212 Constant *C = GetSelectFoldableConstant(TVI);
5213 std::string Name = TVI->getName(); TVI->setName("");
5214 Instruction *NewSel =
5215 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
5216 Name);
5217 InsertNewInstBefore(NewSel, SI);
5218 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
5219 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
5220 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
5221 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
5222 else {
5223 assert(0 && "Unknown instruction!!");
5224 }
5225 }
5226 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00005227
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005228 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
5229 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
5230 !isa<Constant>(TrueVal))
5231 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
5232 unsigned OpToFold = 0;
5233 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
5234 OpToFold = 1;
5235 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
5236 OpToFold = 2;
5237 }
5238
5239 if (OpToFold) {
5240 Constant *C = GetSelectFoldableConstant(FVI);
5241 std::string Name = FVI->getName(); FVI->setName("");
5242 Instruction *NewSel =
5243 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
5244 Name);
5245 InsertNewInstBefore(NewSel, SI);
5246 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
5247 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
5248 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
5249 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
5250 else {
5251 assert(0 && "Unknown instruction!!");
5252 }
5253 }
5254 }
5255 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00005256
5257 if (BinaryOperator::isNot(CondVal)) {
5258 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
5259 SI.setOperand(1, FalseVal);
5260 SI.setOperand(2, TrueVal);
5261 return &SI;
5262 }
5263
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005264 return 0;
5265}
5266
5267
Chris Lattnerc66b2232006-01-13 20:11:04 +00005268/// visitCallInst - CallInst simplification. This mostly only handles folding
5269/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
5270/// the heavy lifting.
5271///
Chris Lattner970c33a2003-06-19 17:00:31 +00005272Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00005273 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
5274 if (!II) return visitCallSite(&CI);
5275
Chris Lattner51ea1272004-02-28 05:22:00 +00005276 // Intrinsics cannot occur in an invoke, so handle them here instead of in
5277 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00005278 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00005279 bool Changed = false;
5280
5281 // memmove/cpy/set of zero bytes is a noop.
5282 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
5283 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
5284
5285 // FIXME: Increase alignment here.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005286
Chris Lattner00648e12004-10-12 04:52:52 +00005287 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
5288 if (CI->getRawValue() == 1) {
5289 // Replace the instruction with just byte operations. We would
5290 // transform other cases to loads/stores, but we don't know if
5291 // alignment is sufficient.
5292 }
Chris Lattner51ea1272004-02-28 05:22:00 +00005293 }
5294
Chris Lattner00648e12004-10-12 04:52:52 +00005295 // If we have a memmove and the source operation is a constant global,
5296 // then the source and dest pointers can't alias, so we can change this
5297 // into a call to memcpy.
Chris Lattnerc66b2232006-01-13 20:11:04 +00005298 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II))
Chris Lattner00648e12004-10-12 04:52:52 +00005299 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
5300 if (GVSrc->isConstant()) {
5301 Module *M = CI.getParent()->getParent()->getParent();
5302 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
5303 CI.getCalledFunction()->getFunctionType());
5304 CI.setOperand(0, MemCpy);
5305 Changed = true;
5306 }
5307
Chris Lattnerc66b2232006-01-13 20:11:04 +00005308 if (Changed) return II;
5309 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(II)) {
Chris Lattner95307542004-11-18 21:41:39 +00005310 // If this stoppoint is at the same source location as the previous
5311 // stoppoint in the chain, it is not needed.
5312 if (DbgStopPointInst *PrevSPI =
5313 dyn_cast<DbgStopPointInst>(SPI->getChain()))
5314 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
5315 SPI->getColNo() == PrevSPI->getColNo()) {
5316 SPI->replaceAllUsesWith(PrevSPI);
5317 return EraseInstFromFunction(CI);
5318 }
Chris Lattner503221f2006-01-13 21:28:09 +00005319 } else {
5320 switch (II->getIntrinsicID()) {
5321 default: break;
5322 case Intrinsic::stackrestore: {
5323 // If the save is right next to the restore, remove the restore. This can
5324 // happen when variable allocas are DCE'd.
5325 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
5326 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
5327 BasicBlock::iterator BI = SS;
5328 if (&*++BI == II)
5329 return EraseInstFromFunction(CI);
5330 }
5331 }
5332
5333 // If the stack restore is in a return/unwind block and if there are no
5334 // allocas or calls between the restore and the return, nuke the restore.
5335 TerminatorInst *TI = II->getParent()->getTerminator();
5336 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
5337 BasicBlock::iterator BI = II;
5338 bool CannotRemove = false;
5339 for (++BI; &*BI != TI; ++BI) {
5340 if (isa<AllocaInst>(BI) ||
5341 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
5342 CannotRemove = true;
5343 break;
5344 }
5345 }
5346 if (!CannotRemove)
5347 return EraseInstFromFunction(CI);
5348 }
5349 break;
5350 }
5351 }
Chris Lattner00648e12004-10-12 04:52:52 +00005352 }
5353
Chris Lattnerc66b2232006-01-13 20:11:04 +00005354 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00005355}
5356
5357// InvokeInst simplification
5358//
5359Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00005360 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00005361}
5362
Chris Lattneraec3d942003-10-07 22:32:43 +00005363// visitCallSite - Improvements for call and invoke instructions.
5364//
5365Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005366 bool Changed = false;
5367
5368 // If the callee is a constexpr cast of a function, attempt to move the cast
5369 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00005370 if (transformConstExprCastCall(CS)) return 0;
5371
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005372 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00005373
Chris Lattner61d9d812005-05-13 07:09:09 +00005374 if (Function *CalleeF = dyn_cast<Function>(Callee))
5375 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
5376 Instruction *OldCall = CS.getInstruction();
5377 // If the call and callee calling conventions don't match, this call must
5378 // be unreachable, as the call is undefined.
5379 new StoreInst(ConstantBool::True,
5380 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
5381 if (!OldCall->use_empty())
5382 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
5383 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
5384 return EraseInstFromFunction(*OldCall);
5385 return 0;
5386 }
5387
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005388 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
5389 // This instruction is not reachable, just remove it. We insert a store to
5390 // undef so that we know that this code is not reachable, despite the fact
5391 // that we can't modify the CFG here.
5392 new StoreInst(ConstantBool::True,
5393 UndefValue::get(PointerType::get(Type::BoolTy)),
5394 CS.getInstruction());
5395
5396 if (!CS.getInstruction()->use_empty())
5397 CS.getInstruction()->
5398 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
5399
5400 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
5401 // Don't break the CFG, insert a dummy cond branch.
5402 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
5403 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00005404 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005405 return EraseInstFromFunction(*CS.getInstruction());
5406 }
Chris Lattner81a7a232004-10-16 18:11:37 +00005407
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005408 const PointerType *PTy = cast<PointerType>(Callee->getType());
5409 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
5410 if (FTy->isVarArg()) {
5411 // See if we can optimize any arguments passed through the varargs area of
5412 // the call.
5413 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
5414 E = CS.arg_end(); I != E; ++I)
5415 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
5416 // If this cast does not effect the value passed through the varargs
5417 // area, we can eliminate the use of the cast.
5418 Value *Op = CI->getOperand(0);
5419 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
5420 *I = Op;
5421 Changed = true;
5422 }
5423 }
5424 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005425
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005426 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00005427}
5428
Chris Lattner970c33a2003-06-19 17:00:31 +00005429// transformConstExprCastCall - If the callee is a constexpr cast of a function,
5430// attempt to move the cast to the arguments of the call/invoke.
5431//
5432bool InstCombiner::transformConstExprCastCall(CallSite CS) {
5433 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
5434 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00005435 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00005436 return false;
Reid Spencer87436872004-07-18 00:38:32 +00005437 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00005438 Instruction *Caller = CS.getInstruction();
5439
5440 // Okay, this is a cast from a function to a different type. Unless doing so
5441 // would cause a type conversion of one of our arguments, change this call to
5442 // be a direct call with arguments casted to the appropriate types.
5443 //
5444 const FunctionType *FT = Callee->getFunctionType();
5445 const Type *OldRetTy = Caller->getType();
5446
Chris Lattner1f7942f2004-01-14 06:06:08 +00005447 // Check to see if we are changing the return type...
5448 if (OldRetTy != FT->getReturnType()) {
5449 if (Callee->isExternal() &&
5450 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
5451 !Caller->use_empty())
5452 return false; // Cannot transform this return value...
5453
5454 // If the callsite is an invoke instruction, and the return value is used by
5455 // a PHI node in a successor, we cannot change the return type of the call
5456 // because there is no place to put the cast instruction (without breaking
5457 // the critical edge). Bail out in this case.
5458 if (!Caller->use_empty())
5459 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
5460 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
5461 UI != E; ++UI)
5462 if (PHINode *PN = dyn_cast<PHINode>(*UI))
5463 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00005464 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00005465 return false;
5466 }
Chris Lattner970c33a2003-06-19 17:00:31 +00005467
5468 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
5469 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005470
Chris Lattner970c33a2003-06-19 17:00:31 +00005471 CallSite::arg_iterator AI = CS.arg_begin();
5472 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
5473 const Type *ParamTy = FT->getParamType(i);
5474 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005475 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00005476 }
5477
5478 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
5479 Callee->isExternal())
5480 return false; // Do not delete arguments unless we have a function body...
5481
5482 // Okay, we decided that this is a safe thing to do: go ahead and start
5483 // inserting cast instructions as necessary...
5484 std::vector<Value*> Args;
5485 Args.reserve(NumActualArgs);
5486
5487 AI = CS.arg_begin();
5488 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
5489 const Type *ParamTy = FT->getParamType(i);
5490 if ((*AI)->getType() == ParamTy) {
5491 Args.push_back(*AI);
5492 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00005493 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
5494 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00005495 }
5496 }
5497
5498 // If the function takes more arguments than the call was taking, add them
5499 // now...
5500 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
5501 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
5502
5503 // If we are removing arguments to the function, emit an obnoxious warning...
5504 if (FT->getNumParams() < NumActualArgs)
5505 if (!FT->isVarArg()) {
5506 std::cerr << "WARNING: While resolving call to function '"
5507 << Callee->getName() << "' arguments were dropped!\n";
5508 } else {
5509 // Add all of the arguments in their promoted form to the arg list...
5510 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
5511 const Type *PTy = getPromotedType((*AI)->getType());
5512 if (PTy != (*AI)->getType()) {
5513 // Must promote to pass through va_arg area!
5514 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
5515 InsertNewInstBefore(Cast, *Caller);
5516 Args.push_back(Cast);
5517 } else {
5518 Args.push_back(*AI);
5519 }
5520 }
5521 }
5522
5523 if (FT->getReturnType() == Type::VoidTy)
5524 Caller->setName(""); // Void type should not have a name...
5525
5526 Instruction *NC;
5527 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00005528 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00005529 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00005530 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00005531 } else {
5532 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00005533 if (cast<CallInst>(Caller)->isTailCall())
5534 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00005535 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00005536 }
5537
5538 // Insert a cast of the return type as necessary...
5539 Value *NV = NC;
5540 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
5541 if (NV->getType() != Type::VoidTy) {
5542 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00005543
5544 // If this is an invoke instruction, we should insert it after the first
5545 // non-phi, instruction in the normal successor block.
5546 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5547 BasicBlock::iterator I = II->getNormalDest()->begin();
5548 while (isa<PHINode>(I)) ++I;
5549 InsertNewInstBefore(NC, *I);
5550 } else {
5551 // Otherwise, it's a call, just insert cast right after the call instr
5552 InsertNewInstBefore(NC, *Caller);
5553 }
Chris Lattner51ea1272004-02-28 05:22:00 +00005554 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00005555 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00005556 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00005557 }
5558 }
5559
5560 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
5561 Caller->replaceAllUsesWith(NV);
5562 Caller->getParent()->getInstList().erase(Caller);
5563 removeFromWorkList(Caller);
5564 return true;
5565}
5566
5567
Chris Lattner7515cab2004-11-14 19:13:23 +00005568// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
5569// operator and they all are only used by the PHI, PHI together their
5570// inputs, and do the operation once, to the result of the PHI.
5571Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
5572 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
5573
5574 // Scan the instruction, looking for input operations that can be folded away.
5575 // If all input operands to the phi are the same instruction (e.g. a cast from
5576 // the same type or "+42") we can pull the operation through the PHI, reducing
5577 // code size and simplifying code.
5578 Constant *ConstantOp = 0;
5579 const Type *CastSrcTy = 0;
5580 if (isa<CastInst>(FirstInst)) {
5581 CastSrcTy = FirstInst->getOperand(0)->getType();
5582 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
5583 // Can fold binop or shift if the RHS is a constant.
5584 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
5585 if (ConstantOp == 0) return 0;
5586 } else {
5587 return 0; // Cannot fold this operation.
5588 }
5589
5590 // Check to see if all arguments are the same operation.
5591 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5592 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
5593 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
5594 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
5595 return 0;
5596 if (CastSrcTy) {
5597 if (I->getOperand(0)->getType() != CastSrcTy)
5598 return 0; // Cast operation must match.
5599 } else if (I->getOperand(1) != ConstantOp) {
5600 return 0;
5601 }
5602 }
5603
5604 // Okay, they are all the same operation. Create a new PHI node of the
5605 // correct type, and PHI together all of the LHS's of the instructions.
5606 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
5607 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00005608 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00005609
5610 Value *InVal = FirstInst->getOperand(0);
5611 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00005612
5613 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00005614 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5615 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
5616 if (NewInVal != InVal)
5617 InVal = 0;
5618 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
5619 }
5620
5621 Value *PhiVal;
5622 if (InVal) {
5623 // The new PHI unions all of the same values together. This is really
5624 // common, so we handle it intelligently here for compile-time speed.
5625 PhiVal = InVal;
5626 delete NewPN;
5627 } else {
5628 InsertNewInstBefore(NewPN, PN);
5629 PhiVal = NewPN;
5630 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005631
Chris Lattner7515cab2004-11-14 19:13:23 +00005632 // Insert and return the new operation.
5633 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00005634 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00005635 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00005636 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00005637 else
5638 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00005639 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00005640}
Chris Lattner48a44f72002-05-02 17:06:02 +00005641
Chris Lattner71536432005-01-17 05:10:15 +00005642/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
5643/// that is dead.
5644static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
5645 if (PN->use_empty()) return true;
5646 if (!PN->hasOneUse()) return false;
5647
5648 // Remember this node, and if we find the cycle, return.
5649 if (!PotentiallyDeadPHIs.insert(PN).second)
5650 return true;
5651
5652 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
5653 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005654
Chris Lattner71536432005-01-17 05:10:15 +00005655 return false;
5656}
5657
Chris Lattnerbbbdd852002-05-06 18:06:38 +00005658// PHINode simplification
5659//
Chris Lattner113f4f42002-06-25 16:13:24 +00005660Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner9f9c2602005-08-05 01:04:30 +00005661 if (Value *V = PN.hasConstantValue())
5662 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00005663
5664 // If the only user of this instruction is a cast instruction, and all of the
5665 // incoming values are constants, change this PHI to merge together the casted
5666 // constants.
5667 if (PN.hasOneUse())
5668 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
5669 if (CI->getType() != PN.getType()) { // noop casts will be folded
5670 bool AllConstant = true;
5671 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
5672 if (!isa<Constant>(PN.getIncomingValue(i))) {
5673 AllConstant = false;
5674 break;
5675 }
5676 if (AllConstant) {
5677 // Make a new PHI with all casted values.
5678 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
5679 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
5680 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
5681 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
5682 PN.getIncomingBlock(i));
5683 }
5684
5685 // Update the cast instruction.
5686 CI->setOperand(0, New);
5687 WorkList.push_back(CI); // revisit the cast instruction to fold.
5688 WorkList.push_back(New); // Make sure to revisit the new Phi
5689 return &PN; // PN is now dead!
5690 }
5691 }
Chris Lattner7515cab2004-11-14 19:13:23 +00005692
5693 // If all PHI operands are the same operation, pull them through the PHI,
5694 // reducing code size.
5695 if (isa<Instruction>(PN.getIncomingValue(0)) &&
5696 PN.getIncomingValue(0)->hasOneUse())
5697 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
5698 return Result;
5699
Chris Lattner71536432005-01-17 05:10:15 +00005700 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
5701 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
5702 // PHI)... break the cycle.
5703 if (PN.hasOneUse())
5704 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
5705 std::set<PHINode*> PotentiallyDeadPHIs;
5706 PotentiallyDeadPHIs.insert(&PN);
5707 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
5708 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
5709 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005710
Chris Lattner91daeb52003-12-19 05:58:40 +00005711 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00005712}
5713
Chris Lattner69193f92004-04-05 01:30:19 +00005714static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
5715 Instruction *InsertPoint,
5716 InstCombiner *IC) {
5717 unsigned PS = IC->getTargetData().getPointerSize();
5718 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00005719 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
5720 // We must insert a cast to ensure we sign-extend.
5721 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
5722 V->getName()), *InsertPoint);
5723 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
5724 *InsertPoint);
5725}
5726
Chris Lattner48a44f72002-05-02 17:06:02 +00005727
Chris Lattner113f4f42002-06-25 16:13:24 +00005728Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00005729 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00005730 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00005731 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005732 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00005733 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005734
Chris Lattner81a7a232004-10-16 18:11:37 +00005735 if (isa<UndefValue>(GEP.getOperand(0)))
5736 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
5737
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005738 bool HasZeroPointerIndex = false;
5739 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
5740 HasZeroPointerIndex = C->isNullValue();
5741
5742 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00005743 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00005744
Chris Lattner69193f92004-04-05 01:30:19 +00005745 // Eliminate unneeded casts for indices.
5746 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00005747 gep_type_iterator GTI = gep_type_begin(GEP);
5748 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
5749 if (isa<SequentialType>(*GTI)) {
5750 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
5751 Value *Src = CI->getOperand(0);
5752 const Type *SrcTy = Src->getType();
5753 const Type *DestTy = CI->getType();
5754 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005755 if (SrcTy->getPrimitiveSizeInBits() ==
5756 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00005757 // We can always eliminate a cast from ulong or long to the other.
5758 // We can always eliminate a cast from uint to int or the other on
5759 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005760 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00005761 MadeChange = true;
5762 GEP.setOperand(i, Src);
5763 }
5764 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
5765 SrcTy->getPrimitiveSize() == 4) {
5766 // We can always eliminate a cast from int to [u]long. We can
5767 // eliminate a cast from uint to [u]long iff the target is a 32-bit
5768 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005769 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005770 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00005771 MadeChange = true;
5772 GEP.setOperand(i, Src);
5773 }
Chris Lattner69193f92004-04-05 01:30:19 +00005774 }
5775 }
5776 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00005777 // If we are using a wider index than needed for this platform, shrink it
5778 // to what we need. If the incoming value needs a cast instruction,
5779 // insert it. This explicit cast can make subsequent optimizations more
5780 // obvious.
5781 Value *Op = GEP.getOperand(i);
5782 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00005783 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00005784 GEP.setOperand(i, ConstantExpr::getCast(C,
5785 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00005786 MadeChange = true;
5787 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00005788 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
5789 Op->getName()), GEP);
5790 GEP.setOperand(i, Op);
5791 MadeChange = true;
5792 }
Chris Lattner44d0b952004-07-20 01:48:15 +00005793
5794 // If this is a constant idx, make sure to canonicalize it to be a signed
5795 // operand, otherwise CSE and other optimizations are pessimized.
5796 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
5797 GEP.setOperand(i, ConstantExpr::getCast(CUI,
5798 CUI->getType()->getSignedVersion()));
5799 MadeChange = true;
5800 }
Chris Lattner69193f92004-04-05 01:30:19 +00005801 }
5802 if (MadeChange) return &GEP;
5803
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005804 // Combine Indices - If the source pointer to this getelementptr instruction
5805 // is a getelementptr instruction, combine the indices of the two
5806 // getelementptr instructions into a single instruction.
5807 //
Chris Lattner57c67b02004-03-25 22:59:29 +00005808 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00005809 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00005810 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00005811
5812 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00005813 // Note that if our source is a gep chain itself that we wait for that
5814 // chain to be resolved before we perform this transformation. This
5815 // avoids us creating a TON of code in some cases.
5816 //
5817 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
5818 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
5819 return 0; // Wait until our source is folded to completion.
5820
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005821 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00005822
5823 // Find out whether the last index in the source GEP is a sequential idx.
5824 bool EndsWithSequential = false;
5825 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
5826 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00005827 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005828
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005829 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00005830 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00005831 // Replace: gep (gep %P, long B), long A, ...
5832 // With: T = long A+B; gep %P, T, ...
5833 //
Chris Lattner5f667a62004-05-07 22:09:22 +00005834 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00005835 if (SO1 == Constant::getNullValue(SO1->getType())) {
5836 Sum = GO1;
5837 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
5838 Sum = SO1;
5839 } else {
5840 // If they aren't the same type, convert both to an integer of the
5841 // target's pointer size.
5842 if (SO1->getType() != GO1->getType()) {
5843 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
5844 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
5845 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
5846 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
5847 } else {
5848 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00005849 if (SO1->getType()->getPrimitiveSize() == PS) {
5850 // Convert GO1 to SO1's type.
5851 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
5852
5853 } else if (GO1->getType()->getPrimitiveSize() == PS) {
5854 // Convert SO1 to GO1's type.
5855 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
5856 } else {
5857 const Type *PT = TD->getIntPtrType();
5858 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
5859 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
5860 }
5861 }
5862 }
Chris Lattner5f667a62004-05-07 22:09:22 +00005863 if (isa<Constant>(SO1) && isa<Constant>(GO1))
5864 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
5865 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005866 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
5867 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00005868 }
Chris Lattner69193f92004-04-05 01:30:19 +00005869 }
Chris Lattner5f667a62004-05-07 22:09:22 +00005870
5871 // Recycle the GEP we already have if possible.
5872 if (SrcGEPOperands.size() == 2) {
5873 GEP.setOperand(0, SrcGEPOperands[0]);
5874 GEP.setOperand(1, Sum);
5875 return &GEP;
5876 } else {
5877 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5878 SrcGEPOperands.end()-1);
5879 Indices.push_back(Sum);
5880 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
5881 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005882 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00005883 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005884 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005885 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00005886 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5887 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005888 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
5889 }
5890
5891 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00005892 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005893
Chris Lattner5f667a62004-05-07 22:09:22 +00005894 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005895 // GEP of global variable. If all of the indices for this GEP are
5896 // constants, we can promote this to a constexpr instead of an instruction.
5897
5898 // Scan for nonconstants...
5899 std::vector<Constant*> Indices;
5900 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
5901 for (; I != E && isa<Constant>(*I); ++I)
5902 Indices.push_back(cast<Constant>(*I));
5903
5904 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00005905 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005906
5907 // Replace all uses of the GEP with the new constexpr...
5908 return ReplaceInstUsesWith(GEP, CE);
5909 }
Chris Lattner567b81f2005-09-13 00:40:14 +00005910 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
5911 if (!isa<PointerType>(X->getType())) {
5912 // Not interesting. Source pointer must be a cast from pointer.
5913 } else if (HasZeroPointerIndex) {
5914 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
5915 // into : GEP [10 x ubyte]* X, long 0, ...
5916 //
5917 // This occurs when the program declares an array extern like "int X[];"
5918 //
5919 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
5920 const PointerType *XTy = cast<PointerType>(X->getType());
5921 if (const ArrayType *XATy =
5922 dyn_cast<ArrayType>(XTy->getElementType()))
5923 if (const ArrayType *CATy =
5924 dyn_cast<ArrayType>(CPTy->getElementType()))
5925 if (CATy->getElementType() == XATy->getElementType()) {
5926 // At this point, we know that the cast source type is a pointer
5927 // to an array of the same type as the destination pointer
5928 // array. Because the array type is never stepped over (there
5929 // is a leading zero) we can fold the cast into this GEP.
5930 GEP.setOperand(0, X);
5931 return &GEP;
5932 }
5933 } else if (GEP.getNumOperands() == 2) {
5934 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00005935 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
5936 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00005937 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
5938 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
5939 if (isa<ArrayType>(SrcElTy) &&
5940 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
5941 TD->getTypeSize(ResElTy)) {
5942 Value *V = InsertNewInstBefore(
5943 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5944 GEP.getOperand(1), GEP.getName()), GEP);
5945 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005946 }
Chris Lattner2a893292005-09-13 18:36:04 +00005947
5948 // Transform things like:
5949 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
5950 // (where tmp = 8*tmp2) into:
5951 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
5952
5953 if (isa<ArrayType>(SrcElTy) &&
5954 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
5955 uint64_t ArrayEltSize =
5956 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
5957
5958 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
5959 // allow either a mul, shift, or constant here.
5960 Value *NewIdx = 0;
5961 ConstantInt *Scale = 0;
5962 if (ArrayEltSize == 1) {
5963 NewIdx = GEP.getOperand(1);
5964 Scale = ConstantInt::get(NewIdx->getType(), 1);
5965 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00005966 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00005967 Scale = CI;
5968 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
5969 if (Inst->getOpcode() == Instruction::Shl &&
5970 isa<ConstantInt>(Inst->getOperand(1))) {
5971 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
5972 if (Inst->getType()->isSigned())
5973 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
5974 else
5975 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
5976 NewIdx = Inst->getOperand(0);
5977 } else if (Inst->getOpcode() == Instruction::Mul &&
5978 isa<ConstantInt>(Inst->getOperand(1))) {
5979 Scale = cast<ConstantInt>(Inst->getOperand(1));
5980 NewIdx = Inst->getOperand(0);
5981 }
5982 }
5983
5984 // If the index will be to exactly the right offset with the scale taken
5985 // out, perform the transformation.
5986 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
5987 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
5988 Scale = ConstantSInt::get(C->getType(),
Chris Lattnera393e4d2005-09-14 17:32:56 +00005989 (int64_t)C->getRawValue() /
5990 (int64_t)ArrayEltSize);
Chris Lattner2a893292005-09-13 18:36:04 +00005991 else
5992 Scale = ConstantUInt::get(Scale->getType(),
5993 Scale->getRawValue() / ArrayEltSize);
5994 if (Scale->getRawValue() != 1) {
5995 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
5996 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
5997 NewIdx = InsertNewInstBefore(Sc, GEP);
5998 }
5999
6000 // Insert the new GEP instruction.
6001 Instruction *Idx =
6002 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6003 NewIdx, GEP.getName());
6004 Idx = InsertNewInstBefore(Idx, GEP);
6005 return new CastInst(Idx, GEP.getType());
6006 }
6007 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006008 }
Chris Lattnerca081252001-12-14 16:52:21 +00006009 }
6010
Chris Lattnerca081252001-12-14 16:52:21 +00006011 return 0;
6012}
6013
Chris Lattner1085bdf2002-11-04 16:18:53 +00006014Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
6015 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
6016 if (AI.isArrayAllocation()) // Check C != 1
6017 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
6018 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006019 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00006020
6021 // Create and insert the replacement instruction...
6022 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00006023 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006024 else {
6025 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00006026 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006027 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00006028
6029 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006030
Chris Lattner1085bdf2002-11-04 16:18:53 +00006031 // Scan to the end of the allocation instructions, to skip over a block of
6032 // allocas if possible...
6033 //
6034 BasicBlock::iterator It = New;
6035 while (isa<AllocationInst>(*It)) ++It;
6036
6037 // Now that I is pointing to the first non-allocation-inst in the block,
6038 // insert our getelementptr instruction...
6039 //
Chris Lattner809dfac2005-05-04 19:10:26 +00006040 Value *NullIdx = Constant::getNullValue(Type::IntTy);
6041 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
6042 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00006043
6044 // Now make everything use the getelementptr instead of the original
6045 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00006046 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00006047 } else if (isa<UndefValue>(AI.getArraySize())) {
6048 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00006049 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00006050
6051 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
6052 // Note that we only do this for alloca's, because malloc should allocate and
6053 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00006054 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00006055 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00006056 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
6057
Chris Lattner1085bdf2002-11-04 16:18:53 +00006058 return 0;
6059}
6060
Chris Lattner8427bff2003-12-07 01:24:23 +00006061Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
6062 Value *Op = FI.getOperand(0);
6063
6064 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
6065 if (CastInst *CI = dyn_cast<CastInst>(Op))
6066 if (isa<PointerType>(CI->getOperand(0)->getType())) {
6067 FI.setOperand(0, CI->getOperand(0));
6068 return &FI;
6069 }
6070
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006071 // free undef -> unreachable.
6072 if (isa<UndefValue>(Op)) {
6073 // Insert a new store to null because we cannot modify the CFG here.
6074 new StoreInst(ConstantBool::True,
6075 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
6076 return EraseInstFromFunction(FI);
6077 }
6078
Chris Lattnerf3a36602004-02-28 04:57:37 +00006079 // If we have 'free null' delete the instruction. This can happen in stl code
6080 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006081 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00006082 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00006083
Chris Lattner8427bff2003-12-07 01:24:23 +00006084 return 0;
6085}
6086
6087
Chris Lattner72684fe2005-01-31 05:51:45 +00006088/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00006089static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
6090 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006091 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00006092
6093 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006094 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00006095 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006096
6097 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
6098 // If the source is an array, the code below will not succeed. Check to
6099 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6100 // constants.
6101 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6102 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6103 if (ASrcTy->getNumElements() != 0) {
6104 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6105 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6106 SrcTy = cast<PointerType>(CastOp->getType());
6107 SrcPTy = SrcTy->getElementType();
6108 }
6109
6110 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00006111 // Do not allow turning this into a load of an integer, which is then
6112 // casted to a pointer, this pessimizes pointer analysis a lot.
6113 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006114 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006115 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00006116
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006117 // Okay, we are casting from one integer or pointer type to another of
6118 // the same size. Instead of casting the pointer before the load, cast
6119 // the result of the loaded value.
6120 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
6121 CI->getName(),
6122 LI.isVolatile()),LI);
6123 // Now cast the result of the load.
6124 return new CastInst(NewLoad, LI.getType());
6125 }
Chris Lattner35e24772004-07-13 01:49:43 +00006126 }
6127 }
6128 return 0;
6129}
6130
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006131/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00006132/// from this value cannot trap. If it is not obviously safe to load from the
6133/// specified pointer, we do a quick local scan of the basic block containing
6134/// ScanFrom, to determine if the address is already accessed.
6135static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
6136 // If it is an alloca or global variable, it is always safe to load from.
6137 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
6138
6139 // Otherwise, be a little bit agressive by scanning the local block where we
6140 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006141 // from/to. If so, the previous load or store would have already trapped,
6142 // so there is no harm doing an extra load (also, CSE will later eliminate
6143 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00006144 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
6145
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006146 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00006147 --BBI;
6148
6149 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6150 if (LI->getOperand(0) == V) return true;
6151 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6152 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00006153
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006154 }
Chris Lattnere6f13092004-09-19 19:18:10 +00006155 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006156}
6157
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006158Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
6159 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00006160
Chris Lattnera9d84e32005-05-01 04:24:53 +00006161 // load (cast X) --> cast (load X) iff safe
6162 if (CastInst *CI = dyn_cast<CastInst>(Op))
6163 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6164 return Res;
6165
6166 // None of the following transforms are legal for volatile loads.
6167 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006168
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006169 if (&LI.getParent()->front() != &LI) {
6170 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00006171 // If the instruction immediately before this is a store to the same
6172 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006173 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6174 if (SI->getOperand(1) == LI.getOperand(0))
6175 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00006176 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
6177 if (LIB->getOperand(0) == LI.getOperand(0))
6178 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006179 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00006180
6181 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
6182 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
6183 isa<UndefValue>(GEPI->getOperand(0))) {
6184 // Insert a new store to null instruction before the load to indicate
6185 // that this code is not reachable. We do this instead of inserting
6186 // an unreachable instruction directly because we cannot modify the
6187 // CFG.
6188 new StoreInst(UndefValue::get(LI.getType()),
6189 Constant::getNullValue(Op->getType()), &LI);
6190 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6191 }
6192
Chris Lattner81a7a232004-10-16 18:11:37 +00006193 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00006194 // load null/undef -> undef
6195 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006196 // Insert a new store to null instruction before the load to indicate that
6197 // this code is not reachable. We do this instead of inserting an
6198 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00006199 new StoreInst(UndefValue::get(LI.getType()),
6200 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00006201 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006202 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006203
Chris Lattner81a7a232004-10-16 18:11:37 +00006204 // Instcombine load (constant global) into the value loaded.
6205 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
6206 if (GV->isConstant() && !GV->isExternal())
6207 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00006208
Chris Lattner81a7a232004-10-16 18:11:37 +00006209 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
6210 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
6211 if (CE->getOpcode() == Instruction::GetElementPtr) {
6212 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
6213 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00006214 if (Constant *V =
6215 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00006216 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00006217 if (CE->getOperand(0)->isNullValue()) {
6218 // Insert a new store to null instruction before the load to indicate
6219 // that this code is not reachable. We do this instead of inserting
6220 // an unreachable instruction directly because we cannot modify the
6221 // CFG.
6222 new StoreInst(UndefValue::get(LI.getType()),
6223 Constant::getNullValue(Op->getType()), &LI);
6224 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6225 }
6226
Chris Lattner81a7a232004-10-16 18:11:37 +00006227 } else if (CE->getOpcode() == Instruction::Cast) {
6228 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6229 return Res;
6230 }
6231 }
Chris Lattnere228ee52004-04-08 20:39:49 +00006232
Chris Lattnera9d84e32005-05-01 04:24:53 +00006233 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006234 // Change select and PHI nodes to select values instead of addresses: this
6235 // helps alias analysis out a lot, allows many others simplifications, and
6236 // exposes redundancy in the code.
6237 //
6238 // Note that we cannot do the transformation unless we know that the
6239 // introduced loads cannot trap! Something like this is valid as long as
6240 // the condition is always false: load (select bool %C, int* null, int* %G),
6241 // but it would not be valid if we transformed it to load from null
6242 // unconditionally.
6243 //
6244 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
6245 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00006246 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
6247 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006248 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00006249 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006250 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00006251 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006252 return new SelectInst(SI->getCondition(), V1, V2);
6253 }
6254
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00006255 // load (select (cond, null, P)) -> load P
6256 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
6257 if (C->isNullValue()) {
6258 LI.setOperand(0, SI->getOperand(2));
6259 return &LI;
6260 }
6261
6262 // load (select (cond, P, null)) -> load P
6263 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
6264 if (C->isNullValue()) {
6265 LI.setOperand(0, SI->getOperand(1));
6266 return &LI;
6267 }
6268
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006269 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
6270 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00006271 bool Safe = PN->getParent() == LI.getParent();
6272
6273 // Scan all of the instructions between the PHI and the load to make
6274 // sure there are no instructions that might possibly alter the value
6275 // loaded from the PHI.
6276 if (Safe) {
6277 BasicBlock::iterator I = &LI;
6278 for (--I; !isa<PHINode>(I); --I)
6279 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
6280 Safe = false;
6281 break;
6282 }
6283 }
6284
6285 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00006286 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00006287 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006288 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00006289
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006290 if (Safe) {
6291 // Create the PHI.
6292 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
6293 InsertNewInstBefore(NewPN, *PN);
6294 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
6295
6296 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6297 BasicBlock *BB = PN->getIncomingBlock(i);
6298 Value *&TheLoad = LoadMap[BB];
6299 if (TheLoad == 0) {
6300 Value *InVal = PN->getIncomingValue(i);
6301 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
6302 InVal->getName()+".val"),
6303 *BB->getTerminator());
6304 }
6305 NewPN->addIncoming(TheLoad, BB);
6306 }
6307 return ReplaceInstUsesWith(LI, NewPN);
6308 }
6309 }
6310 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006311 return 0;
6312}
6313
Chris Lattner72684fe2005-01-31 05:51:45 +00006314/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
6315/// when possible.
6316static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
6317 User *CI = cast<User>(SI.getOperand(1));
6318 Value *CastOp = CI->getOperand(0);
6319
6320 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
6321 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
6322 const Type *SrcPTy = SrcTy->getElementType();
6323
6324 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
6325 // If the source is an array, the code below will not succeed. Check to
6326 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6327 // constants.
6328 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6329 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6330 if (ASrcTy->getNumElements() != 0) {
6331 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6332 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6333 SrcTy = cast<PointerType>(CastOp->getType());
6334 SrcPTy = SrcTy->getElementType();
6335 }
6336
6337 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006338 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00006339 IC.getTargetData().getTypeSize(DestPTy)) {
6340
6341 // Okay, we are casting from one integer or pointer type to another of
6342 // the same size. Instead of casting the pointer before the store, cast
6343 // the value to be stored.
6344 Value *NewCast;
6345 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
6346 NewCast = ConstantExpr::getCast(C, SrcPTy);
6347 else
6348 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
6349 SrcPTy,
6350 SI.getOperand(0)->getName()+".c"), SI);
6351
6352 return new StoreInst(NewCast, CastOp);
6353 }
6354 }
6355 }
6356 return 0;
6357}
6358
Chris Lattner31f486c2005-01-31 05:36:43 +00006359Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
6360 Value *Val = SI.getOperand(0);
6361 Value *Ptr = SI.getOperand(1);
6362
6363 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00006364 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00006365 ++NumCombined;
6366 return 0;
6367 }
6368
Chris Lattner5997cf92006-02-08 03:25:32 +00006369 // Do really simple DSE, to catch cases where there are several consequtive
6370 // stores to the same location, separated by a few arithmetic operations. This
6371 // situation often occurs with bitfield accesses.
6372 BasicBlock::iterator BBI = &SI;
6373 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
6374 --ScanInsts) {
6375 --BBI;
6376
6377 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
6378 // Prev store isn't volatile, and stores to the same location?
6379 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
6380 ++NumDeadStore;
6381 ++BBI;
6382 EraseInstFromFunction(*PrevSI);
6383 continue;
6384 }
6385 break;
6386 }
6387
6388 // Don't skip over loads or things that can modify memory.
6389 if (BBI->mayWriteToMemory() || isa<LoadInst>(BBI))
6390 break;
6391 }
6392
6393
6394 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00006395
6396 // store X, null -> turns into 'unreachable' in SimplifyCFG
6397 if (isa<ConstantPointerNull>(Ptr)) {
6398 if (!isa<UndefValue>(Val)) {
6399 SI.setOperand(0, UndefValue::get(Val->getType()));
6400 if (Instruction *U = dyn_cast<Instruction>(Val))
6401 WorkList.push_back(U); // Dropped a use.
6402 ++NumCombined;
6403 }
6404 return 0; // Do not modify these!
6405 }
6406
6407 // store undef, Ptr -> noop
6408 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00006409 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00006410 ++NumCombined;
6411 return 0;
6412 }
6413
Chris Lattner72684fe2005-01-31 05:51:45 +00006414 // If the pointer destination is a cast, see if we can fold the cast into the
6415 // source instead.
6416 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
6417 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6418 return Res;
6419 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
6420 if (CE->getOpcode() == Instruction::Cast)
6421 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6422 return Res;
6423
Chris Lattner219175c2005-09-12 23:23:25 +00006424
6425 // If this store is the last instruction in the basic block, and if the block
6426 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00006427 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00006428 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
6429 if (BI->isUnconditional()) {
6430 // Check to see if the successor block has exactly two incoming edges. If
6431 // so, see if the other predecessor contains a store to the same location.
6432 // if so, insert a PHI node (if needed) and move the stores down.
6433 BasicBlock *Dest = BI->getSuccessor(0);
6434
6435 pred_iterator PI = pred_begin(Dest);
6436 BasicBlock *Other = 0;
6437 if (*PI != BI->getParent())
6438 Other = *PI;
6439 ++PI;
6440 if (PI != pred_end(Dest)) {
6441 if (*PI != BI->getParent())
6442 if (Other)
6443 Other = 0;
6444 else
6445 Other = *PI;
6446 if (++PI != pred_end(Dest))
6447 Other = 0;
6448 }
6449 if (Other) { // If only one other pred...
6450 BBI = Other->getTerminator();
6451 // Make sure this other block ends in an unconditional branch and that
6452 // there is an instruction before the branch.
6453 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
6454 BBI != Other->begin()) {
6455 --BBI;
6456 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
6457
6458 // If this instruction is a store to the same location.
6459 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
6460 // Okay, we know we can perform this transformation. Insert a PHI
6461 // node now if we need it.
6462 Value *MergedVal = OtherStore->getOperand(0);
6463 if (MergedVal != SI.getOperand(0)) {
6464 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
6465 PN->reserveOperandSpace(2);
6466 PN->addIncoming(SI.getOperand(0), SI.getParent());
6467 PN->addIncoming(OtherStore->getOperand(0), Other);
6468 MergedVal = InsertNewInstBefore(PN, Dest->front());
6469 }
6470
6471 // Advance to a place where it is safe to insert the new store and
6472 // insert it.
6473 BBI = Dest->begin();
6474 while (isa<PHINode>(BBI)) ++BBI;
6475 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
6476 OtherStore->isVolatile()), *BBI);
6477
6478 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00006479 EraseInstFromFunction(SI);
6480 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00006481 ++NumCombined;
6482 return 0;
6483 }
6484 }
6485 }
6486 }
6487
Chris Lattner31f486c2005-01-31 05:36:43 +00006488 return 0;
6489}
6490
6491
Chris Lattner9eef8a72003-06-04 04:46:00 +00006492Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
6493 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00006494 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00006495 BasicBlock *TrueDest;
6496 BasicBlock *FalseDest;
6497 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
6498 !isa<Constant>(X)) {
6499 // Swap Destinations and condition...
6500 BI.setCondition(X);
6501 BI.setSuccessor(0, FalseDest);
6502 BI.setSuccessor(1, TrueDest);
6503 return &BI;
6504 }
6505
6506 // Cannonicalize setne -> seteq
6507 Instruction::BinaryOps Op; Value *Y;
6508 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
6509 TrueDest, FalseDest)))
6510 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
6511 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
6512 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
6513 std::string Name = I->getName(); I->setName("");
6514 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
6515 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00006516 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00006517 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00006518 BI.setSuccessor(0, FalseDest);
6519 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00006520 removeFromWorkList(I);
6521 I->getParent()->getInstList().erase(I);
6522 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00006523 return &BI;
6524 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006525
Chris Lattner9eef8a72003-06-04 04:46:00 +00006526 return 0;
6527}
Chris Lattner1085bdf2002-11-04 16:18:53 +00006528
Chris Lattner4c9c20a2004-07-03 00:26:11 +00006529Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
6530 Value *Cond = SI.getCondition();
6531 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
6532 if (I->getOpcode() == Instruction::Add)
6533 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6534 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
6535 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00006536 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00006537 AddRHS));
6538 SI.setOperand(0, I->getOperand(0));
6539 WorkList.push_back(I);
6540 return &SI;
6541 }
6542 }
6543 return 0;
6544}
6545
Robert Bocchinoa8352962006-01-13 22:48:06 +00006546Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
6547 if (ConstantAggregateZero *C =
6548 dyn_cast<ConstantAggregateZero>(EI.getOperand(0))) {
6549 // If packed val is constant 0, replace extract with scalar 0
6550 const Type *Ty = cast<PackedType>(C->getType())->getElementType();
6551 EI.replaceAllUsesWith(Constant::getNullValue(Ty));
6552 return ReplaceInstUsesWith(EI, Constant::getNullValue(Ty));
6553 }
6554 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
6555 // If packed val is constant with uniform operands, replace EI
6556 // with that operand
6557 Constant *op0 = cast<Constant>(C->getOperand(0));
6558 for (unsigned i = 1; i < C->getNumOperands(); ++i)
6559 if (C->getOperand(i) != op0) return 0;
6560 return ReplaceInstUsesWith(EI, op0);
6561 }
6562 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0)))
6563 if (I->hasOneUse()) {
6564 // Push extractelement into predecessor operation if legal and
6565 // profitable to do so
6566 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
6567 if (!isa<Constant>(BO->getOperand(0)) &&
6568 !isa<Constant>(BO->getOperand(1)))
6569 return 0;
6570 ExtractElementInst *newEI0 =
6571 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
6572 EI.getName());
6573 ExtractElementInst *newEI1 =
6574 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
6575 EI.getName());
6576 InsertNewInstBefore(newEI0, EI);
6577 InsertNewInstBefore(newEI1, EI);
6578 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
6579 }
6580 switch(I->getOpcode()) {
6581 case Instruction::Load: {
6582 Value *Ptr = InsertCastBefore(I->getOperand(0),
6583 PointerType::get(EI.getType()), EI);
6584 GetElementPtrInst *GEP =
6585 new GetElementPtrInst(Ptr, EI.getOperand(1),
6586 I->getName() + ".gep");
6587 InsertNewInstBefore(GEP, EI);
6588 return new LoadInst(GEP);
6589 }
6590 default:
6591 return 0;
6592 }
6593 }
6594 return 0;
6595}
6596
6597
Chris Lattner99f48c62002-09-02 04:59:56 +00006598void InstCombiner::removeFromWorkList(Instruction *I) {
6599 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
6600 WorkList.end());
6601}
6602
Chris Lattner39c98bb2004-12-08 23:43:58 +00006603
6604/// TryToSinkInstruction - Try to move the specified instruction from its
6605/// current block into the beginning of DestBlock, which can only happen if it's
6606/// safe to move the instruction past all of the instructions between it and the
6607/// end of its block.
6608static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
6609 assert(I->hasOneUse() && "Invariants didn't hold!");
6610
Chris Lattnerc4f67e62005-10-27 17:13:11 +00006611 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
6612 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00006613
Chris Lattner39c98bb2004-12-08 23:43:58 +00006614 // Do not sink alloca instructions out of the entry block.
6615 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
6616 return false;
6617
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00006618 // We can only sink load instructions if there is nothing between the load and
6619 // the end of block that could change the value.
6620 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00006621 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
6622 Scan != E; ++Scan)
6623 if (Scan->mayWriteToMemory())
6624 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00006625 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00006626
6627 BasicBlock::iterator InsertPos = DestBlock->begin();
6628 while (isa<PHINode>(InsertPos)) ++InsertPos;
6629
Chris Lattner9f269e42005-08-08 19:11:57 +00006630 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00006631 ++NumSunkInst;
6632 return true;
6633}
6634
Chris Lattner113f4f42002-06-25 16:13:24 +00006635bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00006636 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006637 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00006638
Chris Lattner4ed40f72005-07-07 20:40:38 +00006639 {
6640 // Populate the worklist with the reachable instructions.
6641 std::set<BasicBlock*> Visited;
6642 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
6643 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
6644 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
6645 WorkList.push_back(I);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00006646
Chris Lattner4ed40f72005-07-07 20:40:38 +00006647 // Do a quick scan over the function. If we find any blocks that are
6648 // unreachable, remove any instructions inside of them. This prevents
6649 // the instcombine code from having to deal with some bad special cases.
6650 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
6651 if (!Visited.count(BB)) {
6652 Instruction *Term = BB->getTerminator();
6653 while (Term != BB->begin()) { // Remove instrs bottom-up
6654 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00006655
Chris Lattner4ed40f72005-07-07 20:40:38 +00006656 DEBUG(std::cerr << "IC: DCE: " << *I);
6657 ++NumDeadInst;
6658
6659 if (!I->use_empty())
6660 I->replaceAllUsesWith(UndefValue::get(I->getType()));
6661 I->eraseFromParent();
6662 }
6663 }
6664 }
Chris Lattnerca081252001-12-14 16:52:21 +00006665
6666 while (!WorkList.empty()) {
6667 Instruction *I = WorkList.back(); // Get an instruction from the worklist
6668 WorkList.pop_back();
6669
Misha Brukman632df282002-10-29 23:06:16 +00006670 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00006671 // Check to see if we can DIE the instruction...
6672 if (isInstructionTriviallyDead(I)) {
6673 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006674 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00006675 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00006676 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006677
Chris Lattnercd517ff2005-01-28 19:32:01 +00006678 DEBUG(std::cerr << "IC: DCE: " << *I);
6679
6680 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006681 removeFromWorkList(I);
6682 continue;
6683 }
Chris Lattner99f48c62002-09-02 04:59:56 +00006684
Misha Brukman632df282002-10-29 23:06:16 +00006685 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00006686 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00006687 Value* Ptr = I->getOperand(0);
Chris Lattner6580e092004-10-16 19:44:59 +00006688 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00006689 cast<Constant>(Ptr)->isNullValue() &&
6690 !isa<ConstantPointerNull>(C) &&
6691 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner6580e092004-10-16 19:44:59 +00006692 // If this is a constant expr gep that is effectively computing an
6693 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
6694 bool isFoldableGEP = true;
6695 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
6696 if (!isa<ConstantInt>(I->getOperand(i)))
6697 isFoldableGEP = false;
6698 if (isFoldableGEP) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00006699 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner6580e092004-10-16 19:44:59 +00006700 std::vector<Value*>(I->op_begin()+1, I->op_end()));
6701 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00006702 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00006703 C = ConstantExpr::getCast(C, I->getType());
6704 }
6705 }
6706
Chris Lattnercd517ff2005-01-28 19:32:01 +00006707 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
6708
Chris Lattner99f48c62002-09-02 04:59:56 +00006709 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00006710 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00006711 ReplaceInstUsesWith(*I, C);
6712
Chris Lattner99f48c62002-09-02 04:59:56 +00006713 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006714 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00006715 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006716 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00006717 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006718
Chris Lattner39c98bb2004-12-08 23:43:58 +00006719 // See if we can trivially sink this instruction to a successor basic block.
6720 if (I->hasOneUse()) {
6721 BasicBlock *BB = I->getParent();
6722 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
6723 if (UserParent != BB) {
6724 bool UserIsSuccessor = false;
6725 // See if the user is one of our successors.
6726 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
6727 if (*SI == UserParent) {
6728 UserIsSuccessor = true;
6729 break;
6730 }
6731
6732 // If the user is one of our immediate successors, and if that successor
6733 // only has us as a predecessors (we'd have to split the critical edge
6734 // otherwise), we can keep going.
6735 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
6736 next(pred_begin(UserParent)) == pred_end(UserParent))
6737 // Okay, the CFG is simple enough, try to sink this instruction.
6738 Changed |= TryToSinkInstruction(I, UserParent);
6739 }
6740 }
6741
Chris Lattnerca081252001-12-14 16:52:21 +00006742 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006743 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00006744 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00006745 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00006746 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00006747 DEBUG(std::cerr << "IC: Old = " << *I
6748 << " New = " << *Result);
6749
Chris Lattner396dbfe2004-06-09 05:08:07 +00006750 // Everything uses the new instruction now.
6751 I->replaceAllUsesWith(Result);
6752
6753 // Push the new instruction and any users onto the worklist.
6754 WorkList.push_back(Result);
6755 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006756
6757 // Move the name to the new instruction first...
6758 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00006759 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006760
6761 // Insert the new instruction into the basic block...
6762 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00006763 BasicBlock::iterator InsertPos = I;
6764
6765 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
6766 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
6767 ++InsertPos;
6768
6769 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006770
Chris Lattner63d75af2004-05-01 23:27:23 +00006771 // Make sure that we reprocess all operands now that we reduced their
6772 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00006773 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6774 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6775 WorkList.push_back(OpI);
6776
Chris Lattner396dbfe2004-06-09 05:08:07 +00006777 // Instructions can end up on the worklist more than once. Make sure
6778 // we do not process an instruction that has been deleted.
6779 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006780
6781 // Erase the old instruction.
6782 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00006783 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00006784 DEBUG(std::cerr << "IC: MOD = " << *I);
6785
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006786 // If the instruction was modified, it's possible that it is now dead.
6787 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00006788 if (isInstructionTriviallyDead(I)) {
6789 // Make sure we process all operands now that we are reducing their
6790 // use counts.
6791 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6792 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6793 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006794
Chris Lattner63d75af2004-05-01 23:27:23 +00006795 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00006796 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00006797 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00006798 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00006799 } else {
6800 WorkList.push_back(Result);
6801 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006802 }
Chris Lattner053c0932002-05-14 15:24:07 +00006803 }
Chris Lattner260ab202002-04-18 17:39:14 +00006804 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00006805 }
6806 }
6807
Chris Lattner260ab202002-04-18 17:39:14 +00006808 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00006809}
6810
Brian Gaeke38b79e82004-07-27 17:43:21 +00006811FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00006812 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00006813}
Brian Gaeke960707c2003-11-11 22:41:34 +00006814