blob: 98f9846624e33339ad6c9aa3c51bcb9036250453 [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
3// 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.
7//
8//===----------------------------------------------------------------------===//
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 Lattner60a65912002-02-12 21:07:25 +000048#include "llvm/Support/InstIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000049#include "llvm/Support/InstVisitor.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000051#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000052#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000053#include <algorithm>
Chris Lattner8427bff2003-12-07 01:24:23 +000054using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000055using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000056
Chris Lattner260ab202002-04-18 17:39:14 +000057namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000058 Statistic<> NumCombined ("instcombine", "Number of insts combined");
59 Statistic<> NumConstProp("instcombine", "Number of constant folds");
60 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattner39c98bb2004-12-08 23:43:58 +000061 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000062
Chris Lattnerc8e66542002-04-27 06:56:12 +000063 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000064 public InstVisitor<InstCombiner, Instruction*> {
65 // Worklist of all of the instructions that need to be simplified.
66 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000067 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000068
Chris Lattner51ea1272004-02-28 05:22:00 +000069 /// AddUsersToWorkList - When an instruction is simplified, add all users of
70 /// the instruction to the work lists because they might get more simplified
71 /// now.
72 ///
73 void AddUsersToWorkList(Instruction &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000074 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000075 UI != UE; ++UI)
76 WorkList.push_back(cast<Instruction>(*UI));
77 }
78
Chris Lattner51ea1272004-02-28 05:22:00 +000079 /// AddUsesToWorkList - When an instruction is simplified, add operands to
80 /// the work lists because they might get more simplified now.
81 ///
82 void AddUsesToWorkList(Instruction &I) {
83 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
84 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
85 WorkList.push_back(Op);
86 }
87
Chris Lattner99f48c62002-09-02 04:59:56 +000088 // removeFromWorkList - remove all instances of I from the worklist.
89 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000090 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000091 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000092
Chris Lattnerf12cc842002-04-28 21:27:06 +000093 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000094 AU.addRequired<TargetData>();
Chris Lattner820d9712002-10-21 20:00:28 +000095 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000096 }
97
Chris Lattner69193f92004-04-05 01:30:19 +000098 TargetData &getTargetData() const { return *TD; }
99
Chris Lattner260ab202002-04-18 17:39:14 +0000100 // Visitation implementation - Implement instruction combining for different
101 // instruction types. The semantics are as follows:
102 // Return Value:
103 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000104 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000105 // otherwise - Change was made, replace I with returned instruction
106 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000107 Instruction *visitAdd(BinaryOperator &I);
108 Instruction *visitSub(BinaryOperator &I);
109 Instruction *visitMul(BinaryOperator &I);
110 Instruction *visitDiv(BinaryOperator &I);
111 Instruction *visitRem(BinaryOperator &I);
112 Instruction *visitAnd(BinaryOperator &I);
113 Instruction *visitOr (BinaryOperator &I);
114 Instruction *visitXor(BinaryOperator &I);
115 Instruction *visitSetCondInst(BinaryOperator &I);
Reid Spencer279fa252004-11-28 21:31:15 +0000116 Instruction *visitSetCondInstWithCastAndConstant(BinaryOperator&I,
117 CastInst*LHSI,
118 ConstantInt* CI);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000119 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000120 Instruction *visitCastInst(CastInst &CI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000121 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000122 Instruction *visitCallInst(CallInst &CI);
123 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000124 Instruction *visitPHINode(PHINode &PN);
125 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000126 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000127 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000128 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000129 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000130 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner260ab202002-04-18 17:39:14 +0000131
132 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000133 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000134
Chris Lattner970c33a2003-06-19 17:00:31 +0000135 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000136 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000137 bool transformConstExprCastCall(CallSite CS);
138
Chris Lattner69193f92004-04-05 01:30:19 +0000139 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000140 // InsertNewInstBefore - insert an instruction New before instruction Old
141 // in the program. Add the new instruction to the worklist.
142 //
Chris Lattner623826c2004-09-28 21:48:02 +0000143 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000144 assert(New && New->getParent() == 0 &&
145 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000146 BasicBlock *BB = Old.getParent();
147 BB->getInstList().insert(&Old, New); // Insert inst
148 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000149 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000150 }
151
Chris Lattner7e794272004-09-24 15:21:34 +0000152 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
153 /// This also adds the cast to the worklist. Finally, this returns the
154 /// cast.
155 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
156 if (V->getType() == Ty) return V;
157
158 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
159 WorkList.push_back(C);
160 return C;
161 }
162
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000163 // ReplaceInstUsesWith - This method is to be used when an instruction is
164 // found to be dead, replacable with another preexisting expression. Here
165 // we add all uses of I to the worklist, replace all uses of I with the new
166 // value, then return I, so that the inst combiner will know that I was
167 // modified.
168 //
169 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000170 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000171 if (&I != V) {
172 I.replaceAllUsesWith(V);
173 return &I;
174 } else {
175 // If we are replacing the instruction with itself, this must be in a
176 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000177 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000178 return &I;
179 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000180 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000181
182 // EraseInstFromFunction - When dealing with an instruction that has side
183 // effects or produces a void value, we can't rely on DCE to delete the
184 // instruction. Instead, visit methods should return the value returned by
185 // this function.
186 Instruction *EraseInstFromFunction(Instruction &I) {
187 assert(I.use_empty() && "Cannot erase instruction that is used!");
188 AddUsesToWorkList(I);
189 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000190 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000191 return 0; // Don't do anything with FI
192 }
193
194
Chris Lattner3ac7c262003-08-13 20:16:26 +0000195 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000196 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
197 /// InsertBefore instruction. This is specialized a bit to avoid inserting
198 /// casts that are known to not do anything...
199 ///
200 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
201 Instruction *InsertBefore);
202
Chris Lattner7fb29e12003-03-11 00:12:48 +0000203 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000204 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000205 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000206
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000207
208 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
209 // PHI node as operand #0, see if we can fold the instruction into the PHI
210 // (which is only possible if all operands to the PHI are constants).
211 Instruction *FoldOpIntoPhi(Instruction &I);
212
Chris Lattner7515cab2004-11-14 19:13:23 +0000213 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
214 // operator and they all are only used by the PHI, PHI together their
215 // inputs, and do the operation once, to the result of the PHI.
216 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
217
Chris Lattnerba1cb382003-09-19 17:17:26 +0000218 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
219 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000220
221 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
222 bool Inside, Instruction &IB);
Chris Lattner260ab202002-04-18 17:39:14 +0000223 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000224
Chris Lattnerc8b70922002-07-26 21:12:46 +0000225 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000226}
227
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000228// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000229// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000230static unsigned getComplexity(Value *V) {
231 if (isa<Instruction>(V)) {
232 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000233 return 3;
234 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000235 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000236 if (isa<Argument>(V)) return 3;
237 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000238}
Chris Lattner260ab202002-04-18 17:39:14 +0000239
Chris Lattner7fb29e12003-03-11 00:12:48 +0000240// isOnlyUse - Return true if this instruction will be deleted if we stop using
241// it.
242static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000243 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000244}
245
Chris Lattnere79e8542004-02-23 06:38:22 +0000246// getPromotedType - Return the specified type promoted as it would be to pass
247// though a va_arg area...
248static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000249 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000250 case Type::SByteTyID:
251 case Type::ShortTyID: return Type::IntTy;
252 case Type::UByteTyID:
253 case Type::UShortTyID: return Type::UIntTy;
254 case Type::FloatTyID: return Type::DoubleTy;
255 default: return Ty;
256 }
257}
258
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000259// SimplifyCommutative - This performs a few simplifications for commutative
260// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000261//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000262// 1. Order operands such that they are listed from right (least complex) to
263// left (most complex). This puts constants before unary operators before
264// binary operators.
265//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000266// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
267// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000268//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000269bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000270 bool Changed = false;
271 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
272 Changed = !I.swapOperands();
273
274 if (!I.isAssociative()) return Changed;
275 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000276 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
277 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
278 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000279 Constant *Folded = ConstantExpr::get(I.getOpcode(),
280 cast<Constant>(I.getOperand(1)),
281 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000282 I.setOperand(0, Op->getOperand(0));
283 I.setOperand(1, Folded);
284 return true;
285 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
286 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
287 isOnlyUse(Op) && isOnlyUse(Op1)) {
288 Constant *C1 = cast<Constant>(Op->getOperand(1));
289 Constant *C2 = cast<Constant>(Op1->getOperand(1));
290
291 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000292 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000293 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
294 Op1->getOperand(0),
295 Op1->getName(), &I);
296 WorkList.push_back(New);
297 I.setOperand(0, New);
298 I.setOperand(1, Folded);
299 return true;
300 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000301 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000302 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000303}
Chris Lattnerca081252001-12-14 16:52:21 +0000304
Chris Lattnerbb74e222003-03-10 23:06:50 +0000305// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
306// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000307//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000308static inline Value *dyn_castNegVal(Value *V) {
309 if (BinaryOperator::isNeg(V))
310 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
311
Chris Lattner9ad0d552004-12-14 20:08:06 +0000312 // Constants can be considered to be negated values if they can be folded.
313 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
314 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000315 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000316}
317
Chris Lattnerbb74e222003-03-10 23:06:50 +0000318static inline Value *dyn_castNotVal(Value *V) {
319 if (BinaryOperator::isNot(V))
320 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
321
322 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000323 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000324 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000325 return 0;
326}
327
Chris Lattner7fb29e12003-03-11 00:12:48 +0000328// dyn_castFoldableMul - If this value is a multiply that can be folded into
329// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000330// non-constant operand of the multiply, and set CST to point to the multiplier.
331// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000332//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000333static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000334 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000335 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000336 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000337 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000338 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000339 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000340 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000341 // The multiplier is really 1 << CST.
342 Constant *One = ConstantInt::get(V->getType(), 1);
343 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
344 return I->getOperand(0);
345 }
346 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000347 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000348}
Chris Lattner31ae8632002-08-14 17:51:49 +0000349
Chris Lattner3082c5a2003-02-18 19:28:33 +0000350// Log2 - Calculate the log base 2 for the specified value if it is exactly a
351// power of 2.
352static unsigned Log2(uint64_t Val) {
353 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
354 unsigned Count = 0;
355 while (Val != 1) {
356 if (Val & 1) return 0; // Multiple bits set?
357 Val >>= 1;
358 ++Count;
359 }
360 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000361}
362
Chris Lattner623826c2004-09-28 21:48:02 +0000363// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000364static ConstantInt *AddOne(ConstantInt *C) {
365 return cast<ConstantInt>(ConstantExpr::getAdd(C,
366 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000367}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000368static ConstantInt *SubOne(ConstantInt *C) {
369 return cast<ConstantInt>(ConstantExpr::getSub(C,
370 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000371}
372
373// isTrueWhenEqual - Return true if the specified setcondinst instruction is
374// true when both operands are equal...
375//
376static bool isTrueWhenEqual(Instruction &I) {
377 return I.getOpcode() == Instruction::SetEQ ||
378 I.getOpcode() == Instruction::SetGE ||
379 I.getOpcode() == Instruction::SetLE;
380}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000381
382/// AssociativeOpt - Perform an optimization on an associative operator. This
383/// function is designed to check a chain of associative operators for a
384/// potential to apply a certain optimization. Since the optimization may be
385/// applicable if the expression was reassociated, this checks the chain, then
386/// reassociates the expression as necessary to expose the optimization
387/// opportunity. This makes use of a special Functor, which must define
388/// 'shouldApply' and 'apply' methods.
389///
390template<typename Functor>
391Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
392 unsigned Opcode = Root.getOpcode();
393 Value *LHS = Root.getOperand(0);
394
395 // Quick check, see if the immediate LHS matches...
396 if (F.shouldApply(LHS))
397 return F.apply(Root);
398
399 // Otherwise, if the LHS is not of the same opcode as the root, return.
400 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000401 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000402 // Should we apply this transform to the RHS?
403 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
404
405 // If not to the RHS, check to see if we should apply to the LHS...
406 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
407 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
408 ShouldApply = true;
409 }
410
411 // If the functor wants to apply the optimization to the RHS of LHSI,
412 // reassociate the expression from ((? op A) op B) to (? op (A op B))
413 if (ShouldApply) {
414 BasicBlock *BB = Root.getParent();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000415
416 // Now all of the instructions are in the current basic block, go ahead
417 // and perform the reassociation.
418 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
419
420 // First move the selected RHS to the LHS of the root...
421 Root.setOperand(0, LHSI->getOperand(1));
422
423 // Make what used to be the LHS of the root be the user of the root...
424 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000425 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000426 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
427 return 0;
428 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000429 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000430 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000431 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
432 BasicBlock::iterator ARI = &Root; ++ARI;
433 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
434 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000435
436 // Now propagate the ExtraOperand down the chain of instructions until we
437 // get to LHSI.
438 while (TmpLHSI != LHSI) {
439 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000440 // Move the instruction to immediately before the chain we are
441 // constructing to avoid breaking dominance properties.
442 NextLHSI->getParent()->getInstList().remove(NextLHSI);
443 BB->getInstList().insert(ARI, NextLHSI);
444 ARI = NextLHSI;
445
Chris Lattnerb8b97502003-08-13 19:01:45 +0000446 Value *NextOp = NextLHSI->getOperand(1);
447 NextLHSI->setOperand(1, ExtraOperand);
448 TmpLHSI = NextLHSI;
449 ExtraOperand = NextOp;
450 }
451
452 // Now that the instructions are reassociated, have the functor perform
453 // the transformation...
454 return F.apply(Root);
455 }
456
457 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
458 }
459 return 0;
460}
461
462
463// AddRHS - Implements: X + X --> X << 1
464struct AddRHS {
465 Value *RHS;
466 AddRHS(Value *rhs) : RHS(rhs) {}
467 bool shouldApply(Value *LHS) const { return LHS == RHS; }
468 Instruction *apply(BinaryOperator &Add) const {
469 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
470 ConstantInt::get(Type::UByteTy, 1));
471 }
472};
473
474// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
475// iff C1&C2 == 0
476struct AddMaskingAnd {
477 Constant *C2;
478 AddMaskingAnd(Constant *c) : C2(c) {}
479 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000480 ConstantInt *C1;
481 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
482 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000483 }
484 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000485 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000486 }
487};
488
Chris Lattner86102b82005-01-01 16:22:27 +0000489static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +0000490 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +0000491 if (isa<CastInst>(I)) {
492 if (Constant *SOC = dyn_cast<Constant>(SO))
493 return ConstantExpr::getCast(SOC, I.getType());
494
495 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
496 SO->getName() + ".cast"), I);
497 }
498
Chris Lattner183b3362004-04-09 19:05:30 +0000499 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +0000500 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
501 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000502
Chris Lattner183b3362004-04-09 19:05:30 +0000503 if (Constant *SOC = dyn_cast<Constant>(SO)) {
504 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +0000505 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
506 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +0000507 }
508
509 Value *Op0 = SO, *Op1 = ConstOperand;
510 if (!ConstIsRHS)
511 std::swap(Op0, Op1);
512 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +0000513 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
514 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
515 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
516 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000517 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000518 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000519 abort();
520 }
Chris Lattner86102b82005-01-01 16:22:27 +0000521 return IC->InsertNewInstBefore(New, I);
522}
523
524// FoldOpIntoSelect - Given an instruction with a select as one operand and a
525// constant as the other operand, try to fold the binary operator into the
526// select arguments. This also works for Cast instructions, which obviously do
527// not have a second operand.
528static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
529 InstCombiner *IC) {
530 // Don't modify shared select instructions
531 if (!SI->hasOneUse()) return 0;
532 Value *TV = SI->getOperand(1);
533 Value *FV = SI->getOperand(2);
534
535 if (isa<Constant>(TV) || isa<Constant>(FV)) {
536 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
537 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
538
539 return new SelectInst(SI->getCondition(), SelectTrueVal,
540 SelectFalseVal);
541 }
542 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +0000543}
544
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000545
546/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
547/// node as operand #0, see if we can fold the instruction into the PHI (which
548/// is only possible if all operands to the PHI are constants).
549Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
550 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +0000551 unsigned NumPHIValues = PN->getNumIncomingValues();
552 if (!PN->hasOneUse() || NumPHIValues == 0 ||
553 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000554
555 // Check to see if all of the operands of the PHI are constants. If not, we
556 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +0000557 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000558 if (!isa<Constant>(PN->getIncomingValue(i)))
559 return 0;
560
561 // Okay, we can do the transformation: create the new PHI node.
562 PHINode *NewPN = new PHINode(I.getType(), I.getName());
563 I.setName("");
564 NewPN->op_reserve(PN->getNumOperands());
565 InsertNewInstBefore(NewPN, *PN);
566
567 // Next, add all of the operands to the PHI.
568 if (I.getNumOperands() == 2) {
569 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +0000570 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000571 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
572 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
573 PN->getIncomingBlock(i));
574 }
575 } else {
576 assert(isa<CastInst>(I) && "Unary op should be a cast!");
577 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +0000578 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000579 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
580 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
581 PN->getIncomingBlock(i));
582 }
583 }
584 return ReplaceInstUsesWith(I, NewPN);
585}
586
Chris Lattner113f4f42002-06-25 16:13:24 +0000587Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000588 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000589 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000590
Chris Lattnercf4a9962004-04-10 22:01:55 +0000591 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000592 // X + undef -> undef
593 if (isa<UndefValue>(RHS))
594 return ReplaceInstUsesWith(I, RHS);
595
Chris Lattnercf4a9962004-04-10 22:01:55 +0000596 // X + 0 --> X
597 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
598 RHSC->isNullValue())
599 return ReplaceInstUsesWith(I, LHS);
600
601 // X + (signbit) --> X ^ signbit
602 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
603 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
604 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
Chris Lattner33eb9092004-11-05 04:45:43 +0000605 if (Val == (1ULL << (NumBits-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000606 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000607 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000608
609 if (isa<PHINode>(LHS))
610 if (Instruction *NV = FoldOpIntoPhi(I))
611 return NV;
Chris Lattnercf4a9962004-04-10 22:01:55 +0000612 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000613
Chris Lattnerb8b97502003-08-13 19:01:45 +0000614 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000615 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000616 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000617 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000618
Chris Lattner147e9752002-05-08 22:46:53 +0000619 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000620 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000621 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000622
623 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000624 if (!isa<Constant>(RHS))
625 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000626 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000627
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000628 ConstantInt *C2;
629 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
630 if (X == RHS) // X*C + X --> X * (C+1)
631 return BinaryOperator::createMul(RHS, AddOne(C2));
632
633 // X*C1 + X*C2 --> X * (C1+C2)
634 ConstantInt *C1;
635 if (X == dyn_castFoldableMul(RHS, C1))
636 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +0000637 }
638
639 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000640 if (dyn_castFoldableMul(RHS, C2) == LHS)
641 return BinaryOperator::createMul(LHS, AddOne(C2));
642
Chris Lattner57c8d992003-02-18 19:57:07 +0000643
Chris Lattnerb8b97502003-08-13 19:01:45 +0000644 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000645 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000646 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000647
Chris Lattnerb9cde762003-10-02 15:11:26 +0000648 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000649 Value *X;
650 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
651 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
652 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000653 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000654
Chris Lattnerbff91d92004-10-08 05:07:56 +0000655 // (X & FF00) + xx00 -> (X+xx00) & FF00
656 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
657 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
658 if (Anded == CRHS) {
659 // See if all bits from the first bit set in the Add RHS up are included
660 // in the mask. First, get the rightmost bit.
661 uint64_t AddRHSV = CRHS->getRawValue();
662
663 // Form a mask of all bits from the lowest bit added through the top.
664 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
665 AddRHSHighBits &= (1ULL << C2->getType()->getPrimitiveSize()*8)-1;
666
667 // See if the and mask includes all of these bits.
668 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
669
670 if (AddRHSHighBits == AddRHSHighBitsAnd) {
671 // Okay, the xform is safe. Insert the new add pronto.
672 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
673 LHS->getName()), I);
674 return BinaryOperator::createAnd(NewAdd, C2);
675 }
676 }
677 }
678
Chris Lattnerd4252a72004-07-30 07:50:03 +0000679 // Try to fold constant add into select arguments.
680 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +0000681 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +0000682 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000683 }
684
Chris Lattner113f4f42002-06-25 16:13:24 +0000685 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000686}
687
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000688// isSignBit - Return true if the value represented by the constant only has the
689// highest order bit set.
690static bool isSignBit(ConstantInt *CI) {
691 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
692 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
693}
694
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000695static unsigned getTypeSizeInBits(const Type *Ty) {
696 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
697}
698
Chris Lattner022167f2004-03-13 00:11:49 +0000699/// RemoveNoopCast - Strip off nonconverting casts from the value.
700///
701static Value *RemoveNoopCast(Value *V) {
702 if (CastInst *CI = dyn_cast<CastInst>(V)) {
703 const Type *CTy = CI->getType();
704 const Type *OpTy = CI->getOperand(0)->getType();
705 if (CTy->isInteger() && OpTy->isInteger()) {
706 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
707 return RemoveNoopCast(CI->getOperand(0));
708 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
709 return RemoveNoopCast(CI->getOperand(0));
710 }
711 return V;
712}
713
Chris Lattner113f4f42002-06-25 16:13:24 +0000714Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000715 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000716
Chris Lattnere6794492002-08-12 21:17:25 +0000717 if (Op0 == Op1) // sub X, X -> 0
718 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000719
Chris Lattnere6794492002-08-12 21:17:25 +0000720 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000721 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000722 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000723
Chris Lattner81a7a232004-10-16 18:11:37 +0000724 if (isa<UndefValue>(Op0))
725 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
726 if (isa<UndefValue>(Op1))
727 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
728
Chris Lattner8f2f5982003-11-05 01:06:05 +0000729 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
730 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000731 if (C->isAllOnesValue())
732 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000733
Chris Lattner8f2f5982003-11-05 01:06:05 +0000734 // C - ~X == X + (1+C)
Chris Lattnerd4252a72004-07-30 07:50:03 +0000735 Value *X;
736 if (match(Op1, m_Not(m_Value(X))))
737 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000738 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000739 // -((uint)X >> 31) -> ((int)X >> 31)
740 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000741 if (C->isNullValue()) {
742 Value *NoopCastedRHS = RemoveNoopCast(Op1);
743 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000744 if (SI->getOpcode() == Instruction::Shr)
745 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
746 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000747 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000748 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000749 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000750 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000751 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner022167f2004-03-13 00:11:49 +0000752 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000753 // Ok, the transformation is safe. Insert a cast of the incoming
754 // value, then the new shift, then the new cast.
755 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
756 SI->getOperand(0)->getName());
757 Value *InV = InsertNewInstBefore(FirstCast, I);
758 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
759 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000760 if (NewShift->getType() == I.getType())
761 return NewShift;
762 else {
763 InV = InsertNewInstBefore(NewShift, I);
764 return new CastInst(NewShift, I.getType());
765 }
Chris Lattner92295c52004-03-12 23:53:13 +0000766 }
767 }
Chris Lattner022167f2004-03-13 00:11:49 +0000768 }
Chris Lattner183b3362004-04-09 19:05:30 +0000769
770 // Try to fold constant sub into select arguments.
771 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +0000772 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +0000773 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000774
775 if (isa<PHINode>(Op0))
776 if (Instruction *NV = FoldOpIntoPhi(I))
777 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000778 }
779
Chris Lattner3082c5a2003-02-18 19:28:33 +0000780 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000781 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000782 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
783 // is not used by anyone else...
784 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000785 if (Op1I->getOpcode() == Instruction::Sub &&
786 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000787 // Swap the two operands of the subexpr...
788 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
789 Op1I->setOperand(0, IIOp1);
790 Op1I->setOperand(1, IIOp0);
791
792 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000793 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000794 }
795
796 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
797 //
798 if (Op1I->getOpcode() == Instruction::And &&
799 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
800 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
801
Chris Lattner396dbfe2004-06-09 05:08:07 +0000802 Value *NewNot =
803 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000804 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000805 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000806
Chris Lattner0aee4b72004-10-06 15:08:25 +0000807 // -(X sdiv C) -> (X sdiv -C)
808 if (Op1I->getOpcode() == Instruction::Div)
809 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
810 if (CSI->getValue() == 0)
811 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
812 return BinaryOperator::createDiv(Op1I->getOperand(0),
813 ConstantExpr::getNeg(DivRHS));
814
Chris Lattner57c8d992003-02-18 19:57:07 +0000815 // X - X*C --> X * (1-C)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000816 ConstantInt *C2;
817 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
818 Constant *CP1 =
819 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000820 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000821 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000822 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000823
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000824
825 ConstantInt *C1;
826 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
827 if (X == Op1) { // X*C - X --> X * (C-1)
828 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
829 return BinaryOperator::createMul(Op1, CP1);
830 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000831
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000832 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
833 if (X == dyn_castFoldableMul(Op1, C2))
834 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
835 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000836 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000837}
838
Chris Lattnere79e8542004-02-23 06:38:22 +0000839/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
840/// really just returns true if the most significant (sign) bit is set.
841static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
842 if (RHS->getType()->isSigned()) {
843 // True if source is LHS < 0 or LHS <= -1
844 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
845 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
846 } else {
847 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
848 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
849 // the size of the integer type.
850 if (Opcode == Instruction::SetGE)
851 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
852 if (Opcode == Instruction::SetGT)
853 return RHSC->getValue() ==
854 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
855 }
856 return false;
857}
858
Chris Lattner113f4f42002-06-25 16:13:24 +0000859Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000860 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000861 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000862
Chris Lattner81a7a232004-10-16 18:11:37 +0000863 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
864 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
865
Chris Lattnere6794492002-08-12 21:17:25 +0000866 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000867 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
868 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000869
870 // ((X << C1)*C2) == (X * (C2 << C1))
871 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
872 if (SI->getOpcode() == Instruction::Shl)
873 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000874 return BinaryOperator::createMul(SI->getOperand(0),
875 ConstantExpr::getShl(CI, ShOp));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000876
Chris Lattnercce81be2003-09-11 22:24:54 +0000877 if (CI->isNullValue())
878 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
879 if (CI->equalsInt(1)) // X * 1 == X
880 return ReplaceInstUsesWith(I, Op0);
881 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000882 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000883
Chris Lattnercce81be2003-09-11 22:24:54 +0000884 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000885 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
886 return new ShiftInst(Instruction::Shl, Op0,
887 ConstantUInt::get(Type::UByteTy, C));
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000888 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000889 if (Op1F->isNullValue())
890 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000891
Chris Lattner3082c5a2003-02-18 19:28:33 +0000892 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
893 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
894 if (Op1F->getValue() == 1.0)
895 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
896 }
Chris Lattner183b3362004-04-09 19:05:30 +0000897
898 // Try to fold constant mul into select arguments.
899 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +0000900 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +0000901 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000902
903 if (isa<PHINode>(Op0))
904 if (Instruction *NV = FoldOpIntoPhi(I))
905 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +0000906 }
907
Chris Lattner934a64cf2003-03-10 23:23:04 +0000908 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
909 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000910 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +0000911
Chris Lattner2635b522004-02-23 05:39:21 +0000912 // If one of the operands of the multiply is a cast from a boolean value, then
913 // we know the bool is either zero or one, so this is a 'masking' multiply.
914 // See if we can simplify things based on how the boolean was originally
915 // formed.
916 CastInst *BoolCast = 0;
917 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
918 if (CI->getOperand(0)->getType() == Type::BoolTy)
919 BoolCast = CI;
920 if (!BoolCast)
921 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
922 if (CI->getOperand(0)->getType() == Type::BoolTy)
923 BoolCast = CI;
924 if (BoolCast) {
925 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
926 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
927 const Type *SCOpTy = SCIOp0->getType();
928
Chris Lattnere79e8542004-02-23 06:38:22 +0000929 // If the setcc is true iff the sign bit of X is set, then convert this
930 // multiply into a shift/and combination.
931 if (isa<ConstantInt>(SCIOp1) &&
932 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000933 // Shift the X value right to turn it into "all signbits".
934 Constant *Amt = ConstantUInt::get(Type::UByteTy,
935 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000936 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000937 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +0000938 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
939 SCIOp0->getName()), I);
940 }
941
942 Value *V =
943 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
944 BoolCast->getOperand(0)->getName()+
945 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +0000946
947 // If the multiply type is not the same as the source type, sign extend
948 // or truncate to the multiply type.
949 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +0000950 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattner2635b522004-02-23 05:39:21 +0000951
952 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000953 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +0000954 }
955 }
956 }
957
Chris Lattner113f4f42002-06-25 16:13:24 +0000958 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000959}
960
Chris Lattner113f4f42002-06-25 16:13:24 +0000961Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000962 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +0000963
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000964 if (isa<UndefValue>(Op0)) // undef / X -> 0
965 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
966 if (isa<UndefValue>(Op1))
967 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
968
969 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +0000970 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000971 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000972 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000973
Chris Lattnere20c3342004-04-26 14:01:59 +0000974 // div X, -1 == -X
975 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000976 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +0000977
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000978 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +0000979 if (LHS->getOpcode() == Instruction::Div)
980 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +0000981 // (X / C1) / C2 -> X / (C1*C2)
982 return BinaryOperator::createDiv(LHS->getOperand(0),
983 ConstantExpr::getMul(RHS, LHSRHS));
984 }
985
Chris Lattner3082c5a2003-02-18 19:28:33 +0000986 // Check to see if this is an unsigned division with an exact power of 2,
987 // if so, convert to a right shift.
988 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
989 if (uint64_t Val = C->getValue()) // Don't break X / 0
990 if (uint64_t C = Log2(Val))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000991 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +0000992 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000993
Chris Lattner4ad08352004-10-09 02:50:40 +0000994 // -X/C -> X/-C
995 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000996 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +0000997 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
998
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000999 if (!RHS->isNullValue()) {
1000 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001001 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001002 return R;
1003 if (isa<PHINode>(Op0))
1004 if (Instruction *NV = FoldOpIntoPhi(I))
1005 return NV;
1006 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001007 }
1008
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001009 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1010 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1011 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1012 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1013 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1014 if (STO->getValue() == 0) { // Couldn't be this argument.
1015 I.setOperand(1, SFO);
1016 return &I;
1017 } else if (SFO->getValue() == 0) {
1018 I.setOperand(1, STO);
1019 return &I;
1020 }
1021
1022 if (uint64_t TSA = Log2(STO->getValue()))
1023 if (uint64_t FSA = Log2(SFO->getValue())) {
1024 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1025 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1026 TC, SI->getName()+".t");
1027 TSI = InsertNewInstBefore(TSI, I);
1028
1029 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1030 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1031 FC, SI->getName()+".f");
1032 FSI = InsertNewInstBefore(FSI, I);
1033 return new SelectInst(SI->getOperand(0), TSI, FSI);
1034 }
1035 }
1036
Chris Lattner3082c5a2003-02-18 19:28:33 +00001037 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001038 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001039 if (LHS->equalsInt(0))
1040 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1041
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001042 return 0;
1043}
1044
1045
Chris Lattner113f4f42002-06-25 16:13:24 +00001046Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001047 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner7fd5f072004-07-06 07:01:22 +00001048 if (I.getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001049 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00001050 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00001051 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001052 // X % -Y -> X % Y
1053 AddUsesToWorkList(I);
1054 I.setOperand(1, RHSNeg);
1055 return &I;
1056 }
1057
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001058 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00001059 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001060 if (isa<UndefValue>(Op1))
1061 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattner81a7a232004-10-16 18:11:37 +00001062
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001063 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001064 if (RHS->equalsInt(1)) // X % 1 == 0
1065 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1066
1067 // Check to see if this is an unsigned remainder with an exact power of 2,
1068 // if so, convert to a bitwise and.
1069 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1070 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +00001071 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001072 return BinaryOperator::createAnd(Op0,
1073 ConstantUInt::get(I.getType(), Val-1));
1074
1075 if (!RHS->isNullValue()) {
1076 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001077 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001078 return R;
1079 if (isa<PHINode>(Op0))
1080 if (Instruction *NV = FoldOpIntoPhi(I))
1081 return NV;
1082 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001083 }
1084
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001085 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1086 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1087 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1088 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1089 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1090 if (STO->getValue() == 0) { // Couldn't be this argument.
1091 I.setOperand(1, SFO);
1092 return &I;
1093 } else if (SFO->getValue() == 0) {
1094 I.setOperand(1, STO);
1095 return &I;
1096 }
1097
1098 if (!(STO->getValue() & (STO->getValue()-1)) &&
1099 !(SFO->getValue() & (SFO->getValue()-1))) {
1100 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1101 SubOne(STO), SI->getName()+".t"), I);
1102 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1103 SubOne(SFO), SI->getName()+".f"), I);
1104 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1105 }
1106 }
1107
Chris Lattner3082c5a2003-02-18 19:28:33 +00001108 // 0 % X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001109 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001110 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +00001111 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1112
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001113 return 0;
1114}
1115
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001116// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001117static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001118 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1119 // Calculate -1 casted to the right type...
1120 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1121 uint64_t Val = ~0ULL; // All ones
1122 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1123 return CU->getValue() == Val-1;
1124 }
1125
1126 const ConstantSInt *CS = cast<ConstantSInt>(C);
1127
1128 // Calculate 0111111111..11111
1129 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1130 int64_t Val = INT64_MAX; // All ones
1131 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1132 return CS->getValue() == Val-1;
1133}
1134
1135// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001136static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001137 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1138 return CU->getValue() == 1;
1139
1140 const ConstantSInt *CS = cast<ConstantSInt>(C);
1141
1142 // Calculate 1111111111000000000000
1143 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1144 int64_t Val = -1; // All ones
1145 Val <<= TypeBits-1; // Shift over to the right spot
1146 return CS->getValue() == Val+1;
1147}
1148
Chris Lattner35167c32004-06-09 07:59:58 +00001149// isOneBitSet - Return true if there is exactly one bit set in the specified
1150// constant.
1151static bool isOneBitSet(const ConstantInt *CI) {
1152 uint64_t V = CI->getRawValue();
1153 return V && (V & (V-1)) == 0;
1154}
1155
Chris Lattner8fc5af42004-09-23 21:46:38 +00001156#if 0 // Currently unused
1157// isLowOnes - Return true if the constant is of the form 0+1+.
1158static bool isLowOnes(const ConstantInt *CI) {
1159 uint64_t V = CI->getRawValue();
1160
1161 // There won't be bits set in parts that the type doesn't contain.
1162 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1163
1164 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1165 return U && V && (U & V) == 0;
1166}
1167#endif
1168
1169// isHighOnes - Return true if the constant is of the form 1+0+.
1170// This is the same as lowones(~X).
1171static bool isHighOnes(const ConstantInt *CI) {
1172 uint64_t V = ~CI->getRawValue();
1173
1174 // There won't be bits set in parts that the type doesn't contain.
1175 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1176
1177 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1178 return U && V && (U & V) == 0;
1179}
1180
1181
Chris Lattner3ac7c262003-08-13 20:16:26 +00001182/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1183/// are carefully arranged to allow folding of expressions such as:
1184///
1185/// (A < B) | (A > B) --> (A != B)
1186///
1187/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1188/// represents that the comparison is true if A == B, and bit value '1' is true
1189/// if A < B.
1190///
1191static unsigned getSetCondCode(const SetCondInst *SCI) {
1192 switch (SCI->getOpcode()) {
1193 // False -> 0
1194 case Instruction::SetGT: return 1;
1195 case Instruction::SetEQ: return 2;
1196 case Instruction::SetGE: return 3;
1197 case Instruction::SetLT: return 4;
1198 case Instruction::SetNE: return 5;
1199 case Instruction::SetLE: return 6;
1200 // True -> 7
1201 default:
1202 assert(0 && "Invalid SetCC opcode!");
1203 return 0;
1204 }
1205}
1206
1207/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1208/// opcode and two operands into either a constant true or false, or a brand new
1209/// SetCC instruction.
1210static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1211 switch (Opcode) {
1212 case 0: return ConstantBool::False;
1213 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1214 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1215 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1216 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1217 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1218 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1219 case 7: return ConstantBool::True;
1220 default: assert(0 && "Illegal SetCCCode!"); return 0;
1221 }
1222}
1223
1224// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1225struct FoldSetCCLogical {
1226 InstCombiner &IC;
1227 Value *LHS, *RHS;
1228 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1229 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1230 bool shouldApply(Value *V) const {
1231 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1232 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1233 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1234 return false;
1235 }
1236 Instruction *apply(BinaryOperator &Log) const {
1237 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1238 if (SCI->getOperand(0) != LHS) {
1239 assert(SCI->getOperand(1) == LHS);
1240 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1241 }
1242
1243 unsigned LHSCode = getSetCondCode(SCI);
1244 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1245 unsigned Code;
1246 switch (Log.getOpcode()) {
1247 case Instruction::And: Code = LHSCode & RHSCode; break;
1248 case Instruction::Or: Code = LHSCode | RHSCode; break;
1249 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001250 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001251 }
1252
1253 Value *RV = getSetCCValue(Code, LHS, RHS);
1254 if (Instruction *I = dyn_cast<Instruction>(RV))
1255 return I;
1256 // Otherwise, it's a constant boolean value...
1257 return IC.ReplaceInstUsesWith(Log, RV);
1258 }
1259};
1260
1261
Chris Lattner86102b82005-01-01 16:22:27 +00001262/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1263/// this predicate to simplify operations downstream. V and Mask are known to
1264/// be the same type.
1265static bool MaskedValueIsZero(Value *V, ConstantIntegral *Mask) {
1266 if (isa<UndefValue>(V) || Mask->isNullValue())
1267 return true;
1268 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
1269 return ConstantExpr::getAnd(CI, Mask)->isNullValue();
1270
1271 if (Instruction *I = dyn_cast<Instruction>(V)) {
1272 switch (I->getOpcode()) {
1273 case Instruction::And:
1274 // (X & C1) & C2 == 0 iff C1 & C2 == 0.
1275 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1)))
1276 if (ConstantExpr::getAnd(CI, Mask)->isNullValue())
1277 return true;
1278 break;
1279 case Instruction::Cast: {
1280 const Type *SrcTy = I->getOperand(0)->getType();
1281 if (SrcTy->isIntegral()) {
1282 // (cast <ty> X to int) & C2 == 0 iff <ty> could not have contained C2.
1283 if (SrcTy->isUnsigned() && // Only handle zero ext.
1284 ConstantExpr::getCast(Mask, SrcTy)->isNullValue())
1285 return true;
1286
1287 // If this is a noop cast, recurse.
1288 if (SrcTy != Type::BoolTy)
1289 if ((SrcTy->isSigned() && SrcTy->getUnsignedVersion() ==I->getType()) ||
1290 SrcTy->getSignedVersion() == I->getType()) {
1291 Constant *NewMask =
1292 ConstantExpr::getCast(Mask, I->getOperand(0)->getType());
1293 return MaskedValueIsZero(I->getOperand(0),
1294 cast<ConstantIntegral>(NewMask));
1295 }
1296 }
1297 break;
1298 }
1299 case Instruction::Shl:
1300 // (shl X, C1) & C2 == 0 iff (-1 << C1) & C2 == 0
1301 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1302 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
1303 C1 = ConstantExpr::getShl(C1, SA);
1304 C1 = ConstantExpr::getAnd(C1, Mask);
1305 if (C1->isNullValue())
1306 return true;
1307 }
1308 break;
1309 case Instruction::Shr:
1310 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1311 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1312 if (I->getType()->isUnsigned()) {
1313 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
1314 C1 = ConstantExpr::getShr(C1, SA);
1315 C1 = ConstantExpr::getAnd(C1, Mask);
1316 if (C1->isNullValue())
1317 return true;
1318 }
1319 break;
1320 }
1321 }
1322
1323 return false;
1324}
1325
Chris Lattnerba1cb382003-09-19 17:17:26 +00001326// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1327// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1328// guaranteed to be either a shift instruction or a binary operator.
1329Instruction *InstCombiner::OptAndOp(Instruction *Op,
1330 ConstantIntegral *OpRHS,
1331 ConstantIntegral *AndRHS,
1332 BinaryOperator &TheAnd) {
1333 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001334 Constant *Together = 0;
1335 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001336 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001337
Chris Lattnerba1cb382003-09-19 17:17:26 +00001338 switch (Op->getOpcode()) {
1339 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00001340 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001341 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1342 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001343 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001344 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001345 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001346 }
1347 break;
1348 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00001349 if (Together == AndRHS) // (X | C) & C --> C
1350 return ReplaceInstUsesWith(TheAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001351
Chris Lattner86102b82005-01-01 16:22:27 +00001352 if (Op->hasOneUse() && Together != OpRHS) {
1353 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1354 std::string Op0Name = Op->getName(); Op->setName("");
1355 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1356 InsertNewInstBefore(Or, TheAnd);
1357 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001358 }
1359 break;
1360 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001361 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001362 // Adding a one to a single bit bit-field should be turned into an XOR
1363 // of the bit. First thing to check is to see if this AND is with a
1364 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001365 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001366
1367 // Clear bits that are not part of the constant.
1368 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1369
1370 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001371 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001372 // Ok, at this point, we know that we are masking the result of the
1373 // ADD down to exactly one bit. If the constant we are adding has
1374 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001375 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001376
1377 // Check to see if any bits below the one bit set in AndRHSV are set.
1378 if ((AddRHS & (AndRHSV-1)) == 0) {
1379 // If not, the only thing that can effect the output of the AND is
1380 // the bit specified by AndRHSV. If that bit is set, the effect of
1381 // the XOR is to toggle the bit. If it is clear, then the ADD has
1382 // no effect.
1383 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1384 TheAnd.setOperand(0, X);
1385 return &TheAnd;
1386 } else {
1387 std::string Name = Op->getName(); Op->setName("");
1388 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001389 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001390 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001391 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001392 }
1393 }
1394 }
1395 }
1396 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001397
1398 case Instruction::Shl: {
1399 // We know that the AND will not produce any of the bits shifted in, so if
1400 // the anded constant includes them, clear them now!
1401 //
1402 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001403 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1404 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1405
1406 if (CI == ShlMask) { // Masking out bits that the shift already masks
1407 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1408 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001409 TheAnd.setOperand(1, CI);
1410 return &TheAnd;
1411 }
1412 break;
1413 }
1414 case Instruction::Shr:
1415 // We know that the AND will not produce any of the bits shifted in, so if
1416 // the anded constant includes them, clear them now! This only applies to
1417 // unsigned shifts, because a signed shr may bring in set bits!
1418 //
1419 if (AndRHS->getType()->isUnsigned()) {
1420 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001421 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1422 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1423
1424 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1425 return ReplaceInstUsesWith(TheAnd, Op);
1426 } else if (CI != AndRHS) {
1427 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001428 return &TheAnd;
1429 }
Chris Lattner7e794272004-09-24 15:21:34 +00001430 } else { // Signed shr.
1431 // See if this is shifting in some sign extension, then masking it out
1432 // with an and.
1433 if (Op->hasOneUse()) {
1434 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1435 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1436 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00001437 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00001438 // Make the argument unsigned.
1439 Value *ShVal = Op->getOperand(0);
1440 ShVal = InsertCastBefore(ShVal,
1441 ShVal->getType()->getUnsignedVersion(),
1442 TheAnd);
1443 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1444 OpRHS, Op->getName()),
1445 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00001446 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1447 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1448 TheAnd.getName()),
1449 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00001450 return new CastInst(ShVal, Op->getType());
1451 }
1452 }
Chris Lattner2da29172003-09-19 19:05:02 +00001453 }
1454 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001455 }
1456 return 0;
1457}
1458
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001459
Chris Lattner6862fbd2004-09-29 17:40:11 +00001460/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1461/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1462/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1463/// insert new instructions.
1464Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1465 bool Inside, Instruction &IB) {
1466 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1467 "Lo is not <= Hi in range emission code!");
1468 if (Inside) {
1469 if (Lo == Hi) // Trivially false.
1470 return new SetCondInst(Instruction::SetNE, V, V);
1471 if (cast<ConstantIntegral>(Lo)->isMinValue())
1472 return new SetCondInst(Instruction::SetLT, V, Hi);
1473
1474 Constant *AddCST = ConstantExpr::getNeg(Lo);
1475 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1476 InsertNewInstBefore(Add, IB);
1477 // Convert to unsigned for the comparison.
1478 const Type *UnsType = Add->getType()->getUnsignedVersion();
1479 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1480 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1481 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1482 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1483 }
1484
1485 if (Lo == Hi) // Trivially true.
1486 return new SetCondInst(Instruction::SetEQ, V, V);
1487
1488 Hi = SubOne(cast<ConstantInt>(Hi));
1489 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1490 return new SetCondInst(Instruction::SetGT, V, Hi);
1491
1492 // Emit X-Lo > Hi-Lo-1
1493 Constant *AddCST = ConstantExpr::getNeg(Lo);
1494 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1495 InsertNewInstBefore(Add, IB);
1496 // Convert to unsigned for the comparison.
1497 const Type *UnsType = Add->getType()->getUnsignedVersion();
1498 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1499 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1500 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1501 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1502}
1503
1504
Chris Lattner113f4f42002-06-25 16:13:24 +00001505Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001506 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001507 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001508
Chris Lattner81a7a232004-10-16 18:11:37 +00001509 if (isa<UndefValue>(Op1)) // X & undef -> 0
1510 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1511
Chris Lattner86102b82005-01-01 16:22:27 +00001512 // and X, X = X
1513 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00001514 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001515
1516 // and X, -1 == X
Chris Lattner86102b82005-01-01 16:22:27 +00001517 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
1518 if (AndRHS->isAllOnesValue()) // and X, -1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001519 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001520
Chris Lattner86102b82005-01-01 16:22:27 +00001521 if (MaskedValueIsZero(Op0, AndRHS)) // LHS & RHS == 0
1522 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1523
1524 // If the mask is not masking out any bits, there is no reason to do the
1525 // and in the first place.
1526 if (MaskedValueIsZero(Op0,
1527 cast<ConstantIntegral>(ConstantExpr::getNot(AndRHS))))
1528 return ReplaceInstUsesWith(I, Op0);
1529
Chris Lattnerba1cb382003-09-19 17:17:26 +00001530 // Optimize a variety of ((val OP C1) & C2) combinations...
1531 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1532 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001533 Value *Op0LHS = Op0I->getOperand(0);
1534 Value *Op0RHS = Op0I->getOperand(1);
1535 switch (Op0I->getOpcode()) {
1536 case Instruction::Xor:
1537 case Instruction::Or:
1538 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1539 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
1540 if (MaskedValueIsZero(Op0LHS, AndRHS))
1541 return BinaryOperator::createAnd(Op0RHS, AndRHS);
1542 if (MaskedValueIsZero(Op0RHS, AndRHS))
1543 return BinaryOperator::createAnd(Op0LHS, AndRHS);
1544 break;
1545 case Instruction::And:
1546 // (X & V) & C2 --> 0 iff (V & C2) == 0
1547 if (MaskedValueIsZero(Op0LHS, AndRHS) ||
1548 MaskedValueIsZero(Op0RHS, AndRHS))
1549 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1550 break;
1551 }
1552
Chris Lattner16464b32003-07-23 19:25:52 +00001553 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00001554 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001555 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00001556 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1557 const Type *SrcTy = CI->getOperand(0)->getType();
1558
1559 // If this is an integer sign or zero extension instruction.
1560 if (SrcTy->isIntegral() &&
1561 SrcTy->getPrimitiveSize() < CI->getType()->getPrimitiveSize()) {
1562
1563 if (SrcTy->isUnsigned()) {
1564 // See if this and is clearing out bits that are known to be zero
1565 // anyway (due to the zero extension).
1566 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1567 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1568 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
1569 if (Result == Mask) // The "and" isn't doing anything, remove it.
1570 return ReplaceInstUsesWith(I, CI);
1571 if (Result != AndRHS) { // Reduce the and RHS constant.
1572 I.setOperand(1, Result);
1573 return &I;
1574 }
1575
1576 } else {
1577 if (CI->hasOneUse() && SrcTy->isInteger()) {
1578 // We can only do this if all of the sign bits brought in are masked
1579 // out. Compute this by first getting 0000011111, then inverting
1580 // it.
1581 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1582 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1583 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
1584 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
1585 // If the and is clearing all of the sign bits, change this to a
1586 // zero extension cast. To do this, cast the cast input to
1587 // unsigned, then to the requested size.
1588 Value *CastOp = CI->getOperand(0);
1589 Instruction *NC =
1590 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
1591 CI->getName()+".uns");
1592 NC = InsertNewInstBefore(NC, I);
1593 // Finally, insert a replacement for CI.
1594 NC = new CastInst(NC, CI->getType(), CI->getName());
1595 CI->setName("");
1596 NC = InsertNewInstBefore(NC, I);
1597 WorkList.push_back(CI); // Delete CI later.
1598 I.setOperand(0, NC);
1599 return &I; // The AND operand was modified.
1600 }
1601 }
1602 }
1603 }
Chris Lattner33217db2003-07-23 19:36:21 +00001604 }
Chris Lattner183b3362004-04-09 19:05:30 +00001605
1606 // Try to fold constant and into select arguments.
1607 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001608 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001609 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001610 if (isa<PHINode>(Op0))
1611 if (Instruction *NV = FoldOpIntoPhi(I))
1612 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001613 }
1614
Chris Lattnerbb74e222003-03-10 23:06:50 +00001615 Value *Op0NotVal = dyn_castNotVal(Op0);
1616 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001617
Chris Lattner023a4832004-06-18 06:07:51 +00001618 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1619 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1620
Misha Brukman9c003d82004-07-30 12:50:08 +00001621 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001622 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001623 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1624 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001625 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001626 return BinaryOperator::createNot(Or);
1627 }
1628
Chris Lattner623826c2004-09-28 21:48:02 +00001629 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1630 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001631 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1632 return R;
1633
Chris Lattner623826c2004-09-28 21:48:02 +00001634 Value *LHSVal, *RHSVal;
1635 ConstantInt *LHSCst, *RHSCst;
1636 Instruction::BinaryOps LHSCC, RHSCC;
1637 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1638 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1639 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1640 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1641 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1642 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1643 // Ensure that the larger constant is on the RHS.
1644 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1645 SetCondInst *LHS = cast<SetCondInst>(Op0);
1646 if (cast<ConstantBool>(Cmp)->getValue()) {
1647 std::swap(LHS, RHS);
1648 std::swap(LHSCst, RHSCst);
1649 std::swap(LHSCC, RHSCC);
1650 }
1651
1652 // At this point, we know we have have two setcc instructions
1653 // comparing a value against two constants and and'ing the result
1654 // together. Because of the above check, we know that we only have
1655 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1656 // FoldSetCCLogical check above), that the two constants are not
1657 // equal.
1658 assert(LHSCst != RHSCst && "Compares not folded above?");
1659
1660 switch (LHSCC) {
1661 default: assert(0 && "Unknown integer condition code!");
1662 case Instruction::SetEQ:
1663 switch (RHSCC) {
1664 default: assert(0 && "Unknown integer condition code!");
1665 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1666 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1667 return ReplaceInstUsesWith(I, ConstantBool::False);
1668 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1669 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1670 return ReplaceInstUsesWith(I, LHS);
1671 }
1672 case Instruction::SetNE:
1673 switch (RHSCC) {
1674 default: assert(0 && "Unknown integer condition code!");
1675 case Instruction::SetLT:
1676 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1677 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1678 break; // (X != 13 & X < 15) -> no change
1679 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1680 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1681 return ReplaceInstUsesWith(I, RHS);
1682 case Instruction::SetNE:
1683 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1684 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1685 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1686 LHSVal->getName()+".off");
1687 InsertNewInstBefore(Add, I);
1688 const Type *UnsType = Add->getType()->getUnsignedVersion();
1689 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1690 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1691 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1692 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1693 }
1694 break; // (X != 13 & X != 15) -> no change
1695 }
1696 break;
1697 case Instruction::SetLT:
1698 switch (RHSCC) {
1699 default: assert(0 && "Unknown integer condition code!");
1700 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1701 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1702 return ReplaceInstUsesWith(I, ConstantBool::False);
1703 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1704 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1705 return ReplaceInstUsesWith(I, LHS);
1706 }
1707 case Instruction::SetGT:
1708 switch (RHSCC) {
1709 default: assert(0 && "Unknown integer condition code!");
1710 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1711 return ReplaceInstUsesWith(I, LHS);
1712 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1713 return ReplaceInstUsesWith(I, RHS);
1714 case Instruction::SetNE:
1715 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1716 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1717 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00001718 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1719 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00001720 }
1721 }
1722 }
1723 }
1724
Chris Lattner113f4f42002-06-25 16:13:24 +00001725 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001726}
1727
Chris Lattner113f4f42002-06-25 16:13:24 +00001728Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001729 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001730 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001731
Chris Lattner81a7a232004-10-16 18:11:37 +00001732 if (isa<UndefValue>(Op1))
1733 return ReplaceInstUsesWith(I, // X | undef -> -1
1734 ConstantIntegral::getAllOnesValue(I.getType()));
1735
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001736 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001737 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1738 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001739
1740 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001741 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001742 // If X is known to only contain bits that already exist in RHS, just
1743 // replace this instruction with RHS directly.
1744 if (MaskedValueIsZero(Op0,
1745 cast<ConstantIntegral>(ConstantExpr::getNot(RHS))))
1746 return ReplaceInstUsesWith(I, RHS);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001747
Chris Lattnerd4252a72004-07-30 07:50:03 +00001748 ConstantInt *C1; Value *X;
1749 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1750 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1751 std::string Op0Name = Op0->getName(); Op0->setName("");
1752 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1753 InsertNewInstBefore(Or, I);
1754 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1755 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00001756
Chris Lattnerd4252a72004-07-30 07:50:03 +00001757 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1758 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1759 std::string Op0Name = Op0->getName(); Op0->setName("");
1760 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1761 InsertNewInstBefore(Or, I);
1762 return BinaryOperator::createXor(Or,
1763 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001764 }
Chris Lattner183b3362004-04-09 19:05:30 +00001765
1766 // Try to fold constant and into select arguments.
1767 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001768 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001769 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001770 if (isa<PHINode>(Op0))
1771 if (Instruction *NV = FoldOpIntoPhi(I))
1772 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001773 }
1774
Chris Lattner812aab72003-08-12 19:11:07 +00001775 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00001776 Value *A, *B; ConstantInt *C1, *C2;
1777 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1778 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1779 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner812aab72003-08-12 19:11:07 +00001780
Chris Lattnerd4252a72004-07-30 07:50:03 +00001781 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1782 if (A == Op1) // ~A | A == -1
1783 return ReplaceInstUsesWith(I,
1784 ConstantIntegral::getAllOnesValue(I.getType()));
1785 } else {
1786 A = 0;
1787 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001788
Chris Lattnerd4252a72004-07-30 07:50:03 +00001789 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1790 if (Op0 == B)
1791 return ReplaceInstUsesWith(I,
1792 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00001793
Misha Brukman9c003d82004-07-30 12:50:08 +00001794 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00001795 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1796 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1797 I.getName()+".demorgan"), I);
1798 return BinaryOperator::createNot(And);
1799 }
Chris Lattner3e327a42003-03-10 23:13:59 +00001800 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001801
Chris Lattner3ac7c262003-08-13 20:16:26 +00001802 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001803 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00001804 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1805 return R;
1806
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001807 Value *LHSVal, *RHSVal;
1808 ConstantInt *LHSCst, *RHSCst;
1809 Instruction::BinaryOps LHSCC, RHSCC;
1810 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1811 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1812 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1813 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1814 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1815 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1816 // Ensure that the larger constant is on the RHS.
1817 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1818 SetCondInst *LHS = cast<SetCondInst>(Op0);
1819 if (cast<ConstantBool>(Cmp)->getValue()) {
1820 std::swap(LHS, RHS);
1821 std::swap(LHSCst, RHSCst);
1822 std::swap(LHSCC, RHSCC);
1823 }
1824
1825 // At this point, we know we have have two setcc instructions
1826 // comparing a value against two constants and or'ing the result
1827 // together. Because of the above check, we know that we only have
1828 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1829 // FoldSetCCLogical check above), that the two constants are not
1830 // equal.
1831 assert(LHSCst != RHSCst && "Compares not folded above?");
1832
1833 switch (LHSCC) {
1834 default: assert(0 && "Unknown integer condition code!");
1835 case Instruction::SetEQ:
1836 switch (RHSCC) {
1837 default: assert(0 && "Unknown integer condition code!");
1838 case Instruction::SetEQ:
1839 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1840 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1841 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1842 LHSVal->getName()+".off");
1843 InsertNewInstBefore(Add, I);
1844 const Type *UnsType = Add->getType()->getUnsignedVersion();
1845 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1846 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1847 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1848 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1849 }
1850 break; // (X == 13 | X == 15) -> no change
1851
1852 case Instruction::SetGT:
1853 if (LHSCst == SubOne(RHSCst)) // (X == 13 | X > 14) -> X > 13
1854 return new SetCondInst(Instruction::SetGT, LHSVal, LHSCst);
1855 break; // (X == 13 | X > 15) -> no change
1856 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
1857 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
1858 return ReplaceInstUsesWith(I, RHS);
1859 }
1860 break;
1861 case Instruction::SetNE:
1862 switch (RHSCC) {
1863 default: assert(0 && "Unknown integer condition code!");
1864 case Instruction::SetLT: // (X != 13 | X < 15) -> X < 15
1865 return ReplaceInstUsesWith(I, RHS);
1866 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
1867 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
1868 return ReplaceInstUsesWith(I, LHS);
1869 case Instruction::SetNE: // (X != 13 | X != 15) -> true
1870 return ReplaceInstUsesWith(I, ConstantBool::True);
1871 }
1872 break;
1873 case Instruction::SetLT:
1874 switch (RHSCC) {
1875 default: assert(0 && "Unknown integer condition code!");
1876 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
1877 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00001878 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
1879 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001880 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
1881 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
1882 return ReplaceInstUsesWith(I, RHS);
1883 }
1884 break;
1885 case Instruction::SetGT:
1886 switch (RHSCC) {
1887 default: assert(0 && "Unknown integer condition code!");
1888 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
1889 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
1890 return ReplaceInstUsesWith(I, LHS);
1891 case Instruction::SetNE: // (X > 13 | X != 15) -> true
1892 case Instruction::SetLT: // (X > 13 | X < 15) -> true
1893 return ReplaceInstUsesWith(I, ConstantBool::True);
1894 }
1895 }
1896 }
1897 }
Chris Lattner113f4f42002-06-25 16:13:24 +00001898 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001899}
1900
Chris Lattnerc2076352004-02-16 01:20:27 +00001901// XorSelf - Implements: X ^ X --> 0
1902struct XorSelf {
1903 Value *RHS;
1904 XorSelf(Value *rhs) : RHS(rhs) {}
1905 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1906 Instruction *apply(BinaryOperator &Xor) const {
1907 return &Xor;
1908 }
1909};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001910
1911
Chris Lattner113f4f42002-06-25 16:13:24 +00001912Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001913 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001914 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001915
Chris Lattner81a7a232004-10-16 18:11:37 +00001916 if (isa<UndefValue>(Op1))
1917 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
1918
Chris Lattnerc2076352004-02-16 01:20:27 +00001919 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1920 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1921 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00001922 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00001923 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001924
Chris Lattner97638592003-07-23 21:37:07 +00001925 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001926 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00001927 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001928 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001929
Chris Lattner97638592003-07-23 21:37:07 +00001930 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001931 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00001932 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001933 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001934 return new SetCondInst(SCI->getInverseCondition(),
1935 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00001936
Chris Lattner8f2f5982003-11-05 01:06:05 +00001937 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001938 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1939 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001940 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1941 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001942 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001943 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001944 }
Chris Lattner023a4832004-06-18 06:07:51 +00001945
1946 // ~(~X & Y) --> (X | ~Y)
1947 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1948 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1949 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1950 Instruction *NotY =
1951 BinaryOperator::createNot(Op0I->getOperand(1),
1952 Op0I->getOperand(1)->getName()+".not");
1953 InsertNewInstBefore(NotY, I);
1954 return BinaryOperator::createOr(Op0NotVal, NotY);
1955 }
1956 }
Chris Lattner97638592003-07-23 21:37:07 +00001957
1958 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00001959 switch (Op0I->getOpcode()) {
1960 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00001961 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001962 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001963 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1964 return BinaryOperator::createSub(
1965 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001966 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00001967 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001968 }
Chris Lattnere5806662003-11-04 23:50:51 +00001969 break;
1970 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00001971 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001972 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1973 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00001974 break;
1975 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00001976 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001977 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001978 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00001979 break;
1980 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00001981 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001982 }
Chris Lattner183b3362004-04-09 19:05:30 +00001983
1984 // Try to fold constant and into select arguments.
1985 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001986 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001987 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001988 if (isa<PHINode>(Op0))
1989 if (Instruction *NV = FoldOpIntoPhi(I))
1990 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001991 }
1992
Chris Lattnerbb74e222003-03-10 23:06:50 +00001993 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001994 if (X == Op1)
1995 return ReplaceInstUsesWith(I,
1996 ConstantIntegral::getAllOnesValue(I.getType()));
1997
Chris Lattnerbb74e222003-03-10 23:06:50 +00001998 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001999 if (X == Op0)
2000 return ReplaceInstUsesWith(I,
2001 ConstantIntegral::getAllOnesValue(I.getType()));
2002
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002003 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00002004 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002005 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2006 cast<BinaryOperator>(Op1I)->swapOperands();
2007 I.swapOperands();
2008 std::swap(Op0, Op1);
2009 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2010 I.swapOperands();
2011 std::swap(Op0, Op1);
Chris Lattnerb36d9082004-02-16 03:54:20 +00002012 }
2013 } else if (Op1I->getOpcode() == Instruction::Xor) {
2014 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2015 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2016 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2017 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2018 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002019
2020 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002021 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002022 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2023 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002024 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00002025 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2026 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002027 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002028 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002029 } else if (Op0I->getOpcode() == Instruction::Xor) {
2030 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2031 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2032 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2033 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002034 }
2035
Chris Lattner7aa2d472004-08-01 19:42:59 +00002036 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002037 Value *A, *B; ConstantInt *C1, *C2;
2038 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2039 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00002040 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00002041 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00002042
Chris Lattner3ac7c262003-08-13 20:16:26 +00002043 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2044 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2045 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2046 return R;
2047
Chris Lattner113f4f42002-06-25 16:13:24 +00002048 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002049}
2050
Chris Lattner6862fbd2004-09-29 17:40:11 +00002051/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2052/// overflowed for this type.
2053static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2054 ConstantInt *In2) {
2055 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2056 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2057}
2058
2059static bool isPositive(ConstantInt *C) {
2060 return cast<ConstantSInt>(C)->getValue() >= 0;
2061}
2062
2063/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2064/// overflowed for this type.
2065static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2066 ConstantInt *In2) {
2067 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2068
2069 if (In1->getType()->isUnsigned())
2070 return cast<ConstantUInt>(Result)->getValue() <
2071 cast<ConstantUInt>(In1)->getValue();
2072 if (isPositive(In1) != isPositive(In2))
2073 return false;
2074 if (isPositive(In1))
2075 return cast<ConstantSInt>(Result)->getValue() <
2076 cast<ConstantSInt>(In1)->getValue();
2077 return cast<ConstantSInt>(Result)->getValue() >
2078 cast<ConstantSInt>(In1)->getValue();
2079}
2080
Chris Lattner113f4f42002-06-25 16:13:24 +00002081Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002082 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002083 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2084 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002085
2086 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002087 if (Op0 == Op1)
2088 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00002089
Chris Lattner81a7a232004-10-16 18:11:37 +00002090 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2091 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2092
Chris Lattner15ff1e12004-11-14 07:33:16 +00002093 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2094 // addresses never equal each other! We already know that Op0 != Op1.
2095 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2096 isa<ConstantPointerNull>(Op0)) &&
2097 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
2098 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002099 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2100
2101 // setcc's with boolean values can always be turned into bitwise operations
2102 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00002103 switch (I.getOpcode()) {
2104 default: assert(0 && "Invalid setcc instruction!");
2105 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002106 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002107 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00002108 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002109 }
Chris Lattner4456da62004-08-11 00:50:51 +00002110 case Instruction::SetNE:
2111 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002112
Chris Lattner4456da62004-08-11 00:50:51 +00002113 case Instruction::SetGT:
2114 std::swap(Op0, Op1); // Change setgt -> setlt
2115 // FALL THROUGH
2116 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2117 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2118 InsertNewInstBefore(Not, I);
2119 return BinaryOperator::createAnd(Not, Op1);
2120 }
2121 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002122 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00002123 // FALL THROUGH
2124 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
2125 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2126 InsertNewInstBefore(Not, I);
2127 return BinaryOperator::createOr(Not, Op1);
2128 }
2129 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002130 }
2131
Chris Lattner2dd01742004-06-09 04:24:29 +00002132 // See if we are doing a comparison between a constant and an instruction that
2133 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002134 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002135 // Check to see if we are comparing against the minimum or maximum value...
2136 if (CI->isMinValue()) {
2137 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2138 return ReplaceInstUsesWith(I, ConstantBool::False);
2139 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2140 return ReplaceInstUsesWith(I, ConstantBool::True);
2141 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2142 return BinaryOperator::createSetEQ(Op0, Op1);
2143 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2144 return BinaryOperator::createSetNE(Op0, Op1);
2145
2146 } else if (CI->isMaxValue()) {
2147 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2148 return ReplaceInstUsesWith(I, ConstantBool::False);
2149 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2150 return ReplaceInstUsesWith(I, ConstantBool::True);
2151 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2152 return BinaryOperator::createSetEQ(Op0, Op1);
2153 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2154 return BinaryOperator::createSetNE(Op0, Op1);
2155
2156 // Comparing against a value really close to min or max?
2157 } else if (isMinValuePlusOne(CI)) {
2158 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2159 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2160 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2161 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2162
2163 } else if (isMaxValueMinusOne(CI)) {
2164 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2165 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2166 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2167 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2168 }
2169
2170 // If we still have a setle or setge instruction, turn it into the
2171 // appropriate setlt or setgt instruction. Since the border cases have
2172 // already been handled above, this requires little checking.
2173 //
2174 if (I.getOpcode() == Instruction::SetLE)
2175 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2176 if (I.getOpcode() == Instruction::SetGE)
2177 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2178
Chris Lattnere1e10e12004-05-25 06:32:08 +00002179 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002180 switch (LHSI->getOpcode()) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002181 case Instruction::PHI:
2182 if (Instruction *NV = FoldOpIntoPhi(I))
2183 return NV;
2184 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002185 case Instruction::And:
2186 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2187 LHSI->getOperand(0)->hasOneUse()) {
2188 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2189 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2190 // happens a LOT in code produced by the C front-end, for bitfield
2191 // access.
2192 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2193 ConstantUInt *ShAmt;
2194 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2195 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2196 const Type *Ty = LHSI->getType();
2197
2198 // We can fold this as long as we can't shift unknown bits
2199 // into the mask. This can only happen with signed shift
2200 // rights, as they sign-extend.
2201 if (ShAmt) {
2202 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00002203 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002204 if (!CanFold) {
2205 // To test for the bad case of the signed shr, see if any
2206 // of the bits shifted in could be tested after the mask.
2207 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd8f5e2c2004-07-21 20:14:10 +00002208 Ty->getPrimitiveSize()*8-ShAmt->getValue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002209 Constant *ShVal =
2210 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2211 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2212 CanFold = true;
2213 }
2214
2215 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00002216 Constant *NewCst;
2217 if (Shift->getOpcode() == Instruction::Shl)
2218 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2219 else
2220 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002221
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002222 // Check to see if we are shifting out any of the bits being
2223 // compared.
2224 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2225 // If we shifted bits out, the fold is not going to work out.
2226 // As a special case, check to see if this means that the
2227 // result is always true or false now.
2228 if (I.getOpcode() == Instruction::SetEQ)
2229 return ReplaceInstUsesWith(I, ConstantBool::False);
2230 if (I.getOpcode() == Instruction::SetNE)
2231 return ReplaceInstUsesWith(I, ConstantBool::True);
2232 } else {
2233 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00002234 Constant *NewAndCST;
2235 if (Shift->getOpcode() == Instruction::Shl)
2236 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2237 else
2238 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2239 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002240 LHSI->setOperand(0, Shift->getOperand(0));
2241 WorkList.push_back(Shift); // Shift is dead.
2242 AddUsesToWorkList(I);
2243 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00002244 }
2245 }
Chris Lattner35167c32004-06-09 07:59:58 +00002246 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002247 }
2248 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002249
Reid Spencer279fa252004-11-28 21:31:15 +00002250 // (setcc (cast X to larger), CI)
2251 case Instruction::Cast: {
2252 Instruction* replacement =
2253 visitSetCondInstWithCastAndConstant(I,cast<CastInst>(LHSI),CI);
2254 if (replacement)
2255 return replacement;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002256 break;
2257 }
Reid Spencer279fa252004-11-28 21:31:15 +00002258
Chris Lattner272d5ca2004-09-28 18:22:15 +00002259 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2260 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2261 switch (I.getOpcode()) {
2262 default: break;
2263 case Instruction::SetEQ:
2264 case Instruction::SetNE: {
2265 // If we are comparing against bits always shifted out, the
2266 // comparison cannot succeed.
2267 Constant *Comp =
2268 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2269 if (Comp != CI) {// Comparing against a bit that we know is zero.
2270 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2271 Constant *Cst = ConstantBool::get(IsSetNE);
2272 return ReplaceInstUsesWith(I, Cst);
2273 }
2274
2275 if (LHSI->hasOneUse()) {
2276 // Otherwise strength reduce the shift into an and.
2277 unsigned ShAmtVal = ShAmt->getValue();
2278 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2279 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2280
2281 Constant *Mask;
2282 if (CI->getType()->isUnsigned()) {
2283 Mask = ConstantUInt::get(CI->getType(), Val);
2284 } else if (ShAmtVal != 0) {
2285 Mask = ConstantSInt::get(CI->getType(), Val);
2286 } else {
2287 Mask = ConstantInt::getAllOnesValue(CI->getType());
2288 }
2289
2290 Instruction *AndI =
2291 BinaryOperator::createAnd(LHSI->getOperand(0),
2292 Mask, LHSI->getName()+".mask");
2293 Value *And = InsertNewInstBefore(AndI, I);
2294 return new SetCondInst(I.getOpcode(), And,
2295 ConstantExpr::getUShr(CI, ShAmt));
2296 }
2297 }
2298 }
2299 }
2300 break;
2301
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002302 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00002303 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00002304 switch (I.getOpcode()) {
2305 default: break;
2306 case Instruction::SetEQ:
2307 case Instruction::SetNE: {
2308 // If we are comparing against bits always shifted out, the
2309 // comparison cannot succeed.
2310 Constant *Comp =
2311 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2312
2313 if (Comp != CI) {// Comparing against a bit that we know is zero.
2314 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2315 Constant *Cst = ConstantBool::get(IsSetNE);
2316 return ReplaceInstUsesWith(I, Cst);
2317 }
2318
2319 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00002320 unsigned ShAmtVal = ShAmt->getValue();
2321
Chris Lattner1023b872004-09-27 16:18:50 +00002322 // Otherwise strength reduce the shift into an and.
2323 uint64_t Val = ~0ULL; // All ones.
2324 Val <<= ShAmtVal; // Shift over to the right spot.
2325
2326 Constant *Mask;
2327 if (CI->getType()->isUnsigned()) {
2328 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2329 Val &= (1ULL << TypeBits)-1;
2330 Mask = ConstantUInt::get(CI->getType(), Val);
2331 } else {
2332 Mask = ConstantSInt::get(CI->getType(), Val);
2333 }
2334
2335 Instruction *AndI =
2336 BinaryOperator::createAnd(LHSI->getOperand(0),
2337 Mask, LHSI->getName()+".mask");
2338 Value *And = InsertNewInstBefore(AndI, I);
2339 return new SetCondInst(I.getOpcode(), And,
2340 ConstantExpr::getShl(CI, ShAmt));
2341 }
2342 break;
2343 }
2344 }
2345 }
2346 break;
Chris Lattner7e794272004-09-24 15:21:34 +00002347
Chris Lattner6862fbd2004-09-29 17:40:11 +00002348 case Instruction::Div:
2349 // Fold: (div X, C1) op C2 -> range check
2350 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2351 // Fold this div into the comparison, producing a range check.
2352 // Determine, based on the divide type, what the range is being
2353 // checked. If there is an overflow on the low or high side, remember
2354 // it, otherwise compute the range [low, hi) bounding the new value.
2355 bool LoOverflow = false, HiOverflow = 0;
2356 ConstantInt *LoBound = 0, *HiBound = 0;
2357
2358 ConstantInt *Prod;
2359 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2360
Chris Lattnera92af962004-10-11 19:40:04 +00002361 Instruction::BinaryOps Opcode = I.getOpcode();
2362
Chris Lattner6862fbd2004-09-29 17:40:11 +00002363 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2364 } else if (LHSI->getType()->isUnsigned()) { // udiv
2365 LoBound = Prod;
2366 LoOverflow = ProdOV;
2367 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2368 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2369 if (CI->isNullValue()) { // (X / pos) op 0
2370 // Can't overflow.
2371 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2372 HiBound = DivRHS;
2373 } else if (isPositive(CI)) { // (X / pos) op pos
2374 LoBound = Prod;
2375 LoOverflow = ProdOV;
2376 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2377 } else { // (X / pos) op neg
2378 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2379 LoOverflow = AddWithOverflow(LoBound, Prod,
2380 cast<ConstantInt>(DivRHSH));
2381 HiBound = Prod;
2382 HiOverflow = ProdOV;
2383 }
2384 } else { // Divisor is < 0.
2385 if (CI->isNullValue()) { // (X / neg) op 0
2386 LoBound = AddOne(DivRHS);
2387 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2388 } else if (isPositive(CI)) { // (X / neg) op pos
2389 HiOverflow = LoOverflow = ProdOV;
2390 if (!LoOverflow)
2391 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2392 HiBound = AddOne(Prod);
2393 } else { // (X / neg) op neg
2394 LoBound = Prod;
2395 LoOverflow = HiOverflow = ProdOV;
2396 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2397 }
Chris Lattner0b41e862004-10-08 19:15:44 +00002398
Chris Lattnera92af962004-10-11 19:40:04 +00002399 // Dividing by a negate swaps the condition.
2400 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002401 }
2402
2403 if (LoBound) {
2404 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00002405 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002406 default: assert(0 && "Unhandled setcc opcode!");
2407 case Instruction::SetEQ:
2408 if (LoOverflow && HiOverflow)
2409 return ReplaceInstUsesWith(I, ConstantBool::False);
2410 else if (HiOverflow)
2411 return new SetCondInst(Instruction::SetGE, X, LoBound);
2412 else if (LoOverflow)
2413 return new SetCondInst(Instruction::SetLT, X, HiBound);
2414 else
2415 return InsertRangeTest(X, LoBound, HiBound, true, I);
2416 case Instruction::SetNE:
2417 if (LoOverflow && HiOverflow)
2418 return ReplaceInstUsesWith(I, ConstantBool::True);
2419 else if (HiOverflow)
2420 return new SetCondInst(Instruction::SetLT, X, LoBound);
2421 else if (LoOverflow)
2422 return new SetCondInst(Instruction::SetGE, X, HiBound);
2423 else
2424 return InsertRangeTest(X, LoBound, HiBound, false, I);
2425 case Instruction::SetLT:
2426 if (LoOverflow)
2427 return ReplaceInstUsesWith(I, ConstantBool::False);
2428 return new SetCondInst(Instruction::SetLT, X, LoBound);
2429 case Instruction::SetGT:
2430 if (HiOverflow)
2431 return ReplaceInstUsesWith(I, ConstantBool::False);
2432 return new SetCondInst(Instruction::SetGE, X, HiBound);
2433 }
2434 }
2435 }
2436 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002437 case Instruction::Select:
2438 // If either operand of the select is a constant, we can fold the
2439 // comparison into the select arms, which will cause one to be
2440 // constant folded and the select turned into a bitwise or.
2441 Value *Op1 = 0, *Op2 = 0;
2442 if (LHSI->hasOneUse()) {
Chris Lattner35167c32004-06-09 07:59:58 +00002443 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002444 // Fold the known value into the constant operand.
2445 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
2446 // Insert a new SetCC of the other select operand.
2447 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002448 LHSI->getOperand(2), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002449 I.getName()), I);
Chris Lattner35167c32004-06-09 07:59:58 +00002450 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002451 // Fold the known value into the constant operand.
2452 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
2453 // Insert a new SetCC of the other select operand.
2454 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002455 LHSI->getOperand(1), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002456 I.getName()), I);
2457 }
Chris Lattner2dd01742004-06-09 04:24:29 +00002458 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002459
2460 if (Op1)
2461 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2462 break;
2463 }
2464
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002465 // Simplify seteq and setne instructions...
2466 if (I.getOpcode() == Instruction::SetEQ ||
2467 I.getOpcode() == Instruction::SetNE) {
2468 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2469
Chris Lattnercfbce7c2003-07-23 17:26:36 +00002470 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002471 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00002472 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2473 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00002474 case Instruction::Rem:
2475 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2476 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2477 BO->hasOneUse() &&
2478 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2479 if (unsigned L2 =
2480 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2481 const Type *UTy = BO->getType()->getUnsignedVersion();
2482 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2483 UTy, "tmp"), I);
2484 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2485 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2486 RHSCst, BO->getName()), I);
2487 return BinaryOperator::create(I.getOpcode(), NewRem,
2488 Constant::getNullValue(UTy));
2489 }
2490 break;
2491
Chris Lattnerc992add2003-08-13 05:33:12 +00002492 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00002493 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2494 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00002495 if (BO->hasOneUse())
2496 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2497 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00002498 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002499 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2500 // efficiently invertible, or if the add has just this one use.
2501 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner6e079362004-06-27 22:51:36 +00002502
Chris Lattnerc992add2003-08-13 05:33:12 +00002503 if (Value *NegVal = dyn_castNegVal(BOp1))
2504 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2505 else if (Value *NegVal = dyn_castNegVal(BOp0))
2506 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002507 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002508 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2509 BO->setName("");
2510 InsertNewInstBefore(Neg, I);
2511 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2512 }
2513 }
2514 break;
2515 case Instruction::Xor:
2516 // For the xor case, we can xor two constants together, eliminating
2517 // the explicit xor.
2518 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2519 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002520 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00002521
2522 // FALLTHROUGH
2523 case Instruction::Sub:
2524 // Replace (([sub|xor] A, B) != 0) with (A != B)
2525 if (CI->isNullValue())
2526 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2527 BO->getOperand(1));
2528 break;
2529
2530 case Instruction::Or:
2531 // If bits are being or'd in that are not present in the constant we
2532 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002533 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002534 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002535 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002536 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002537 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002538 break;
2539
2540 case Instruction::And:
2541 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002542 // If bits are being compared against that are and'd out, then the
2543 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002544 if (!ConstantExpr::getAnd(CI,
2545 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002546 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00002547
Chris Lattner35167c32004-06-09 07:59:58 +00002548 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00002549 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00002550 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2551 Instruction::SetNE, Op0,
2552 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00002553
Chris Lattnerc992add2003-08-13 05:33:12 +00002554 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2555 // to be a signed value as appropriate.
2556 if (isSignBit(BOC)) {
2557 Value *X = BO->getOperand(0);
2558 // If 'X' is not signed, insert a cast now...
2559 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002560 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002561 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00002562 }
2563 return new SetCondInst(isSetNE ? Instruction::SetLT :
2564 Instruction::SetGE, X,
2565 Constant::getNullValue(X->getType()));
2566 }
Chris Lattner8fc5af42004-09-23 21:46:38 +00002567
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002568 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00002569 if (CI->isNullValue() && isHighOnes(BOC)) {
2570 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002571 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002572
2573 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002574 if (NegX->getType()->isSigned()) {
2575 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2576 X = InsertCastBefore(X, DestTy, I);
2577 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002578 }
2579
2580 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002581 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002582 }
2583
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002584 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002585 default: break;
2586 }
2587 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00002588 } else { // Not a SetEQ/SetNE
2589 // If the LHS is a cast from an integral value of the same size,
2590 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2591 Value *CastOp = Cast->getOperand(0);
2592 const Type *SrcTy = CastOp->getType();
2593 unsigned SrcTySize = SrcTy->getPrimitiveSize();
2594 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2595 SrcTySize == Cast->getType()->getPrimitiveSize()) {
2596 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
2597 "Source and destination signednesses should differ!");
2598 if (Cast->getType()->isSigned()) {
2599 // If this is a signed comparison, check for comparisons in the
2600 // vicinity of zero.
2601 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2602 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002603 return BinaryOperator::createSetGT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002604 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2605 else if (I.getOpcode() == Instruction::SetGT &&
2606 cast<ConstantSInt>(CI)->getValue() == -1)
2607 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002608 return BinaryOperator::createSetLT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002609 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2610 } else {
2611 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2612 if (I.getOpcode() == Instruction::SetLT &&
2613 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2614 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002615 return BinaryOperator::createSetGT(CastOp,
2616 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002617 else if (I.getOpcode() == Instruction::SetGT &&
2618 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2619 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002620 return BinaryOperator::createSetLT(CastOp,
2621 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002622 }
2623 }
2624 }
Chris Lattnere967b342003-06-04 05:10:11 +00002625 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002626 }
2627
Chris Lattner16930792003-11-03 04:25:02 +00002628 // Test to see if the operands of the setcc are casted versions of other
2629 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00002630 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2631 Value *CastOp0 = CI->getOperand(0);
2632 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00002633 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00002634 (I.getOpcode() == Instruction::SetEQ ||
2635 I.getOpcode() == Instruction::SetNE)) {
2636 // We keep moving the cast from the left operand over to the right
2637 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00002638 Op0 = CastOp0;
Chris Lattner16930792003-11-03 04:25:02 +00002639
2640 // If operand #1 is a cast instruction, see if we can eliminate it as
2641 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00002642 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2643 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00002644 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00002645 Op1 = CI2->getOperand(0);
Chris Lattner16930792003-11-03 04:25:02 +00002646
2647 // If Op1 is a constant, we can fold the cast into the constant.
2648 if (Op1->getType() != Op0->getType())
2649 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2650 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2651 } else {
2652 // Otherwise, cast the RHS right before the setcc
2653 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2654 InsertNewInstBefore(cast<Instruction>(Op1), I);
2655 }
2656 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2657 }
2658
Chris Lattner6444c372003-11-03 05:17:03 +00002659 // Handle the special case of: setcc (cast bool to X), <cst>
2660 // This comes up when you have code like
2661 // int X = A < B;
2662 // if (X) ...
2663 // For generality, we handle any zero-extension of any operand comparison
2664 // with a constant.
2665 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2666 const Type *SrcTy = CastOp0->getType();
2667 const Type *DestTy = Op0->getType();
2668 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2669 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2670 // Ok, we have an expansion of operand 0 into a new type. Get the
2671 // constant value, masink off bits which are not set in the RHS. These
2672 // could be set if the destination value is signed.
2673 uint64_t ConstVal = ConstantRHS->getRawValue();
2674 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2675
2676 // If the constant we are comparing it with has high bits set, which
2677 // don't exist in the original value, the values could never be equal,
2678 // because the source would be zero extended.
2679 unsigned SrcBits =
2680 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner7c94d112003-11-05 17:31:36 +00002681 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2682 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner6444c372003-11-03 05:17:03 +00002683 switch (I.getOpcode()) {
2684 default: assert(0 && "Unknown comparison type!");
2685 case Instruction::SetEQ:
2686 return ReplaceInstUsesWith(I, ConstantBool::False);
2687 case Instruction::SetNE:
2688 return ReplaceInstUsesWith(I, ConstantBool::True);
2689 case Instruction::SetLT:
2690 case Instruction::SetLE:
2691 if (DestTy->isSigned() && HasSignBit)
2692 return ReplaceInstUsesWith(I, ConstantBool::False);
2693 return ReplaceInstUsesWith(I, ConstantBool::True);
2694 case Instruction::SetGT:
2695 case Instruction::SetGE:
2696 if (DestTy->isSigned() && HasSignBit)
2697 return ReplaceInstUsesWith(I, ConstantBool::True);
2698 return ReplaceInstUsesWith(I, ConstantBool::False);
2699 }
2700 }
2701
2702 // Otherwise, we can replace the setcc with a setcc of the smaller
2703 // operand value.
2704 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2705 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2706 }
2707 }
2708 }
Chris Lattner113f4f42002-06-25 16:13:24 +00002709 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002710}
2711
Reid Spencer279fa252004-11-28 21:31:15 +00002712// visitSetCondInstWithCastAndConstant - this method is part of the
2713// visitSetCondInst method. It handles the situation where we have:
2714// (setcc (cast X to larger), CI)
2715// It tries to remove the cast and even the setcc if the CI value
2716// and range of the cast allow it.
2717Instruction *
2718InstCombiner::visitSetCondInstWithCastAndConstant(BinaryOperator&I,
2719 CastInst* LHSI,
2720 ConstantInt* CI) {
2721 const Type *SrcTy = LHSI->getOperand(0)->getType();
2722 const Type *DestTy = LHSI->getType();
2723 if (SrcTy->isIntegral() && DestTy->isIntegral()) {
2724 unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
2725 unsigned DestBits = DestTy->getPrimitiveSize()*8;
2726 if (SrcTy == Type::BoolTy)
2727 SrcBits = 1;
2728 if (DestTy == Type::BoolTy)
2729 DestBits = 1;
2730 if (SrcBits < DestBits) {
2731 // There are fewer bits in the source of the cast than in the result
2732 // of the cast. Any other case doesn't matter because the constant
2733 // value won't have changed due to sign extension.
2734 Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
2735 if (ConstantExpr::getCast(NewCst, DestTy) == CI) {
2736 // The constant value operand of the setCC before and after a
2737 // cast to the source type of the cast instruction is the same
2738 // value, so we just replace with the same setcc opcode, but
2739 // using the source value compared to the constant casted to the
2740 // source type.
2741 if (SrcTy->isSigned() && DestTy->isUnsigned()) {
2742 CastInst* Cst = new CastInst(LHSI->getOperand(0),
2743 SrcTy->getUnsignedVersion(), LHSI->getName());
2744 InsertNewInstBefore(Cst,I);
2745 return new SetCondInst(I.getOpcode(), Cst,
2746 ConstantExpr::getCast(CI, SrcTy->getUnsignedVersion()));
2747 }
2748 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),NewCst);
2749 }
2750 // The constant value before and after a cast to the source type
2751 // is different, so various cases are possible depending on the
2752 // opcode and the signs of the types involved in the cast.
2753 switch (I.getOpcode()) {
2754 case Instruction::SetLT: {
2755 Constant* Max = ConstantIntegral::getMaxValue(SrcTy);
2756 Max = ConstantExpr::getCast(Max, DestTy);
2757 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
2758 }
2759 case Instruction::SetGT: {
2760 Constant* Min = ConstantIntegral::getMinValue(SrcTy);
2761 Min = ConstantExpr::getCast(Min, DestTy);
2762 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
2763 }
2764 case Instruction::SetEQ:
2765 // We're looking for equality, and we know the values are not
2766 // equal so replace with constant False.
2767 return ReplaceInstUsesWith(I, ConstantBool::False);
2768 case Instruction::SetNE:
2769 // We're testing for inequality, and we know the values are not
2770 // equal so replace with constant True.
2771 return ReplaceInstUsesWith(I, ConstantBool::True);
2772 case Instruction::SetLE:
2773 case Instruction::SetGE:
2774 assert(!"SetLE and SetGE should be handled elsewhere");
2775 default:
2776 assert(!"unknown integer comparison");
2777 }
2778 }
2779 }
2780 return 0;
2781}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002782
2783
Chris Lattnere8d6c602003-03-10 19:16:08 +00002784Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002785 assert(I.getOperand(1)->getType() == Type::UByteTy);
2786 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002787 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002788
2789 // shl X, 0 == X and shr X, 0 == X
2790 // shl 0, X == 0 and shr 0, X == 0
2791 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00002792 Op0 == Constant::getNullValue(Op0->getType()))
2793 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002794
Chris Lattner81a7a232004-10-16 18:11:37 +00002795 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
2796 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00002797 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00002798 else // undef << X -> 0 AND undef >>u X -> 0
2799 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2800 }
2801 if (isa<UndefValue>(Op1)) {
2802 if (isLeftShift || I.getType()->isUnsigned())
2803 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2804 else
2805 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
2806 }
2807
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002808 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
2809 if (!isLeftShift)
2810 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
2811 if (CSI->isAllOnesValue())
2812 return ReplaceInstUsesWith(I, CSI);
2813
Chris Lattner183b3362004-04-09 19:05:30 +00002814 // Try to fold constant and into select arguments.
2815 if (isa<Constant>(Op0))
2816 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002817 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002818 return R;
2819
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002820 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002821 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
2822 // of a signed value.
2823 //
Chris Lattnere8d6c602003-03-10 19:16:08 +00002824 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00002825 if (CUI->getValue() >= TypeBits) {
2826 if (!Op0->getType()->isSigned() || isLeftShift)
2827 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
2828 else {
2829 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
2830 return &I;
2831 }
2832 }
Chris Lattner55f3d942002-09-10 23:04:09 +00002833
Chris Lattnerede3fe02003-08-13 04:18:28 +00002834 // ((X*C1) << C2) == (X * (C1 << C2))
2835 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
2836 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
2837 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002838 return BinaryOperator::createMul(BO->getOperand(0),
2839 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnerede3fe02003-08-13 04:18:28 +00002840
Chris Lattner183b3362004-04-09 19:05:30 +00002841 // Try to fold constant and into select arguments.
2842 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002843 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002844 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002845 if (isa<PHINode>(Op0))
2846 if (Instruction *NV = FoldOpIntoPhi(I))
2847 return NV;
Chris Lattnerede3fe02003-08-13 04:18:28 +00002848
Chris Lattner86102b82005-01-01 16:22:27 +00002849 if (Op0->hasOneUse()) {
2850 // If this is a SHL of a sign-extending cast, see if we can turn the input
2851 // into a zero extending cast (a simple strength reduction).
2852 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2853 const Type *SrcTy = CI->getOperand(0)->getType();
2854 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
2855 SrcTy->getPrimitiveSize() < CI->getType()->getPrimitiveSize()) {
2856 // We can change it to a zero extension if we are shifting out all of
2857 // the sign extended bits. To check this, form a mask of all of the
2858 // sign extend bits, then shift them left and see if we have anything
2859 // left.
2860 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
2861 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
2862 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
2863 if (ConstantExpr::getShl(Mask, CUI)->isNullValue()) {
2864 // If the shift is nuking all of the sign bits, change this to a
2865 // zero extension cast. To do this, cast the cast input to
2866 // unsigned, then to the requested size.
2867 Value *CastOp = CI->getOperand(0);
2868 Instruction *NC =
2869 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
2870 CI->getName()+".uns");
2871 NC = InsertNewInstBefore(NC, I);
2872 // Finally, insert a replacement for CI.
2873 NC = new CastInst(NC, CI->getType(), CI->getName());
2874 CI->setName("");
2875 NC = InsertNewInstBefore(NC, I);
2876 WorkList.push_back(CI); // Delete CI later.
2877 I.setOperand(0, NC);
2878 return &I; // The SHL operand was modified.
2879 }
2880 }
2881 }
2882
2883 // If the operand is an bitwise operator with a constant RHS, and the
2884 // shift is the only use, we can pull it out of the shift.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002885 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
2886 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
2887 bool isValid = true; // Valid only for And, Or, Xor
2888 bool highBitSet = false; // Transform if high bit of constant set?
2889
2890 switch (Op0BO->getOpcode()) {
2891 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00002892 case Instruction::Add:
2893 isValid = isLeftShift;
2894 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002895 case Instruction::Or:
2896 case Instruction::Xor:
2897 highBitSet = false;
2898 break;
2899 case Instruction::And:
2900 highBitSet = true;
2901 break;
2902 }
2903
2904 // If this is a signed shift right, and the high bit is modified
2905 // by the logical operation, do not perform the transformation.
2906 // The highBitSet boolean indicates the value of the high bit of
2907 // the constant which would cause it to be modified for this
2908 // operation.
2909 //
2910 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
2911 uint64_t Val = Op0C->getRawValue();
2912 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
2913 }
2914
2915 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002916 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002917
2918 Instruction *NewShift =
2919 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
2920 Op0BO->getName());
2921 Op0BO->setName("");
2922 InsertNewInstBefore(NewShift, I);
2923
2924 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
2925 NewRHS);
2926 }
2927 }
Chris Lattner86102b82005-01-01 16:22:27 +00002928 }
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002929
Chris Lattner3204d4e2003-07-24 17:52:58 +00002930 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002931 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00002932 if (ConstantUInt *ShiftAmt1C =
2933 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002934 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
2935 unsigned ShiftAmt2 = CUI->getValue();
2936
2937 // Check for (A << c1) << c2 and (A >> c1) >> c2
2938 if (I.getOpcode() == Op0SI->getOpcode()) {
2939 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerf5ce2542004-02-23 20:30:06 +00002940 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
2941 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner3204d4e2003-07-24 17:52:58 +00002942 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
2943 ConstantUInt::get(Type::UByteTy, Amt));
2944 }
2945
Chris Lattnerab780df2003-07-24 18:38:56 +00002946 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
2947 // signed types, we can only support the (A >> c1) << c2 configuration,
2948 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002949 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002950 // Calculate bitmask for what gets shifted off the edge...
2951 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002952 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002953 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002954 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002955 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +00002956
2957 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002958 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
2959 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00002960 InsertNewInstBefore(Mask, I);
2961
2962 // Figure out what flavor of shift we should use...
2963 if (ShiftAmt1 == ShiftAmt2)
2964 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
2965 else if (ShiftAmt1 < ShiftAmt2) {
2966 return new ShiftInst(I.getOpcode(), Mask,
2967 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
2968 } else {
2969 return new ShiftInst(Op0SI->getOpcode(), Mask,
2970 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
2971 }
2972 }
2973 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002974 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00002975
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002976 return 0;
2977}
2978
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002979enum CastType {
2980 Noop = 0,
2981 Truncate = 1,
2982 Signext = 2,
2983 Zeroext = 3
2984};
2985
2986/// getCastType - In the future, we will split the cast instruction into these
2987/// various types. Until then, we have to do the analysis here.
2988static CastType getCastType(const Type *Src, const Type *Dest) {
2989 assert(Src->isIntegral() && Dest->isIntegral() &&
2990 "Only works on integral types!");
2991 unsigned SrcSize = Src->getPrimitiveSize()*8;
2992 if (Src == Type::BoolTy) SrcSize = 1;
2993 unsigned DestSize = Dest->getPrimitiveSize()*8;
2994 if (Dest == Type::BoolTy) DestSize = 1;
2995
2996 if (SrcSize == DestSize) return Noop;
2997 if (SrcSize > DestSize) return Truncate;
2998 if (Src->isSigned()) return Signext;
2999 return Zeroext;
3000}
3001
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003002
Chris Lattner48a44f72002-05-02 17:06:02 +00003003// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3004// instruction.
3005//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003006static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00003007 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003008
Chris Lattner650b6da2002-08-02 20:00:25 +00003009 // It is legal to eliminate the instruction if casting A->B->A if the sizes
3010 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00003011 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00003012 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00003013 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00003014
Chris Lattner4fbad962004-07-21 04:27:24 +00003015 // If we are casting between pointer and integer types, treat pointers as
3016 // integers of the appropriate size for the code below.
3017 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3018 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3019 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00003020
Chris Lattner48a44f72002-05-02 17:06:02 +00003021 // Allow free casting and conversion of sizes as long as the sign doesn't
3022 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003023 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003024 CastType FirstCast = getCastType(SrcTy, MidTy);
3025 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00003026
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003027 // Capture the effect of these two casts. If the result is a legal cast,
3028 // the CastType is stored here, otherwise a special code is used.
3029 static const unsigned CastResult[] = {
3030 // First cast is noop
3031 0, 1, 2, 3,
3032 // First cast is a truncate
3033 1, 1, 4, 4, // trunc->extend is not safe to eliminate
3034 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00003035 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003036 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00003037 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003038 };
3039
3040 unsigned Result = CastResult[FirstCast*4+SecondCast];
3041 switch (Result) {
3042 default: assert(0 && "Illegal table value!");
3043 case 0:
3044 case 1:
3045 case 2:
3046 case 3:
3047 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
3048 // truncates, we could eliminate more casts.
3049 return (unsigned)getCastType(SrcTy, DstTy) == Result;
3050 case 4:
3051 return false; // Not possible to eliminate this here.
3052 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00003053 // Sign or zero extend followed by truncate is always ok if the result
3054 // is a truncate or noop.
3055 CastType ResultCast = getCastType(SrcTy, DstTy);
3056 if (ResultCast == Noop || ResultCast == Truncate)
3057 return true;
3058 // Otherwise we are still growing the value, we are only safe if the
3059 // result will match the sign/zeroextendness of the result.
3060 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00003061 }
Chris Lattner650b6da2002-08-02 20:00:25 +00003062 }
Chris Lattner48a44f72002-05-02 17:06:02 +00003063 return false;
3064}
3065
Chris Lattner11ffd592004-07-20 05:21:00 +00003066static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003067 if (V->getType() == Ty || isa<Constant>(V)) return false;
3068 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00003069 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
3070 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003071 return false;
3072 return true;
3073}
3074
3075/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
3076/// InsertBefore instruction. This is specialized a bit to avoid inserting
3077/// casts that are known to not do anything...
3078///
3079Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
3080 Instruction *InsertBefore) {
3081 if (V->getType() == DestTy) return V;
3082 if (Constant *C = dyn_cast<Constant>(V))
3083 return ConstantExpr::getCast(C, DestTy);
3084
3085 CastInst *CI = new CastInst(V, DestTy, V->getName());
3086 InsertNewInstBefore(CI, *InsertBefore);
3087 return CI;
3088}
Chris Lattner48a44f72002-05-02 17:06:02 +00003089
3090// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00003091//
Chris Lattner113f4f42002-06-25 16:13:24 +00003092Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00003093 Value *Src = CI.getOperand(0);
3094
Chris Lattner48a44f72002-05-02 17:06:02 +00003095 // If the user is casting a value to the same type, eliminate this cast
3096 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00003097 if (CI.getType() == Src->getType())
3098 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00003099
Chris Lattner81a7a232004-10-16 18:11:37 +00003100 if (isa<UndefValue>(Src)) // cast undef -> undef
3101 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
3102
Chris Lattner48a44f72002-05-02 17:06:02 +00003103 // If casting the result of another cast instruction, try to eliminate this
3104 // one!
3105 //
Chris Lattner86102b82005-01-01 16:22:27 +00003106 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
3107 Value *A = CSrc->getOperand(0);
3108 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
3109 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003110 // This instruction now refers directly to the cast's src operand. This
3111 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00003112 CI.setOperand(0, CSrc->getOperand(0));
3113 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00003114 }
3115
Chris Lattner650b6da2002-08-02 20:00:25 +00003116 // If this is an A->B->A cast, and we are dealing with integral types, try
3117 // to convert this into a logical 'and' instruction.
3118 //
Chris Lattner86102b82005-01-01 16:22:27 +00003119 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003120 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00003121 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
3122 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()&&
3123 A->getType()->getPrimitiveSize() == CI.getType()->getPrimitiveSize()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00003124 assert(CSrc->getType() != Type::ULongTy &&
3125 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00003126 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner86102b82005-01-01 16:22:27 +00003127 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
3128 AndValue);
3129 AndOp = ConstantExpr::getCast(AndOp, A->getType());
3130 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
3131 if (And->getType() != CI.getType()) {
3132 And->setName(CSrc->getName()+".mask");
3133 InsertNewInstBefore(And, CI);
3134 And = new CastInst(And, CI.getType());
3135 }
3136 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00003137 }
3138 }
Chris Lattner86102b82005-01-01 16:22:27 +00003139
Chris Lattner03841652004-05-25 04:29:21 +00003140 // If this is a cast to bool, turn it into the appropriate setne instruction.
3141 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003142 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00003143 Constant::getNullValue(CI.getOperand(0)->getType()));
3144
Chris Lattnerd0d51602003-06-21 23:12:02 +00003145 // If casting the result of a getelementptr instruction with no offset, turn
3146 // this into a cast of the original pointer!
3147 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00003148 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00003149 bool AllZeroOperands = true;
3150 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
3151 if (!isa<Constant>(GEP->getOperand(i)) ||
3152 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
3153 AllZeroOperands = false;
3154 break;
3155 }
3156 if (AllZeroOperands) {
3157 CI.setOperand(0, GEP->getOperand(0));
3158 return &CI;
3159 }
3160 }
3161
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003162 // If we are casting a malloc or alloca to a pointer to a type of the same
3163 // size, rewrite the allocation instruction to allocate the "right" type.
3164 //
3165 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00003166 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003167 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
3168 // Get the type really allocated and the type casted to...
3169 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003170 const Type *CastElTy = PTy->getElementType();
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003171 if (AllocElTy->isSized() && CastElTy->isSized()) {
3172 unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
3173 unsigned CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00003174
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003175 // If the allocation is for an even multiple of the cast type size
3176 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
3177 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003178 AllocElTySize/CastElTySize);
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003179 std::string Name = AI->getName(); AI->setName("");
3180 AllocationInst *New;
3181 if (isa<MallocInst>(AI))
3182 New = new MallocInst(CastElTy, Amt, Name);
3183 else
3184 New = new AllocaInst(CastElTy, Amt, Name);
3185 InsertNewInstBefore(New, *AI);
3186 return ReplaceInstUsesWith(CI, New);
3187 }
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003188 }
3189 }
3190
Chris Lattner86102b82005-01-01 16:22:27 +00003191 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
3192 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
3193 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003194 if (isa<PHINode>(Src))
3195 if (Instruction *NV = FoldOpIntoPhi(CI))
3196 return NV;
3197
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003198 // If the source value is an instruction with only this use, we can attempt to
3199 // propagate the cast into the instruction. Also, only handle integral types
3200 // for now.
3201 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003202 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003203 CI.getType()->isInteger()) { // Don't mess with casts to bool here
3204 const Type *DestTy = CI.getType();
3205 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
3206 unsigned DestBitSize = getTypeSizeInBits(DestTy);
3207
3208 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
3209 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
3210
3211 switch (SrcI->getOpcode()) {
3212 case Instruction::Add:
3213 case Instruction::Mul:
3214 case Instruction::And:
3215 case Instruction::Or:
3216 case Instruction::Xor:
3217 // If we are discarding information, or just changing the sign, rewrite.
3218 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
3219 // Don't insert two casts if they cannot be eliminated. We allow two
3220 // casts to be inserted if the sizes are the same. This could only be
3221 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00003222 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
3223 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003224 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3225 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
3226 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
3227 ->getOpcode(), Op0c, Op1c);
3228 }
3229 }
3230 break;
3231 case Instruction::Shl:
3232 // Allow changing the sign of the source operand. Do not allow changing
3233 // the size of the shift, UNLESS the shift amount is a constant. We
3234 // mush not change variable sized shifts to a smaller size, because it
3235 // is undefined to shift more bits out than exist in the value.
3236 if (DestBitSize == SrcBitSize ||
3237 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
3238 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3239 return new ShiftInst(Instruction::Shl, Op0c, Op1);
3240 }
3241 break;
3242 }
3243 }
3244
Chris Lattner260ab202002-04-18 17:39:14 +00003245 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00003246}
3247
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003248/// GetSelectFoldableOperands - We want to turn code that looks like this:
3249/// %C = or %A, %B
3250/// %D = select %cond, %C, %A
3251/// into:
3252/// %C = select %cond, %B, 0
3253/// %D = or %A, %C
3254///
3255/// Assuming that the specified instruction is an operand to the select, return
3256/// a bitmask indicating which operands of this instruction are foldable if they
3257/// equal the other incoming value of the select.
3258///
3259static unsigned GetSelectFoldableOperands(Instruction *I) {
3260 switch (I->getOpcode()) {
3261 case Instruction::Add:
3262 case Instruction::Mul:
3263 case Instruction::And:
3264 case Instruction::Or:
3265 case Instruction::Xor:
3266 return 3; // Can fold through either operand.
3267 case Instruction::Sub: // Can only fold on the amount subtracted.
3268 case Instruction::Shl: // Can only fold on the shift amount.
3269 case Instruction::Shr:
3270 return 1;
3271 default:
3272 return 0; // Cannot fold
3273 }
3274}
3275
3276/// GetSelectFoldableConstant - For the same transformation as the previous
3277/// function, return the identity constant that goes into the select.
3278static Constant *GetSelectFoldableConstant(Instruction *I) {
3279 switch (I->getOpcode()) {
3280 default: assert(0 && "This cannot happen!"); abort();
3281 case Instruction::Add:
3282 case Instruction::Sub:
3283 case Instruction::Or:
3284 case Instruction::Xor:
3285 return Constant::getNullValue(I->getType());
3286 case Instruction::Shl:
3287 case Instruction::Shr:
3288 return Constant::getNullValue(Type::UByteTy);
3289 case Instruction::And:
3290 return ConstantInt::getAllOnesValue(I->getType());
3291 case Instruction::Mul:
3292 return ConstantInt::get(I->getType(), 1);
3293 }
3294}
3295
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003296Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00003297 Value *CondVal = SI.getCondition();
3298 Value *TrueVal = SI.getTrueValue();
3299 Value *FalseVal = SI.getFalseValue();
3300
3301 // select true, X, Y -> X
3302 // select false, X, Y -> Y
3303 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003304 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00003305 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003306 else {
3307 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00003308 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003309 }
Chris Lattner533bc492004-03-30 19:37:13 +00003310
3311 // select C, X, X -> X
3312 if (TrueVal == FalseVal)
3313 return ReplaceInstUsesWith(SI, TrueVal);
3314
Chris Lattner81a7a232004-10-16 18:11:37 +00003315 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3316 return ReplaceInstUsesWith(SI, FalseVal);
3317 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3318 return ReplaceInstUsesWith(SI, TrueVal);
3319 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3320 if (isa<Constant>(TrueVal))
3321 return ReplaceInstUsesWith(SI, TrueVal);
3322 else
3323 return ReplaceInstUsesWith(SI, FalseVal);
3324 }
3325
Chris Lattner1c631e82004-04-08 04:43:23 +00003326 if (SI.getType() == Type::BoolTy)
3327 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
3328 if (C == ConstantBool::True) {
3329 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003330 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003331 } else {
3332 // Change: A = select B, false, C --> A = and !B, C
3333 Value *NotCond =
3334 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3335 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003336 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003337 }
3338 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
3339 if (C == ConstantBool::False) {
3340 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003341 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003342 } else {
3343 // Change: A = select B, C, true --> A = or !B, C
3344 Value *NotCond =
3345 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3346 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003347 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003348 }
3349 }
3350
Chris Lattner183b3362004-04-09 19:05:30 +00003351 // Selecting between two integer constants?
3352 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
3353 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
3354 // select C, 1, 0 -> cast C to int
3355 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
3356 return new CastInst(CondVal, SI.getType());
3357 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
3358 // select C, 0, 1 -> cast !C to int
3359 Value *NotCond =
3360 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00003361 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00003362 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00003363 }
Chris Lattner35167c32004-06-09 07:59:58 +00003364
3365 // If one of the constants is zero (we know they can't both be) and we
3366 // have a setcc instruction with zero, and we have an 'and' with the
3367 // non-constant value, eliminate this whole mess. This corresponds to
3368 // cases like this: ((X & 27) ? 27 : 0)
3369 if (TrueValC->isNullValue() || FalseValC->isNullValue())
3370 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
3371 if ((IC->getOpcode() == Instruction::SetEQ ||
3372 IC->getOpcode() == Instruction::SetNE) &&
3373 isa<ConstantInt>(IC->getOperand(1)) &&
3374 cast<Constant>(IC->getOperand(1))->isNullValue())
3375 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
3376 if (ICA->getOpcode() == Instruction::And &&
3377 isa<ConstantInt>(ICA->getOperand(1)) &&
3378 (ICA->getOperand(1) == TrueValC ||
3379 ICA->getOperand(1) == FalseValC) &&
3380 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
3381 // Okay, now we know that everything is set up, we just don't
3382 // know whether we have a setne or seteq and whether the true or
3383 // false val is the zero.
3384 bool ShouldNotVal = !TrueValC->isNullValue();
3385 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
3386 Value *V = ICA;
3387 if (ShouldNotVal)
3388 V = InsertNewInstBefore(BinaryOperator::create(
3389 Instruction::Xor, V, ICA->getOperand(1)), SI);
3390 return ReplaceInstUsesWith(SI, V);
3391 }
Chris Lattner533bc492004-03-30 19:37:13 +00003392 }
Chris Lattner623fba12004-04-10 22:21:27 +00003393
3394 // See if we are selecting two values based on a comparison of the two values.
3395 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
3396 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
3397 // Transform (X == Y) ? X : Y -> Y
3398 if (SCI->getOpcode() == Instruction::SetEQ)
3399 return ReplaceInstUsesWith(SI, FalseVal);
3400 // Transform (X != Y) ? X : Y -> X
3401 if (SCI->getOpcode() == Instruction::SetNE)
3402 return ReplaceInstUsesWith(SI, TrueVal);
3403 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3404
3405 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
3406 // Transform (X == Y) ? Y : X -> X
3407 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00003408 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003409 // Transform (X != Y) ? Y : X -> Y
3410 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00003411 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003412 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3413 }
3414 }
Chris Lattner1c631e82004-04-08 04:43:23 +00003415
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003416 // See if we can fold the select into one of our operands.
3417 if (SI.getType()->isInteger()) {
3418 // See the comment above GetSelectFoldableOperands for a description of the
3419 // transformation we are doing here.
3420 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
3421 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
3422 !isa<Constant>(FalseVal))
3423 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3424 unsigned OpToFold = 0;
3425 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3426 OpToFold = 1;
3427 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3428 OpToFold = 2;
3429 }
3430
3431 if (OpToFold) {
3432 Constant *C = GetSelectFoldableConstant(TVI);
3433 std::string Name = TVI->getName(); TVI->setName("");
3434 Instruction *NewSel =
3435 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3436 Name);
3437 InsertNewInstBefore(NewSel, SI);
3438 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3439 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3440 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3441 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3442 else {
3443 assert(0 && "Unknown instruction!!");
3444 }
3445 }
3446 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00003447
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003448 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
3449 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
3450 !isa<Constant>(TrueVal))
3451 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
3452 unsigned OpToFold = 0;
3453 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
3454 OpToFold = 1;
3455 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
3456 OpToFold = 2;
3457 }
3458
3459 if (OpToFold) {
3460 Constant *C = GetSelectFoldableConstant(FVI);
3461 std::string Name = FVI->getName(); FVI->setName("");
3462 Instruction *NewSel =
3463 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
3464 Name);
3465 InsertNewInstBefore(NewSel, SI);
3466 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
3467 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
3468 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
3469 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
3470 else {
3471 assert(0 && "Unknown instruction!!");
3472 }
3473 }
3474 }
3475 }
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003476 return 0;
3477}
3478
3479
Chris Lattner970c33a2003-06-19 17:00:31 +00003480// CallInst simplification
3481//
3482Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00003483 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3484 // visitCallSite.
Chris Lattner00648e12004-10-12 04:52:52 +00003485 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
3486 bool Changed = false;
3487
3488 // memmove/cpy/set of zero bytes is a noop.
3489 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
3490 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
3491
3492 // FIXME: Increase alignment here.
3493
3494 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
3495 if (CI->getRawValue() == 1) {
3496 // Replace the instruction with just byte operations. We would
3497 // transform other cases to loads/stores, but we don't know if
3498 // alignment is sufficient.
3499 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003500 }
3501
Chris Lattner00648e12004-10-12 04:52:52 +00003502 // If we have a memmove and the source operation is a constant global,
3503 // then the source and dest pointers can't alias, so we can change this
3504 // into a call to memcpy.
3505 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
3506 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
3507 if (GVSrc->isConstant()) {
3508 Module *M = CI.getParent()->getParent()->getParent();
3509 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
3510 CI.getCalledFunction()->getFunctionType());
3511 CI.setOperand(0, MemCpy);
3512 Changed = true;
3513 }
3514
3515 if (Changed) return &CI;
Chris Lattner95307542004-11-18 21:41:39 +00003516 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(&CI)) {
3517 // If this stoppoint is at the same source location as the previous
3518 // stoppoint in the chain, it is not needed.
3519 if (DbgStopPointInst *PrevSPI =
3520 dyn_cast<DbgStopPointInst>(SPI->getChain()))
3521 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
3522 SPI->getColNo() == PrevSPI->getColNo()) {
3523 SPI->replaceAllUsesWith(PrevSPI);
3524 return EraseInstFromFunction(CI);
3525 }
Chris Lattner00648e12004-10-12 04:52:52 +00003526 }
3527
Chris Lattneraec3d942003-10-07 22:32:43 +00003528 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00003529}
3530
3531// InvokeInst simplification
3532//
3533Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00003534 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00003535}
3536
Chris Lattneraec3d942003-10-07 22:32:43 +00003537// visitCallSite - Improvements for call and invoke instructions.
3538//
3539Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003540 bool Changed = false;
3541
3542 // If the callee is a constexpr cast of a function, attempt to move the cast
3543 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00003544 if (transformConstExprCastCall(CS)) return 0;
3545
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003546 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00003547
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003548 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
3549 // This instruction is not reachable, just remove it. We insert a store to
3550 // undef so that we know that this code is not reachable, despite the fact
3551 // that we can't modify the CFG here.
3552 new StoreInst(ConstantBool::True,
3553 UndefValue::get(PointerType::get(Type::BoolTy)),
3554 CS.getInstruction());
3555
3556 if (!CS.getInstruction()->use_empty())
3557 CS.getInstruction()->
3558 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
3559
3560 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
3561 // Don't break the CFG, insert a dummy cond branch.
3562 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
3563 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00003564 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003565 return EraseInstFromFunction(*CS.getInstruction());
3566 }
Chris Lattner81a7a232004-10-16 18:11:37 +00003567
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003568 const PointerType *PTy = cast<PointerType>(Callee->getType());
3569 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3570 if (FTy->isVarArg()) {
3571 // See if we can optimize any arguments passed through the varargs area of
3572 // the call.
3573 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
3574 E = CS.arg_end(); I != E; ++I)
3575 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
3576 // If this cast does not effect the value passed through the varargs
3577 // area, we can eliminate the use of the cast.
3578 Value *Op = CI->getOperand(0);
3579 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
3580 *I = Op;
3581 Changed = true;
3582 }
3583 }
3584 }
Chris Lattneraec3d942003-10-07 22:32:43 +00003585
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003586 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00003587}
3588
Chris Lattner970c33a2003-06-19 17:00:31 +00003589// transformConstExprCastCall - If the callee is a constexpr cast of a function,
3590// attempt to move the cast to the arguments of the call/invoke.
3591//
3592bool InstCombiner::transformConstExprCastCall(CallSite CS) {
3593 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
3594 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00003595 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00003596 return false;
Reid Spencer87436872004-07-18 00:38:32 +00003597 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00003598 Instruction *Caller = CS.getInstruction();
3599
3600 // Okay, this is a cast from a function to a different type. Unless doing so
3601 // would cause a type conversion of one of our arguments, change this call to
3602 // be a direct call with arguments casted to the appropriate types.
3603 //
3604 const FunctionType *FT = Callee->getFunctionType();
3605 const Type *OldRetTy = Caller->getType();
3606
Chris Lattner1f7942f2004-01-14 06:06:08 +00003607 // Check to see if we are changing the return type...
3608 if (OldRetTy != FT->getReturnType()) {
3609 if (Callee->isExternal() &&
3610 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
3611 !Caller->use_empty())
3612 return false; // Cannot transform this return value...
3613
3614 // If the callsite is an invoke instruction, and the return value is used by
3615 // a PHI node in a successor, we cannot change the return type of the call
3616 // because there is no place to put the cast instruction (without breaking
3617 // the critical edge). Bail out in this case.
3618 if (!Caller->use_empty())
3619 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
3620 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
3621 UI != E; ++UI)
3622 if (PHINode *PN = dyn_cast<PHINode>(*UI))
3623 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003624 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00003625 return false;
3626 }
Chris Lattner970c33a2003-06-19 17:00:31 +00003627
3628 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
3629 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3630
3631 CallSite::arg_iterator AI = CS.arg_begin();
3632 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3633 const Type *ParamTy = FT->getParamType(i);
3634 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
3635 if (Callee->isExternal() && !isConvertible) return false;
3636 }
3637
3638 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
3639 Callee->isExternal())
3640 return false; // Do not delete arguments unless we have a function body...
3641
3642 // Okay, we decided that this is a safe thing to do: go ahead and start
3643 // inserting cast instructions as necessary...
3644 std::vector<Value*> Args;
3645 Args.reserve(NumActualArgs);
3646
3647 AI = CS.arg_begin();
3648 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3649 const Type *ParamTy = FT->getParamType(i);
3650 if ((*AI)->getType() == ParamTy) {
3651 Args.push_back(*AI);
3652 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00003653 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
3654 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00003655 }
3656 }
3657
3658 // If the function takes more arguments than the call was taking, add them
3659 // now...
3660 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
3661 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3662
3663 // If we are removing arguments to the function, emit an obnoxious warning...
3664 if (FT->getNumParams() < NumActualArgs)
3665 if (!FT->isVarArg()) {
3666 std::cerr << "WARNING: While resolving call to function '"
3667 << Callee->getName() << "' arguments were dropped!\n";
3668 } else {
3669 // Add all of the arguments in their promoted form to the arg list...
3670 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3671 const Type *PTy = getPromotedType((*AI)->getType());
3672 if (PTy != (*AI)->getType()) {
3673 // Must promote to pass through va_arg area!
3674 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
3675 InsertNewInstBefore(Cast, *Caller);
3676 Args.push_back(Cast);
3677 } else {
3678 Args.push_back(*AI);
3679 }
3680 }
3681 }
3682
3683 if (FT->getReturnType() == Type::VoidTy)
3684 Caller->setName(""); // Void type should not have a name...
3685
3686 Instruction *NC;
3687 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003688 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00003689 Args, Caller->getName(), Caller);
3690 } else {
3691 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
3692 }
3693
3694 // Insert a cast of the return type as necessary...
3695 Value *NV = NC;
3696 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
3697 if (NV->getType() != Type::VoidTy) {
3698 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00003699
3700 // If this is an invoke instruction, we should insert it after the first
3701 // non-phi, instruction in the normal successor block.
3702 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3703 BasicBlock::iterator I = II->getNormalDest()->begin();
3704 while (isa<PHINode>(I)) ++I;
3705 InsertNewInstBefore(NC, *I);
3706 } else {
3707 // Otherwise, it's a call, just insert cast right after the call instr
3708 InsertNewInstBefore(NC, *Caller);
3709 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003710 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00003711 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00003712 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00003713 }
3714 }
3715
3716 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
3717 Caller->replaceAllUsesWith(NV);
3718 Caller->getParent()->getInstList().erase(Caller);
3719 removeFromWorkList(Caller);
3720 return true;
3721}
3722
3723
Chris Lattner7515cab2004-11-14 19:13:23 +00003724// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
3725// operator and they all are only used by the PHI, PHI together their
3726// inputs, and do the operation once, to the result of the PHI.
3727Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
3728 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
3729
3730 // Scan the instruction, looking for input operations that can be folded away.
3731 // If all input operands to the phi are the same instruction (e.g. a cast from
3732 // the same type or "+42") we can pull the operation through the PHI, reducing
3733 // code size and simplifying code.
3734 Constant *ConstantOp = 0;
3735 const Type *CastSrcTy = 0;
3736 if (isa<CastInst>(FirstInst)) {
3737 CastSrcTy = FirstInst->getOperand(0)->getType();
3738 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
3739 // Can fold binop or shift if the RHS is a constant.
3740 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
3741 if (ConstantOp == 0) return 0;
3742 } else {
3743 return 0; // Cannot fold this operation.
3744 }
3745
3746 // Check to see if all arguments are the same operation.
3747 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
3748 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
3749 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
3750 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
3751 return 0;
3752 if (CastSrcTy) {
3753 if (I->getOperand(0)->getType() != CastSrcTy)
3754 return 0; // Cast operation must match.
3755 } else if (I->getOperand(1) != ConstantOp) {
3756 return 0;
3757 }
3758 }
3759
3760 // Okay, they are all the same operation. Create a new PHI node of the
3761 // correct type, and PHI together all of the LHS's of the instructions.
3762 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
3763 PN.getName()+".in");
3764 NewPN->op_reserve(PN.getNumOperands());
Chris Lattner46dd5a62004-11-14 19:29:34 +00003765
3766 Value *InVal = FirstInst->getOperand(0);
3767 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00003768
3769 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00003770 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
3771 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
3772 if (NewInVal != InVal)
3773 InVal = 0;
3774 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
3775 }
3776
3777 Value *PhiVal;
3778 if (InVal) {
3779 // The new PHI unions all of the same values together. This is really
3780 // common, so we handle it intelligently here for compile-time speed.
3781 PhiVal = InVal;
3782 delete NewPN;
3783 } else {
3784 InsertNewInstBefore(NewPN, PN);
3785 PhiVal = NewPN;
3786 }
Chris Lattner7515cab2004-11-14 19:13:23 +00003787
3788 // Insert and return the new operation.
3789 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00003790 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00003791 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00003792 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00003793 else
3794 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00003795 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00003796}
Chris Lattner48a44f72002-05-02 17:06:02 +00003797
Chris Lattnerbbbdd852002-05-06 18:06:38 +00003798// PHINode simplification
3799//
Chris Lattner113f4f42002-06-25 16:13:24 +00003800Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnere29d6342004-10-17 21:22:38 +00003801 if (Value *V = hasConstantValue(&PN)) {
3802 // If V is an instruction, we have to be certain that it dominates PN.
3803 // However, because we don't have dom info, we can't do a perfect job.
3804 if (Instruction *I = dyn_cast<Instruction>(V)) {
3805 // We know that the instruction dominates the PHI if there are no undef
3806 // values coming in.
Chris Lattner3b92f172004-10-18 01:48:31 +00003807 if (I->getParent() != &I->getParent()->getParent()->front() ||
3808 isa<InvokeInst>(I))
Chris Lattner107c15c2004-10-17 21:31:34 +00003809 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3810 if (isa<UndefValue>(PN.getIncomingValue(i))) {
3811 V = 0;
3812 break;
3813 }
Chris Lattnere29d6342004-10-17 21:22:38 +00003814 }
3815
3816 if (V)
3817 return ReplaceInstUsesWith(PN, V);
3818 }
Chris Lattner4db2d222004-02-16 05:07:08 +00003819
3820 // If the only user of this instruction is a cast instruction, and all of the
3821 // incoming values are constants, change this PHI to merge together the casted
3822 // constants.
3823 if (PN.hasOneUse())
3824 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
3825 if (CI->getType() != PN.getType()) { // noop casts will be folded
3826 bool AllConstant = true;
3827 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3828 if (!isa<Constant>(PN.getIncomingValue(i))) {
3829 AllConstant = false;
3830 break;
3831 }
3832 if (AllConstant) {
3833 // Make a new PHI with all casted values.
3834 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
3835 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3836 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
3837 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
3838 PN.getIncomingBlock(i));
3839 }
3840
3841 // Update the cast instruction.
3842 CI->setOperand(0, New);
3843 WorkList.push_back(CI); // revisit the cast instruction to fold.
3844 WorkList.push_back(New); // Make sure to revisit the new Phi
3845 return &PN; // PN is now dead!
3846 }
3847 }
Chris Lattner7515cab2004-11-14 19:13:23 +00003848
3849 // If all PHI operands are the same operation, pull them through the PHI,
3850 // reducing code size.
3851 if (isa<Instruction>(PN.getIncomingValue(0)) &&
3852 PN.getIncomingValue(0)->hasOneUse())
3853 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
3854 return Result;
3855
3856
Chris Lattner91daeb52003-12-19 05:58:40 +00003857 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00003858}
3859
Chris Lattner69193f92004-04-05 01:30:19 +00003860static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
3861 Instruction *InsertPoint,
3862 InstCombiner *IC) {
3863 unsigned PS = IC->getTargetData().getPointerSize();
3864 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00003865 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
3866 // We must insert a cast to ensure we sign-extend.
3867 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
3868 V->getName()), *InsertPoint);
3869 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
3870 *InsertPoint);
3871}
3872
Chris Lattner48a44f72002-05-02 17:06:02 +00003873
Chris Lattner113f4f42002-06-25 16:13:24 +00003874Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00003875 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00003876 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00003877 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003878 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00003879 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003880
Chris Lattner81a7a232004-10-16 18:11:37 +00003881 if (isa<UndefValue>(GEP.getOperand(0)))
3882 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
3883
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003884 bool HasZeroPointerIndex = false;
3885 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
3886 HasZeroPointerIndex = C->isNullValue();
3887
3888 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00003889 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00003890
Chris Lattner69193f92004-04-05 01:30:19 +00003891 // Eliminate unneeded casts for indices.
3892 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00003893 gep_type_iterator GTI = gep_type_begin(GEP);
3894 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
3895 if (isa<SequentialType>(*GTI)) {
3896 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
3897 Value *Src = CI->getOperand(0);
3898 const Type *SrcTy = Src->getType();
3899 const Type *DestTy = CI->getType();
3900 if (Src->getType()->isInteger()) {
3901 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
3902 // We can always eliminate a cast from ulong or long to the other.
3903 // We can always eliminate a cast from uint to int or the other on
3904 // 32-bit pointer platforms.
3905 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
3906 MadeChange = true;
3907 GEP.setOperand(i, Src);
3908 }
3909 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
3910 SrcTy->getPrimitiveSize() == 4) {
3911 // We can always eliminate a cast from int to [u]long. We can
3912 // eliminate a cast from uint to [u]long iff the target is a 32-bit
3913 // pointer target.
3914 if (SrcTy->isSigned() ||
3915 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
3916 MadeChange = true;
3917 GEP.setOperand(i, Src);
3918 }
Chris Lattner69193f92004-04-05 01:30:19 +00003919 }
3920 }
3921 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00003922 // If we are using a wider index than needed for this platform, shrink it
3923 // to what we need. If the incoming value needs a cast instruction,
3924 // insert it. This explicit cast can make subsequent optimizations more
3925 // obvious.
3926 Value *Op = GEP.getOperand(i);
3927 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00003928 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00003929 GEP.setOperand(i, ConstantExpr::getCast(C,
3930 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00003931 MadeChange = true;
3932 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00003933 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
3934 Op->getName()), GEP);
3935 GEP.setOperand(i, Op);
3936 MadeChange = true;
3937 }
Chris Lattner44d0b952004-07-20 01:48:15 +00003938
3939 // If this is a constant idx, make sure to canonicalize it to be a signed
3940 // operand, otherwise CSE and other optimizations are pessimized.
3941 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
3942 GEP.setOperand(i, ConstantExpr::getCast(CUI,
3943 CUI->getType()->getSignedVersion()));
3944 MadeChange = true;
3945 }
Chris Lattner69193f92004-04-05 01:30:19 +00003946 }
3947 if (MadeChange) return &GEP;
3948
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003949 // Combine Indices - If the source pointer to this getelementptr instruction
3950 // is a getelementptr instruction, combine the indices of the two
3951 // getelementptr instructions into a single instruction.
3952 //
Chris Lattner57c67b02004-03-25 22:59:29 +00003953 std::vector<Value*> SrcGEPOperands;
Chris Lattner5f667a62004-05-07 22:09:22 +00003954 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00003955 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner5f667a62004-05-07 22:09:22 +00003956 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00003957 if (CE->getOpcode() == Instruction::GetElementPtr)
3958 SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
3959 }
3960
3961 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00003962 // Note that if our source is a gep chain itself that we wait for that
3963 // chain to be resolved before we perform this transformation. This
3964 // avoids us creating a TON of code in some cases.
3965 //
3966 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
3967 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
3968 return 0; // Wait until our source is folded to completion.
3969
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003970 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00003971
3972 // Find out whether the last index in the source GEP is a sequential idx.
3973 bool EndsWithSequential = false;
3974 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
3975 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00003976 EndsWithSequential = !isa<StructType>(*I);
Chris Lattnerca081252001-12-14 16:52:21 +00003977
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003978 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00003979 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00003980 // Replace: gep (gep %P, long B), long A, ...
3981 // With: T = long A+B; gep %P, T, ...
3982 //
Chris Lattner5f667a62004-05-07 22:09:22 +00003983 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00003984 if (SO1 == Constant::getNullValue(SO1->getType())) {
3985 Sum = GO1;
3986 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
3987 Sum = SO1;
3988 } else {
3989 // If they aren't the same type, convert both to an integer of the
3990 // target's pointer size.
3991 if (SO1->getType() != GO1->getType()) {
3992 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
3993 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
3994 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
3995 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
3996 } else {
3997 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00003998 if (SO1->getType()->getPrimitiveSize() == PS) {
3999 // Convert GO1 to SO1's type.
4000 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
4001
4002 } else if (GO1->getType()->getPrimitiveSize() == PS) {
4003 // Convert SO1 to GO1's type.
4004 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
4005 } else {
4006 const Type *PT = TD->getIntPtrType();
4007 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
4008 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
4009 }
4010 }
4011 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004012 if (isa<Constant>(SO1) && isa<Constant>(GO1))
4013 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
4014 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004015 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
4016 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00004017 }
Chris Lattner69193f92004-04-05 01:30:19 +00004018 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004019
4020 // Recycle the GEP we already have if possible.
4021 if (SrcGEPOperands.size() == 2) {
4022 GEP.setOperand(0, SrcGEPOperands[0]);
4023 GEP.setOperand(1, Sum);
4024 return &GEP;
4025 } else {
4026 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4027 SrcGEPOperands.end()-1);
4028 Indices.push_back(Sum);
4029 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
4030 }
Chris Lattner69193f92004-04-05 01:30:19 +00004031 } else if (isa<Constant>(*GEP.idx_begin()) &&
4032 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner57c67b02004-03-25 22:59:29 +00004033 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004034 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00004035 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4036 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004037 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
4038 }
4039
4040 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00004041 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004042
Chris Lattner5f667a62004-05-07 22:09:22 +00004043 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004044 // GEP of global variable. If all of the indices for this GEP are
4045 // constants, we can promote this to a constexpr instead of an instruction.
4046
4047 // Scan for nonconstants...
4048 std::vector<Constant*> Indices;
4049 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
4050 for (; I != E && isa<Constant>(*I); ++I)
4051 Indices.push_back(cast<Constant>(*I));
4052
4053 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00004054 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004055
4056 // Replace all uses of the GEP with the new constexpr...
4057 return ReplaceInstUsesWith(GEP, CE);
4058 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004059 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004060 if (CE->getOpcode() == Instruction::Cast) {
4061 if (HasZeroPointerIndex) {
4062 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
4063 // into : GEP [10 x ubyte]* X, long 0, ...
4064 //
4065 // This occurs when the program declares an array extern like "int X[];"
4066 //
4067 Constant *X = CE->getOperand(0);
4068 const PointerType *CPTy = cast<PointerType>(CE->getType());
4069 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
4070 if (const ArrayType *XATy =
4071 dyn_cast<ArrayType>(XTy->getElementType()))
4072 if (const ArrayType *CATy =
4073 dyn_cast<ArrayType>(CPTy->getElementType()))
4074 if (CATy->getElementType() == XATy->getElementType()) {
4075 // At this point, we know that the cast source type is a pointer
4076 // to an array of the same type as the destination pointer
4077 // array. Because the array type is never stepped over (there
4078 // is a leading zero) we can fold the cast into this GEP.
4079 GEP.setOperand(0, X);
4080 return &GEP;
4081 }
Chris Lattner14f3cdc2004-11-27 17:55:46 +00004082 } else if (GEP.getNumOperands() == 2) {
4083 // Transform things like:
4084 // %t = getelementptr ubyte* cast ([2 x sbyte]* %str to ubyte*), uint %V
4085 // into: %t1 = getelementptr [2 x sbyte*]* %str, int 0, uint %V; cast
4086 Constant *X = CE->getOperand(0);
4087 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
4088 const Type *ResElTy =cast<PointerType>(CE->getType())->getElementType();
4089 if (isa<ArrayType>(SrcElTy) &&
4090 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
4091 TD->getTypeSize(ResElTy)) {
4092 Value *V = InsertNewInstBefore(
4093 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
4094 GEP.getOperand(1), GEP.getName()), GEP);
4095 return new CastInst(V, GEP.getType());
4096 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004097 }
4098 }
Chris Lattnerca081252001-12-14 16:52:21 +00004099 }
4100
Chris Lattnerca081252001-12-14 16:52:21 +00004101 return 0;
4102}
4103
Chris Lattner1085bdf2002-11-04 16:18:53 +00004104Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
4105 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
4106 if (AI.isArrayAllocation()) // Check C != 1
4107 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
4108 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004109 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00004110
4111 // Create and insert the replacement instruction...
4112 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00004113 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004114 else {
4115 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00004116 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004117 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00004118
4119 InsertNewInstBefore(New, AI);
Chris Lattner1085bdf2002-11-04 16:18:53 +00004120
4121 // Scan to the end of the allocation instructions, to skip over a block of
4122 // allocas if possible...
4123 //
4124 BasicBlock::iterator It = New;
4125 while (isa<AllocationInst>(*It)) ++It;
4126
4127 // Now that I is pointing to the first non-allocation-inst in the block,
4128 // insert our getelementptr instruction...
4129 //
Chris Lattner69193f92004-04-05 01:30:19 +00004130 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner1085bdf2002-11-04 16:18:53 +00004131 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
4132
4133 // Now make everything use the getelementptr instead of the original
4134 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00004135 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00004136 } else if (isa<UndefValue>(AI.getArraySize())) {
4137 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00004138 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00004139
4140 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
4141 // Note that we only do this for alloca's, because malloc should allocate and
4142 // return a unique pointer, even for a zero byte allocation.
Chris Lattner49df6ce2004-07-02 22:55:47 +00004143 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
4144 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00004145 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
4146
Chris Lattner1085bdf2002-11-04 16:18:53 +00004147 return 0;
4148}
4149
Chris Lattner8427bff2003-12-07 01:24:23 +00004150Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
4151 Value *Op = FI.getOperand(0);
4152
4153 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
4154 if (CastInst *CI = dyn_cast<CastInst>(Op))
4155 if (isa<PointerType>(CI->getOperand(0)->getType())) {
4156 FI.setOperand(0, CI->getOperand(0));
4157 return &FI;
4158 }
4159
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004160 // free undef -> unreachable.
4161 if (isa<UndefValue>(Op)) {
4162 // Insert a new store to null because we cannot modify the CFG here.
4163 new StoreInst(ConstantBool::True,
4164 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
4165 return EraseInstFromFunction(FI);
4166 }
4167
Chris Lattnerf3a36602004-02-28 04:57:37 +00004168 // If we have 'free null' delete the instruction. This can happen in stl code
4169 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004170 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00004171 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00004172
Chris Lattner8427bff2003-12-07 01:24:23 +00004173 return 0;
4174}
4175
4176
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004177/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
4178/// constantexpr, return the constant value being addressed by the constant
4179/// expression, or null if something is funny.
4180///
4181static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00004182 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004183 return 0; // Do not allow stepping over the value!
4184
4185 // Loop over all of the operands, tracking down which value we are
4186 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00004187 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
4188 for (++I; I != E; ++I)
4189 if (const StructType *STy = dyn_cast<StructType>(*I)) {
4190 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
4191 assert(CU->getValue() < STy->getNumElements() &&
4192 "Struct index out of range!");
4193 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Alkis Evlogimenos83243722004-08-04 08:44:43 +00004194 C = CS->getOperand(CU->getValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00004195 } else if (isa<ConstantAggregateZero>(C)) {
4196 C = Constant::getNullValue(STy->getElementType(CU->getValue()));
Chris Lattner81a7a232004-10-16 18:11:37 +00004197 } else if (isa<UndefValue>(C)) {
4198 C = UndefValue::get(STy->getElementType(CU->getValue()));
Chris Lattnered79d8a2004-05-27 17:30:27 +00004199 } else {
4200 return 0;
4201 }
4202 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
4203 const ArrayType *ATy = cast<ArrayType>(*I);
4204 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
4205 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Alkis Evlogimenos83243722004-08-04 08:44:43 +00004206 C = CA->getOperand(CI->getRawValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00004207 else if (isa<ConstantAggregateZero>(C))
4208 C = Constant::getNullValue(ATy->getElementType());
Chris Lattner81a7a232004-10-16 18:11:37 +00004209 else if (isa<UndefValue>(C))
4210 C = UndefValue::get(ATy->getElementType());
Chris Lattnered79d8a2004-05-27 17:30:27 +00004211 else
4212 return 0;
4213 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004214 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00004215 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004216 return C;
4217}
4218
Chris Lattner35e24772004-07-13 01:49:43 +00004219static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
4220 User *CI = cast<User>(LI.getOperand(0));
4221
4222 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
4223 if (const PointerType *SrcTy =
4224 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
4225 const Type *SrcPTy = SrcTy->getElementType();
4226 if (SrcPTy->isSized() && DestPTy->isSized() &&
4227 IC.getTargetData().getTypeSize(SrcPTy) ==
4228 IC.getTargetData().getTypeSize(DestPTy) &&
4229 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
4230 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
4231 // Okay, we are casting from one integer or pointer type to another of
4232 // the same size. Instead of casting the pointer before the load, cast
4233 // the result of the loaded value.
4234 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004235 CI->getName(),
4236 LI.isVolatile()),LI);
Chris Lattner35e24772004-07-13 01:49:43 +00004237 // Now cast the result of the load.
4238 return new CastInst(NewLoad, LI.getType());
4239 }
4240 }
4241 return 0;
4242}
4243
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004244/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00004245/// from this value cannot trap. If it is not obviously safe to load from the
4246/// specified pointer, we do a quick local scan of the basic block containing
4247/// ScanFrom, to determine if the address is already accessed.
4248static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
4249 // If it is an alloca or global variable, it is always safe to load from.
4250 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
4251
4252 // Otherwise, be a little bit agressive by scanning the local block where we
4253 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004254 // from/to. If so, the previous load or store would have already trapped,
4255 // so there is no harm doing an extra load (also, CSE will later eliminate
4256 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00004257 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
4258
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004259 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00004260 --BBI;
4261
4262 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
4263 if (LI->getOperand(0) == V) return true;
4264 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
4265 if (SI->getOperand(1) == V) return true;
4266
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004267 }
Chris Lattnere6f13092004-09-19 19:18:10 +00004268 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004269}
4270
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004271Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
4272 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00004273
Chris Lattner81a7a232004-10-16 18:11:37 +00004274 if (Constant *C = dyn_cast<Constant>(Op)) {
4275 if ((C->isNullValue() || isa<UndefValue>(C)) &&
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004276 !LI.isVolatile()) { // load null/undef -> undef
4277 // Insert a new store to null instruction before the load to indicate that
4278 // this code is not reachable. We do this instead of inserting an
4279 // unreachable instruction directly because we cannot modify the CFG.
4280 new StoreInst(UndefValue::get(LI.getType()), C, &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00004281 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004282 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004283
Chris Lattner81a7a232004-10-16 18:11:37 +00004284 // Instcombine load (constant global) into the value loaded.
4285 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
4286 if (GV->isConstant() && !GV->isExternal())
4287 return ReplaceInstUsesWith(LI, GV->getInitializer());
4288
4289 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
4290 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
4291 if (CE->getOpcode() == Instruction::GetElementPtr) {
4292 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
4293 if (GV->isConstant() && !GV->isExternal())
4294 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
4295 return ReplaceInstUsesWith(LI, V);
4296 } else if (CE->getOpcode() == Instruction::Cast) {
4297 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4298 return Res;
4299 }
4300 }
Chris Lattnere228ee52004-04-08 20:39:49 +00004301
4302 // load (cast X) --> cast (load X) iff safe
Chris Lattner35e24772004-07-13 01:49:43 +00004303 if (CastInst *CI = dyn_cast<CastInst>(Op))
4304 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4305 return Res;
Chris Lattnere228ee52004-04-08 20:39:49 +00004306
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004307 if (!LI.isVolatile() && Op->hasOneUse()) {
4308 // Change select and PHI nodes to select values instead of addresses: this
4309 // helps alias analysis out a lot, allows many others simplifications, and
4310 // exposes redundancy in the code.
4311 //
4312 // Note that we cannot do the transformation unless we know that the
4313 // introduced loads cannot trap! Something like this is valid as long as
4314 // the condition is always false: load (select bool %C, int* null, int* %G),
4315 // but it would not be valid if we transformed it to load from null
4316 // unconditionally.
4317 //
4318 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
4319 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00004320 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
4321 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004322 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00004323 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004324 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00004325 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004326 return new SelectInst(SI->getCondition(), V1, V2);
4327 }
4328
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00004329 // load (select (cond, null, P)) -> load P
4330 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
4331 if (C->isNullValue()) {
4332 LI.setOperand(0, SI->getOperand(2));
4333 return &LI;
4334 }
4335
4336 // load (select (cond, P, null)) -> load P
4337 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
4338 if (C->isNullValue()) {
4339 LI.setOperand(0, SI->getOperand(1));
4340 return &LI;
4341 }
4342
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004343 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
4344 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00004345 bool Safe = PN->getParent() == LI.getParent();
4346
4347 // Scan all of the instructions between the PHI and the load to make
4348 // sure there are no instructions that might possibly alter the value
4349 // loaded from the PHI.
4350 if (Safe) {
4351 BasicBlock::iterator I = &LI;
4352 for (--I; !isa<PHINode>(I); --I)
4353 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
4354 Safe = false;
4355 break;
4356 }
4357 }
4358
4359 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00004360 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00004361 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004362 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00004363
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004364 if (Safe) {
4365 // Create the PHI.
4366 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
4367 InsertNewInstBefore(NewPN, *PN);
4368 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
4369
4370 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4371 BasicBlock *BB = PN->getIncomingBlock(i);
4372 Value *&TheLoad = LoadMap[BB];
4373 if (TheLoad == 0) {
4374 Value *InVal = PN->getIncomingValue(i);
4375 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
4376 InVal->getName()+".val"),
4377 *BB->getTerminator());
4378 }
4379 NewPN->addIncoming(TheLoad, BB);
4380 }
4381 return ReplaceInstUsesWith(LI, NewPN);
4382 }
4383 }
4384 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004385 return 0;
4386}
4387
Chris Lattner9eef8a72003-06-04 04:46:00 +00004388Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
4389 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattnerd4252a72004-07-30 07:50:03 +00004390 Value *X;
4391 BasicBlock *TrueDest;
4392 BasicBlock *FalseDest;
4393 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
4394 !isa<Constant>(X)) {
4395 // Swap Destinations and condition...
4396 BI.setCondition(X);
4397 BI.setSuccessor(0, FalseDest);
4398 BI.setSuccessor(1, TrueDest);
4399 return &BI;
4400 }
4401
4402 // Cannonicalize setne -> seteq
4403 Instruction::BinaryOps Op; Value *Y;
4404 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
4405 TrueDest, FalseDest)))
4406 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
4407 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
4408 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
4409 std::string Name = I->getName(); I->setName("");
4410 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
4411 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00004412 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00004413 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00004414 BI.setSuccessor(0, FalseDest);
4415 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004416 removeFromWorkList(I);
4417 I->getParent()->getInstList().erase(I);
4418 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00004419 return &BI;
4420 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00004421
Chris Lattner9eef8a72003-06-04 04:46:00 +00004422 return 0;
4423}
Chris Lattner1085bdf2002-11-04 16:18:53 +00004424
Chris Lattner4c9c20a2004-07-03 00:26:11 +00004425Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
4426 Value *Cond = SI.getCondition();
4427 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
4428 if (I->getOpcode() == Instruction::Add)
4429 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
4430 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
4431 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00004432 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00004433 AddRHS));
4434 SI.setOperand(0, I->getOperand(0));
4435 WorkList.push_back(I);
4436 return &SI;
4437 }
4438 }
4439 return 0;
4440}
4441
Chris Lattnerca081252001-12-14 16:52:21 +00004442
Chris Lattner99f48c62002-09-02 04:59:56 +00004443void InstCombiner::removeFromWorkList(Instruction *I) {
4444 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
4445 WorkList.end());
4446}
4447
Chris Lattner39c98bb2004-12-08 23:43:58 +00004448
4449/// TryToSinkInstruction - Try to move the specified instruction from its
4450/// current block into the beginning of DestBlock, which can only happen if it's
4451/// safe to move the instruction past all of the instructions between it and the
4452/// end of its block.
4453static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
4454 assert(I->hasOneUse() && "Invariants didn't hold!");
4455
4456 // Cannot move control-flow-involving instructions.
4457 if (isa<PHINode>(I) || isa<InvokeInst>(I) || isa<CallInst>(I)) return false;
4458
4459 // Do not sink alloca instructions out of the entry block.
4460 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
4461 return false;
4462
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00004463 // We can only sink load instructions if there is nothing between the load and
4464 // the end of block that could change the value.
4465 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
4466 if (LI->isVolatile()) return false; // Don't sink volatile loads.
4467
4468 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
4469 Scan != E; ++Scan)
4470 if (Scan->mayWriteToMemory())
4471 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00004472 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00004473
4474 BasicBlock::iterator InsertPos = DestBlock->begin();
4475 while (isa<PHINode>(InsertPos)) ++InsertPos;
4476
4477 BasicBlock *SrcBlock = I->getParent();
4478 DestBlock->getInstList().splice(InsertPos, SrcBlock->getInstList(), I);
4479 ++NumSunkInst;
4480 return true;
4481}
4482
Chris Lattner113f4f42002-06-25 16:13:24 +00004483bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00004484 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004485 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00004486
Chris Lattnerb643a9e2004-05-01 23:19:52 +00004487 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
4488 WorkList.push_back(&*i);
Chris Lattner2d3a7a62004-04-27 15:13:33 +00004489
Chris Lattnerca081252001-12-14 16:52:21 +00004490
4491 while (!WorkList.empty()) {
4492 Instruction *I = WorkList.back(); // Get an instruction from the worklist
4493 WorkList.pop_back();
4494
Misha Brukman632df282002-10-29 23:06:16 +00004495 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00004496 // Check to see if we can DIE the instruction...
4497 if (isInstructionTriviallyDead(I)) {
4498 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004499 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00004500 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00004501 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004502
4503 I->getParent()->getInstList().erase(I);
4504 removeFromWorkList(I);
4505 continue;
4506 }
Chris Lattner99f48c62002-09-02 04:59:56 +00004507
Misha Brukman632df282002-10-29 23:06:16 +00004508 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00004509 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00004510 Value* Ptr = I->getOperand(0);
Chris Lattner6580e092004-10-16 19:44:59 +00004511 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00004512 cast<Constant>(Ptr)->isNullValue() &&
4513 !isa<ConstantPointerNull>(C) &&
4514 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner6580e092004-10-16 19:44:59 +00004515 // If this is a constant expr gep that is effectively computing an
4516 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
4517 bool isFoldableGEP = true;
4518 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
4519 if (!isa<ConstantInt>(I->getOperand(i)))
4520 isFoldableGEP = false;
4521 if (isFoldableGEP) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00004522 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner6580e092004-10-16 19:44:59 +00004523 std::vector<Value*>(I->op_begin()+1, I->op_end()));
4524 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00004525 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00004526 C = ConstantExpr::getCast(C, I->getType());
4527 }
4528 }
4529
Chris Lattner99f48c62002-09-02 04:59:56 +00004530 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00004531 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00004532 ReplaceInstUsesWith(*I, C);
4533
Chris Lattner99f48c62002-09-02 04:59:56 +00004534 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004535 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00004536 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004537 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00004538 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004539
Chris Lattner39c98bb2004-12-08 23:43:58 +00004540 // See if we can trivially sink this instruction to a successor basic block.
4541 if (I->hasOneUse()) {
4542 BasicBlock *BB = I->getParent();
4543 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
4544 if (UserParent != BB) {
4545 bool UserIsSuccessor = false;
4546 // See if the user is one of our successors.
4547 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
4548 if (*SI == UserParent) {
4549 UserIsSuccessor = true;
4550 break;
4551 }
4552
4553 // If the user is one of our immediate successors, and if that successor
4554 // only has us as a predecessors (we'd have to split the critical edge
4555 // otherwise), we can keep going.
4556 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
4557 next(pred_begin(UserParent)) == pred_end(UserParent))
4558 // Okay, the CFG is simple enough, try to sink this instruction.
4559 Changed |= TryToSinkInstruction(I, UserParent);
4560 }
4561 }
4562
Chris Lattnerca081252001-12-14 16:52:21 +00004563 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004564 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00004565 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00004566 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00004567 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00004568 DEBUG(std::cerr << "IC: Old = " << *I
4569 << " New = " << *Result);
4570
Chris Lattner396dbfe2004-06-09 05:08:07 +00004571 // Everything uses the new instruction now.
4572 I->replaceAllUsesWith(Result);
4573
4574 // Push the new instruction and any users onto the worklist.
4575 WorkList.push_back(Result);
4576 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004577
4578 // Move the name to the new instruction first...
4579 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00004580 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004581
4582 // Insert the new instruction into the basic block...
4583 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00004584 BasicBlock::iterator InsertPos = I;
4585
4586 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
4587 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
4588 ++InsertPos;
4589
4590 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004591
Chris Lattner63d75af2004-05-01 23:27:23 +00004592 // Make sure that we reprocess all operands now that we reduced their
4593 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00004594 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4595 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4596 WorkList.push_back(OpI);
4597
Chris Lattner396dbfe2004-06-09 05:08:07 +00004598 // Instructions can end up on the worklist more than once. Make sure
4599 // we do not process an instruction that has been deleted.
4600 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004601
4602 // Erase the old instruction.
4603 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00004604 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00004605 DEBUG(std::cerr << "IC: MOD = " << *I);
4606
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004607 // If the instruction was modified, it's possible that it is now dead.
4608 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00004609 if (isInstructionTriviallyDead(I)) {
4610 // Make sure we process all operands now that we are reducing their
4611 // use counts.
4612 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4613 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4614 WorkList.push_back(OpI);
4615
4616 // Instructions may end up in the worklist more than once. Erase all
4617 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00004618 removeFromWorkList(I);
Chris Lattner63d75af2004-05-01 23:27:23 +00004619 I->getParent()->getInstList().erase(I);
Chris Lattner396dbfe2004-06-09 05:08:07 +00004620 } else {
4621 WorkList.push_back(Result);
4622 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004623 }
Chris Lattner053c0932002-05-14 15:24:07 +00004624 }
Chris Lattner260ab202002-04-18 17:39:14 +00004625 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00004626 }
4627 }
4628
Chris Lattner260ab202002-04-18 17:39:14 +00004629 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00004630}
4631
Brian Gaeke38b79e82004-07-27 17:43:21 +00004632FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00004633 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00004634}
Brian Gaeke960707c2003-11-11 22:41:34 +00004635