blob: f78a14d4273965af80882fa92500006425a88f85 [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 Lattner183b3362004-04-09 19:05:30 +0000489static Value *FoldOperationIntoSelectOperand(Instruction &BI, Value *SO,
490 InstCombiner *IC) {
491 // Figure out if the constant is the left or the right argument.
492 bool ConstIsRHS = isa<Constant>(BI.getOperand(1));
493 Constant *ConstOperand = cast<Constant>(BI.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000494
Chris Lattner183b3362004-04-09 19:05:30 +0000495 if (Constant *SOC = dyn_cast<Constant>(SO)) {
496 if (ConstIsRHS)
497 return ConstantExpr::get(BI.getOpcode(), SOC, ConstOperand);
498 return ConstantExpr::get(BI.getOpcode(), ConstOperand, SOC);
499 }
500
501 Value *Op0 = SO, *Op1 = ConstOperand;
502 if (!ConstIsRHS)
503 std::swap(Op0, Op1);
504 Instruction *New;
505 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&BI))
506 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1);
507 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&BI))
508 New = new ShiftInst(SI->getOpcode(), Op0, Op1);
Chris Lattnerf9d96652004-04-10 19:15:56 +0000509 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000510 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000511 abort();
512 }
Chris Lattner183b3362004-04-09 19:05:30 +0000513 return IC->InsertNewInstBefore(New, BI);
514}
515
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000516
517/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
518/// node as operand #0, see if we can fold the instruction into the PHI (which
519/// is only possible if all operands to the PHI are constants).
520Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
521 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +0000522 unsigned NumPHIValues = PN->getNumIncomingValues();
523 if (!PN->hasOneUse() || NumPHIValues == 0 ||
524 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000525
526 // Check to see if all of the operands of the PHI are constants. If not, we
527 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +0000528 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000529 if (!isa<Constant>(PN->getIncomingValue(i)))
530 return 0;
531
532 // Okay, we can do the transformation: create the new PHI node.
533 PHINode *NewPN = new PHINode(I.getType(), I.getName());
534 I.setName("");
535 NewPN->op_reserve(PN->getNumOperands());
536 InsertNewInstBefore(NewPN, *PN);
537
538 // Next, add all of the operands to the PHI.
539 if (I.getNumOperands() == 2) {
540 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +0000541 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000542 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
543 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
544 PN->getIncomingBlock(i));
545 }
546 } else {
547 assert(isa<CastInst>(I) && "Unary op should be a cast!");
548 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +0000549 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000550 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
551 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
552 PN->getIncomingBlock(i));
553 }
554 }
555 return ReplaceInstUsesWith(I, NewPN);
556}
557
Chris Lattner183b3362004-04-09 19:05:30 +0000558// FoldBinOpIntoSelect - Given an instruction with a select as one operand and a
559// constant as the other operand, try to fold the binary operator into the
560// select arguments.
561static Instruction *FoldBinOpIntoSelect(Instruction &BI, SelectInst *SI,
562 InstCombiner *IC) {
563 // Don't modify shared select instructions
564 if (!SI->hasOneUse()) return 0;
565 Value *TV = SI->getOperand(1);
566 Value *FV = SI->getOperand(2);
567
568 if (isa<Constant>(TV) || isa<Constant>(FV)) {
569 Value *SelectTrueVal = FoldOperationIntoSelectOperand(BI, TV, IC);
570 Value *SelectFalseVal = FoldOperationIntoSelectOperand(BI, FV, IC);
571
572 return new SelectInst(SI->getCondition(), SelectTrueVal,
573 SelectFalseVal);
574 }
575 return 0;
576}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000577
Chris Lattner113f4f42002-06-25 16:13:24 +0000578Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000579 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000580 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000581
Chris Lattnercf4a9962004-04-10 22:01:55 +0000582 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000583 // X + undef -> undef
584 if (isa<UndefValue>(RHS))
585 return ReplaceInstUsesWith(I, RHS);
586
Chris Lattnercf4a9962004-04-10 22:01:55 +0000587 // X + 0 --> X
588 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
589 RHSC->isNullValue())
590 return ReplaceInstUsesWith(I, LHS);
591
592 // X + (signbit) --> X ^ signbit
593 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
594 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
595 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
Chris Lattner33eb9092004-11-05 04:45:43 +0000596 if (Val == (1ULL << (NumBits-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000597 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000598 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000599
600 if (isa<PHINode>(LHS))
601 if (Instruction *NV = FoldOpIntoPhi(I))
602 return NV;
Chris Lattnercf4a9962004-04-10 22:01:55 +0000603 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000604
Chris Lattnerb8b97502003-08-13 19:01:45 +0000605 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000606 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000607 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000608 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000609
Chris Lattner147e9752002-05-08 22:46:53 +0000610 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000611 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000612 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000613
614 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000615 if (!isa<Constant>(RHS))
616 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000617 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000618
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000619 ConstantInt *C2;
620 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
621 if (X == RHS) // X*C + X --> X * (C+1)
622 return BinaryOperator::createMul(RHS, AddOne(C2));
623
624 // X*C1 + X*C2 --> X * (C1+C2)
625 ConstantInt *C1;
626 if (X == dyn_castFoldableMul(RHS, C1))
627 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +0000628 }
629
630 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000631 if (dyn_castFoldableMul(RHS, C2) == LHS)
632 return BinaryOperator::createMul(LHS, AddOne(C2));
633
Chris Lattner57c8d992003-02-18 19:57:07 +0000634
Chris Lattnerb8b97502003-08-13 19:01:45 +0000635 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000636 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000637 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000638
Chris Lattnerb9cde762003-10-02 15:11:26 +0000639 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000640 Value *X;
641 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
642 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
643 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000644 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000645
Chris Lattnerbff91d92004-10-08 05:07:56 +0000646 // (X & FF00) + xx00 -> (X+xx00) & FF00
647 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
648 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
649 if (Anded == CRHS) {
650 // See if all bits from the first bit set in the Add RHS up are included
651 // in the mask. First, get the rightmost bit.
652 uint64_t AddRHSV = CRHS->getRawValue();
653
654 // Form a mask of all bits from the lowest bit added through the top.
655 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
656 AddRHSHighBits &= (1ULL << C2->getType()->getPrimitiveSize()*8)-1;
657
658 // See if the and mask includes all of these bits.
659 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
660
661 if (AddRHSHighBits == AddRHSHighBitsAnd) {
662 // Okay, the xform is safe. Insert the new add pronto.
663 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
664 LHS->getName()), I);
665 return BinaryOperator::createAnd(NewAdd, C2);
666 }
667 }
668 }
669
670
Chris Lattnerd4252a72004-07-30 07:50:03 +0000671 // Try to fold constant add into select arguments.
672 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
673 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
674 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000675 }
676
Chris Lattner113f4f42002-06-25 16:13:24 +0000677 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000678}
679
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000680// isSignBit - Return true if the value represented by the constant only has the
681// highest order bit set.
682static bool isSignBit(ConstantInt *CI) {
683 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
684 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
685}
686
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000687static unsigned getTypeSizeInBits(const Type *Ty) {
688 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
689}
690
Chris Lattner022167f2004-03-13 00:11:49 +0000691/// RemoveNoopCast - Strip off nonconverting casts from the value.
692///
693static Value *RemoveNoopCast(Value *V) {
694 if (CastInst *CI = dyn_cast<CastInst>(V)) {
695 const Type *CTy = CI->getType();
696 const Type *OpTy = CI->getOperand(0)->getType();
697 if (CTy->isInteger() && OpTy->isInteger()) {
698 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
699 return RemoveNoopCast(CI->getOperand(0));
700 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
701 return RemoveNoopCast(CI->getOperand(0));
702 }
703 return V;
704}
705
Chris Lattner113f4f42002-06-25 16:13:24 +0000706Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000707 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000708
Chris Lattnere6794492002-08-12 21:17:25 +0000709 if (Op0 == Op1) // sub X, X -> 0
710 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000711
Chris Lattnere6794492002-08-12 21:17:25 +0000712 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000713 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000714 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000715
Chris Lattner81a7a232004-10-16 18:11:37 +0000716 if (isa<UndefValue>(Op0))
717 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
718 if (isa<UndefValue>(Op1))
719 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
720
Chris Lattner8f2f5982003-11-05 01:06:05 +0000721 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
722 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000723 if (C->isAllOnesValue())
724 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000725
Chris Lattner8f2f5982003-11-05 01:06:05 +0000726 // C - ~X == X + (1+C)
Chris Lattnerd4252a72004-07-30 07:50:03 +0000727 Value *X;
728 if (match(Op1, m_Not(m_Value(X))))
729 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000730 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000731 // -((uint)X >> 31) -> ((int)X >> 31)
732 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000733 if (C->isNullValue()) {
734 Value *NoopCastedRHS = RemoveNoopCast(Op1);
735 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000736 if (SI->getOpcode() == Instruction::Shr)
737 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
738 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000739 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000740 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000741 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000742 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000743 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner022167f2004-03-13 00:11:49 +0000744 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000745 // Ok, the transformation is safe. Insert a cast of the incoming
746 // value, then the new shift, then the new cast.
747 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
748 SI->getOperand(0)->getName());
749 Value *InV = InsertNewInstBefore(FirstCast, I);
750 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
751 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000752 if (NewShift->getType() == I.getType())
753 return NewShift;
754 else {
755 InV = InsertNewInstBefore(NewShift, I);
756 return new CastInst(NewShift, I.getType());
757 }
Chris Lattner92295c52004-03-12 23:53:13 +0000758 }
759 }
Chris Lattner022167f2004-03-13 00:11:49 +0000760 }
Chris Lattner183b3362004-04-09 19:05:30 +0000761
762 // Try to fold constant sub into select arguments.
763 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
764 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
765 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000766
767 if (isa<PHINode>(Op0))
768 if (Instruction *NV = FoldOpIntoPhi(I))
769 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000770 }
771
Chris Lattner3082c5a2003-02-18 19:28:33 +0000772 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000773 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000774 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
775 // is not used by anyone else...
776 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000777 if (Op1I->getOpcode() == Instruction::Sub &&
778 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000779 // Swap the two operands of the subexpr...
780 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
781 Op1I->setOperand(0, IIOp1);
782 Op1I->setOperand(1, IIOp0);
783
784 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000785 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000786 }
787
788 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
789 //
790 if (Op1I->getOpcode() == Instruction::And &&
791 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
792 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
793
Chris Lattner396dbfe2004-06-09 05:08:07 +0000794 Value *NewNot =
795 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000796 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000797 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000798
Chris Lattner0aee4b72004-10-06 15:08:25 +0000799 // -(X sdiv C) -> (X sdiv -C)
800 if (Op1I->getOpcode() == Instruction::Div)
801 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
802 if (CSI->getValue() == 0)
803 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
804 return BinaryOperator::createDiv(Op1I->getOperand(0),
805 ConstantExpr::getNeg(DivRHS));
806
Chris Lattner57c8d992003-02-18 19:57:07 +0000807 // X - X*C --> X * (1-C)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000808 ConstantInt *C2;
809 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
810 Constant *CP1 =
811 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000812 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000813 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000814 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000815
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000816
817 ConstantInt *C1;
818 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
819 if (X == Op1) { // X*C - X --> X * (C-1)
820 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
821 return BinaryOperator::createMul(Op1, CP1);
822 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000823
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000824 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
825 if (X == dyn_castFoldableMul(Op1, C2))
826 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
827 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000828 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000829}
830
Chris Lattnere79e8542004-02-23 06:38:22 +0000831/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
832/// really just returns true if the most significant (sign) bit is set.
833static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
834 if (RHS->getType()->isSigned()) {
835 // True if source is LHS < 0 or LHS <= -1
836 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
837 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
838 } else {
839 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
840 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
841 // the size of the integer type.
842 if (Opcode == Instruction::SetGE)
843 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
844 if (Opcode == Instruction::SetGT)
845 return RHSC->getValue() ==
846 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
847 }
848 return false;
849}
850
Chris Lattner113f4f42002-06-25 16:13:24 +0000851Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000852 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000853 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000854
Chris Lattner81a7a232004-10-16 18:11:37 +0000855 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
856 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
857
Chris Lattnere6794492002-08-12 21:17:25 +0000858 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000859 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
860 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000861
862 // ((X << C1)*C2) == (X * (C2 << C1))
863 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
864 if (SI->getOpcode() == Instruction::Shl)
865 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000866 return BinaryOperator::createMul(SI->getOperand(0),
867 ConstantExpr::getShl(CI, ShOp));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000868
Chris Lattnercce81be2003-09-11 22:24:54 +0000869 if (CI->isNullValue())
870 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
871 if (CI->equalsInt(1)) // X * 1 == X
872 return ReplaceInstUsesWith(I, Op0);
873 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000874 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000875
Chris Lattnercce81be2003-09-11 22:24:54 +0000876 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000877 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
878 return new ShiftInst(Instruction::Shl, Op0,
879 ConstantUInt::get(Type::UByteTy, C));
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000880 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000881 if (Op1F->isNullValue())
882 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000883
Chris Lattner3082c5a2003-02-18 19:28:33 +0000884 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
885 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
886 if (Op1F->getValue() == 1.0)
887 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
888 }
Chris Lattner183b3362004-04-09 19:05:30 +0000889
890 // Try to fold constant mul into select arguments.
891 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
892 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
893 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000894
895 if (isa<PHINode>(Op0))
896 if (Instruction *NV = FoldOpIntoPhi(I))
897 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +0000898 }
899
Chris Lattner934a64cf2003-03-10 23:23:04 +0000900 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
901 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000902 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +0000903
Chris Lattner2635b522004-02-23 05:39:21 +0000904 // If one of the operands of the multiply is a cast from a boolean value, then
905 // we know the bool is either zero or one, so this is a 'masking' multiply.
906 // See if we can simplify things based on how the boolean was originally
907 // formed.
908 CastInst *BoolCast = 0;
909 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
910 if (CI->getOperand(0)->getType() == Type::BoolTy)
911 BoolCast = CI;
912 if (!BoolCast)
913 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
914 if (CI->getOperand(0)->getType() == Type::BoolTy)
915 BoolCast = CI;
916 if (BoolCast) {
917 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
918 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
919 const Type *SCOpTy = SCIOp0->getType();
920
Chris Lattnere79e8542004-02-23 06:38:22 +0000921 // If the setcc is true iff the sign bit of X is set, then convert this
922 // multiply into a shift/and combination.
923 if (isa<ConstantInt>(SCIOp1) &&
924 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000925 // Shift the X value right to turn it into "all signbits".
926 Constant *Amt = ConstantUInt::get(Type::UByteTy,
927 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000928 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000929 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +0000930 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
931 SCIOp0->getName()), I);
932 }
933
934 Value *V =
935 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
936 BoolCast->getOperand(0)->getName()+
937 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +0000938
939 // If the multiply type is not the same as the source type, sign extend
940 // or truncate to the multiply type.
941 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +0000942 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattner2635b522004-02-23 05:39:21 +0000943
944 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000945 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +0000946 }
947 }
948 }
949
Chris Lattner113f4f42002-06-25 16:13:24 +0000950 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000951}
952
Chris Lattner113f4f42002-06-25 16:13:24 +0000953Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000954 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +0000955
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000956 if (isa<UndefValue>(Op0)) // undef / X -> 0
957 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
958 if (isa<UndefValue>(Op1))
959 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
960
961 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +0000962 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000963 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000964 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000965
Chris Lattnere20c3342004-04-26 14:01:59 +0000966 // div X, -1 == -X
967 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000968 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +0000969
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000970 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +0000971 if (LHS->getOpcode() == Instruction::Div)
972 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +0000973 // (X / C1) / C2 -> X / (C1*C2)
974 return BinaryOperator::createDiv(LHS->getOperand(0),
975 ConstantExpr::getMul(RHS, LHSRHS));
976 }
977
Chris Lattner3082c5a2003-02-18 19:28:33 +0000978 // Check to see if this is an unsigned division with an exact power of 2,
979 // if so, convert to a right shift.
980 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
981 if (uint64_t Val = C->getValue()) // Don't break X / 0
982 if (uint64_t C = Log2(Val))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000983 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +0000984 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000985
Chris Lattner4ad08352004-10-09 02:50:40 +0000986 // -X/C -> X/-C
987 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000988 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +0000989 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
990
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000991 if (!RHS->isNullValue()) {
992 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
993 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
994 return R;
995 if (isa<PHINode>(Op0))
996 if (Instruction *NV = FoldOpIntoPhi(I))
997 return NV;
998 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000999 }
1000
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001001 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1002 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1003 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1004 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1005 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1006 if (STO->getValue() == 0) { // Couldn't be this argument.
1007 I.setOperand(1, SFO);
1008 return &I;
1009 } else if (SFO->getValue() == 0) {
1010 I.setOperand(1, STO);
1011 return &I;
1012 }
1013
1014 if (uint64_t TSA = Log2(STO->getValue()))
1015 if (uint64_t FSA = Log2(SFO->getValue())) {
1016 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1017 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1018 TC, SI->getName()+".t");
1019 TSI = InsertNewInstBefore(TSI, I);
1020
1021 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1022 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1023 FC, SI->getName()+".f");
1024 FSI = InsertNewInstBefore(FSI, I);
1025 return new SelectInst(SI->getOperand(0), TSI, FSI);
1026 }
1027 }
1028
Chris Lattner3082c5a2003-02-18 19:28:33 +00001029 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001030 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001031 if (LHS->equalsInt(0))
1032 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1033
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001034 return 0;
1035}
1036
1037
Chris Lattner113f4f42002-06-25 16:13:24 +00001038Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001039 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner7fd5f072004-07-06 07:01:22 +00001040 if (I.getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001041 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00001042 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00001043 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001044 // X % -Y -> X % Y
1045 AddUsesToWorkList(I);
1046 I.setOperand(1, RHSNeg);
1047 return &I;
1048 }
1049
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001050 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00001051 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001052 if (isa<UndefValue>(Op1))
1053 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattner81a7a232004-10-16 18:11:37 +00001054
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001055 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001056 if (RHS->equalsInt(1)) // X % 1 == 0
1057 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1058
1059 // Check to see if this is an unsigned remainder with an exact power of 2,
1060 // if so, convert to a bitwise and.
1061 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1062 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +00001063 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001064 return BinaryOperator::createAnd(Op0,
1065 ConstantUInt::get(I.getType(), Val-1));
1066
1067 if (!RHS->isNullValue()) {
1068 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1069 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1070 return R;
1071 if (isa<PHINode>(Op0))
1072 if (Instruction *NV = FoldOpIntoPhi(I))
1073 return NV;
1074 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001075 }
1076
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001077 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1078 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1079 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1080 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1081 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1082 if (STO->getValue() == 0) { // Couldn't be this argument.
1083 I.setOperand(1, SFO);
1084 return &I;
1085 } else if (SFO->getValue() == 0) {
1086 I.setOperand(1, STO);
1087 return &I;
1088 }
1089
1090 if (!(STO->getValue() & (STO->getValue()-1)) &&
1091 !(SFO->getValue() & (SFO->getValue()-1))) {
1092 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1093 SubOne(STO), SI->getName()+".t"), I);
1094 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1095 SubOne(SFO), SI->getName()+".f"), I);
1096 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1097 }
1098 }
1099
Chris Lattner3082c5a2003-02-18 19:28:33 +00001100 // 0 % X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001101 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001102 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +00001103 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1104
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001105 return 0;
1106}
1107
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001108// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001109static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001110 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1111 // Calculate -1 casted to the right type...
1112 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1113 uint64_t Val = ~0ULL; // All ones
1114 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1115 return CU->getValue() == Val-1;
1116 }
1117
1118 const ConstantSInt *CS = cast<ConstantSInt>(C);
1119
1120 // Calculate 0111111111..11111
1121 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1122 int64_t Val = INT64_MAX; // All ones
1123 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1124 return CS->getValue() == Val-1;
1125}
1126
1127// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001128static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001129 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1130 return CU->getValue() == 1;
1131
1132 const ConstantSInt *CS = cast<ConstantSInt>(C);
1133
1134 // Calculate 1111111111000000000000
1135 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1136 int64_t Val = -1; // All ones
1137 Val <<= TypeBits-1; // Shift over to the right spot
1138 return CS->getValue() == Val+1;
1139}
1140
Chris Lattner35167c32004-06-09 07:59:58 +00001141// isOneBitSet - Return true if there is exactly one bit set in the specified
1142// constant.
1143static bool isOneBitSet(const ConstantInt *CI) {
1144 uint64_t V = CI->getRawValue();
1145 return V && (V & (V-1)) == 0;
1146}
1147
Chris Lattner8fc5af42004-09-23 21:46:38 +00001148#if 0 // Currently unused
1149// isLowOnes - Return true if the constant is of the form 0+1+.
1150static bool isLowOnes(const ConstantInt *CI) {
1151 uint64_t V = CI->getRawValue();
1152
1153 // There won't be bits set in parts that the type doesn't contain.
1154 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1155
1156 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1157 return U && V && (U & V) == 0;
1158}
1159#endif
1160
1161// isHighOnes - Return true if the constant is of the form 1+0+.
1162// This is the same as lowones(~X).
1163static bool isHighOnes(const ConstantInt *CI) {
1164 uint64_t V = ~CI->getRawValue();
1165
1166 // There won't be bits set in parts that the type doesn't contain.
1167 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1168
1169 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1170 return U && V && (U & V) == 0;
1171}
1172
1173
Chris Lattner3ac7c262003-08-13 20:16:26 +00001174/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1175/// are carefully arranged to allow folding of expressions such as:
1176///
1177/// (A < B) | (A > B) --> (A != B)
1178///
1179/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1180/// represents that the comparison is true if A == B, and bit value '1' is true
1181/// if A < B.
1182///
1183static unsigned getSetCondCode(const SetCondInst *SCI) {
1184 switch (SCI->getOpcode()) {
1185 // False -> 0
1186 case Instruction::SetGT: return 1;
1187 case Instruction::SetEQ: return 2;
1188 case Instruction::SetGE: return 3;
1189 case Instruction::SetLT: return 4;
1190 case Instruction::SetNE: return 5;
1191 case Instruction::SetLE: return 6;
1192 // True -> 7
1193 default:
1194 assert(0 && "Invalid SetCC opcode!");
1195 return 0;
1196 }
1197}
1198
1199/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1200/// opcode and two operands into either a constant true or false, or a brand new
1201/// SetCC instruction.
1202static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1203 switch (Opcode) {
1204 case 0: return ConstantBool::False;
1205 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1206 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1207 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1208 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1209 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1210 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1211 case 7: return ConstantBool::True;
1212 default: assert(0 && "Illegal SetCCCode!"); return 0;
1213 }
1214}
1215
1216// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1217struct FoldSetCCLogical {
1218 InstCombiner &IC;
1219 Value *LHS, *RHS;
1220 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1221 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1222 bool shouldApply(Value *V) const {
1223 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1224 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1225 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1226 return false;
1227 }
1228 Instruction *apply(BinaryOperator &Log) const {
1229 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1230 if (SCI->getOperand(0) != LHS) {
1231 assert(SCI->getOperand(1) == LHS);
1232 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1233 }
1234
1235 unsigned LHSCode = getSetCondCode(SCI);
1236 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1237 unsigned Code;
1238 switch (Log.getOpcode()) {
1239 case Instruction::And: Code = LHSCode & RHSCode; break;
1240 case Instruction::Or: Code = LHSCode | RHSCode; break;
1241 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001242 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001243 }
1244
1245 Value *RV = getSetCCValue(Code, LHS, RHS);
1246 if (Instruction *I = dyn_cast<Instruction>(RV))
1247 return I;
1248 // Otherwise, it's a constant boolean value...
1249 return IC.ReplaceInstUsesWith(Log, RV);
1250 }
1251};
1252
1253
Chris Lattnerba1cb382003-09-19 17:17:26 +00001254// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1255// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1256// guaranteed to be either a shift instruction or a binary operator.
1257Instruction *InstCombiner::OptAndOp(Instruction *Op,
1258 ConstantIntegral *OpRHS,
1259 ConstantIntegral *AndRHS,
1260 BinaryOperator &TheAnd) {
1261 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001262 Constant *Together = 0;
1263 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001264 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001265
Chris Lattnerba1cb382003-09-19 17:17:26 +00001266 switch (Op->getOpcode()) {
1267 case Instruction::Xor:
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001268 if (Together->isNullValue()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001269 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001270 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001271 } else if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001272 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1273 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001274 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001275 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001276 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001277 }
1278 break;
1279 case Instruction::Or:
1280 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001281 if (Together->isNullValue())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001282 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001283 else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001284 if (Together == AndRHS) // (X | C) & C --> C
1285 return ReplaceInstUsesWith(TheAnd, AndRHS);
1286
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001287 if (Op->hasOneUse() && Together != OpRHS) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001288 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1289 std::string Op0Name = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001290 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001291 InsertNewInstBefore(Or, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001292 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001293 }
1294 }
1295 break;
1296 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001297 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001298 // Adding a one to a single bit bit-field should be turned into an XOR
1299 // of the bit. First thing to check is to see if this AND is with a
1300 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001301 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001302
1303 // Clear bits that are not part of the constant.
1304 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1305
1306 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001307 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001308 // Ok, at this point, we know that we are masking the result of the
1309 // ADD down to exactly one bit. If the constant we are adding has
1310 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001311 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001312
1313 // Check to see if any bits below the one bit set in AndRHSV are set.
1314 if ((AddRHS & (AndRHSV-1)) == 0) {
1315 // If not, the only thing that can effect the output of the AND is
1316 // the bit specified by AndRHSV. If that bit is set, the effect of
1317 // the XOR is to toggle the bit. If it is clear, then the ADD has
1318 // no effect.
1319 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1320 TheAnd.setOperand(0, X);
1321 return &TheAnd;
1322 } else {
1323 std::string Name = Op->getName(); Op->setName("");
1324 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001325 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001326 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001327 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001328 }
1329 }
1330 }
1331 }
1332 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001333
1334 case Instruction::Shl: {
1335 // We know that the AND will not produce any of the bits shifted in, so if
1336 // the anded constant includes them, clear them now!
1337 //
1338 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001339 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1340 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1341
1342 if (CI == ShlMask) { // Masking out bits that the shift already masks
1343 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1344 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001345 TheAnd.setOperand(1, CI);
1346 return &TheAnd;
1347 }
1348 break;
1349 }
1350 case Instruction::Shr:
1351 // We know that the AND will not produce any of the bits shifted in, so if
1352 // the anded constant includes them, clear them now! This only applies to
1353 // unsigned shifts, because a signed shr may bring in set bits!
1354 //
1355 if (AndRHS->getType()->isUnsigned()) {
1356 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001357 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1358 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1359
1360 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1361 return ReplaceInstUsesWith(TheAnd, Op);
1362 } else if (CI != AndRHS) {
1363 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001364 return &TheAnd;
1365 }
Chris Lattner7e794272004-09-24 15:21:34 +00001366 } else { // Signed shr.
1367 // See if this is shifting in some sign extension, then masking it out
1368 // with an and.
1369 if (Op->hasOneUse()) {
1370 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1371 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1372 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00001373 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00001374 // Make the argument unsigned.
1375 Value *ShVal = Op->getOperand(0);
1376 ShVal = InsertCastBefore(ShVal,
1377 ShVal->getType()->getUnsignedVersion(),
1378 TheAnd);
1379 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1380 OpRHS, Op->getName()),
1381 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00001382 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1383 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1384 TheAnd.getName()),
1385 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00001386 return new CastInst(ShVal, Op->getType());
1387 }
1388 }
Chris Lattner2da29172003-09-19 19:05:02 +00001389 }
1390 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001391 }
1392 return 0;
1393}
1394
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001395
Chris Lattner6862fbd2004-09-29 17:40:11 +00001396/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1397/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1398/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1399/// insert new instructions.
1400Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1401 bool Inside, Instruction &IB) {
1402 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1403 "Lo is not <= Hi in range emission code!");
1404 if (Inside) {
1405 if (Lo == Hi) // Trivially false.
1406 return new SetCondInst(Instruction::SetNE, V, V);
1407 if (cast<ConstantIntegral>(Lo)->isMinValue())
1408 return new SetCondInst(Instruction::SetLT, V, Hi);
1409
1410 Constant *AddCST = ConstantExpr::getNeg(Lo);
1411 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1412 InsertNewInstBefore(Add, IB);
1413 // Convert to unsigned for the comparison.
1414 const Type *UnsType = Add->getType()->getUnsignedVersion();
1415 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1416 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1417 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1418 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1419 }
1420
1421 if (Lo == Hi) // Trivially true.
1422 return new SetCondInst(Instruction::SetEQ, V, V);
1423
1424 Hi = SubOne(cast<ConstantInt>(Hi));
1425 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1426 return new SetCondInst(Instruction::SetGT, V, Hi);
1427
1428 // Emit X-Lo > Hi-Lo-1
1429 Constant *AddCST = ConstantExpr::getNeg(Lo);
1430 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1431 InsertNewInstBefore(Add, IB);
1432 // Convert to unsigned for the comparison.
1433 const Type *UnsType = Add->getType()->getUnsignedVersion();
1434 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1435 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1436 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1437 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1438}
1439
1440
Chris Lattner113f4f42002-06-25 16:13:24 +00001441Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001442 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001443 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001444
Chris Lattner81a7a232004-10-16 18:11:37 +00001445 if (isa<UndefValue>(Op1)) // X & undef -> 0
1446 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1447
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001448 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +00001449 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1450 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001451
1452 // and X, -1 == X
Chris Lattner49b47ae2003-07-23 17:57:01 +00001453 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001454 if (RHS->isAllOnesValue())
1455 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001456
Chris Lattnerba1cb382003-09-19 17:17:26 +00001457 // Optimize a variety of ((val OP C1) & C2) combinations...
1458 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1459 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner33217db2003-07-23 19:36:21 +00001460 Value *X = Op0I->getOperand(0);
Chris Lattner16464b32003-07-23 19:25:52 +00001461 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001462 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1463 return Res;
Chris Lattner33217db2003-07-23 19:36:21 +00001464 }
Chris Lattner183b3362004-04-09 19:05:30 +00001465
1466 // Try to fold constant and into select arguments.
1467 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1468 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1469 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001470 if (isa<PHINode>(Op0))
1471 if (Instruction *NV = FoldOpIntoPhi(I))
1472 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001473 }
1474
Chris Lattnerbb74e222003-03-10 23:06:50 +00001475 Value *Op0NotVal = dyn_castNotVal(Op0);
1476 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001477
Chris Lattner023a4832004-06-18 06:07:51 +00001478 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1479 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1480
Misha Brukman9c003d82004-07-30 12:50:08 +00001481 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001482 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001483 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1484 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001485 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001486 return BinaryOperator::createNot(Or);
1487 }
1488
Chris Lattner623826c2004-09-28 21:48:02 +00001489 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1490 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001491 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1492 return R;
1493
Chris Lattner623826c2004-09-28 21:48:02 +00001494 Value *LHSVal, *RHSVal;
1495 ConstantInt *LHSCst, *RHSCst;
1496 Instruction::BinaryOps LHSCC, RHSCC;
1497 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1498 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1499 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1500 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1501 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1502 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1503 // Ensure that the larger constant is on the RHS.
1504 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1505 SetCondInst *LHS = cast<SetCondInst>(Op0);
1506 if (cast<ConstantBool>(Cmp)->getValue()) {
1507 std::swap(LHS, RHS);
1508 std::swap(LHSCst, RHSCst);
1509 std::swap(LHSCC, RHSCC);
1510 }
1511
1512 // At this point, we know we have have two setcc instructions
1513 // comparing a value against two constants and and'ing the result
1514 // together. Because of the above check, we know that we only have
1515 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1516 // FoldSetCCLogical check above), that the two constants are not
1517 // equal.
1518 assert(LHSCst != RHSCst && "Compares not folded above?");
1519
1520 switch (LHSCC) {
1521 default: assert(0 && "Unknown integer condition code!");
1522 case Instruction::SetEQ:
1523 switch (RHSCC) {
1524 default: assert(0 && "Unknown integer condition code!");
1525 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1526 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1527 return ReplaceInstUsesWith(I, ConstantBool::False);
1528 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1529 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1530 return ReplaceInstUsesWith(I, LHS);
1531 }
1532 case Instruction::SetNE:
1533 switch (RHSCC) {
1534 default: assert(0 && "Unknown integer condition code!");
1535 case Instruction::SetLT:
1536 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1537 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1538 break; // (X != 13 & X < 15) -> no change
1539 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1540 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1541 return ReplaceInstUsesWith(I, RHS);
1542 case Instruction::SetNE:
1543 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1544 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1545 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1546 LHSVal->getName()+".off");
1547 InsertNewInstBefore(Add, I);
1548 const Type *UnsType = Add->getType()->getUnsignedVersion();
1549 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1550 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1551 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1552 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1553 }
1554 break; // (X != 13 & X != 15) -> no change
1555 }
1556 break;
1557 case Instruction::SetLT:
1558 switch (RHSCC) {
1559 default: assert(0 && "Unknown integer condition code!");
1560 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1561 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1562 return ReplaceInstUsesWith(I, ConstantBool::False);
1563 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1564 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1565 return ReplaceInstUsesWith(I, LHS);
1566 }
1567 case Instruction::SetGT:
1568 switch (RHSCC) {
1569 default: assert(0 && "Unknown integer condition code!");
1570 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1571 return ReplaceInstUsesWith(I, LHS);
1572 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1573 return ReplaceInstUsesWith(I, RHS);
1574 case Instruction::SetNE:
1575 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1576 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1577 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00001578 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1579 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00001580 }
1581 }
1582 }
1583 }
1584
Chris Lattner113f4f42002-06-25 16:13:24 +00001585 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001586}
1587
Chris Lattner113f4f42002-06-25 16:13:24 +00001588Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001589 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001590 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001591
Chris Lattner81a7a232004-10-16 18:11:37 +00001592 if (isa<UndefValue>(Op1))
1593 return ReplaceInstUsesWith(I, // X | undef -> -1
1594 ConstantIntegral::getAllOnesValue(I.getType()));
1595
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001596 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001597 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1598 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001599
1600 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001601 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001602 if (RHS->isAllOnesValue())
1603 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001604
Chris Lattnerd4252a72004-07-30 07:50:03 +00001605 ConstantInt *C1; Value *X;
1606 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1607 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1608 std::string Op0Name = Op0->getName(); Op0->setName("");
1609 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1610 InsertNewInstBefore(Or, I);
1611 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1612 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00001613
Chris Lattnerd4252a72004-07-30 07:50:03 +00001614 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1615 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1616 std::string Op0Name = Op0->getName(); Op0->setName("");
1617 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1618 InsertNewInstBefore(Or, I);
1619 return BinaryOperator::createXor(Or,
1620 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001621 }
Chris Lattner183b3362004-04-09 19:05:30 +00001622
1623 // Try to fold constant and into select arguments.
1624 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1625 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1626 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001627 if (isa<PHINode>(Op0))
1628 if (Instruction *NV = FoldOpIntoPhi(I))
1629 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001630 }
1631
Chris Lattner812aab72003-08-12 19:11:07 +00001632 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00001633 Value *A, *B; ConstantInt *C1, *C2;
1634 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1635 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1636 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner812aab72003-08-12 19:11:07 +00001637
Chris Lattnerd4252a72004-07-30 07:50:03 +00001638 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1639 if (A == Op1) // ~A | A == -1
1640 return ReplaceInstUsesWith(I,
1641 ConstantIntegral::getAllOnesValue(I.getType()));
1642 } else {
1643 A = 0;
1644 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001645
Chris Lattnerd4252a72004-07-30 07:50:03 +00001646 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1647 if (Op0 == B)
1648 return ReplaceInstUsesWith(I,
1649 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00001650
Misha Brukman9c003d82004-07-30 12:50:08 +00001651 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00001652 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1653 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1654 I.getName()+".demorgan"), I);
1655 return BinaryOperator::createNot(And);
1656 }
Chris Lattner3e327a42003-03-10 23:13:59 +00001657 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001658
Chris Lattner3ac7c262003-08-13 20:16:26 +00001659 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001660 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00001661 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1662 return R;
1663
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001664 Value *LHSVal, *RHSVal;
1665 ConstantInt *LHSCst, *RHSCst;
1666 Instruction::BinaryOps LHSCC, RHSCC;
1667 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1668 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1669 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1670 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1671 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1672 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1673 // Ensure that the larger constant is on the RHS.
1674 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1675 SetCondInst *LHS = cast<SetCondInst>(Op0);
1676 if (cast<ConstantBool>(Cmp)->getValue()) {
1677 std::swap(LHS, RHS);
1678 std::swap(LHSCst, RHSCst);
1679 std::swap(LHSCC, RHSCC);
1680 }
1681
1682 // At this point, we know we have have two setcc instructions
1683 // comparing a value against two constants and or'ing the result
1684 // together. Because of the above check, we know that we only have
1685 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1686 // FoldSetCCLogical check above), that the two constants are not
1687 // equal.
1688 assert(LHSCst != RHSCst && "Compares not folded above?");
1689
1690 switch (LHSCC) {
1691 default: assert(0 && "Unknown integer condition code!");
1692 case Instruction::SetEQ:
1693 switch (RHSCC) {
1694 default: assert(0 && "Unknown integer condition code!");
1695 case Instruction::SetEQ:
1696 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1697 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1698 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1699 LHSVal->getName()+".off");
1700 InsertNewInstBefore(Add, I);
1701 const Type *UnsType = Add->getType()->getUnsignedVersion();
1702 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1703 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1704 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1705 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1706 }
1707 break; // (X == 13 | X == 15) -> no change
1708
1709 case Instruction::SetGT:
1710 if (LHSCst == SubOne(RHSCst)) // (X == 13 | X > 14) -> X > 13
1711 return new SetCondInst(Instruction::SetGT, LHSVal, LHSCst);
1712 break; // (X == 13 | X > 15) -> no change
1713 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
1714 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
1715 return ReplaceInstUsesWith(I, RHS);
1716 }
1717 break;
1718 case Instruction::SetNE:
1719 switch (RHSCC) {
1720 default: assert(0 && "Unknown integer condition code!");
1721 case Instruction::SetLT: // (X != 13 | X < 15) -> X < 15
1722 return ReplaceInstUsesWith(I, RHS);
1723 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
1724 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
1725 return ReplaceInstUsesWith(I, LHS);
1726 case Instruction::SetNE: // (X != 13 | X != 15) -> true
1727 return ReplaceInstUsesWith(I, ConstantBool::True);
1728 }
1729 break;
1730 case Instruction::SetLT:
1731 switch (RHSCC) {
1732 default: assert(0 && "Unknown integer condition code!");
1733 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
1734 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00001735 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
1736 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001737 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
1738 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
1739 return ReplaceInstUsesWith(I, RHS);
1740 }
1741 break;
1742 case Instruction::SetGT:
1743 switch (RHSCC) {
1744 default: assert(0 && "Unknown integer condition code!");
1745 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
1746 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
1747 return ReplaceInstUsesWith(I, LHS);
1748 case Instruction::SetNE: // (X > 13 | X != 15) -> true
1749 case Instruction::SetLT: // (X > 13 | X < 15) -> true
1750 return ReplaceInstUsesWith(I, ConstantBool::True);
1751 }
1752 }
1753 }
1754 }
Chris Lattner113f4f42002-06-25 16:13:24 +00001755 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001756}
1757
Chris Lattnerc2076352004-02-16 01:20:27 +00001758// XorSelf - Implements: X ^ X --> 0
1759struct XorSelf {
1760 Value *RHS;
1761 XorSelf(Value *rhs) : RHS(rhs) {}
1762 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1763 Instruction *apply(BinaryOperator &Xor) const {
1764 return &Xor;
1765 }
1766};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001767
1768
Chris Lattner113f4f42002-06-25 16:13:24 +00001769Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001770 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001771 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001772
Chris Lattner81a7a232004-10-16 18:11:37 +00001773 if (isa<UndefValue>(Op1))
1774 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
1775
Chris Lattnerc2076352004-02-16 01:20:27 +00001776 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1777 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1778 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00001779 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00001780 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001781
Chris Lattner97638592003-07-23 21:37:07 +00001782 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001783 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00001784 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001785 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001786
Chris Lattner97638592003-07-23 21:37:07 +00001787 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001788 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00001789 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001790 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001791 return new SetCondInst(SCI->getInverseCondition(),
1792 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00001793
Chris Lattner8f2f5982003-11-05 01:06:05 +00001794 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001795 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1796 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001797 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1798 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001799 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001800 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001801 }
Chris Lattner023a4832004-06-18 06:07:51 +00001802
1803 // ~(~X & Y) --> (X | ~Y)
1804 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1805 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1806 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1807 Instruction *NotY =
1808 BinaryOperator::createNot(Op0I->getOperand(1),
1809 Op0I->getOperand(1)->getName()+".not");
1810 InsertNewInstBefore(NotY, I);
1811 return BinaryOperator::createOr(Op0NotVal, NotY);
1812 }
1813 }
Chris Lattner97638592003-07-23 21:37:07 +00001814
1815 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00001816 switch (Op0I->getOpcode()) {
1817 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00001818 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001819 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001820 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1821 return BinaryOperator::createSub(
1822 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001823 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00001824 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001825 }
Chris Lattnere5806662003-11-04 23:50:51 +00001826 break;
1827 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00001828 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001829 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1830 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00001831 break;
1832 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00001833 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001834 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001835 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00001836 break;
1837 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00001838 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001839 }
Chris Lattner183b3362004-04-09 19:05:30 +00001840
1841 // Try to fold constant and into select arguments.
1842 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1843 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1844 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001845 if (isa<PHINode>(Op0))
1846 if (Instruction *NV = FoldOpIntoPhi(I))
1847 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001848 }
1849
Chris Lattnerbb74e222003-03-10 23:06:50 +00001850 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001851 if (X == Op1)
1852 return ReplaceInstUsesWith(I,
1853 ConstantIntegral::getAllOnesValue(I.getType()));
1854
Chris Lattnerbb74e222003-03-10 23:06:50 +00001855 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001856 if (X == Op0)
1857 return ReplaceInstUsesWith(I,
1858 ConstantIntegral::getAllOnesValue(I.getType()));
1859
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001860 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00001861 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001862 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1863 cast<BinaryOperator>(Op1I)->swapOperands();
1864 I.swapOperands();
1865 std::swap(Op0, Op1);
1866 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1867 I.swapOperands();
1868 std::swap(Op0, Op1);
Chris Lattnerb36d9082004-02-16 03:54:20 +00001869 }
1870 } else if (Op1I->getOpcode() == Instruction::Xor) {
1871 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
1872 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1873 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
1874 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1875 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001876
1877 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001878 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001879 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1880 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001881 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00001882 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1883 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001884 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001885 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00001886 } else if (Op0I->getOpcode() == Instruction::Xor) {
1887 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
1888 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1889 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
1890 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001891 }
1892
Chris Lattner7aa2d472004-08-01 19:42:59 +00001893 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001894 Value *A, *B; ConstantInt *C1, *C2;
1895 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1896 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00001897 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00001898 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00001899
Chris Lattner3ac7c262003-08-13 20:16:26 +00001900 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1901 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1902 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1903 return R;
1904
Chris Lattner113f4f42002-06-25 16:13:24 +00001905 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001906}
1907
Chris Lattner6862fbd2004-09-29 17:40:11 +00001908/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
1909/// overflowed for this type.
1910static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1911 ConstantInt *In2) {
1912 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
1913 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
1914}
1915
1916static bool isPositive(ConstantInt *C) {
1917 return cast<ConstantSInt>(C)->getValue() >= 0;
1918}
1919
1920/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
1921/// overflowed for this type.
1922static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1923 ConstantInt *In2) {
1924 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
1925
1926 if (In1->getType()->isUnsigned())
1927 return cast<ConstantUInt>(Result)->getValue() <
1928 cast<ConstantUInt>(In1)->getValue();
1929 if (isPositive(In1) != isPositive(In2))
1930 return false;
1931 if (isPositive(In1))
1932 return cast<ConstantSInt>(Result)->getValue() <
1933 cast<ConstantSInt>(In1)->getValue();
1934 return cast<ConstantSInt>(Result)->getValue() >
1935 cast<ConstantSInt>(In1)->getValue();
1936}
1937
Chris Lattner113f4f42002-06-25 16:13:24 +00001938Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001939 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001940 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1941 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001942
1943 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001944 if (Op0 == Op1)
1945 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00001946
Chris Lattner81a7a232004-10-16 18:11:37 +00001947 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
1948 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
1949
Chris Lattner15ff1e12004-11-14 07:33:16 +00001950 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
1951 // addresses never equal each other! We already know that Op0 != Op1.
1952 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
1953 isa<ConstantPointerNull>(Op0)) &&
1954 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
1955 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001956 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1957
1958 // setcc's with boolean values can always be turned into bitwise operations
1959 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00001960 switch (I.getOpcode()) {
1961 default: assert(0 && "Invalid setcc instruction!");
1962 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001963 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001964 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00001965 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001966 }
Chris Lattner4456da62004-08-11 00:50:51 +00001967 case Instruction::SetNE:
1968 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001969
Chris Lattner4456da62004-08-11 00:50:51 +00001970 case Instruction::SetGT:
1971 std::swap(Op0, Op1); // Change setgt -> setlt
1972 // FALL THROUGH
1973 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
1974 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1975 InsertNewInstBefore(Not, I);
1976 return BinaryOperator::createAnd(Not, Op1);
1977 }
1978 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001979 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00001980 // FALL THROUGH
1981 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
1982 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1983 InsertNewInstBefore(Not, I);
1984 return BinaryOperator::createOr(Not, Op1);
1985 }
1986 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001987 }
1988
Chris Lattner2dd01742004-06-09 04:24:29 +00001989 // See if we are doing a comparison between a constant and an instruction that
1990 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001991 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00001992 // Check to see if we are comparing against the minimum or maximum value...
1993 if (CI->isMinValue()) {
1994 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1995 return ReplaceInstUsesWith(I, ConstantBool::False);
1996 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1997 return ReplaceInstUsesWith(I, ConstantBool::True);
1998 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
1999 return BinaryOperator::createSetEQ(Op0, Op1);
2000 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2001 return BinaryOperator::createSetNE(Op0, Op1);
2002
2003 } else if (CI->isMaxValue()) {
2004 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2005 return ReplaceInstUsesWith(I, ConstantBool::False);
2006 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2007 return ReplaceInstUsesWith(I, ConstantBool::True);
2008 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2009 return BinaryOperator::createSetEQ(Op0, Op1);
2010 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2011 return BinaryOperator::createSetNE(Op0, Op1);
2012
2013 // Comparing against a value really close to min or max?
2014 } else if (isMinValuePlusOne(CI)) {
2015 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2016 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2017 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2018 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2019
2020 } else if (isMaxValueMinusOne(CI)) {
2021 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2022 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2023 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2024 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2025 }
2026
2027 // If we still have a setle or setge instruction, turn it into the
2028 // appropriate setlt or setgt instruction. Since the border cases have
2029 // already been handled above, this requires little checking.
2030 //
2031 if (I.getOpcode() == Instruction::SetLE)
2032 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2033 if (I.getOpcode() == Instruction::SetGE)
2034 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2035
Chris Lattnere1e10e12004-05-25 06:32:08 +00002036 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002037 switch (LHSI->getOpcode()) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002038 case Instruction::PHI:
2039 if (Instruction *NV = FoldOpIntoPhi(I))
2040 return NV;
2041 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002042 case Instruction::And:
2043 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2044 LHSI->getOperand(0)->hasOneUse()) {
2045 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2046 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2047 // happens a LOT in code produced by the C front-end, for bitfield
2048 // access.
2049 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2050 ConstantUInt *ShAmt;
2051 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2052 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2053 const Type *Ty = LHSI->getType();
2054
2055 // We can fold this as long as we can't shift unknown bits
2056 // into the mask. This can only happen with signed shift
2057 // rights, as they sign-extend.
2058 if (ShAmt) {
2059 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00002060 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002061 if (!CanFold) {
2062 // To test for the bad case of the signed shr, see if any
2063 // of the bits shifted in could be tested after the mask.
2064 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd8f5e2c2004-07-21 20:14:10 +00002065 Ty->getPrimitiveSize()*8-ShAmt->getValue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002066 Constant *ShVal =
2067 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2068 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2069 CanFold = true;
2070 }
2071
2072 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00002073 Constant *NewCst;
2074 if (Shift->getOpcode() == Instruction::Shl)
2075 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2076 else
2077 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002078
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002079 // Check to see if we are shifting out any of the bits being
2080 // compared.
2081 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2082 // If we shifted bits out, the fold is not going to work out.
2083 // As a special case, check to see if this means that the
2084 // result is always true or false now.
2085 if (I.getOpcode() == Instruction::SetEQ)
2086 return ReplaceInstUsesWith(I, ConstantBool::False);
2087 if (I.getOpcode() == Instruction::SetNE)
2088 return ReplaceInstUsesWith(I, ConstantBool::True);
2089 } else {
2090 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00002091 Constant *NewAndCST;
2092 if (Shift->getOpcode() == Instruction::Shl)
2093 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2094 else
2095 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2096 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002097 LHSI->setOperand(0, Shift->getOperand(0));
2098 WorkList.push_back(Shift); // Shift is dead.
2099 AddUsesToWorkList(I);
2100 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00002101 }
2102 }
Chris Lattner35167c32004-06-09 07:59:58 +00002103 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002104 }
2105 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002106
Reid Spencer279fa252004-11-28 21:31:15 +00002107 // (setcc (cast X to larger), CI)
2108 case Instruction::Cast: {
2109 Instruction* replacement =
2110 visitSetCondInstWithCastAndConstant(I,cast<CastInst>(LHSI),CI);
2111 if (replacement)
2112 return replacement;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002113 break;
2114 }
Reid Spencer279fa252004-11-28 21:31:15 +00002115
Chris Lattner272d5ca2004-09-28 18:22:15 +00002116 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2117 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2118 switch (I.getOpcode()) {
2119 default: break;
2120 case Instruction::SetEQ:
2121 case Instruction::SetNE: {
2122 // If we are comparing against bits always shifted out, the
2123 // comparison cannot succeed.
2124 Constant *Comp =
2125 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2126 if (Comp != CI) {// Comparing against a bit that we know is zero.
2127 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2128 Constant *Cst = ConstantBool::get(IsSetNE);
2129 return ReplaceInstUsesWith(I, Cst);
2130 }
2131
2132 if (LHSI->hasOneUse()) {
2133 // Otherwise strength reduce the shift into an and.
2134 unsigned ShAmtVal = ShAmt->getValue();
2135 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2136 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2137
2138 Constant *Mask;
2139 if (CI->getType()->isUnsigned()) {
2140 Mask = ConstantUInt::get(CI->getType(), Val);
2141 } else if (ShAmtVal != 0) {
2142 Mask = ConstantSInt::get(CI->getType(), Val);
2143 } else {
2144 Mask = ConstantInt::getAllOnesValue(CI->getType());
2145 }
2146
2147 Instruction *AndI =
2148 BinaryOperator::createAnd(LHSI->getOperand(0),
2149 Mask, LHSI->getName()+".mask");
2150 Value *And = InsertNewInstBefore(AndI, I);
2151 return new SetCondInst(I.getOpcode(), And,
2152 ConstantExpr::getUShr(CI, ShAmt));
2153 }
2154 }
2155 }
2156 }
2157 break;
2158
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002159 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00002160 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00002161 switch (I.getOpcode()) {
2162 default: break;
2163 case Instruction::SetEQ:
2164 case Instruction::SetNE: {
2165 // If we are comparing against bits always shifted out, the
2166 // comparison cannot succeed.
2167 Constant *Comp =
2168 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2169
2170 if (Comp != CI) {// Comparing against a bit that we know is zero.
2171 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2172 Constant *Cst = ConstantBool::get(IsSetNE);
2173 return ReplaceInstUsesWith(I, Cst);
2174 }
2175
2176 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00002177 unsigned ShAmtVal = ShAmt->getValue();
2178
Chris Lattner1023b872004-09-27 16:18:50 +00002179 // Otherwise strength reduce the shift into an and.
2180 uint64_t Val = ~0ULL; // All ones.
2181 Val <<= ShAmtVal; // Shift over to the right spot.
2182
2183 Constant *Mask;
2184 if (CI->getType()->isUnsigned()) {
2185 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2186 Val &= (1ULL << TypeBits)-1;
2187 Mask = ConstantUInt::get(CI->getType(), Val);
2188 } else {
2189 Mask = ConstantSInt::get(CI->getType(), Val);
2190 }
2191
2192 Instruction *AndI =
2193 BinaryOperator::createAnd(LHSI->getOperand(0),
2194 Mask, LHSI->getName()+".mask");
2195 Value *And = InsertNewInstBefore(AndI, I);
2196 return new SetCondInst(I.getOpcode(), And,
2197 ConstantExpr::getShl(CI, ShAmt));
2198 }
2199 break;
2200 }
2201 }
2202 }
2203 break;
Chris Lattner7e794272004-09-24 15:21:34 +00002204
Chris Lattner6862fbd2004-09-29 17:40:11 +00002205 case Instruction::Div:
2206 // Fold: (div X, C1) op C2 -> range check
2207 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2208 // Fold this div into the comparison, producing a range check.
2209 // Determine, based on the divide type, what the range is being
2210 // checked. If there is an overflow on the low or high side, remember
2211 // it, otherwise compute the range [low, hi) bounding the new value.
2212 bool LoOverflow = false, HiOverflow = 0;
2213 ConstantInt *LoBound = 0, *HiBound = 0;
2214
2215 ConstantInt *Prod;
2216 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2217
Chris Lattnera92af962004-10-11 19:40:04 +00002218 Instruction::BinaryOps Opcode = I.getOpcode();
2219
Chris Lattner6862fbd2004-09-29 17:40:11 +00002220 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2221 } else if (LHSI->getType()->isUnsigned()) { // udiv
2222 LoBound = Prod;
2223 LoOverflow = ProdOV;
2224 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2225 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2226 if (CI->isNullValue()) { // (X / pos) op 0
2227 // Can't overflow.
2228 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2229 HiBound = DivRHS;
2230 } else if (isPositive(CI)) { // (X / pos) op pos
2231 LoBound = Prod;
2232 LoOverflow = ProdOV;
2233 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2234 } else { // (X / pos) op neg
2235 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2236 LoOverflow = AddWithOverflow(LoBound, Prod,
2237 cast<ConstantInt>(DivRHSH));
2238 HiBound = Prod;
2239 HiOverflow = ProdOV;
2240 }
2241 } else { // Divisor is < 0.
2242 if (CI->isNullValue()) { // (X / neg) op 0
2243 LoBound = AddOne(DivRHS);
2244 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2245 } else if (isPositive(CI)) { // (X / neg) op pos
2246 HiOverflow = LoOverflow = ProdOV;
2247 if (!LoOverflow)
2248 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2249 HiBound = AddOne(Prod);
2250 } else { // (X / neg) op neg
2251 LoBound = Prod;
2252 LoOverflow = HiOverflow = ProdOV;
2253 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2254 }
Chris Lattner0b41e862004-10-08 19:15:44 +00002255
Chris Lattnera92af962004-10-11 19:40:04 +00002256 // Dividing by a negate swaps the condition.
2257 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002258 }
2259
2260 if (LoBound) {
2261 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00002262 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002263 default: assert(0 && "Unhandled setcc opcode!");
2264 case Instruction::SetEQ:
2265 if (LoOverflow && HiOverflow)
2266 return ReplaceInstUsesWith(I, ConstantBool::False);
2267 else if (HiOverflow)
2268 return new SetCondInst(Instruction::SetGE, X, LoBound);
2269 else if (LoOverflow)
2270 return new SetCondInst(Instruction::SetLT, X, HiBound);
2271 else
2272 return InsertRangeTest(X, LoBound, HiBound, true, I);
2273 case Instruction::SetNE:
2274 if (LoOverflow && HiOverflow)
2275 return ReplaceInstUsesWith(I, ConstantBool::True);
2276 else if (HiOverflow)
2277 return new SetCondInst(Instruction::SetLT, X, LoBound);
2278 else if (LoOverflow)
2279 return new SetCondInst(Instruction::SetGE, X, HiBound);
2280 else
2281 return InsertRangeTest(X, LoBound, HiBound, false, I);
2282 case Instruction::SetLT:
2283 if (LoOverflow)
2284 return ReplaceInstUsesWith(I, ConstantBool::False);
2285 return new SetCondInst(Instruction::SetLT, X, LoBound);
2286 case Instruction::SetGT:
2287 if (HiOverflow)
2288 return ReplaceInstUsesWith(I, ConstantBool::False);
2289 return new SetCondInst(Instruction::SetGE, X, HiBound);
2290 }
2291 }
2292 }
2293 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002294 case Instruction::Select:
2295 // If either operand of the select is a constant, we can fold the
2296 // comparison into the select arms, which will cause one to be
2297 // constant folded and the select turned into a bitwise or.
2298 Value *Op1 = 0, *Op2 = 0;
2299 if (LHSI->hasOneUse()) {
Chris Lattner35167c32004-06-09 07:59:58 +00002300 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002301 // Fold the known value into the constant operand.
2302 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
2303 // Insert a new SetCC of the other select operand.
2304 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002305 LHSI->getOperand(2), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002306 I.getName()), I);
Chris Lattner35167c32004-06-09 07:59:58 +00002307 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002308 // Fold the known value into the constant operand.
2309 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
2310 // Insert a new SetCC of the other select operand.
2311 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002312 LHSI->getOperand(1), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002313 I.getName()), I);
2314 }
Chris Lattner2dd01742004-06-09 04:24:29 +00002315 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002316
2317 if (Op1)
2318 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2319 break;
2320 }
2321
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002322 // Simplify seteq and setne instructions...
2323 if (I.getOpcode() == Instruction::SetEQ ||
2324 I.getOpcode() == Instruction::SetNE) {
2325 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2326
Chris Lattnercfbce7c2003-07-23 17:26:36 +00002327 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002328 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00002329 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2330 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00002331 case Instruction::Rem:
2332 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2333 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2334 BO->hasOneUse() &&
2335 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2336 if (unsigned L2 =
2337 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2338 const Type *UTy = BO->getType()->getUnsignedVersion();
2339 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2340 UTy, "tmp"), I);
2341 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2342 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2343 RHSCst, BO->getName()), I);
2344 return BinaryOperator::create(I.getOpcode(), NewRem,
2345 Constant::getNullValue(UTy));
2346 }
2347 break;
2348
Chris Lattnerc992add2003-08-13 05:33:12 +00002349 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00002350 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2351 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00002352 if (BO->hasOneUse())
2353 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2354 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00002355 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002356 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2357 // efficiently invertible, or if the add has just this one use.
2358 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner6e079362004-06-27 22:51:36 +00002359
Chris Lattnerc992add2003-08-13 05:33:12 +00002360 if (Value *NegVal = dyn_castNegVal(BOp1))
2361 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2362 else if (Value *NegVal = dyn_castNegVal(BOp0))
2363 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002364 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002365 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2366 BO->setName("");
2367 InsertNewInstBefore(Neg, I);
2368 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2369 }
2370 }
2371 break;
2372 case Instruction::Xor:
2373 // For the xor case, we can xor two constants together, eliminating
2374 // the explicit xor.
2375 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2376 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002377 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00002378
2379 // FALLTHROUGH
2380 case Instruction::Sub:
2381 // Replace (([sub|xor] A, B) != 0) with (A != B)
2382 if (CI->isNullValue())
2383 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2384 BO->getOperand(1));
2385 break;
2386
2387 case Instruction::Or:
2388 // If bits are being or'd in that are not present in the constant we
2389 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002390 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002391 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002392 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002393 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002394 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002395 break;
2396
2397 case Instruction::And:
2398 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002399 // If bits are being compared against that are and'd out, then the
2400 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002401 if (!ConstantExpr::getAnd(CI,
2402 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002403 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00002404
Chris Lattner35167c32004-06-09 07:59:58 +00002405 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00002406 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00002407 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2408 Instruction::SetNE, Op0,
2409 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00002410
Chris Lattnerc992add2003-08-13 05:33:12 +00002411 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2412 // to be a signed value as appropriate.
2413 if (isSignBit(BOC)) {
2414 Value *X = BO->getOperand(0);
2415 // If 'X' is not signed, insert a cast now...
2416 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002417 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002418 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00002419 }
2420 return new SetCondInst(isSetNE ? Instruction::SetLT :
2421 Instruction::SetGE, X,
2422 Constant::getNullValue(X->getType()));
2423 }
Chris Lattner8fc5af42004-09-23 21:46:38 +00002424
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002425 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00002426 if (CI->isNullValue() && isHighOnes(BOC)) {
2427 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002428 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002429
2430 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002431 if (NegX->getType()->isSigned()) {
2432 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2433 X = InsertCastBefore(X, DestTy, I);
2434 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002435 }
2436
2437 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002438 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002439 }
2440
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002441 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002442 default: break;
2443 }
2444 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00002445 } else { // Not a SetEQ/SetNE
2446 // If the LHS is a cast from an integral value of the same size,
2447 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2448 Value *CastOp = Cast->getOperand(0);
2449 const Type *SrcTy = CastOp->getType();
2450 unsigned SrcTySize = SrcTy->getPrimitiveSize();
2451 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2452 SrcTySize == Cast->getType()->getPrimitiveSize()) {
2453 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
2454 "Source and destination signednesses should differ!");
2455 if (Cast->getType()->isSigned()) {
2456 // If this is a signed comparison, check for comparisons in the
2457 // vicinity of zero.
2458 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2459 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002460 return BinaryOperator::createSetGT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002461 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2462 else if (I.getOpcode() == Instruction::SetGT &&
2463 cast<ConstantSInt>(CI)->getValue() == -1)
2464 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002465 return BinaryOperator::createSetLT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002466 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2467 } else {
2468 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2469 if (I.getOpcode() == Instruction::SetLT &&
2470 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2471 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002472 return BinaryOperator::createSetGT(CastOp,
2473 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002474 else if (I.getOpcode() == Instruction::SetGT &&
2475 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2476 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002477 return BinaryOperator::createSetLT(CastOp,
2478 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002479 }
2480 }
2481 }
Chris Lattnere967b342003-06-04 05:10:11 +00002482 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002483 }
2484
Chris Lattner16930792003-11-03 04:25:02 +00002485 // Test to see if the operands of the setcc are casted versions of other
2486 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00002487 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2488 Value *CastOp0 = CI->getOperand(0);
2489 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00002490 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00002491 (I.getOpcode() == Instruction::SetEQ ||
2492 I.getOpcode() == Instruction::SetNE)) {
2493 // We keep moving the cast from the left operand over to the right
2494 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00002495 Op0 = CastOp0;
Chris Lattner16930792003-11-03 04:25:02 +00002496
2497 // If operand #1 is a cast instruction, see if we can eliminate it as
2498 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00002499 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2500 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00002501 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00002502 Op1 = CI2->getOperand(0);
Chris Lattner16930792003-11-03 04:25:02 +00002503
2504 // If Op1 is a constant, we can fold the cast into the constant.
2505 if (Op1->getType() != Op0->getType())
2506 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2507 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2508 } else {
2509 // Otherwise, cast the RHS right before the setcc
2510 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2511 InsertNewInstBefore(cast<Instruction>(Op1), I);
2512 }
2513 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2514 }
2515
Chris Lattner6444c372003-11-03 05:17:03 +00002516 // Handle the special case of: setcc (cast bool to X), <cst>
2517 // This comes up when you have code like
2518 // int X = A < B;
2519 // if (X) ...
2520 // For generality, we handle any zero-extension of any operand comparison
2521 // with a constant.
2522 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2523 const Type *SrcTy = CastOp0->getType();
2524 const Type *DestTy = Op0->getType();
2525 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2526 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2527 // Ok, we have an expansion of operand 0 into a new type. Get the
2528 // constant value, masink off bits which are not set in the RHS. These
2529 // could be set if the destination value is signed.
2530 uint64_t ConstVal = ConstantRHS->getRawValue();
2531 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2532
2533 // If the constant we are comparing it with has high bits set, which
2534 // don't exist in the original value, the values could never be equal,
2535 // because the source would be zero extended.
2536 unsigned SrcBits =
2537 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner7c94d112003-11-05 17:31:36 +00002538 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2539 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner6444c372003-11-03 05:17:03 +00002540 switch (I.getOpcode()) {
2541 default: assert(0 && "Unknown comparison type!");
2542 case Instruction::SetEQ:
2543 return ReplaceInstUsesWith(I, ConstantBool::False);
2544 case Instruction::SetNE:
2545 return ReplaceInstUsesWith(I, ConstantBool::True);
2546 case Instruction::SetLT:
2547 case Instruction::SetLE:
2548 if (DestTy->isSigned() && HasSignBit)
2549 return ReplaceInstUsesWith(I, ConstantBool::False);
2550 return ReplaceInstUsesWith(I, ConstantBool::True);
2551 case Instruction::SetGT:
2552 case Instruction::SetGE:
2553 if (DestTy->isSigned() && HasSignBit)
2554 return ReplaceInstUsesWith(I, ConstantBool::True);
2555 return ReplaceInstUsesWith(I, ConstantBool::False);
2556 }
2557 }
2558
2559 // Otherwise, we can replace the setcc with a setcc of the smaller
2560 // operand value.
2561 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2562 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2563 }
2564 }
2565 }
Chris Lattner113f4f42002-06-25 16:13:24 +00002566 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002567}
2568
Reid Spencer279fa252004-11-28 21:31:15 +00002569// visitSetCondInstWithCastAndConstant - this method is part of the
2570// visitSetCondInst method. It handles the situation where we have:
2571// (setcc (cast X to larger), CI)
2572// It tries to remove the cast and even the setcc if the CI value
2573// and range of the cast allow it.
2574Instruction *
2575InstCombiner::visitSetCondInstWithCastAndConstant(BinaryOperator&I,
2576 CastInst* LHSI,
2577 ConstantInt* CI) {
2578 const Type *SrcTy = LHSI->getOperand(0)->getType();
2579 const Type *DestTy = LHSI->getType();
2580 if (SrcTy->isIntegral() && DestTy->isIntegral()) {
2581 unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
2582 unsigned DestBits = DestTy->getPrimitiveSize()*8;
2583 if (SrcTy == Type::BoolTy)
2584 SrcBits = 1;
2585 if (DestTy == Type::BoolTy)
2586 DestBits = 1;
2587 if (SrcBits < DestBits) {
2588 // There are fewer bits in the source of the cast than in the result
2589 // of the cast. Any other case doesn't matter because the constant
2590 // value won't have changed due to sign extension.
2591 Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
2592 if (ConstantExpr::getCast(NewCst, DestTy) == CI) {
2593 // The constant value operand of the setCC before and after a
2594 // cast to the source type of the cast instruction is the same
2595 // value, so we just replace with the same setcc opcode, but
2596 // using the source value compared to the constant casted to the
2597 // source type.
2598 if (SrcTy->isSigned() && DestTy->isUnsigned()) {
2599 CastInst* Cst = new CastInst(LHSI->getOperand(0),
2600 SrcTy->getUnsignedVersion(), LHSI->getName());
2601 InsertNewInstBefore(Cst,I);
2602 return new SetCondInst(I.getOpcode(), Cst,
2603 ConstantExpr::getCast(CI, SrcTy->getUnsignedVersion()));
2604 }
2605 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),NewCst);
2606 }
2607 // The constant value before and after a cast to the source type
2608 // is different, so various cases are possible depending on the
2609 // opcode and the signs of the types involved in the cast.
2610 switch (I.getOpcode()) {
2611 case Instruction::SetLT: {
2612 Constant* Max = ConstantIntegral::getMaxValue(SrcTy);
2613 Max = ConstantExpr::getCast(Max, DestTy);
2614 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
2615 }
2616 case Instruction::SetGT: {
2617 Constant* Min = ConstantIntegral::getMinValue(SrcTy);
2618 Min = ConstantExpr::getCast(Min, DestTy);
2619 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
2620 }
2621 case Instruction::SetEQ:
2622 // We're looking for equality, and we know the values are not
2623 // equal so replace with constant False.
2624 return ReplaceInstUsesWith(I, ConstantBool::False);
2625 case Instruction::SetNE:
2626 // We're testing for inequality, and we know the values are not
2627 // equal so replace with constant True.
2628 return ReplaceInstUsesWith(I, ConstantBool::True);
2629 case Instruction::SetLE:
2630 case Instruction::SetGE:
2631 assert(!"SetLE and SetGE should be handled elsewhere");
2632 default:
2633 assert(!"unknown integer comparison");
2634 }
2635 }
2636 }
2637 return 0;
2638}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002639
2640
Chris Lattnere8d6c602003-03-10 19:16:08 +00002641Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002642 assert(I.getOperand(1)->getType() == Type::UByteTy);
2643 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002644 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002645
2646 // shl X, 0 == X and shr X, 0 == X
2647 // shl 0, X == 0 and shr 0, X == 0
2648 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00002649 Op0 == Constant::getNullValue(Op0->getType()))
2650 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002651
Chris Lattner81a7a232004-10-16 18:11:37 +00002652 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
2653 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00002654 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00002655 else // undef << X -> 0 AND undef >>u X -> 0
2656 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2657 }
2658 if (isa<UndefValue>(Op1)) {
2659 if (isLeftShift || I.getType()->isUnsigned())
2660 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2661 else
2662 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
2663 }
2664
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002665 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
2666 if (!isLeftShift)
2667 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
2668 if (CSI->isAllOnesValue())
2669 return ReplaceInstUsesWith(I, CSI);
2670
Chris Lattner183b3362004-04-09 19:05:30 +00002671 // Try to fold constant and into select arguments.
2672 if (isa<Constant>(Op0))
2673 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2674 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2675 return R;
2676
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002677 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002678 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
2679 // of a signed value.
2680 //
Chris Lattnere8d6c602003-03-10 19:16:08 +00002681 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00002682 if (CUI->getValue() >= TypeBits) {
2683 if (!Op0->getType()->isSigned() || isLeftShift)
2684 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
2685 else {
2686 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
2687 return &I;
2688 }
2689 }
Chris Lattner55f3d942002-09-10 23:04:09 +00002690
Chris Lattnerede3fe02003-08-13 04:18:28 +00002691 // ((X*C1) << C2) == (X * (C1 << C2))
2692 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
2693 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
2694 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002695 return BinaryOperator::createMul(BO->getOperand(0),
2696 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnerede3fe02003-08-13 04:18:28 +00002697
Chris Lattner183b3362004-04-09 19:05:30 +00002698 // Try to fold constant and into select arguments.
2699 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2700 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2701 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002702 if (isa<PHINode>(Op0))
2703 if (Instruction *NV = FoldOpIntoPhi(I))
2704 return NV;
Chris Lattnerede3fe02003-08-13 04:18:28 +00002705
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002706 // If the operand is an bitwise operator with a constant RHS, and the
2707 // shift is the only use, we can pull it out of the shift.
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002708 if (Op0->hasOneUse())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002709 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
2710 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
2711 bool isValid = true; // Valid only for And, Or, Xor
2712 bool highBitSet = false; // Transform if high bit of constant set?
2713
2714 switch (Op0BO->getOpcode()) {
2715 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00002716 case Instruction::Add:
2717 isValid = isLeftShift;
2718 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002719 case Instruction::Or:
2720 case Instruction::Xor:
2721 highBitSet = false;
2722 break;
2723 case Instruction::And:
2724 highBitSet = true;
2725 break;
2726 }
2727
2728 // If this is a signed shift right, and the high bit is modified
2729 // by the logical operation, do not perform the transformation.
2730 // The highBitSet boolean indicates the value of the high bit of
2731 // the constant which would cause it to be modified for this
2732 // operation.
2733 //
2734 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
2735 uint64_t Val = Op0C->getRawValue();
2736 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
2737 }
2738
2739 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002740 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002741
2742 Instruction *NewShift =
2743 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
2744 Op0BO->getName());
2745 Op0BO->setName("");
2746 InsertNewInstBefore(NewShift, I);
2747
2748 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
2749 NewRHS);
2750 }
2751 }
2752
Chris Lattner3204d4e2003-07-24 17:52:58 +00002753 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002754 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00002755 if (ConstantUInt *ShiftAmt1C =
2756 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002757 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
2758 unsigned ShiftAmt2 = CUI->getValue();
2759
2760 // Check for (A << c1) << c2 and (A >> c1) >> c2
2761 if (I.getOpcode() == Op0SI->getOpcode()) {
2762 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerf5ce2542004-02-23 20:30:06 +00002763 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
2764 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner3204d4e2003-07-24 17:52:58 +00002765 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
2766 ConstantUInt::get(Type::UByteTy, Amt));
2767 }
2768
Chris Lattnerab780df2003-07-24 18:38:56 +00002769 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
2770 // signed types, we can only support the (A >> c1) << c2 configuration,
2771 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002772 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002773 // Calculate bitmask for what gets shifted off the edge...
2774 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002775 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002776 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002777 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002778 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +00002779
2780 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002781 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
2782 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00002783 InsertNewInstBefore(Mask, I);
2784
2785 // Figure out what flavor of shift we should use...
2786 if (ShiftAmt1 == ShiftAmt2)
2787 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
2788 else if (ShiftAmt1 < ShiftAmt2) {
2789 return new ShiftInst(I.getOpcode(), Mask,
2790 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
2791 } else {
2792 return new ShiftInst(Op0SI->getOpcode(), Mask,
2793 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
2794 }
2795 }
2796 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002797 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00002798
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002799 return 0;
2800}
2801
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002802enum CastType {
2803 Noop = 0,
2804 Truncate = 1,
2805 Signext = 2,
2806 Zeroext = 3
2807};
2808
2809/// getCastType - In the future, we will split the cast instruction into these
2810/// various types. Until then, we have to do the analysis here.
2811static CastType getCastType(const Type *Src, const Type *Dest) {
2812 assert(Src->isIntegral() && Dest->isIntegral() &&
2813 "Only works on integral types!");
2814 unsigned SrcSize = Src->getPrimitiveSize()*8;
2815 if (Src == Type::BoolTy) SrcSize = 1;
2816 unsigned DestSize = Dest->getPrimitiveSize()*8;
2817 if (Dest == Type::BoolTy) DestSize = 1;
2818
2819 if (SrcSize == DestSize) return Noop;
2820 if (SrcSize > DestSize) return Truncate;
2821 if (Src->isSigned()) return Signext;
2822 return Zeroext;
2823}
2824
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002825
Chris Lattner48a44f72002-05-02 17:06:02 +00002826// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
2827// instruction.
2828//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002829static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00002830 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002831
Chris Lattner650b6da2002-08-02 20:00:25 +00002832 // It is legal to eliminate the instruction if casting A->B->A if the sizes
2833 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00002834 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00002835 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00002836 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00002837
Chris Lattner4fbad962004-07-21 04:27:24 +00002838 // If we are casting between pointer and integer types, treat pointers as
2839 // integers of the appropriate size for the code below.
2840 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
2841 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
2842 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00002843
Chris Lattner48a44f72002-05-02 17:06:02 +00002844 // Allow free casting and conversion of sizes as long as the sign doesn't
2845 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002846 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002847 CastType FirstCast = getCastType(SrcTy, MidTy);
2848 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00002849
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002850 // Capture the effect of these two casts. If the result is a legal cast,
2851 // the CastType is stored here, otherwise a special code is used.
2852 static const unsigned CastResult[] = {
2853 // First cast is noop
2854 0, 1, 2, 3,
2855 // First cast is a truncate
2856 1, 1, 4, 4, // trunc->extend is not safe to eliminate
2857 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00002858 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002859 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00002860 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002861 };
2862
2863 unsigned Result = CastResult[FirstCast*4+SecondCast];
2864 switch (Result) {
2865 default: assert(0 && "Illegal table value!");
2866 case 0:
2867 case 1:
2868 case 2:
2869 case 3:
2870 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
2871 // truncates, we could eliminate more casts.
2872 return (unsigned)getCastType(SrcTy, DstTy) == Result;
2873 case 4:
2874 return false; // Not possible to eliminate this here.
2875 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00002876 // Sign or zero extend followed by truncate is always ok if the result
2877 // is a truncate or noop.
2878 CastType ResultCast = getCastType(SrcTy, DstTy);
2879 if (ResultCast == Noop || ResultCast == Truncate)
2880 return true;
2881 // Otherwise we are still growing the value, we are only safe if the
2882 // result will match the sign/zeroextendness of the result.
2883 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00002884 }
Chris Lattner650b6da2002-08-02 20:00:25 +00002885 }
Chris Lattner48a44f72002-05-02 17:06:02 +00002886 return false;
2887}
2888
Chris Lattner11ffd592004-07-20 05:21:00 +00002889static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002890 if (V->getType() == Ty || isa<Constant>(V)) return false;
2891 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00002892 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
2893 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002894 return false;
2895 return true;
2896}
2897
2898/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
2899/// InsertBefore instruction. This is specialized a bit to avoid inserting
2900/// casts that are known to not do anything...
2901///
2902Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
2903 Instruction *InsertBefore) {
2904 if (V->getType() == DestTy) return V;
2905 if (Constant *C = dyn_cast<Constant>(V))
2906 return ConstantExpr::getCast(C, DestTy);
2907
2908 CastInst *CI = new CastInst(V, DestTy, V->getName());
2909 InsertNewInstBefore(CI, *InsertBefore);
2910 return CI;
2911}
Chris Lattner48a44f72002-05-02 17:06:02 +00002912
2913// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00002914//
Chris Lattner113f4f42002-06-25 16:13:24 +00002915Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00002916 Value *Src = CI.getOperand(0);
2917
Chris Lattner48a44f72002-05-02 17:06:02 +00002918 // If the user is casting a value to the same type, eliminate this cast
2919 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00002920 if (CI.getType() == Src->getType())
2921 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00002922
Chris Lattner81a7a232004-10-16 18:11:37 +00002923 if (isa<UndefValue>(Src)) // cast undef -> undef
2924 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
2925
Chris Lattner48a44f72002-05-02 17:06:02 +00002926 // If casting the result of another cast instruction, try to eliminate this
2927 // one!
2928 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002929 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002930 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
Chris Lattner11ffd592004-07-20 05:21:00 +00002931 CSrc->getType(), CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002932 // This instruction now refers directly to the cast's src operand. This
2933 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00002934 CI.setOperand(0, CSrc->getOperand(0));
2935 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00002936 }
2937
Chris Lattner650b6da2002-08-02 20:00:25 +00002938 // If this is an A->B->A cast, and we are dealing with integral types, try
2939 // to convert this into a logical 'and' instruction.
2940 //
2941 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002942 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +00002943 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2944 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2945 assert(CSrc->getType() != Type::ULongTy &&
2946 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00002947 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +00002948 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002949 return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
Chris Lattner650b6da2002-08-02 20:00:25 +00002950 }
2951 }
2952
Chris Lattner03841652004-05-25 04:29:21 +00002953 // If this is a cast to bool, turn it into the appropriate setne instruction.
2954 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002955 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00002956 Constant::getNullValue(CI.getOperand(0)->getType()));
2957
Chris Lattnerd0d51602003-06-21 23:12:02 +00002958 // If casting the result of a getelementptr instruction with no offset, turn
2959 // this into a cast of the original pointer!
2960 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002961 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00002962 bool AllZeroOperands = true;
2963 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2964 if (!isa<Constant>(GEP->getOperand(i)) ||
2965 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2966 AllZeroOperands = false;
2967 break;
2968 }
2969 if (AllZeroOperands) {
2970 CI.setOperand(0, GEP->getOperand(0));
2971 return &CI;
2972 }
2973 }
2974
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002975 // If we are casting a malloc or alloca to a pointer to a type of the same
2976 // size, rewrite the allocation instruction to allocate the "right" type.
2977 //
2978 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00002979 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002980 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2981 // Get the type really allocated and the type casted to...
2982 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002983 const Type *CastElTy = PTy->getElementType();
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002984 if (AllocElTy->isSized() && CastElTy->isSized()) {
2985 unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2986 unsigned CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00002987
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002988 // If the allocation is for an even multiple of the cast type size
2989 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
2990 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002991 AllocElTySize/CastElTySize);
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002992 std::string Name = AI->getName(); AI->setName("");
2993 AllocationInst *New;
2994 if (isa<MallocInst>(AI))
2995 New = new MallocInst(CastElTy, Amt, Name);
2996 else
2997 New = new AllocaInst(CastElTy, Amt, Name);
2998 InsertNewInstBefore(New, *AI);
2999 return ReplaceInstUsesWith(CI, New);
3000 }
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003001 }
3002 }
3003
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003004 if (isa<PHINode>(Src))
3005 if (Instruction *NV = FoldOpIntoPhi(CI))
3006 return NV;
3007
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003008 // If the source value is an instruction with only this use, we can attempt to
3009 // propagate the cast into the instruction. Also, only handle integral types
3010 // for now.
3011 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003012 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003013 CI.getType()->isInteger()) { // Don't mess with casts to bool here
3014 const Type *DestTy = CI.getType();
3015 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
3016 unsigned DestBitSize = getTypeSizeInBits(DestTy);
3017
3018 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
3019 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
3020
3021 switch (SrcI->getOpcode()) {
3022 case Instruction::Add:
3023 case Instruction::Mul:
3024 case Instruction::And:
3025 case Instruction::Or:
3026 case Instruction::Xor:
3027 // If we are discarding information, or just changing the sign, rewrite.
3028 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
3029 // Don't insert two casts if they cannot be eliminated. We allow two
3030 // casts to be inserted if the sizes are the same. This could only be
3031 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00003032 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
3033 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003034 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3035 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
3036 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
3037 ->getOpcode(), Op0c, Op1c);
3038 }
3039 }
3040 break;
3041 case Instruction::Shl:
3042 // Allow changing the sign of the source operand. Do not allow changing
3043 // the size of the shift, UNLESS the shift amount is a constant. We
3044 // mush not change variable sized shifts to a smaller size, because it
3045 // is undefined to shift more bits out than exist in the value.
3046 if (DestBitSize == SrcBitSize ||
3047 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
3048 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3049 return new ShiftInst(Instruction::Shl, Op0c, Op1);
3050 }
3051 break;
3052 }
3053 }
3054
Chris Lattner260ab202002-04-18 17:39:14 +00003055 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00003056}
3057
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003058/// GetSelectFoldableOperands - We want to turn code that looks like this:
3059/// %C = or %A, %B
3060/// %D = select %cond, %C, %A
3061/// into:
3062/// %C = select %cond, %B, 0
3063/// %D = or %A, %C
3064///
3065/// Assuming that the specified instruction is an operand to the select, return
3066/// a bitmask indicating which operands of this instruction are foldable if they
3067/// equal the other incoming value of the select.
3068///
3069static unsigned GetSelectFoldableOperands(Instruction *I) {
3070 switch (I->getOpcode()) {
3071 case Instruction::Add:
3072 case Instruction::Mul:
3073 case Instruction::And:
3074 case Instruction::Or:
3075 case Instruction::Xor:
3076 return 3; // Can fold through either operand.
3077 case Instruction::Sub: // Can only fold on the amount subtracted.
3078 case Instruction::Shl: // Can only fold on the shift amount.
3079 case Instruction::Shr:
3080 return 1;
3081 default:
3082 return 0; // Cannot fold
3083 }
3084}
3085
3086/// GetSelectFoldableConstant - For the same transformation as the previous
3087/// function, return the identity constant that goes into the select.
3088static Constant *GetSelectFoldableConstant(Instruction *I) {
3089 switch (I->getOpcode()) {
3090 default: assert(0 && "This cannot happen!"); abort();
3091 case Instruction::Add:
3092 case Instruction::Sub:
3093 case Instruction::Or:
3094 case Instruction::Xor:
3095 return Constant::getNullValue(I->getType());
3096 case Instruction::Shl:
3097 case Instruction::Shr:
3098 return Constant::getNullValue(Type::UByteTy);
3099 case Instruction::And:
3100 return ConstantInt::getAllOnesValue(I->getType());
3101 case Instruction::Mul:
3102 return ConstantInt::get(I->getType(), 1);
3103 }
3104}
3105
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003106Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00003107 Value *CondVal = SI.getCondition();
3108 Value *TrueVal = SI.getTrueValue();
3109 Value *FalseVal = SI.getFalseValue();
3110
3111 // select true, X, Y -> X
3112 // select false, X, Y -> Y
3113 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003114 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00003115 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003116 else {
3117 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00003118 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003119 }
Chris Lattner533bc492004-03-30 19:37:13 +00003120
3121 // select C, X, X -> X
3122 if (TrueVal == FalseVal)
3123 return ReplaceInstUsesWith(SI, TrueVal);
3124
Chris Lattner81a7a232004-10-16 18:11:37 +00003125 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3126 return ReplaceInstUsesWith(SI, FalseVal);
3127 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3128 return ReplaceInstUsesWith(SI, TrueVal);
3129 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3130 if (isa<Constant>(TrueVal))
3131 return ReplaceInstUsesWith(SI, TrueVal);
3132 else
3133 return ReplaceInstUsesWith(SI, FalseVal);
3134 }
3135
Chris Lattner1c631e82004-04-08 04:43:23 +00003136 if (SI.getType() == Type::BoolTy)
3137 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
3138 if (C == ConstantBool::True) {
3139 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003140 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003141 } else {
3142 // Change: A = select B, false, C --> A = and !B, C
3143 Value *NotCond =
3144 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3145 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003146 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003147 }
3148 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
3149 if (C == ConstantBool::False) {
3150 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003151 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003152 } else {
3153 // Change: A = select B, C, true --> A = or !B, C
3154 Value *NotCond =
3155 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3156 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003157 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003158 }
3159 }
3160
Chris Lattner183b3362004-04-09 19:05:30 +00003161 // Selecting between two integer constants?
3162 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
3163 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
3164 // select C, 1, 0 -> cast C to int
3165 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
3166 return new CastInst(CondVal, SI.getType());
3167 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
3168 // select C, 0, 1 -> cast !C to int
3169 Value *NotCond =
3170 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00003171 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00003172 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00003173 }
Chris Lattner35167c32004-06-09 07:59:58 +00003174
3175 // If one of the constants is zero (we know they can't both be) and we
3176 // have a setcc instruction with zero, and we have an 'and' with the
3177 // non-constant value, eliminate this whole mess. This corresponds to
3178 // cases like this: ((X & 27) ? 27 : 0)
3179 if (TrueValC->isNullValue() || FalseValC->isNullValue())
3180 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
3181 if ((IC->getOpcode() == Instruction::SetEQ ||
3182 IC->getOpcode() == Instruction::SetNE) &&
3183 isa<ConstantInt>(IC->getOperand(1)) &&
3184 cast<Constant>(IC->getOperand(1))->isNullValue())
3185 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
3186 if (ICA->getOpcode() == Instruction::And &&
3187 isa<ConstantInt>(ICA->getOperand(1)) &&
3188 (ICA->getOperand(1) == TrueValC ||
3189 ICA->getOperand(1) == FalseValC) &&
3190 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
3191 // Okay, now we know that everything is set up, we just don't
3192 // know whether we have a setne or seteq and whether the true or
3193 // false val is the zero.
3194 bool ShouldNotVal = !TrueValC->isNullValue();
3195 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
3196 Value *V = ICA;
3197 if (ShouldNotVal)
3198 V = InsertNewInstBefore(BinaryOperator::create(
3199 Instruction::Xor, V, ICA->getOperand(1)), SI);
3200 return ReplaceInstUsesWith(SI, V);
3201 }
Chris Lattner533bc492004-03-30 19:37:13 +00003202 }
Chris Lattner623fba12004-04-10 22:21:27 +00003203
3204 // See if we are selecting two values based on a comparison of the two values.
3205 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
3206 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
3207 // Transform (X == Y) ? X : Y -> Y
3208 if (SCI->getOpcode() == Instruction::SetEQ)
3209 return ReplaceInstUsesWith(SI, FalseVal);
3210 // Transform (X != Y) ? X : Y -> X
3211 if (SCI->getOpcode() == Instruction::SetNE)
3212 return ReplaceInstUsesWith(SI, TrueVal);
3213 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3214
3215 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
3216 // Transform (X == Y) ? Y : X -> X
3217 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00003218 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003219 // Transform (X != Y) ? Y : X -> Y
3220 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00003221 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003222 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3223 }
3224 }
Chris Lattner1c631e82004-04-08 04:43:23 +00003225
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003226 // See if we can fold the select into one of our operands.
3227 if (SI.getType()->isInteger()) {
3228 // See the comment above GetSelectFoldableOperands for a description of the
3229 // transformation we are doing here.
3230 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
3231 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
3232 !isa<Constant>(FalseVal))
3233 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3234 unsigned OpToFold = 0;
3235 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3236 OpToFold = 1;
3237 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3238 OpToFold = 2;
3239 }
3240
3241 if (OpToFold) {
3242 Constant *C = GetSelectFoldableConstant(TVI);
3243 std::string Name = TVI->getName(); TVI->setName("");
3244 Instruction *NewSel =
3245 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3246 Name);
3247 InsertNewInstBefore(NewSel, SI);
3248 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3249 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3250 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3251 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3252 else {
3253 assert(0 && "Unknown instruction!!");
3254 }
3255 }
3256 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00003257
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003258 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
3259 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
3260 !isa<Constant>(TrueVal))
3261 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
3262 unsigned OpToFold = 0;
3263 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
3264 OpToFold = 1;
3265 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
3266 OpToFold = 2;
3267 }
3268
3269 if (OpToFold) {
3270 Constant *C = GetSelectFoldableConstant(FVI);
3271 std::string Name = FVI->getName(); FVI->setName("");
3272 Instruction *NewSel =
3273 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
3274 Name);
3275 InsertNewInstBefore(NewSel, SI);
3276 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
3277 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
3278 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
3279 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
3280 else {
3281 assert(0 && "Unknown instruction!!");
3282 }
3283 }
3284 }
3285 }
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003286 return 0;
3287}
3288
3289
Chris Lattner970c33a2003-06-19 17:00:31 +00003290// CallInst simplification
3291//
3292Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00003293 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3294 // visitCallSite.
Chris Lattner00648e12004-10-12 04:52:52 +00003295 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
3296 bool Changed = false;
3297
3298 // memmove/cpy/set of zero bytes is a noop.
3299 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
3300 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
3301
3302 // FIXME: Increase alignment here.
3303
3304 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
3305 if (CI->getRawValue() == 1) {
3306 // Replace the instruction with just byte operations. We would
3307 // transform other cases to loads/stores, but we don't know if
3308 // alignment is sufficient.
3309 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003310 }
3311
Chris Lattner00648e12004-10-12 04:52:52 +00003312 // If we have a memmove and the source operation is a constant global,
3313 // then the source and dest pointers can't alias, so we can change this
3314 // into a call to memcpy.
3315 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
3316 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
3317 if (GVSrc->isConstant()) {
3318 Module *M = CI.getParent()->getParent()->getParent();
3319 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
3320 CI.getCalledFunction()->getFunctionType());
3321 CI.setOperand(0, MemCpy);
3322 Changed = true;
3323 }
3324
3325 if (Changed) return &CI;
Chris Lattner95307542004-11-18 21:41:39 +00003326 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(&CI)) {
3327 // If this stoppoint is at the same source location as the previous
3328 // stoppoint in the chain, it is not needed.
3329 if (DbgStopPointInst *PrevSPI =
3330 dyn_cast<DbgStopPointInst>(SPI->getChain()))
3331 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
3332 SPI->getColNo() == PrevSPI->getColNo()) {
3333 SPI->replaceAllUsesWith(PrevSPI);
3334 return EraseInstFromFunction(CI);
3335 }
Chris Lattner00648e12004-10-12 04:52:52 +00003336 }
3337
Chris Lattneraec3d942003-10-07 22:32:43 +00003338 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00003339}
3340
3341// InvokeInst simplification
3342//
3343Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00003344 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00003345}
3346
Chris Lattneraec3d942003-10-07 22:32:43 +00003347// visitCallSite - Improvements for call and invoke instructions.
3348//
3349Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003350 bool Changed = false;
3351
3352 // If the callee is a constexpr cast of a function, attempt to move the cast
3353 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00003354 if (transformConstExprCastCall(CS)) return 0;
3355
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003356 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00003357
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003358 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
3359 // This instruction is not reachable, just remove it. We insert a store to
3360 // undef so that we know that this code is not reachable, despite the fact
3361 // that we can't modify the CFG here.
3362 new StoreInst(ConstantBool::True,
3363 UndefValue::get(PointerType::get(Type::BoolTy)),
3364 CS.getInstruction());
3365
3366 if (!CS.getInstruction()->use_empty())
3367 CS.getInstruction()->
3368 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
3369
3370 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
3371 // Don't break the CFG, insert a dummy cond branch.
3372 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
3373 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00003374 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003375 return EraseInstFromFunction(*CS.getInstruction());
3376 }
Chris Lattner81a7a232004-10-16 18:11:37 +00003377
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003378 const PointerType *PTy = cast<PointerType>(Callee->getType());
3379 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3380 if (FTy->isVarArg()) {
3381 // See if we can optimize any arguments passed through the varargs area of
3382 // the call.
3383 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
3384 E = CS.arg_end(); I != E; ++I)
3385 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
3386 // If this cast does not effect the value passed through the varargs
3387 // area, we can eliminate the use of the cast.
3388 Value *Op = CI->getOperand(0);
3389 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
3390 *I = Op;
3391 Changed = true;
3392 }
3393 }
3394 }
Chris Lattneraec3d942003-10-07 22:32:43 +00003395
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003396 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00003397}
3398
Chris Lattner970c33a2003-06-19 17:00:31 +00003399// transformConstExprCastCall - If the callee is a constexpr cast of a function,
3400// attempt to move the cast to the arguments of the call/invoke.
3401//
3402bool InstCombiner::transformConstExprCastCall(CallSite CS) {
3403 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
3404 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00003405 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00003406 return false;
Reid Spencer87436872004-07-18 00:38:32 +00003407 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00003408 Instruction *Caller = CS.getInstruction();
3409
3410 // Okay, this is a cast from a function to a different type. Unless doing so
3411 // would cause a type conversion of one of our arguments, change this call to
3412 // be a direct call with arguments casted to the appropriate types.
3413 //
3414 const FunctionType *FT = Callee->getFunctionType();
3415 const Type *OldRetTy = Caller->getType();
3416
Chris Lattner1f7942f2004-01-14 06:06:08 +00003417 // Check to see if we are changing the return type...
3418 if (OldRetTy != FT->getReturnType()) {
3419 if (Callee->isExternal() &&
3420 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
3421 !Caller->use_empty())
3422 return false; // Cannot transform this return value...
3423
3424 // If the callsite is an invoke instruction, and the return value is used by
3425 // a PHI node in a successor, we cannot change the return type of the call
3426 // because there is no place to put the cast instruction (without breaking
3427 // the critical edge). Bail out in this case.
3428 if (!Caller->use_empty())
3429 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
3430 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
3431 UI != E; ++UI)
3432 if (PHINode *PN = dyn_cast<PHINode>(*UI))
3433 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003434 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00003435 return false;
3436 }
Chris Lattner970c33a2003-06-19 17:00:31 +00003437
3438 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
3439 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3440
3441 CallSite::arg_iterator AI = CS.arg_begin();
3442 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3443 const Type *ParamTy = FT->getParamType(i);
3444 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
3445 if (Callee->isExternal() && !isConvertible) return false;
3446 }
3447
3448 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
3449 Callee->isExternal())
3450 return false; // Do not delete arguments unless we have a function body...
3451
3452 // Okay, we decided that this is a safe thing to do: go ahead and start
3453 // inserting cast instructions as necessary...
3454 std::vector<Value*> Args;
3455 Args.reserve(NumActualArgs);
3456
3457 AI = CS.arg_begin();
3458 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3459 const Type *ParamTy = FT->getParamType(i);
3460 if ((*AI)->getType() == ParamTy) {
3461 Args.push_back(*AI);
3462 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00003463 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
3464 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00003465 }
3466 }
3467
3468 // If the function takes more arguments than the call was taking, add them
3469 // now...
3470 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
3471 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3472
3473 // If we are removing arguments to the function, emit an obnoxious warning...
3474 if (FT->getNumParams() < NumActualArgs)
3475 if (!FT->isVarArg()) {
3476 std::cerr << "WARNING: While resolving call to function '"
3477 << Callee->getName() << "' arguments were dropped!\n";
3478 } else {
3479 // Add all of the arguments in their promoted form to the arg list...
3480 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3481 const Type *PTy = getPromotedType((*AI)->getType());
3482 if (PTy != (*AI)->getType()) {
3483 // Must promote to pass through va_arg area!
3484 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
3485 InsertNewInstBefore(Cast, *Caller);
3486 Args.push_back(Cast);
3487 } else {
3488 Args.push_back(*AI);
3489 }
3490 }
3491 }
3492
3493 if (FT->getReturnType() == Type::VoidTy)
3494 Caller->setName(""); // Void type should not have a name...
3495
3496 Instruction *NC;
3497 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003498 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00003499 Args, Caller->getName(), Caller);
3500 } else {
3501 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
3502 }
3503
3504 // Insert a cast of the return type as necessary...
3505 Value *NV = NC;
3506 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
3507 if (NV->getType() != Type::VoidTy) {
3508 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00003509
3510 // If this is an invoke instruction, we should insert it after the first
3511 // non-phi, instruction in the normal successor block.
3512 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3513 BasicBlock::iterator I = II->getNormalDest()->begin();
3514 while (isa<PHINode>(I)) ++I;
3515 InsertNewInstBefore(NC, *I);
3516 } else {
3517 // Otherwise, it's a call, just insert cast right after the call instr
3518 InsertNewInstBefore(NC, *Caller);
3519 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003520 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00003521 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00003522 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00003523 }
3524 }
3525
3526 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
3527 Caller->replaceAllUsesWith(NV);
3528 Caller->getParent()->getInstList().erase(Caller);
3529 removeFromWorkList(Caller);
3530 return true;
3531}
3532
3533
Chris Lattner7515cab2004-11-14 19:13:23 +00003534// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
3535// operator and they all are only used by the PHI, PHI together their
3536// inputs, and do the operation once, to the result of the PHI.
3537Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
3538 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
3539
3540 // Scan the instruction, looking for input operations that can be folded away.
3541 // If all input operands to the phi are the same instruction (e.g. a cast from
3542 // the same type or "+42") we can pull the operation through the PHI, reducing
3543 // code size and simplifying code.
3544 Constant *ConstantOp = 0;
3545 const Type *CastSrcTy = 0;
3546 if (isa<CastInst>(FirstInst)) {
3547 CastSrcTy = FirstInst->getOperand(0)->getType();
3548 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
3549 // Can fold binop or shift if the RHS is a constant.
3550 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
3551 if (ConstantOp == 0) return 0;
3552 } else {
3553 return 0; // Cannot fold this operation.
3554 }
3555
3556 // Check to see if all arguments are the same operation.
3557 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
3558 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
3559 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
3560 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
3561 return 0;
3562 if (CastSrcTy) {
3563 if (I->getOperand(0)->getType() != CastSrcTy)
3564 return 0; // Cast operation must match.
3565 } else if (I->getOperand(1) != ConstantOp) {
3566 return 0;
3567 }
3568 }
3569
3570 // Okay, they are all the same operation. Create a new PHI node of the
3571 // correct type, and PHI together all of the LHS's of the instructions.
3572 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
3573 PN.getName()+".in");
3574 NewPN->op_reserve(PN.getNumOperands());
Chris Lattner46dd5a62004-11-14 19:29:34 +00003575
3576 Value *InVal = FirstInst->getOperand(0);
3577 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00003578
3579 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00003580 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
3581 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
3582 if (NewInVal != InVal)
3583 InVal = 0;
3584 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
3585 }
3586
3587 Value *PhiVal;
3588 if (InVal) {
3589 // The new PHI unions all of the same values together. This is really
3590 // common, so we handle it intelligently here for compile-time speed.
3591 PhiVal = InVal;
3592 delete NewPN;
3593 } else {
3594 InsertNewInstBefore(NewPN, PN);
3595 PhiVal = NewPN;
3596 }
Chris Lattner7515cab2004-11-14 19:13:23 +00003597
3598 // Insert and return the new operation.
3599 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00003600 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00003601 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00003602 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00003603 else
3604 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00003605 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00003606}
Chris Lattner48a44f72002-05-02 17:06:02 +00003607
Chris Lattnerbbbdd852002-05-06 18:06:38 +00003608// PHINode simplification
3609//
Chris Lattner113f4f42002-06-25 16:13:24 +00003610Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnere29d6342004-10-17 21:22:38 +00003611 if (Value *V = hasConstantValue(&PN)) {
3612 // If V is an instruction, we have to be certain that it dominates PN.
3613 // However, because we don't have dom info, we can't do a perfect job.
3614 if (Instruction *I = dyn_cast<Instruction>(V)) {
3615 // We know that the instruction dominates the PHI if there are no undef
3616 // values coming in.
Chris Lattner3b92f172004-10-18 01:48:31 +00003617 if (I->getParent() != &I->getParent()->getParent()->front() ||
3618 isa<InvokeInst>(I))
Chris Lattner107c15c2004-10-17 21:31:34 +00003619 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3620 if (isa<UndefValue>(PN.getIncomingValue(i))) {
3621 V = 0;
3622 break;
3623 }
Chris Lattnere29d6342004-10-17 21:22:38 +00003624 }
3625
3626 if (V)
3627 return ReplaceInstUsesWith(PN, V);
3628 }
Chris Lattner4db2d222004-02-16 05:07:08 +00003629
3630 // If the only user of this instruction is a cast instruction, and all of the
3631 // incoming values are constants, change this PHI to merge together the casted
3632 // constants.
3633 if (PN.hasOneUse())
3634 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
3635 if (CI->getType() != PN.getType()) { // noop casts will be folded
3636 bool AllConstant = true;
3637 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3638 if (!isa<Constant>(PN.getIncomingValue(i))) {
3639 AllConstant = false;
3640 break;
3641 }
3642 if (AllConstant) {
3643 // Make a new PHI with all casted values.
3644 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
3645 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3646 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
3647 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
3648 PN.getIncomingBlock(i));
3649 }
3650
3651 // Update the cast instruction.
3652 CI->setOperand(0, New);
3653 WorkList.push_back(CI); // revisit the cast instruction to fold.
3654 WorkList.push_back(New); // Make sure to revisit the new Phi
3655 return &PN; // PN is now dead!
3656 }
3657 }
Chris Lattner7515cab2004-11-14 19:13:23 +00003658
3659 // If all PHI operands are the same operation, pull them through the PHI,
3660 // reducing code size.
3661 if (isa<Instruction>(PN.getIncomingValue(0)) &&
3662 PN.getIncomingValue(0)->hasOneUse())
3663 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
3664 return Result;
3665
3666
Chris Lattner91daeb52003-12-19 05:58:40 +00003667 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00003668}
3669
Chris Lattner69193f92004-04-05 01:30:19 +00003670static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
3671 Instruction *InsertPoint,
3672 InstCombiner *IC) {
3673 unsigned PS = IC->getTargetData().getPointerSize();
3674 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00003675 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
3676 // We must insert a cast to ensure we sign-extend.
3677 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
3678 V->getName()), *InsertPoint);
3679 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
3680 *InsertPoint);
3681}
3682
Chris Lattner48a44f72002-05-02 17:06:02 +00003683
Chris Lattner113f4f42002-06-25 16:13:24 +00003684Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00003685 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00003686 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00003687 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003688 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00003689 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003690
Chris Lattner81a7a232004-10-16 18:11:37 +00003691 if (isa<UndefValue>(GEP.getOperand(0)))
3692 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
3693
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003694 bool HasZeroPointerIndex = false;
3695 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
3696 HasZeroPointerIndex = C->isNullValue();
3697
3698 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00003699 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00003700
Chris Lattner69193f92004-04-05 01:30:19 +00003701 // Eliminate unneeded casts for indices.
3702 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00003703 gep_type_iterator GTI = gep_type_begin(GEP);
3704 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
3705 if (isa<SequentialType>(*GTI)) {
3706 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
3707 Value *Src = CI->getOperand(0);
3708 const Type *SrcTy = Src->getType();
3709 const Type *DestTy = CI->getType();
3710 if (Src->getType()->isInteger()) {
3711 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
3712 // We can always eliminate a cast from ulong or long to the other.
3713 // We can always eliminate a cast from uint to int or the other on
3714 // 32-bit pointer platforms.
3715 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
3716 MadeChange = true;
3717 GEP.setOperand(i, Src);
3718 }
3719 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
3720 SrcTy->getPrimitiveSize() == 4) {
3721 // We can always eliminate a cast from int to [u]long. We can
3722 // eliminate a cast from uint to [u]long iff the target is a 32-bit
3723 // pointer target.
3724 if (SrcTy->isSigned() ||
3725 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
3726 MadeChange = true;
3727 GEP.setOperand(i, Src);
3728 }
Chris Lattner69193f92004-04-05 01:30:19 +00003729 }
3730 }
3731 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00003732 // If we are using a wider index than needed for this platform, shrink it
3733 // to what we need. If the incoming value needs a cast instruction,
3734 // insert it. This explicit cast can make subsequent optimizations more
3735 // obvious.
3736 Value *Op = GEP.getOperand(i);
3737 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00003738 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00003739 GEP.setOperand(i, ConstantExpr::getCast(C,
3740 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00003741 MadeChange = true;
3742 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00003743 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
3744 Op->getName()), GEP);
3745 GEP.setOperand(i, Op);
3746 MadeChange = true;
3747 }
Chris Lattner44d0b952004-07-20 01:48:15 +00003748
3749 // If this is a constant idx, make sure to canonicalize it to be a signed
3750 // operand, otherwise CSE and other optimizations are pessimized.
3751 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
3752 GEP.setOperand(i, ConstantExpr::getCast(CUI,
3753 CUI->getType()->getSignedVersion()));
3754 MadeChange = true;
3755 }
Chris Lattner69193f92004-04-05 01:30:19 +00003756 }
3757 if (MadeChange) return &GEP;
3758
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003759 // Combine Indices - If the source pointer to this getelementptr instruction
3760 // is a getelementptr instruction, combine the indices of the two
3761 // getelementptr instructions into a single instruction.
3762 //
Chris Lattner57c67b02004-03-25 22:59:29 +00003763 std::vector<Value*> SrcGEPOperands;
Chris Lattner5f667a62004-05-07 22:09:22 +00003764 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00003765 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner5f667a62004-05-07 22:09:22 +00003766 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00003767 if (CE->getOpcode() == Instruction::GetElementPtr)
3768 SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
3769 }
3770
3771 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00003772 // Note that if our source is a gep chain itself that we wait for that
3773 // chain to be resolved before we perform this transformation. This
3774 // avoids us creating a TON of code in some cases.
3775 //
3776 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
3777 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
3778 return 0; // Wait until our source is folded to completion.
3779
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003780 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00003781
3782 // Find out whether the last index in the source GEP is a sequential idx.
3783 bool EndsWithSequential = false;
3784 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
3785 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00003786 EndsWithSequential = !isa<StructType>(*I);
Chris Lattnerca081252001-12-14 16:52:21 +00003787
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003788 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00003789 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00003790 // Replace: gep (gep %P, long B), long A, ...
3791 // With: T = long A+B; gep %P, T, ...
3792 //
Chris Lattner5f667a62004-05-07 22:09:22 +00003793 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00003794 if (SO1 == Constant::getNullValue(SO1->getType())) {
3795 Sum = GO1;
3796 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
3797 Sum = SO1;
3798 } else {
3799 // If they aren't the same type, convert both to an integer of the
3800 // target's pointer size.
3801 if (SO1->getType() != GO1->getType()) {
3802 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
3803 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
3804 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
3805 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
3806 } else {
3807 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00003808 if (SO1->getType()->getPrimitiveSize() == PS) {
3809 // Convert GO1 to SO1's type.
3810 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
3811
3812 } else if (GO1->getType()->getPrimitiveSize() == PS) {
3813 // Convert SO1 to GO1's type.
3814 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
3815 } else {
3816 const Type *PT = TD->getIntPtrType();
3817 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
3818 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
3819 }
3820 }
3821 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003822 if (isa<Constant>(SO1) && isa<Constant>(GO1))
3823 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
3824 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003825 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
3826 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00003827 }
Chris Lattner69193f92004-04-05 01:30:19 +00003828 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003829
3830 // Recycle the GEP we already have if possible.
3831 if (SrcGEPOperands.size() == 2) {
3832 GEP.setOperand(0, SrcGEPOperands[0]);
3833 GEP.setOperand(1, Sum);
3834 return &GEP;
3835 } else {
3836 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3837 SrcGEPOperands.end()-1);
3838 Indices.push_back(Sum);
3839 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
3840 }
Chris Lattner69193f92004-04-05 01:30:19 +00003841 } else if (isa<Constant>(*GEP.idx_begin()) &&
3842 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner57c67b02004-03-25 22:59:29 +00003843 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003844 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00003845 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3846 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003847 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
3848 }
3849
3850 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00003851 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003852
Chris Lattner5f667a62004-05-07 22:09:22 +00003853 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003854 // GEP of global variable. If all of the indices for this GEP are
3855 // constants, we can promote this to a constexpr instead of an instruction.
3856
3857 // Scan for nonconstants...
3858 std::vector<Constant*> Indices;
3859 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
3860 for (; I != E && isa<Constant>(*I); ++I)
3861 Indices.push_back(cast<Constant>(*I));
3862
3863 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00003864 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003865
3866 // Replace all uses of the GEP with the new constexpr...
3867 return ReplaceInstUsesWith(GEP, CE);
3868 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003869 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003870 if (CE->getOpcode() == Instruction::Cast) {
3871 if (HasZeroPointerIndex) {
3872 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
3873 // into : GEP [10 x ubyte]* X, long 0, ...
3874 //
3875 // This occurs when the program declares an array extern like "int X[];"
3876 //
3877 Constant *X = CE->getOperand(0);
3878 const PointerType *CPTy = cast<PointerType>(CE->getType());
3879 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
3880 if (const ArrayType *XATy =
3881 dyn_cast<ArrayType>(XTy->getElementType()))
3882 if (const ArrayType *CATy =
3883 dyn_cast<ArrayType>(CPTy->getElementType()))
3884 if (CATy->getElementType() == XATy->getElementType()) {
3885 // At this point, we know that the cast source type is a pointer
3886 // to an array of the same type as the destination pointer
3887 // array. Because the array type is never stepped over (there
3888 // is a leading zero) we can fold the cast into this GEP.
3889 GEP.setOperand(0, X);
3890 return &GEP;
3891 }
Chris Lattner14f3cdc2004-11-27 17:55:46 +00003892 } else if (GEP.getNumOperands() == 2) {
3893 // Transform things like:
3894 // %t = getelementptr ubyte* cast ([2 x sbyte]* %str to ubyte*), uint %V
3895 // into: %t1 = getelementptr [2 x sbyte*]* %str, int 0, uint %V; cast
3896 Constant *X = CE->getOperand(0);
3897 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
3898 const Type *ResElTy =cast<PointerType>(CE->getType())->getElementType();
3899 if (isa<ArrayType>(SrcElTy) &&
3900 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
3901 TD->getTypeSize(ResElTy)) {
3902 Value *V = InsertNewInstBefore(
3903 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
3904 GEP.getOperand(1), GEP.getName()), GEP);
3905 return new CastInst(V, GEP.getType());
3906 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003907 }
3908 }
Chris Lattnerca081252001-12-14 16:52:21 +00003909 }
3910
Chris Lattnerca081252001-12-14 16:52:21 +00003911 return 0;
3912}
3913
Chris Lattner1085bdf2002-11-04 16:18:53 +00003914Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
3915 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
3916 if (AI.isArrayAllocation()) // Check C != 1
3917 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
3918 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003919 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00003920
3921 // Create and insert the replacement instruction...
3922 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00003923 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003924 else {
3925 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00003926 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003927 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00003928
3929 InsertNewInstBefore(New, AI);
Chris Lattner1085bdf2002-11-04 16:18:53 +00003930
3931 // Scan to the end of the allocation instructions, to skip over a block of
3932 // allocas if possible...
3933 //
3934 BasicBlock::iterator It = New;
3935 while (isa<AllocationInst>(*It)) ++It;
3936
3937 // Now that I is pointing to the first non-allocation-inst in the block,
3938 // insert our getelementptr instruction...
3939 //
Chris Lattner69193f92004-04-05 01:30:19 +00003940 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner1085bdf2002-11-04 16:18:53 +00003941 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
3942
3943 // Now make everything use the getelementptr instead of the original
3944 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00003945 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00003946 } else if (isa<UndefValue>(AI.getArraySize())) {
3947 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00003948 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00003949
3950 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
3951 // Note that we only do this for alloca's, because malloc should allocate and
3952 // return a unique pointer, even for a zero byte allocation.
Chris Lattner49df6ce2004-07-02 22:55:47 +00003953 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
3954 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00003955 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
3956
Chris Lattner1085bdf2002-11-04 16:18:53 +00003957 return 0;
3958}
3959
Chris Lattner8427bff2003-12-07 01:24:23 +00003960Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
3961 Value *Op = FI.getOperand(0);
3962
3963 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
3964 if (CastInst *CI = dyn_cast<CastInst>(Op))
3965 if (isa<PointerType>(CI->getOperand(0)->getType())) {
3966 FI.setOperand(0, CI->getOperand(0));
3967 return &FI;
3968 }
3969
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003970 // free undef -> unreachable.
3971 if (isa<UndefValue>(Op)) {
3972 // Insert a new store to null because we cannot modify the CFG here.
3973 new StoreInst(ConstantBool::True,
3974 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
3975 return EraseInstFromFunction(FI);
3976 }
3977
Chris Lattnerf3a36602004-02-28 04:57:37 +00003978 // If we have 'free null' delete the instruction. This can happen in stl code
3979 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003980 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00003981 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00003982
Chris Lattner8427bff2003-12-07 01:24:23 +00003983 return 0;
3984}
3985
3986
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003987/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
3988/// constantexpr, return the constant value being addressed by the constant
3989/// expression, or null if something is funny.
3990///
3991static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00003992 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003993 return 0; // Do not allow stepping over the value!
3994
3995 // Loop over all of the operands, tracking down which value we are
3996 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00003997 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
3998 for (++I; I != E; ++I)
3999 if (const StructType *STy = dyn_cast<StructType>(*I)) {
4000 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
4001 assert(CU->getValue() < STy->getNumElements() &&
4002 "Struct index out of range!");
4003 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Alkis Evlogimenos83243722004-08-04 08:44:43 +00004004 C = CS->getOperand(CU->getValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00004005 } else if (isa<ConstantAggregateZero>(C)) {
4006 C = Constant::getNullValue(STy->getElementType(CU->getValue()));
Chris Lattner81a7a232004-10-16 18:11:37 +00004007 } else if (isa<UndefValue>(C)) {
4008 C = UndefValue::get(STy->getElementType(CU->getValue()));
Chris Lattnered79d8a2004-05-27 17:30:27 +00004009 } else {
4010 return 0;
4011 }
4012 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
4013 const ArrayType *ATy = cast<ArrayType>(*I);
4014 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
4015 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Alkis Evlogimenos83243722004-08-04 08:44:43 +00004016 C = CA->getOperand(CI->getRawValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00004017 else if (isa<ConstantAggregateZero>(C))
4018 C = Constant::getNullValue(ATy->getElementType());
Chris Lattner81a7a232004-10-16 18:11:37 +00004019 else if (isa<UndefValue>(C))
4020 C = UndefValue::get(ATy->getElementType());
Chris Lattnered79d8a2004-05-27 17:30:27 +00004021 else
4022 return 0;
4023 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004024 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00004025 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004026 return C;
4027}
4028
Chris Lattner35e24772004-07-13 01:49:43 +00004029static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
4030 User *CI = cast<User>(LI.getOperand(0));
4031
4032 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
4033 if (const PointerType *SrcTy =
4034 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
4035 const Type *SrcPTy = SrcTy->getElementType();
4036 if (SrcPTy->isSized() && DestPTy->isSized() &&
4037 IC.getTargetData().getTypeSize(SrcPTy) ==
4038 IC.getTargetData().getTypeSize(DestPTy) &&
4039 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
4040 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
4041 // Okay, we are casting from one integer or pointer type to another of
4042 // the same size. Instead of casting the pointer before the load, cast
4043 // the result of the loaded value.
4044 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004045 CI->getName(),
4046 LI.isVolatile()),LI);
Chris Lattner35e24772004-07-13 01:49:43 +00004047 // Now cast the result of the load.
4048 return new CastInst(NewLoad, LI.getType());
4049 }
4050 }
4051 return 0;
4052}
4053
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004054/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00004055/// from this value cannot trap. If it is not obviously safe to load from the
4056/// specified pointer, we do a quick local scan of the basic block containing
4057/// ScanFrom, to determine if the address is already accessed.
4058static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
4059 // If it is an alloca or global variable, it is always safe to load from.
4060 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
4061
4062 // Otherwise, be a little bit agressive by scanning the local block where we
4063 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004064 // from/to. If so, the previous load or store would have already trapped,
4065 // so there is no harm doing an extra load (also, CSE will later eliminate
4066 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00004067 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
4068
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004069 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00004070 --BBI;
4071
4072 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
4073 if (LI->getOperand(0) == V) return true;
4074 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
4075 if (SI->getOperand(1) == V) return true;
4076
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004077 }
Chris Lattnere6f13092004-09-19 19:18:10 +00004078 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004079}
4080
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004081Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
4082 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00004083
Chris Lattner81a7a232004-10-16 18:11:37 +00004084 if (Constant *C = dyn_cast<Constant>(Op)) {
4085 if ((C->isNullValue() || isa<UndefValue>(C)) &&
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004086 !LI.isVolatile()) { // load null/undef -> undef
4087 // Insert a new store to null instruction before the load to indicate that
4088 // this code is not reachable. We do this instead of inserting an
4089 // unreachable instruction directly because we cannot modify the CFG.
4090 new StoreInst(UndefValue::get(LI.getType()), C, &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00004091 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004092 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004093
Chris Lattner81a7a232004-10-16 18:11:37 +00004094 // Instcombine load (constant global) into the value loaded.
4095 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
4096 if (GV->isConstant() && !GV->isExternal())
4097 return ReplaceInstUsesWith(LI, GV->getInitializer());
4098
4099 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
4100 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
4101 if (CE->getOpcode() == Instruction::GetElementPtr) {
4102 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
4103 if (GV->isConstant() && !GV->isExternal())
4104 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
4105 return ReplaceInstUsesWith(LI, V);
4106 } else if (CE->getOpcode() == Instruction::Cast) {
4107 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4108 return Res;
4109 }
4110 }
Chris Lattnere228ee52004-04-08 20:39:49 +00004111
4112 // load (cast X) --> cast (load X) iff safe
Chris Lattner35e24772004-07-13 01:49:43 +00004113 if (CastInst *CI = dyn_cast<CastInst>(Op))
4114 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4115 return Res;
Chris Lattnere228ee52004-04-08 20:39:49 +00004116
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004117 if (!LI.isVolatile() && Op->hasOneUse()) {
4118 // Change select and PHI nodes to select values instead of addresses: this
4119 // helps alias analysis out a lot, allows many others simplifications, and
4120 // exposes redundancy in the code.
4121 //
4122 // Note that we cannot do the transformation unless we know that the
4123 // introduced loads cannot trap! Something like this is valid as long as
4124 // the condition is always false: load (select bool %C, int* null, int* %G),
4125 // but it would not be valid if we transformed it to load from null
4126 // unconditionally.
4127 //
4128 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
4129 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00004130 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
4131 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004132 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00004133 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004134 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00004135 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004136 return new SelectInst(SI->getCondition(), V1, V2);
4137 }
4138
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00004139 // load (select (cond, null, P)) -> load P
4140 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
4141 if (C->isNullValue()) {
4142 LI.setOperand(0, SI->getOperand(2));
4143 return &LI;
4144 }
4145
4146 // load (select (cond, P, null)) -> load P
4147 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
4148 if (C->isNullValue()) {
4149 LI.setOperand(0, SI->getOperand(1));
4150 return &LI;
4151 }
4152
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004153 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
4154 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00004155 bool Safe = PN->getParent() == LI.getParent();
4156
4157 // Scan all of the instructions between the PHI and the load to make
4158 // sure there are no instructions that might possibly alter the value
4159 // loaded from the PHI.
4160 if (Safe) {
4161 BasicBlock::iterator I = &LI;
4162 for (--I; !isa<PHINode>(I); --I)
4163 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
4164 Safe = false;
4165 break;
4166 }
4167 }
4168
4169 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00004170 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00004171 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004172 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00004173
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004174 if (Safe) {
4175 // Create the PHI.
4176 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
4177 InsertNewInstBefore(NewPN, *PN);
4178 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
4179
4180 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4181 BasicBlock *BB = PN->getIncomingBlock(i);
4182 Value *&TheLoad = LoadMap[BB];
4183 if (TheLoad == 0) {
4184 Value *InVal = PN->getIncomingValue(i);
4185 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
4186 InVal->getName()+".val"),
4187 *BB->getTerminator());
4188 }
4189 NewPN->addIncoming(TheLoad, BB);
4190 }
4191 return ReplaceInstUsesWith(LI, NewPN);
4192 }
4193 }
4194 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004195 return 0;
4196}
4197
Chris Lattner9eef8a72003-06-04 04:46:00 +00004198Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
4199 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattnerd4252a72004-07-30 07:50:03 +00004200 Value *X;
4201 BasicBlock *TrueDest;
4202 BasicBlock *FalseDest;
4203 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
4204 !isa<Constant>(X)) {
4205 // Swap Destinations and condition...
4206 BI.setCondition(X);
4207 BI.setSuccessor(0, FalseDest);
4208 BI.setSuccessor(1, TrueDest);
4209 return &BI;
4210 }
4211
4212 // Cannonicalize setne -> seteq
4213 Instruction::BinaryOps Op; Value *Y;
4214 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
4215 TrueDest, FalseDest)))
4216 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
4217 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
4218 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
4219 std::string Name = I->getName(); I->setName("");
4220 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
4221 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00004222 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00004223 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00004224 BI.setSuccessor(0, FalseDest);
4225 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004226 removeFromWorkList(I);
4227 I->getParent()->getInstList().erase(I);
4228 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00004229 return &BI;
4230 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00004231
Chris Lattner9eef8a72003-06-04 04:46:00 +00004232 return 0;
4233}
Chris Lattner1085bdf2002-11-04 16:18:53 +00004234
Chris Lattner4c9c20a2004-07-03 00:26:11 +00004235Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
4236 Value *Cond = SI.getCondition();
4237 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
4238 if (I->getOpcode() == Instruction::Add)
4239 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
4240 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
4241 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00004242 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00004243 AddRHS));
4244 SI.setOperand(0, I->getOperand(0));
4245 WorkList.push_back(I);
4246 return &SI;
4247 }
4248 }
4249 return 0;
4250}
4251
Chris Lattnerca081252001-12-14 16:52:21 +00004252
Chris Lattner99f48c62002-09-02 04:59:56 +00004253void InstCombiner::removeFromWorkList(Instruction *I) {
4254 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
4255 WorkList.end());
4256}
4257
Chris Lattner39c98bb2004-12-08 23:43:58 +00004258
4259/// TryToSinkInstruction - Try to move the specified instruction from its
4260/// current block into the beginning of DestBlock, which can only happen if it's
4261/// safe to move the instruction past all of the instructions between it and the
4262/// end of its block.
4263static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
4264 assert(I->hasOneUse() && "Invariants didn't hold!");
4265
4266 // Cannot move control-flow-involving instructions.
4267 if (isa<PHINode>(I) || isa<InvokeInst>(I) || isa<CallInst>(I)) return false;
4268
4269 // Do not sink alloca instructions out of the entry block.
4270 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
4271 return false;
4272
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00004273 // We can only sink load instructions if there is nothing between the load and
4274 // the end of block that could change the value.
4275 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
4276 if (LI->isVolatile()) return false; // Don't sink volatile loads.
4277
4278 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
4279 Scan != E; ++Scan)
4280 if (Scan->mayWriteToMemory())
4281 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00004282 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00004283
4284 BasicBlock::iterator InsertPos = DestBlock->begin();
4285 while (isa<PHINode>(InsertPos)) ++InsertPos;
4286
4287 BasicBlock *SrcBlock = I->getParent();
4288 DestBlock->getInstList().splice(InsertPos, SrcBlock->getInstList(), I);
4289 ++NumSunkInst;
4290 return true;
4291}
4292
Chris Lattner113f4f42002-06-25 16:13:24 +00004293bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00004294 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004295 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00004296
Chris Lattnerb643a9e2004-05-01 23:19:52 +00004297 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
4298 WorkList.push_back(&*i);
Chris Lattner2d3a7a62004-04-27 15:13:33 +00004299
Chris Lattnerca081252001-12-14 16:52:21 +00004300
4301 while (!WorkList.empty()) {
4302 Instruction *I = WorkList.back(); // Get an instruction from the worklist
4303 WorkList.pop_back();
4304
Misha Brukman632df282002-10-29 23:06:16 +00004305 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00004306 // Check to see if we can DIE the instruction...
4307 if (isInstructionTriviallyDead(I)) {
4308 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004309 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00004310 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00004311 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004312
4313 I->getParent()->getInstList().erase(I);
4314 removeFromWorkList(I);
4315 continue;
4316 }
Chris Lattner99f48c62002-09-02 04:59:56 +00004317
Misha Brukman632df282002-10-29 23:06:16 +00004318 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00004319 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00004320 Value* Ptr = I->getOperand(0);
Chris Lattner6580e092004-10-16 19:44:59 +00004321 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00004322 cast<Constant>(Ptr)->isNullValue() &&
4323 !isa<ConstantPointerNull>(C) &&
4324 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner6580e092004-10-16 19:44:59 +00004325 // If this is a constant expr gep that is effectively computing an
4326 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
4327 bool isFoldableGEP = true;
4328 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
4329 if (!isa<ConstantInt>(I->getOperand(i)))
4330 isFoldableGEP = false;
4331 if (isFoldableGEP) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00004332 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner6580e092004-10-16 19:44:59 +00004333 std::vector<Value*>(I->op_begin()+1, I->op_end()));
4334 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00004335 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00004336 C = ConstantExpr::getCast(C, I->getType());
4337 }
4338 }
4339
Chris Lattner99f48c62002-09-02 04:59:56 +00004340 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00004341 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00004342 ReplaceInstUsesWith(*I, C);
4343
Chris Lattner99f48c62002-09-02 04:59:56 +00004344 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004345 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00004346 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004347 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00004348 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004349
Chris Lattner39c98bb2004-12-08 23:43:58 +00004350 // See if we can trivially sink this instruction to a successor basic block.
4351 if (I->hasOneUse()) {
4352 BasicBlock *BB = I->getParent();
4353 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
4354 if (UserParent != BB) {
4355 bool UserIsSuccessor = false;
4356 // See if the user is one of our successors.
4357 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
4358 if (*SI == UserParent) {
4359 UserIsSuccessor = true;
4360 break;
4361 }
4362
4363 // If the user is one of our immediate successors, and if that successor
4364 // only has us as a predecessors (we'd have to split the critical edge
4365 // otherwise), we can keep going.
4366 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
4367 next(pred_begin(UserParent)) == pred_end(UserParent))
4368 // Okay, the CFG is simple enough, try to sink this instruction.
4369 Changed |= TryToSinkInstruction(I, UserParent);
4370 }
4371 }
4372
Chris Lattnerca081252001-12-14 16:52:21 +00004373 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004374 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00004375 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00004376 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00004377 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00004378 DEBUG(std::cerr << "IC: Old = " << *I
4379 << " New = " << *Result);
4380
Chris Lattner396dbfe2004-06-09 05:08:07 +00004381 // Everything uses the new instruction now.
4382 I->replaceAllUsesWith(Result);
4383
4384 // Push the new instruction and any users onto the worklist.
4385 WorkList.push_back(Result);
4386 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004387
4388 // Move the name to the new instruction first...
4389 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00004390 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004391
4392 // Insert the new instruction into the basic block...
4393 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00004394 BasicBlock::iterator InsertPos = I;
4395
4396 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
4397 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
4398 ++InsertPos;
4399
4400 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004401
Chris Lattner63d75af2004-05-01 23:27:23 +00004402 // Make sure that we reprocess all operands now that we reduced their
4403 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00004404 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4405 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4406 WorkList.push_back(OpI);
4407
Chris Lattner396dbfe2004-06-09 05:08:07 +00004408 // Instructions can end up on the worklist more than once. Make sure
4409 // we do not process an instruction that has been deleted.
4410 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004411
4412 // Erase the old instruction.
4413 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00004414 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00004415 DEBUG(std::cerr << "IC: MOD = " << *I);
4416
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004417 // If the instruction was modified, it's possible that it is now dead.
4418 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00004419 if (isInstructionTriviallyDead(I)) {
4420 // Make sure we process all operands now that we are reducing their
4421 // use counts.
4422 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4423 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4424 WorkList.push_back(OpI);
4425
4426 // Instructions may end up in the worklist more than once. Erase all
4427 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00004428 removeFromWorkList(I);
Chris Lattner63d75af2004-05-01 23:27:23 +00004429 I->getParent()->getInstList().erase(I);
Chris Lattner396dbfe2004-06-09 05:08:07 +00004430 } else {
4431 WorkList.push_back(Result);
4432 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004433 }
Chris Lattner053c0932002-05-14 15:24:07 +00004434 }
Chris Lattner260ab202002-04-18 17:39:14 +00004435 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00004436 }
4437 }
4438
Chris Lattner260ab202002-04-18 17:39:14 +00004439 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00004440}
4441
Brian Gaeke38b79e82004-07-27 17:43:21 +00004442FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00004443 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00004444}
Brian Gaeke960707c2003-11-11 22:41:34 +00004445