blob: 0d23f44799eee23304809ae629e387000f623661 [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000027// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All SetCC instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattner7515cab2004-11-14 19:13:23 +000032// ... etc.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000033//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner00648e12004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner69193f92004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattner22d00a82005-08-02 19:16:58 +000049#include "llvm/Support/MathExtras.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Chris Lattner4ed40f72005-07-07 20:40:38 +000051#include "llvm/ADT/DepthFirstIterator.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000052#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000053#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattnerc597b8a2006-01-22 23:32:06 +000055#include <iostream>
Chris Lattner8427bff2003-12-07 01:24:23 +000056using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000057using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000058
Chris Lattner260ab202002-04-18 17:39:14 +000059namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000060 Statistic<> NumCombined ("instcombine", "Number of insts combined");
61 Statistic<> NumConstProp("instcombine", "Number of constant folds");
62 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattner39c98bb2004-12-08 23:43:58 +000063 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000064
Chris Lattnerc8e66542002-04-27 06:56:12 +000065 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000066 public InstVisitor<InstCombiner, Instruction*> {
67 // Worklist of all of the instructions that need to be simplified.
68 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000069 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000070
Chris Lattner51ea1272004-02-28 05:22:00 +000071 /// AddUsersToWorkList - When an instruction is simplified, add all users of
72 /// the instruction to the work lists because they might get more simplified
73 /// now.
74 ///
Chris Lattner2590e512006-02-07 06:56:34 +000075 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000076 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000077 UI != UE; ++UI)
78 WorkList.push_back(cast<Instruction>(*UI));
79 }
80
Chris Lattner51ea1272004-02-28 05:22:00 +000081 /// AddUsesToWorkList - When an instruction is simplified, add operands to
82 /// the work lists because they might get more simplified now.
83 ///
84 void AddUsesToWorkList(Instruction &I) {
85 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
86 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
87 WorkList.push_back(Op);
88 }
89
Chris Lattner99f48c62002-09-02 04:59:56 +000090 // removeFromWorkList - remove all instances of I from the worklist.
91 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000092 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000093 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000094
Chris Lattnerf12cc842002-04-28 21:27:06 +000095 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000096 AU.addRequired<TargetData>();
Chris Lattner820d9712002-10-21 20:00:28 +000097 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000098 }
99
Chris Lattner69193f92004-04-05 01:30:19 +0000100 TargetData &getTargetData() const { return *TD; }
101
Chris Lattner260ab202002-04-18 17:39:14 +0000102 // Visitation implementation - Implement instruction combining for different
103 // instruction types. The semantics are as follows:
104 // Return Value:
105 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000106 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000107 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000108 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000109 Instruction *visitAdd(BinaryOperator &I);
110 Instruction *visitSub(BinaryOperator &I);
111 Instruction *visitMul(BinaryOperator &I);
112 Instruction *visitDiv(BinaryOperator &I);
113 Instruction *visitRem(BinaryOperator &I);
114 Instruction *visitAnd(BinaryOperator &I);
115 Instruction *visitOr (BinaryOperator &I);
116 Instruction *visitXor(BinaryOperator &I);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000117 Instruction *visitSetCondInst(SetCondInst &I);
118 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
119
Chris Lattner0798af32005-01-13 20:14:25 +0000120 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
121 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000122 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner14553932006-01-06 07:12:35 +0000123 Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
124 ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000125 Instruction *visitCastInst(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000126 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
127 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000128 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000129 Instruction *visitCallInst(CallInst &CI);
130 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000131 Instruction *visitPHINode(PHINode &PN);
132 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000133 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000134 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000135 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000136 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000137 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000138 Instruction *visitSwitchInst(SwitchInst &SI);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000139 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattner260ab202002-04-18 17:39:14 +0000140
141 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000142 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000143
Chris Lattner970c33a2003-06-19 17:00:31 +0000144 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000145 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000146 bool transformConstExprCastCall(CallSite CS);
147
Chris Lattner69193f92004-04-05 01:30:19 +0000148 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000149 // InsertNewInstBefore - insert an instruction New before instruction Old
150 // in the program. Add the new instruction to the worklist.
151 //
Chris Lattner623826c2004-09-28 21:48:02 +0000152 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000153 assert(New && New->getParent() == 0 &&
154 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000155 BasicBlock *BB = Old.getParent();
156 BB->getInstList().insert(&Old, New); // Insert inst
157 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000158 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000159 }
160
Chris Lattner7e794272004-09-24 15:21:34 +0000161 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
162 /// This also adds the cast to the worklist. Finally, this returns the
163 /// cast.
164 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
165 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000166
Chris Lattner7e794272004-09-24 15:21:34 +0000167 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
168 WorkList.push_back(C);
169 return C;
170 }
171
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000172 // ReplaceInstUsesWith - This method is to be used when an instruction is
173 // found to be dead, replacable with another preexisting expression. Here
174 // we add all uses of I to the worklist, replace all uses of I with the new
175 // value, then return I, so that the inst combiner will know that I was
176 // modified.
177 //
178 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000179 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000180 if (&I != V) {
181 I.replaceAllUsesWith(V);
182 return &I;
183 } else {
184 // If we are replacing the instruction with itself, this must be in a
185 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000186 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000187 return &I;
188 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000189 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000190
Chris Lattner2590e512006-02-07 06:56:34 +0000191 // UpdateValueUsesWith - This method is to be used when an value is
192 // found to be replacable with another preexisting expression or was
193 // updated. Here we add all uses of I to the worklist, replace all uses of
194 // I with the new value (unless the instruction was just updated), then
195 // return true, so that the inst combiner will know that I was modified.
196 //
197 bool UpdateValueUsesWith(Value *Old, Value *New) {
198 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
199 if (Old != New)
200 Old->replaceAllUsesWith(New);
201 if (Instruction *I = dyn_cast<Instruction>(Old))
202 WorkList.push_back(I);
203 return true;
204 }
205
Chris Lattner51ea1272004-02-28 05:22:00 +0000206 // EraseInstFromFunction - When dealing with an instruction that has side
207 // effects or produces a void value, we can't rely on DCE to delete the
208 // instruction. Instead, visit methods should return the value returned by
209 // this function.
210 Instruction *EraseInstFromFunction(Instruction &I) {
211 assert(I.use_empty() && "Cannot erase instruction that is used!");
212 AddUsesToWorkList(I);
213 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000214 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000215 return 0; // Don't do anything with FI
216 }
217
Chris Lattner3ac7c262003-08-13 20:16:26 +0000218 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000219 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
220 /// InsertBefore instruction. This is specialized a bit to avoid inserting
221 /// casts that are known to not do anything...
222 ///
223 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
224 Instruction *InsertBefore);
225
Chris Lattner7fb29e12003-03-11 00:12:48 +0000226 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000227 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000228 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000229
Chris Lattner2590e512006-02-07 06:56:34 +0000230 bool SimplifyDemandedBits(Value *V, uint64_t Mask, unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000231
232 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
233 // PHI node as operand #0, see if we can fold the instruction into the PHI
234 // (which is only possible if all operands to the PHI are constants).
235 Instruction *FoldOpIntoPhi(Instruction &I);
236
Chris Lattner7515cab2004-11-14 19:13:23 +0000237 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
238 // operator and they all are only used by the PHI, PHI together their
239 // inputs, and do the operation once, to the result of the PHI.
240 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
241
Chris Lattnerba1cb382003-09-19 17:17:26 +0000242 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
243 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000244
245 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
246 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000247 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
248 bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000249 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattner260ab202002-04-18 17:39:14 +0000250 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000251
Chris Lattnerc8b70922002-07-26 21:12:46 +0000252 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000253}
254
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000255// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000256// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000257static unsigned getComplexity(Value *V) {
258 if (isa<Instruction>(V)) {
259 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000260 return 3;
261 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000262 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000263 if (isa<Argument>(V)) return 3;
264 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000265}
Chris Lattner260ab202002-04-18 17:39:14 +0000266
Chris Lattner7fb29e12003-03-11 00:12:48 +0000267// isOnlyUse - Return true if this instruction will be deleted if we stop using
268// it.
269static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000270 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000271}
272
Chris Lattnere79e8542004-02-23 06:38:22 +0000273// getPromotedType - Return the specified type promoted as it would be to pass
274// though a va_arg area...
275static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000276 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000277 case Type::SByteTyID:
278 case Type::ShortTyID: return Type::IntTy;
279 case Type::UByteTyID:
280 case Type::UShortTyID: return Type::UIntTy;
281 case Type::FloatTyID: return Type::DoubleTy;
282 default: return Ty;
283 }
284}
285
Chris Lattner567b81f2005-09-13 00:40:14 +0000286/// isCast - If the specified operand is a CastInst or a constant expr cast,
287/// return the operand value, otherwise return null.
288static Value *isCast(Value *V) {
289 if (CastInst *I = dyn_cast<CastInst>(V))
290 return I->getOperand(0);
291 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
292 if (CE->getOpcode() == Instruction::Cast)
293 return CE->getOperand(0);
294 return 0;
295}
296
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000297// SimplifyCommutative - This performs a few simplifications for commutative
298// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000299//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000300// 1. Order operands such that they are listed from right (least complex) to
301// left (most complex). This puts constants before unary operators before
302// binary operators.
303//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000304// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
305// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000306//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000307bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000308 bool Changed = false;
309 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
310 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000311
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000312 if (!I.isAssociative()) return Changed;
313 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000314 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
315 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
316 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000317 Constant *Folded = ConstantExpr::get(I.getOpcode(),
318 cast<Constant>(I.getOperand(1)),
319 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000320 I.setOperand(0, Op->getOperand(0));
321 I.setOperand(1, Folded);
322 return true;
323 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
324 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
325 isOnlyUse(Op) && isOnlyUse(Op1)) {
326 Constant *C1 = cast<Constant>(Op->getOperand(1));
327 Constant *C2 = cast<Constant>(Op1->getOperand(1));
328
329 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000330 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000331 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
332 Op1->getOperand(0),
333 Op1->getName(), &I);
334 WorkList.push_back(New);
335 I.setOperand(0, New);
336 I.setOperand(1, Folded);
337 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000338 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000339 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000340 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000341}
Chris Lattnerca081252001-12-14 16:52:21 +0000342
Chris Lattnerbb74e222003-03-10 23:06:50 +0000343// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
344// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000345//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000346static inline Value *dyn_castNegVal(Value *V) {
347 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000348 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000349
Chris Lattner9ad0d552004-12-14 20:08:06 +0000350 // Constants can be considered to be negated values if they can be folded.
351 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
352 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000353 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000354}
355
Chris Lattnerbb74e222003-03-10 23:06:50 +0000356static inline Value *dyn_castNotVal(Value *V) {
357 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000358 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000359
360 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000361 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000362 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000363 return 0;
364}
365
Chris Lattner7fb29e12003-03-11 00:12:48 +0000366// dyn_castFoldableMul - If this value is a multiply that can be folded into
367// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000368// non-constant operand of the multiply, and set CST to point to the multiplier.
369// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000370//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000371static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000372 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000373 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000374 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000375 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000376 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000377 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000378 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000379 // The multiplier is really 1 << CST.
380 Constant *One = ConstantInt::get(V->getType(), 1);
381 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
382 return I->getOperand(0);
383 }
384 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000385 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000386}
Chris Lattner31ae8632002-08-14 17:51:49 +0000387
Chris Lattner0798af32005-01-13 20:14:25 +0000388/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
389/// expression, return it.
390static User *dyn_castGetElementPtr(Value *V) {
391 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
392 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
393 if (CE->getOpcode() == Instruction::GetElementPtr)
394 return cast<User>(V);
395 return false;
396}
397
Chris Lattner623826c2004-09-28 21:48:02 +0000398// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000399static ConstantInt *AddOne(ConstantInt *C) {
400 return cast<ConstantInt>(ConstantExpr::getAdd(C,
401 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000402}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000403static ConstantInt *SubOne(ConstantInt *C) {
404 return cast<ConstantInt>(ConstantExpr::getSub(C,
405 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000406}
407
Chris Lattner0b3557f2005-09-24 23:43:33 +0000408/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000409/// this predicate to simplify operations downstream. Mask is known to be zero
410/// for bits that V cannot have.
411static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000412 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
413 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000414 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000415 // optimized based on the contradictory assumption that it is non-zero.
416 // Because instcombine aggressively folds operations with undef args anyway,
417 // this won't lose us code quality.
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000418 if (Mask == 0)
Chris Lattner0b3557f2005-09-24 23:43:33 +0000419 return true;
420 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000421 return (CI->getRawValue() & Mask) == 0;
Chris Lattner09efd4e2005-10-31 18:35:52 +0000422
423 if (Depth == 6) return false; // Limit search depth.
Chris Lattner0b3557f2005-09-24 23:43:33 +0000424
425 if (Instruction *I = dyn_cast<Instruction>(V)) {
426 switch (I->getOpcode()) {
Chris Lattner62010c42005-10-09 06:36:35 +0000427 case Instruction::And:
428 // (X & C1) & C2 == 0 iff C1 & C2 == 0.
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000429 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1)))
430 return MaskedValueIsZero(I->getOperand(0), CI->getRawValue() & Mask,
431 Depth+1);
Chris Lattner03b9eb52005-10-09 22:08:50 +0000432 // If either the LHS or the RHS are MaskedValueIsZero, the result is zero.
Chris Lattner09efd4e2005-10-31 18:35:52 +0000433 return MaskedValueIsZero(I->getOperand(1), Mask, Depth+1) ||
434 MaskedValueIsZero(I->getOperand(0), Mask, Depth+1);
Chris Lattner62010c42005-10-09 06:36:35 +0000435 case Instruction::Or:
Chris Lattner03b9eb52005-10-09 22:08:50 +0000436 case Instruction::Xor:
Chris Lattner62010c42005-10-09 06:36:35 +0000437 // If the LHS and the RHS are MaskedValueIsZero, the result is also zero.
Chris Lattner09efd4e2005-10-31 18:35:52 +0000438 return MaskedValueIsZero(I->getOperand(1), Mask, Depth+1) &&
439 MaskedValueIsZero(I->getOperand(0), Mask, Depth+1);
Chris Lattner62010c42005-10-09 06:36:35 +0000440 case Instruction::Select:
441 // If the T and F values are MaskedValueIsZero, the result is also zero.
Chris Lattner09efd4e2005-10-31 18:35:52 +0000442 return MaskedValueIsZero(I->getOperand(2), Mask, Depth+1) &&
443 MaskedValueIsZero(I->getOperand(1), Mask, Depth+1);
Chris Lattner62010c42005-10-09 06:36:35 +0000444 case Instruction::Cast: {
445 const Type *SrcTy = I->getOperand(0)->getType();
446 if (SrcTy == Type::BoolTy)
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000447 return (Mask & 1) == 0;
448 if (!SrcTy->isInteger()) return false;
Chris Lattner62010c42005-10-09 06:36:35 +0000449
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000450 // (cast <ty> X to int) & C2 == 0 iff <ty> could not have contained C2.
451 if (SrcTy->isUnsigned()) // Only handle zero ext.
452 return MaskedValueIsZero(I->getOperand(0),
453 Mask & SrcTy->getIntegralTypeMask(), Depth+1);
454
455 // If this is a noop or trunc cast, recurse.
456 if (SrcTy->getPrimitiveSizeInBits() >=
457 I->getType()->getPrimitiveSizeInBits())
458 return MaskedValueIsZero(I->getOperand(0),
459 Mask & SrcTy->getIntegralTypeMask(), Depth+1);
Chris Lattner62010c42005-10-09 06:36:35 +0000460 break;
461 }
462 case Instruction::Shl:
463 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
464 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000465 return MaskedValueIsZero(I->getOperand(0), Mask >> SA->getValue(),
Chris Lattner09efd4e2005-10-31 18:35:52 +0000466 Depth+1);
Chris Lattner62010c42005-10-09 06:36:35 +0000467 break;
468 case Instruction::Shr:
469 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
470 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
471 if (I->getType()->isUnsigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000472 Mask <<= SA->getValue();
473 Mask &= I->getType()->getIntegralTypeMask();
474 return MaskedValueIsZero(I->getOperand(0), Mask, Depth+1);
Chris Lattner62010c42005-10-09 06:36:35 +0000475 }
476 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000477 }
478 }
479
480 return false;
481}
482
Chris Lattner2590e512006-02-07 06:56:34 +0000483/// SimplifyDemandedBits - Look at V. At this point, we know that only the Mask
484/// bits of the result of V are ever used downstream. If we can use this
485/// information to simplify V, return V and set NewVal to the new value we
486/// should use in V's place.
487bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t Mask,
488 unsigned Depth) {
489 if (!V->hasOneUse()) { // Other users may use these bits.
490 if (Depth != 0) // Not at the root.
491 return false;
492 // If this is the root being simplified, allow it to have multiple uses,
493 // just set the Mask to all bits.
494 Mask = V->getType()->getIntegralTypeMask();
495 } else if (Mask == 0) { // Not demanding any bits from V.
496 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
497 } else if (Depth == 6) { // Limit search depth.
498 return false;
499 }
500
501 Instruction *I = dyn_cast<Instruction>(V);
502 if (!I) return false; // Only analyze instructions.
503
504 switch (I->getOpcode()) {
505 default: break;
506 case Instruction::And:
507 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
508 // Only demanding an intersection of the bits.
509 if (SimplifyDemandedBits(I->getOperand(0), RHS->getRawValue() & Mask,
510 Depth+1))
511 return true;
512 if (~Mask & RHS->getRawValue()) {
513 // If this is producing any bits that are not needed, simplify the RHS.
514 if (I->getType()->isSigned()) {
515 int64_t Val = Mask & cast<ConstantSInt>(RHS)->getValue();
516 I->setOperand(1, ConstantSInt::get(I->getType(), Val));
517 } else {
518 uint64_t Val = Mask & cast<ConstantUInt>(RHS)->getValue();
519 I->setOperand(1, ConstantUInt::get(I->getType(), Val));
520 }
521 return UpdateValueUsesWith(I, I);
522 }
523 }
524 // Walk the LHS and the RHS.
525 return SimplifyDemandedBits(I->getOperand(0), Mask, Depth+1) ||
526 SimplifyDemandedBits(I->getOperand(1), Mask, Depth+1);
527 case Instruction::Or:
528 case Instruction::Xor:
529 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
530 // If none of the [x]or'd in bits are demanded, don't both with the [x]or.
531 if ((Mask & RHS->getRawValue()) == 0)
532 return UpdateValueUsesWith(I, I->getOperand(0));
533
534 // Otherwise, for an OR, we only demand those bits not set by the OR.
535 if (I->getOpcode() == Instruction::Or)
536 Mask &= ~RHS->getRawValue();
537 return SimplifyDemandedBits(I->getOperand(0), Mask, Depth+1);
538 }
539 // Walk the LHS and the RHS.
540 return SimplifyDemandedBits(I->getOperand(0), Mask, Depth+1) ||
541 SimplifyDemandedBits(I->getOperand(1), Mask, Depth+1);
542 case Instruction::Cast: {
543 const Type *SrcTy = I->getOperand(0)->getType();
544 if (SrcTy == Type::BoolTy)
545 return SimplifyDemandedBits(I->getOperand(0), Mask&1, Depth+1);
546
547 if (!SrcTy->isInteger()) return false;
548
549 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
550 // If this is a sign-extend, treat specially.
551 if (SrcTy->isSigned() &&
552 SrcBits < I->getType()->getPrimitiveSizeInBits()) {
553 // If none of the top bits are demanded, convert this into an unsigned
554 // extend instead of a sign extend.
555 if ((Mask & ((1ULL << SrcBits)-1)) == 0) {
556 // Convert to unsigned first.
557 Value *NewVal;
558 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
559 I->getOperand(0)->getName(), I);
560 NewVal = new CastInst(I->getOperand(0), I->getType(), I->getName());
561 return UpdateValueUsesWith(I, NewVal);
562 }
563
564 // Otherwise, the high-bits *are* demanded. This means that the code
565 // implicitly demands computation of the sign bit of the input, make sure
566 // we explicitly include it in Mask.
567 Mask |= 1ULL << (SrcBits-1);
568 }
569
570 // If this is an extension, the top bits are ignored.
571 Mask &= SrcTy->getIntegralTypeMask();
572 return SimplifyDemandedBits(I->getOperand(0), Mask, Depth+1);
573 }
574 case Instruction::Select:
575 // Simplify the T and F values if they are not demanded.
576 return SimplifyDemandedBits(I->getOperand(2), Mask, Depth+1) ||
577 SimplifyDemandedBits(I->getOperand(1), Mask, Depth+1);
578 case Instruction::Shl:
579 // We only demand the low bits of the input.
580 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
581 return SimplifyDemandedBits(I->getOperand(0), Mask >> SA->getValue(),
582 Depth+1);
583 break;
584 case Instruction::Shr:
585 // We only demand the high bits of the input.
586 if (I->getType()->isUnsigned())
587 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
588 Mask <<= SA->getValue();
589 Mask &= I->getType()->getIntegralTypeMask();
590 return SimplifyDemandedBits(I->getOperand(0), Mask, Depth+1);
591 }
592 // FIXME: handle signed shr, demanding the appropriate bits. If the top
593 // bits aren't demanded, strength reduce to a logical SHR instead.
594 break;
595 }
596 return false;
597}
598
Chris Lattner623826c2004-09-28 21:48:02 +0000599// isTrueWhenEqual - Return true if the specified setcondinst instruction is
600// true when both operands are equal...
601//
602static bool isTrueWhenEqual(Instruction &I) {
603 return I.getOpcode() == Instruction::SetEQ ||
604 I.getOpcode() == Instruction::SetGE ||
605 I.getOpcode() == Instruction::SetLE;
606}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000607
608/// AssociativeOpt - Perform an optimization on an associative operator. This
609/// function is designed to check a chain of associative operators for a
610/// potential to apply a certain optimization. Since the optimization may be
611/// applicable if the expression was reassociated, this checks the chain, then
612/// reassociates the expression as necessary to expose the optimization
613/// opportunity. This makes use of a special Functor, which must define
614/// 'shouldApply' and 'apply' methods.
615///
616template<typename Functor>
617Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
618 unsigned Opcode = Root.getOpcode();
619 Value *LHS = Root.getOperand(0);
620
621 // Quick check, see if the immediate LHS matches...
622 if (F.shouldApply(LHS))
623 return F.apply(Root);
624
625 // Otherwise, if the LHS is not of the same opcode as the root, return.
626 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000627 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000628 // Should we apply this transform to the RHS?
629 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
630
631 // If not to the RHS, check to see if we should apply to the LHS...
632 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
633 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
634 ShouldApply = true;
635 }
636
637 // If the functor wants to apply the optimization to the RHS of LHSI,
638 // reassociate the expression from ((? op A) op B) to (? op (A op B))
639 if (ShouldApply) {
640 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000641
Chris Lattnerb8b97502003-08-13 19:01:45 +0000642 // Now all of the instructions are in the current basic block, go ahead
643 // and perform the reassociation.
644 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
645
646 // First move the selected RHS to the LHS of the root...
647 Root.setOperand(0, LHSI->getOperand(1));
648
649 // Make what used to be the LHS of the root be the user of the root...
650 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000651 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000652 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
653 return 0;
654 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000655 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000656 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000657 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
658 BasicBlock::iterator ARI = &Root; ++ARI;
659 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
660 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000661
662 // Now propagate the ExtraOperand down the chain of instructions until we
663 // get to LHSI.
664 while (TmpLHSI != LHSI) {
665 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000666 // Move the instruction to immediately before the chain we are
667 // constructing to avoid breaking dominance properties.
668 NextLHSI->getParent()->getInstList().remove(NextLHSI);
669 BB->getInstList().insert(ARI, NextLHSI);
670 ARI = NextLHSI;
671
Chris Lattnerb8b97502003-08-13 19:01:45 +0000672 Value *NextOp = NextLHSI->getOperand(1);
673 NextLHSI->setOperand(1, ExtraOperand);
674 TmpLHSI = NextLHSI;
675 ExtraOperand = NextOp;
676 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000677
Chris Lattnerb8b97502003-08-13 19:01:45 +0000678 // Now that the instructions are reassociated, have the functor perform
679 // the transformation...
680 return F.apply(Root);
681 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000682
Chris Lattnerb8b97502003-08-13 19:01:45 +0000683 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
684 }
685 return 0;
686}
687
688
689// AddRHS - Implements: X + X --> X << 1
690struct AddRHS {
691 Value *RHS;
692 AddRHS(Value *rhs) : RHS(rhs) {}
693 bool shouldApply(Value *LHS) const { return LHS == RHS; }
694 Instruction *apply(BinaryOperator &Add) const {
695 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
696 ConstantInt::get(Type::UByteTy, 1));
697 }
698};
699
700// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
701// iff C1&C2 == 0
702struct AddMaskingAnd {
703 Constant *C2;
704 AddMaskingAnd(Constant *c) : C2(c) {}
705 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000706 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000707 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +0000708 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000709 }
710 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000711 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000712 }
713};
714
Chris Lattner86102b82005-01-01 16:22:27 +0000715static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +0000716 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +0000717 if (isa<CastInst>(I)) {
718 if (Constant *SOC = dyn_cast<Constant>(SO))
719 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000720
Chris Lattner86102b82005-01-01 16:22:27 +0000721 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
722 SO->getName() + ".cast"), I);
723 }
724
Chris Lattner183b3362004-04-09 19:05:30 +0000725 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +0000726 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
727 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000728
Chris Lattner183b3362004-04-09 19:05:30 +0000729 if (Constant *SOC = dyn_cast<Constant>(SO)) {
730 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +0000731 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
732 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +0000733 }
734
735 Value *Op0 = SO, *Op1 = ConstOperand;
736 if (!ConstIsRHS)
737 std::swap(Op0, Op1);
738 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +0000739 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
740 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
741 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
742 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000743 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000744 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000745 abort();
746 }
Chris Lattner86102b82005-01-01 16:22:27 +0000747 return IC->InsertNewInstBefore(New, I);
748}
749
750// FoldOpIntoSelect - Given an instruction with a select as one operand and a
751// constant as the other operand, try to fold the binary operator into the
752// select arguments. This also works for Cast instructions, which obviously do
753// not have a second operand.
754static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
755 InstCombiner *IC) {
756 // Don't modify shared select instructions
757 if (!SI->hasOneUse()) return 0;
758 Value *TV = SI->getOperand(1);
759 Value *FV = SI->getOperand(2);
760
761 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +0000762 // Bool selects with constant operands can be folded to logical ops.
763 if (SI->getType() == Type::BoolTy) return 0;
764
Chris Lattner86102b82005-01-01 16:22:27 +0000765 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
766 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
767
768 return new SelectInst(SI->getCondition(), SelectTrueVal,
769 SelectFalseVal);
770 }
771 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +0000772}
773
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000774
775/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
776/// node as operand #0, see if we can fold the instruction into the PHI (which
777/// is only possible if all operands to the PHI are constants).
778Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
779 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +0000780 unsigned NumPHIValues = PN->getNumIncomingValues();
781 if (!PN->hasOneUse() || NumPHIValues == 0 ||
782 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000783
784 // Check to see if all of the operands of the PHI are constants. If not, we
785 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +0000786 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000787 if (!isa<Constant>(PN->getIncomingValue(i)))
788 return 0;
789
790 // Okay, we can do the transformation: create the new PHI node.
791 PHINode *NewPN = new PHINode(I.getType(), I.getName());
792 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +0000793 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000794 InsertNewInstBefore(NewPN, *PN);
795
796 // Next, add all of the operands to the PHI.
797 if (I.getNumOperands() == 2) {
798 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +0000799 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000800 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
801 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
802 PN->getIncomingBlock(i));
803 }
804 } else {
805 assert(isa<CastInst>(I) && "Unary op should be a cast!");
806 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +0000807 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000808 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
809 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
810 PN->getIncomingBlock(i));
811 }
812 }
813 return ReplaceInstUsesWith(I, NewPN);
814}
815
Chris Lattner113f4f42002-06-25 16:13:24 +0000816Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000817 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000818 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000819
Chris Lattnercf4a9962004-04-10 22:01:55 +0000820 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000821 // X + undef -> undef
822 if (isa<UndefValue>(RHS))
823 return ReplaceInstUsesWith(I, RHS);
824
Chris Lattnercf4a9962004-04-10 22:01:55 +0000825 // X + 0 --> X
Chris Lattner7fde91e2005-10-17 17:56:38 +0000826 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
827 if (RHSC->isNullValue())
828 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +0000829 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
830 if (CFP->isExactlyValue(-0.0))
831 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +0000832 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000833
Chris Lattnercf4a9962004-04-10 22:01:55 +0000834 // X + (signbit) --> X ^ signbit
835 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner77defba2006-02-07 07:00:41 +0000836 uint64_t Val = CI->getRawValue() & CI->getType()->getIntegralTypeMask();
837 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000838 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000839 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000840
841 if (isa<PHINode>(LHS))
842 if (Instruction *NV = FoldOpIntoPhi(I))
843 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000844
Chris Lattner330628a2006-01-06 17:59:59 +0000845 ConstantInt *XorRHS = 0;
846 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000847 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
848 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
849 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
850 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
851
852 uint64_t C0080Val = 1ULL << 31;
853 int64_t CFF80Val = -C0080Val;
854 unsigned Size = 32;
855 do {
856 if (TySizeBits > Size) {
857 bool Found = false;
858 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
859 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
860 if (RHSSExt == CFF80Val) {
861 if (XorRHS->getZExtValue() == C0080Val)
862 Found = true;
863 } else if (RHSZExt == C0080Val) {
864 if (XorRHS->getSExtValue() == CFF80Val)
865 Found = true;
866 }
867 if (Found) {
868 // This is a sign extend if the top bits are known zero.
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000869 uint64_t Mask = XorLHS->getType()->getIntegralTypeMask();
870 Mask <<= 64-(TySizeBits-Size);
871 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +0000872 Size = 0; // Not a sign ext, but can't be any others either.
873 goto FoundSExt;
874 }
875 }
876 Size >>= 1;
877 C0080Val >>= Size;
878 CFF80Val >>= Size;
879 } while (Size >= 8);
880
881FoundSExt:
882 const Type *MiddleType = 0;
883 switch (Size) {
884 default: break;
885 case 32: MiddleType = Type::IntTy; break;
886 case 16: MiddleType = Type::ShortTy; break;
887 case 8: MiddleType = Type::SByteTy; break;
888 }
889 if (MiddleType) {
890 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
891 InsertNewInstBefore(NewTrunc, I);
892 return new CastInst(NewTrunc, I.getType());
893 }
894 }
Chris Lattnercf4a9962004-04-10 22:01:55 +0000895 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000896
Chris Lattnerb8b97502003-08-13 19:01:45 +0000897 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000898 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000899 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +0000900
901 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
902 if (RHSI->getOpcode() == Instruction::Sub)
903 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
904 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
905 }
906 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
907 if (LHSI->getOpcode() == Instruction::Sub)
908 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
909 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
910 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000911 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000912
Chris Lattner147e9752002-05-08 22:46:53 +0000913 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000914 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000915 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000916
917 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000918 if (!isa<Constant>(RHS))
919 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000920 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000921
Misha Brukmanb1c93172005-04-21 23:48:37 +0000922
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000923 ConstantInt *C2;
924 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
925 if (X == RHS) // X*C + X --> X * (C+1)
926 return BinaryOperator::createMul(RHS, AddOne(C2));
927
928 // X*C1 + X*C2 --> X * (C1+C2)
929 ConstantInt *C1;
930 if (X == dyn_castFoldableMul(RHS, C1))
931 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +0000932 }
933
934 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000935 if (dyn_castFoldableMul(RHS, C2) == LHS)
936 return BinaryOperator::createMul(LHS, AddOne(C2));
937
Chris Lattner57c8d992003-02-18 19:57:07 +0000938
Chris Lattnerb8b97502003-08-13 19:01:45 +0000939 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000940 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000941 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000942
Chris Lattnerb9cde762003-10-02 15:11:26 +0000943 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +0000944 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +0000945 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
946 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
947 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000948 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000949
Chris Lattnerbff91d92004-10-08 05:07:56 +0000950 // (X & FF00) + xx00 -> (X+xx00) & FF00
951 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
952 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
953 if (Anded == CRHS) {
954 // See if all bits from the first bit set in the Add RHS up are included
955 // in the mask. First, get the rightmost bit.
956 uint64_t AddRHSV = CRHS->getRawValue();
957
958 // Form a mask of all bits from the lowest bit added through the top.
959 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +0000960 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +0000961
962 // See if the and mask includes all of these bits.
963 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000964
Chris Lattnerbff91d92004-10-08 05:07:56 +0000965 if (AddRHSHighBits == AddRHSHighBitsAnd) {
966 // Okay, the xform is safe. Insert the new add pronto.
967 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
968 LHS->getName()), I);
969 return BinaryOperator::createAnd(NewAdd, C2);
970 }
971 }
972 }
973
Chris Lattnerd4252a72004-07-30 07:50:03 +0000974 // Try to fold constant add into select arguments.
975 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +0000976 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +0000977 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000978 }
979
Chris Lattner113f4f42002-06-25 16:13:24 +0000980 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000981}
982
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000983// isSignBit - Return true if the value represented by the constant only has the
984// highest order bit set.
985static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000986 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner2f1457f2005-04-24 17:46:05 +0000987 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000988}
989
Chris Lattner022167f2004-03-13 00:11:49 +0000990/// RemoveNoopCast - Strip off nonconverting casts from the value.
991///
992static Value *RemoveNoopCast(Value *V) {
993 if (CastInst *CI = dyn_cast<CastInst>(V)) {
994 const Type *CTy = CI->getType();
995 const Type *OpTy = CI->getOperand(0)->getType();
996 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000997 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +0000998 return RemoveNoopCast(CI->getOperand(0));
999 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1000 return RemoveNoopCast(CI->getOperand(0));
1001 }
1002 return V;
1003}
1004
Chris Lattner113f4f42002-06-25 16:13:24 +00001005Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001006 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001007
Chris Lattnere6794492002-08-12 21:17:25 +00001008 if (Op0 == Op1) // sub X, X -> 0
1009 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001010
Chris Lattnere6794492002-08-12 21:17:25 +00001011 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001012 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001013 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001014
Chris Lattner81a7a232004-10-16 18:11:37 +00001015 if (isa<UndefValue>(Op0))
1016 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1017 if (isa<UndefValue>(Op1))
1018 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1019
Chris Lattner8f2f5982003-11-05 01:06:05 +00001020 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1021 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001022 if (C->isAllOnesValue())
1023 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001024
Chris Lattner8f2f5982003-11-05 01:06:05 +00001025 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001026 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001027 if (match(Op1, m_Not(m_Value(X))))
1028 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001029 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001030 // -((uint)X >> 31) -> ((int)X >> 31)
1031 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001032 if (C->isNullValue()) {
1033 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1034 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +00001035 if (SI->getOpcode() == Instruction::Shr)
1036 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1037 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +00001038 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +00001039 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001040 else
Chris Lattner97bfcea2004-06-17 18:16:02 +00001041 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001042 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001043 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +00001044 // Ok, the transformation is safe. Insert a cast of the incoming
1045 // value, then the new shift, then the new cast.
1046 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1047 SI->getOperand(0)->getName());
1048 Value *InV = InsertNewInstBefore(FirstCast, I);
1049 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1050 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +00001051 if (NewShift->getType() == I.getType())
1052 return NewShift;
1053 else {
1054 InV = InsertNewInstBefore(NewShift, I);
1055 return new CastInst(NewShift, I.getType());
1056 }
Chris Lattner92295c52004-03-12 23:53:13 +00001057 }
1058 }
Chris Lattner022167f2004-03-13 00:11:49 +00001059 }
Chris Lattner183b3362004-04-09 19:05:30 +00001060
1061 // Try to fold constant sub into select arguments.
1062 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001063 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001064 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001065
1066 if (isa<PHINode>(Op0))
1067 if (Instruction *NV = FoldOpIntoPhi(I))
1068 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001069 }
1070
Chris Lattnera9be4492005-04-07 16:15:25 +00001071 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1072 if (Op1I->getOpcode() == Instruction::Add &&
1073 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001074 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001075 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001076 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001077 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001078 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1079 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1080 // C1-(X+C2) --> (C1-C2)-X
1081 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1082 Op1I->getOperand(0));
1083 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001084 }
1085
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001086 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001087 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1088 // is not used by anyone else...
1089 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00001090 if (Op1I->getOpcode() == Instruction::Sub &&
1091 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001092 // Swap the two operands of the subexpr...
1093 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1094 Op1I->setOperand(0, IIOp1);
1095 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001096
Chris Lattner3082c5a2003-02-18 19:28:33 +00001097 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001098 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001099 }
1100
1101 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1102 //
1103 if (Op1I->getOpcode() == Instruction::And &&
1104 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1105 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1106
Chris Lattner396dbfe2004-06-09 05:08:07 +00001107 Value *NewNot =
1108 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001109 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001110 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001111
Chris Lattner0aee4b72004-10-06 15:08:25 +00001112 // -(X sdiv C) -> (X sdiv -C)
1113 if (Op1I->getOpcode() == Instruction::Div)
1114 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattnera9be4492005-04-07 16:15:25 +00001115 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00001116 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001117 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00001118 ConstantExpr::getNeg(DivRHS));
1119
Chris Lattner57c8d992003-02-18 19:57:07 +00001120 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001121 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001122 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001123 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001124 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001125 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00001126 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00001127 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001128 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001129
Chris Lattner47060462005-04-07 17:14:51 +00001130 if (!Op0->getType()->isFloatingPoint())
1131 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1132 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00001133 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1134 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1135 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1136 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00001137 } else if (Op0I->getOpcode() == Instruction::Sub) {
1138 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1139 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00001140 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001141
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001142 ConstantInt *C1;
1143 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1144 if (X == Op1) { // X*C - X --> X * (C-1)
1145 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1146 return BinaryOperator::createMul(Op1, CP1);
1147 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001148
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001149 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1150 if (X == dyn_castFoldableMul(Op1, C2))
1151 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1152 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001153 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001154}
1155
Chris Lattnere79e8542004-02-23 06:38:22 +00001156/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1157/// really just returns true if the most significant (sign) bit is set.
1158static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1159 if (RHS->getType()->isSigned()) {
1160 // True if source is LHS < 0 or LHS <= -1
1161 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1162 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1163 } else {
1164 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1165 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1166 // the size of the integer type.
1167 if (Opcode == Instruction::SetGE)
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001168 return RHSC->getValue() ==
1169 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001170 if (Opcode == Instruction::SetGT)
1171 return RHSC->getValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001172 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00001173 }
1174 return false;
1175}
1176
Chris Lattner113f4f42002-06-25 16:13:24 +00001177Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001178 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001179 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00001180
Chris Lattner81a7a232004-10-16 18:11:37 +00001181 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1182 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1183
Chris Lattnere6794492002-08-12 21:17:25 +00001184 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001185 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1186 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00001187
1188 // ((X << C1)*C2) == (X * (C2 << C1))
1189 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1190 if (SI->getOpcode() == Instruction::Shl)
1191 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001192 return BinaryOperator::createMul(SI->getOperand(0),
1193 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001194
Chris Lattnercce81be2003-09-11 22:24:54 +00001195 if (CI->isNullValue())
1196 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1197 if (CI->equalsInt(1)) // X * 1 == X
1198 return ReplaceInstUsesWith(I, Op0);
1199 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00001200 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00001201
Chris Lattnercce81be2003-09-11 22:24:54 +00001202 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001203 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1204 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001205 return new ShiftInst(Instruction::Shl, Op0,
1206 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001207 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001208 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001209 if (Op1F->isNullValue())
1210 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00001211
Chris Lattner3082c5a2003-02-18 19:28:33 +00001212 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1213 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1214 if (Op1F->getValue() == 1.0)
1215 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1216 }
Chris Lattner183b3362004-04-09 19:05:30 +00001217
1218 // Try to fold constant mul into select arguments.
1219 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001220 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001221 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001222
1223 if (isa<PHINode>(Op0))
1224 if (Instruction *NV = FoldOpIntoPhi(I))
1225 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00001226 }
1227
Chris Lattner934a64cf2003-03-10 23:23:04 +00001228 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1229 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001230 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00001231
Chris Lattner2635b522004-02-23 05:39:21 +00001232 // If one of the operands of the multiply is a cast from a boolean value, then
1233 // we know the bool is either zero or one, so this is a 'masking' multiply.
1234 // See if we can simplify things based on how the boolean was originally
1235 // formed.
1236 CastInst *BoolCast = 0;
1237 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1238 if (CI->getOperand(0)->getType() == Type::BoolTy)
1239 BoolCast = CI;
1240 if (!BoolCast)
1241 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1242 if (CI->getOperand(0)->getType() == Type::BoolTy)
1243 BoolCast = CI;
1244 if (BoolCast) {
1245 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1246 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1247 const Type *SCOpTy = SCIOp0->getType();
1248
Chris Lattnere79e8542004-02-23 06:38:22 +00001249 // If the setcc is true iff the sign bit of X is set, then convert this
1250 // multiply into a shift/and combination.
1251 if (isa<ConstantInt>(SCIOp1) &&
1252 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00001253 // Shift the X value right to turn it into "all signbits".
1254 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001255 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001256 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00001257 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +00001258 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1259 SCIOp0->getName()), I);
1260 }
1261
1262 Value *V =
1263 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1264 BoolCast->getOperand(0)->getName()+
1265 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00001266
1267 // If the multiply type is not the same as the source type, sign extend
1268 // or truncate to the multiply type.
1269 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +00001270 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001271
Chris Lattner2635b522004-02-23 05:39:21 +00001272 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001273 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00001274 }
1275 }
1276 }
1277
Chris Lattner113f4f42002-06-25 16:13:24 +00001278 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001279}
1280
Chris Lattner113f4f42002-06-25 16:13:24 +00001281Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001282 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00001283
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001284 if (isa<UndefValue>(Op0)) // undef / X -> 0
1285 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1286 if (isa<UndefValue>(Op1))
1287 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1288
1289 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00001290 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001291 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001292 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001293
Chris Lattnere20c3342004-04-26 14:01:59 +00001294 // div X, -1 == -X
1295 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001296 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00001297
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001298 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001299 if (LHS->getOpcode() == Instruction::Div)
1300 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001301 // (X / C1) / C2 -> X / (C1*C2)
1302 return BinaryOperator::createDiv(LHS->getOperand(0),
1303 ConstantExpr::getMul(RHS, LHSRHS));
1304 }
1305
Chris Lattner3082c5a2003-02-18 19:28:33 +00001306 // Check to see if this is an unsigned division with an exact power of 2,
1307 // if so, convert to a right shift.
1308 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1309 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattner22d00a82005-08-02 19:16:58 +00001310 if (isPowerOf2_64(Val)) {
1311 uint64_t C = Log2_64(Val);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001312 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001313 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001314 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001315
Chris Lattner4ad08352004-10-09 02:50:40 +00001316 // -X/C -> X/-C
1317 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001318 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001319 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1320
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001321 if (!RHS->isNullValue()) {
1322 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001323 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001324 return R;
1325 if (isa<PHINode>(Op0))
1326 if (Instruction *NV = FoldOpIntoPhi(I))
1327 return NV;
1328 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001329 }
1330
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001331 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1332 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1333 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1334 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1335 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1336 if (STO->getValue() == 0) { // Couldn't be this argument.
1337 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001338 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001339 } else if (SFO->getValue() == 0) {
Chris Lattner89dc4f12005-06-16 04:55:52 +00001340 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001341 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001342 }
1343
Chris Lattner42362612005-04-08 04:03:26 +00001344 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001345 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1346 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattner42362612005-04-08 04:03:26 +00001347 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1348 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1349 TC, SI->getName()+".t");
1350 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001351
Chris Lattner42362612005-04-08 04:03:26 +00001352 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1353 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1354 FC, SI->getName()+".f");
1355 FSI = InsertNewInstBefore(FSI, I);
1356 return new SelectInst(SI->getOperand(0), TSI, FSI);
1357 }
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001358 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001359
Chris Lattner3082c5a2003-02-18 19:28:33 +00001360 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001361 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001362 if (LHS->equalsInt(0))
1363 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1364
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001365 if (I.getType()->isSigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001366 // If the sign bits of both operands are zero (i.e. we can prove they are
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001367 // unsigned inputs), turn this into a udiv.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001368 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1369 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001370 const Type *NTy = Op0->getType()->getUnsignedVersion();
1371 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1372 InsertNewInstBefore(LHS, I);
1373 Value *RHS;
1374 if (Constant *R = dyn_cast<Constant>(Op1))
1375 RHS = ConstantExpr::getCast(R, NTy);
1376 else
1377 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1378 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1379 InsertNewInstBefore(Div, I);
1380 return new CastInst(Div, I.getType());
1381 }
Chris Lattner2e90b732006-02-05 07:54:04 +00001382 } else {
1383 // Known to be an unsigned division.
1384 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1385 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
1386 if (RHSI->getOpcode() == Instruction::Shl &&
1387 isa<ConstantUInt>(RHSI->getOperand(0))) {
1388 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1389 if (isPowerOf2_64(C1)) {
1390 unsigned C2 = Log2_64(C1);
1391 Value *Add = RHSI->getOperand(1);
1392 if (C2) {
1393 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
1394 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
1395 "tmp"), I);
1396 }
1397 return new ShiftInst(Instruction::Shr, Op0, Add);
1398 }
1399 }
1400 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001401 }
1402
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001403 return 0;
1404}
1405
1406
Chris Lattner113f4f42002-06-25 16:13:24 +00001407Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001408 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001409 if (I.getType()->isSigned()) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001410 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00001411 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00001412 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001413 // X % -Y -> X % Y
1414 AddUsesToWorkList(I);
1415 I.setOperand(1, RHSNeg);
1416 return &I;
1417 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001418
1419 // If the top bits of both operands are zero (i.e. we can prove they are
1420 // unsigned inputs), turn this into a urem.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001421 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1422 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001423 const Type *NTy = Op0->getType()->getUnsignedVersion();
1424 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1425 InsertNewInstBefore(LHS, I);
1426 Value *RHS;
1427 if (Constant *R = dyn_cast<Constant>(Op1))
1428 RHS = ConstantExpr::getCast(R, NTy);
1429 else
1430 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1431 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
1432 InsertNewInstBefore(Rem, I);
1433 return new CastInst(Rem, I.getType());
1434 }
1435 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00001436
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001437 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00001438 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001439 if (isa<UndefValue>(Op1))
1440 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattner81a7a232004-10-16 18:11:37 +00001441
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001442 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001443 if (RHS->equalsInt(1)) // X % 1 == 0
1444 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1445
1446 // Check to see if this is an unsigned remainder with an exact power of 2,
1447 // if so, convert to a bitwise and.
1448 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1449 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +00001450 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001451 return BinaryOperator::createAnd(Op0,
1452 ConstantUInt::get(I.getType(), Val-1));
1453
1454 if (!RHS->isNullValue()) {
1455 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001456 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001457 return R;
1458 if (isa<PHINode>(Op0))
1459 if (Instruction *NV = FoldOpIntoPhi(I))
1460 return NV;
1461 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001462 }
1463
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001464 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1465 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1466 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1467 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1468 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1469 if (STO->getValue() == 0) { // Couldn't be this argument.
1470 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001471 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001472 } else if (SFO->getValue() == 0) {
1473 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001474 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001475 }
1476
1477 if (!(STO->getValue() & (STO->getValue()-1)) &&
1478 !(SFO->getValue() & (SFO->getValue()-1))) {
1479 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1480 SubOne(STO), SI->getName()+".t"), I);
1481 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1482 SubOne(SFO), SI->getName()+".f"), I);
1483 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1484 }
1485 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001486
Chris Lattner3082c5a2003-02-18 19:28:33 +00001487 // 0 % X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001488 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001489 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +00001490 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1491
Chris Lattner2e90b732006-02-05 07:54:04 +00001492
1493 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1494 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
1495 if (I.getType()->isUnsigned() &&
1496 RHSI->getOpcode() == Instruction::Shl &&
1497 isa<ConstantUInt>(RHSI->getOperand(0))) {
1498 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1499 if (isPowerOf2_64(C1)) {
1500 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
1501 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
1502 "tmp"), I);
1503 return BinaryOperator::createAnd(Op0, Add);
1504 }
1505 }
1506 }
1507
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001508 return 0;
1509}
1510
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001511// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001512static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner77defba2006-02-07 07:00:41 +00001513 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1514 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001515
1516 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001517
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001518 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001519 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001520 int64_t Val = INT64_MAX; // All ones
1521 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1522 return CS->getValue() == Val-1;
1523}
1524
1525// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001526static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001527 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1528 return CU->getValue() == 1;
1529
1530 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001531
1532 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001533 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001534 int64_t Val = -1; // All ones
1535 Val <<= TypeBits-1; // Shift over to the right spot
1536 return CS->getValue() == Val+1;
1537}
1538
Chris Lattner35167c32004-06-09 07:59:58 +00001539// isOneBitSet - Return true if there is exactly one bit set in the specified
1540// constant.
1541static bool isOneBitSet(const ConstantInt *CI) {
1542 uint64_t V = CI->getRawValue();
1543 return V && (V & (V-1)) == 0;
1544}
1545
Chris Lattner8fc5af42004-09-23 21:46:38 +00001546#if 0 // Currently unused
1547// isLowOnes - Return true if the constant is of the form 0+1+.
1548static bool isLowOnes(const ConstantInt *CI) {
1549 uint64_t V = CI->getRawValue();
1550
1551 // There won't be bits set in parts that the type doesn't contain.
1552 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1553
1554 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1555 return U && V && (U & V) == 0;
1556}
1557#endif
1558
1559// isHighOnes - Return true if the constant is of the form 1+0+.
1560// This is the same as lowones(~X).
1561static bool isHighOnes(const ConstantInt *CI) {
1562 uint64_t V = ~CI->getRawValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00001563 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00001564
1565 // There won't be bits set in parts that the type doesn't contain.
1566 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1567
1568 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1569 return U && V && (U & V) == 0;
1570}
1571
1572
Chris Lattner3ac7c262003-08-13 20:16:26 +00001573/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1574/// are carefully arranged to allow folding of expressions such as:
1575///
1576/// (A < B) | (A > B) --> (A != B)
1577///
1578/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1579/// represents that the comparison is true if A == B, and bit value '1' is true
1580/// if A < B.
1581///
1582static unsigned getSetCondCode(const SetCondInst *SCI) {
1583 switch (SCI->getOpcode()) {
1584 // False -> 0
1585 case Instruction::SetGT: return 1;
1586 case Instruction::SetEQ: return 2;
1587 case Instruction::SetGE: return 3;
1588 case Instruction::SetLT: return 4;
1589 case Instruction::SetNE: return 5;
1590 case Instruction::SetLE: return 6;
1591 // True -> 7
1592 default:
1593 assert(0 && "Invalid SetCC opcode!");
1594 return 0;
1595 }
1596}
1597
1598/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1599/// opcode and two operands into either a constant true or false, or a brand new
1600/// SetCC instruction.
1601static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1602 switch (Opcode) {
1603 case 0: return ConstantBool::False;
1604 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1605 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1606 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1607 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1608 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1609 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1610 case 7: return ConstantBool::True;
1611 default: assert(0 && "Illegal SetCCCode!"); return 0;
1612 }
1613}
1614
1615// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1616struct FoldSetCCLogical {
1617 InstCombiner &IC;
1618 Value *LHS, *RHS;
1619 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1620 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1621 bool shouldApply(Value *V) const {
1622 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1623 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1624 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1625 return false;
1626 }
1627 Instruction *apply(BinaryOperator &Log) const {
1628 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1629 if (SCI->getOperand(0) != LHS) {
1630 assert(SCI->getOperand(1) == LHS);
1631 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1632 }
1633
1634 unsigned LHSCode = getSetCondCode(SCI);
1635 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1636 unsigned Code;
1637 switch (Log.getOpcode()) {
1638 case Instruction::And: Code = LHSCode & RHSCode; break;
1639 case Instruction::Or: Code = LHSCode | RHSCode; break;
1640 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001641 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001642 }
1643
1644 Value *RV = getSetCCValue(Code, LHS, RHS);
1645 if (Instruction *I = dyn_cast<Instruction>(RV))
1646 return I;
1647 // Otherwise, it's a constant boolean value...
1648 return IC.ReplaceInstUsesWith(Log, RV);
1649 }
1650};
1651
Chris Lattnerba1cb382003-09-19 17:17:26 +00001652// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1653// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1654// guaranteed to be either a shift instruction or a binary operator.
1655Instruction *InstCombiner::OptAndOp(Instruction *Op,
1656 ConstantIntegral *OpRHS,
1657 ConstantIntegral *AndRHS,
1658 BinaryOperator &TheAnd) {
1659 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001660 Constant *Together = 0;
1661 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001662 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001663
Chris Lattnerba1cb382003-09-19 17:17:26 +00001664 switch (Op->getOpcode()) {
1665 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00001666 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001667 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1668 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001669 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001670 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001671 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001672 }
1673 break;
1674 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00001675 if (Together == AndRHS) // (X | C) & C --> C
1676 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001677
Chris Lattner86102b82005-01-01 16:22:27 +00001678 if (Op->hasOneUse() && Together != OpRHS) {
1679 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1680 std::string Op0Name = Op->getName(); Op->setName("");
1681 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1682 InsertNewInstBefore(Or, TheAnd);
1683 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001684 }
1685 break;
1686 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001687 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001688 // Adding a one to a single bit bit-field should be turned into an XOR
1689 // of the bit. First thing to check is to see if this AND is with a
1690 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001691 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001692
1693 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00001694 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001695
1696 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001697 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001698 // Ok, at this point, we know that we are masking the result of the
1699 // ADD down to exactly one bit. If the constant we are adding has
1700 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001701 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001702
Chris Lattnerba1cb382003-09-19 17:17:26 +00001703 // Check to see if any bits below the one bit set in AndRHSV are set.
1704 if ((AddRHS & (AndRHSV-1)) == 0) {
1705 // If not, the only thing that can effect the output of the AND is
1706 // the bit specified by AndRHSV. If that bit is set, the effect of
1707 // the XOR is to toggle the bit. If it is clear, then the ADD has
1708 // no effect.
1709 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1710 TheAnd.setOperand(0, X);
1711 return &TheAnd;
1712 } else {
1713 std::string Name = Op->getName(); Op->setName("");
1714 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001715 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001716 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001717 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001718 }
1719 }
1720 }
1721 }
1722 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001723
1724 case Instruction::Shl: {
1725 // We know that the AND will not produce any of the bits shifted in, so if
1726 // the anded constant includes them, clear them now!
1727 //
1728 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001729 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1730 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001731
Chris Lattner7e794272004-09-24 15:21:34 +00001732 if (CI == ShlMask) { // Masking out bits that the shift already masks
1733 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1734 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001735 TheAnd.setOperand(1, CI);
1736 return &TheAnd;
1737 }
1738 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001739 }
Chris Lattner2da29172003-09-19 19:05:02 +00001740 case Instruction::Shr:
1741 // We know that the AND will not produce any of the bits shifted in, so if
1742 // the anded constant includes them, clear them now! This only applies to
1743 // unsigned shifts, because a signed shr may bring in set bits!
1744 //
1745 if (AndRHS->getType()->isUnsigned()) {
1746 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001747 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1748 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1749
1750 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1751 return ReplaceInstUsesWith(TheAnd, Op);
1752 } else if (CI != AndRHS) {
1753 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001754 return &TheAnd;
1755 }
Chris Lattner7e794272004-09-24 15:21:34 +00001756 } else { // Signed shr.
1757 // See if this is shifting in some sign extension, then masking it out
1758 // with an and.
1759 if (Op->hasOneUse()) {
1760 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1761 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1762 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00001763 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00001764 // Make the argument unsigned.
1765 Value *ShVal = Op->getOperand(0);
1766 ShVal = InsertCastBefore(ShVal,
1767 ShVal->getType()->getUnsignedVersion(),
1768 TheAnd);
1769 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1770 OpRHS, Op->getName()),
1771 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00001772 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1773 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1774 TheAnd.getName()),
1775 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00001776 return new CastInst(ShVal, Op->getType());
1777 }
1778 }
Chris Lattner2da29172003-09-19 19:05:02 +00001779 }
1780 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001781 }
1782 return 0;
1783}
1784
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001785
Chris Lattner6862fbd2004-09-29 17:40:11 +00001786/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1787/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1788/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1789/// insert new instructions.
1790Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1791 bool Inside, Instruction &IB) {
1792 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1793 "Lo is not <= Hi in range emission code!");
1794 if (Inside) {
1795 if (Lo == Hi) // Trivially false.
1796 return new SetCondInst(Instruction::SetNE, V, V);
1797 if (cast<ConstantIntegral>(Lo)->isMinValue())
1798 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001799
Chris Lattner6862fbd2004-09-29 17:40:11 +00001800 Constant *AddCST = ConstantExpr::getNeg(Lo);
1801 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1802 InsertNewInstBefore(Add, IB);
1803 // Convert to unsigned for the comparison.
1804 const Type *UnsType = Add->getType()->getUnsignedVersion();
1805 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1806 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1807 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1808 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1809 }
1810
1811 if (Lo == Hi) // Trivially true.
1812 return new SetCondInst(Instruction::SetEQ, V, V);
1813
1814 Hi = SubOne(cast<ConstantInt>(Hi));
1815 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1816 return new SetCondInst(Instruction::SetGT, V, Hi);
1817
1818 // Emit X-Lo > Hi-Lo-1
1819 Constant *AddCST = ConstantExpr::getNeg(Lo);
1820 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1821 InsertNewInstBefore(Add, IB);
1822 // Convert to unsigned for the comparison.
1823 const Type *UnsType = Add->getType()->getUnsignedVersion();
1824 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1825 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1826 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1827 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1828}
1829
Chris Lattnerb4b25302005-09-18 07:22:02 +00001830// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
1831// any number of 0s on either side. The 1s are allowed to wrap from LSB to
1832// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
1833// not, since all 1s are not contiguous.
1834static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
1835 uint64_t V = Val->getRawValue();
1836 if (!isShiftedMask_64(V)) return false;
1837
1838 // look for the first zero bit after the run of ones
1839 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
1840 // look for the first non-zero bit
1841 ME = 64-CountLeadingZeros_64(V);
1842 return true;
1843}
1844
1845
1846
1847/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
1848/// where isSub determines whether the operator is a sub. If we can fold one of
1849/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00001850///
1851/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
1852/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1853/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1854///
1855/// return (A +/- B).
1856///
1857Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
1858 ConstantIntegral *Mask, bool isSub,
1859 Instruction &I) {
1860 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1861 if (!LHSI || LHSI->getNumOperands() != 2 ||
1862 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
1863
1864 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
1865
1866 switch (LHSI->getOpcode()) {
1867 default: return 0;
1868 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00001869 if (ConstantExpr::getAnd(N, Mask) == Mask) {
1870 // If the AndRHS is a power of two minus one (0+1+), this is simple.
1871 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
1872 break;
1873
1874 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
1875 // part, we don't need any explicit masks to take them out of A. If that
1876 // is all N is, ignore it.
1877 unsigned MB, ME;
1878 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001879 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
1880 Mask >>= 64-MB+1;
1881 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00001882 break;
1883 }
1884 }
Chris Lattneraf517572005-09-18 04:24:45 +00001885 return 0;
1886 case Instruction::Or:
1887 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00001888 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
1889 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
1890 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00001891 break;
1892 return 0;
1893 }
1894
1895 Instruction *New;
1896 if (isSub)
1897 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
1898 else
1899 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
1900 return InsertNewInstBefore(New, I);
1901}
1902
Chris Lattner113f4f42002-06-25 16:13:24 +00001903Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001904 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001905 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001906
Chris Lattner81a7a232004-10-16 18:11:37 +00001907 if (isa<UndefValue>(Op1)) // X & undef -> 0
1908 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1909
Chris Lattner86102b82005-01-01 16:22:27 +00001910 // and X, X = X
1911 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00001912 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001913
Chris Lattner86102b82005-01-01 16:22:27 +00001914 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001915 // and X, -1 == X
1916 if (AndRHS->isAllOnesValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001917 return ReplaceInstUsesWith(I, Op0);
Chris Lattner38a1b002005-10-26 17:18:16 +00001918
1919 // and (and X, c1), c2 -> and (x, c1&c2). Handle this case here, before
1920 // calling MaskedValueIsZero, to avoid inefficient cases where we traipse
1921 // through many levels of ands.
1922 {
Chris Lattner330628a2006-01-06 17:59:59 +00001923 Value *X = 0; ConstantInt *C1 = 0;
Chris Lattner38a1b002005-10-26 17:18:16 +00001924 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))))
1925 return BinaryOperator::createAnd(X, ConstantExpr::getAnd(C1, AndRHS));
1926 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001927
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001928 if (MaskedValueIsZero(Op0, AndRHS->getZExtValue())) // LHS & RHS == 0
Chris Lattner86102b82005-01-01 16:22:27 +00001929 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1930
1931 // If the mask is not masking out any bits, there is no reason to do the
1932 // and in the first place.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001933 uint64_t NotAndRHS = // ~ANDRHS
1934 AndRHS->getZExtValue()^Op0->getType()->getIntegralTypeMask();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001935 if (MaskedValueIsZero(Op0, NotAndRHS))
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001936 return ReplaceInstUsesWith(I, Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001937
Chris Lattner2590e512006-02-07 06:56:34 +00001938 // See if we can simplify any instructions used by the LHS whose sole
1939 // purpose is to compute bits we don't care about.
1940 if (SimplifyDemandedBits(Op0, AndRHS->getRawValue()))
1941 return &I;
1942
Chris Lattnerba1cb382003-09-19 17:17:26 +00001943 // Optimize a variety of ((val OP C1) & C2) combinations...
1944 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1945 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001946 Value *Op0LHS = Op0I->getOperand(0);
1947 Value *Op0RHS = Op0I->getOperand(1);
1948 switch (Op0I->getOpcode()) {
1949 case Instruction::Xor:
1950 case Instruction::Or:
1951 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1952 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001953 if (MaskedValueIsZero(Op0LHS, AndRHS->getZExtValue()))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001954 return BinaryOperator::createAnd(Op0RHS, AndRHS);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001955 if (MaskedValueIsZero(Op0RHS, AndRHS->getZExtValue()))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001956 return BinaryOperator::createAnd(Op0LHS, AndRHS);
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001957
1958 // If the mask is only needed on one incoming arm, push it up.
1959 if (Op0I->hasOneUse()) {
1960 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1961 // Not masking anything out for the LHS, move to RHS.
1962 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
1963 Op0RHS->getName()+".masked");
1964 InsertNewInstBefore(NewRHS, I);
1965 return BinaryOperator::create(
1966 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001967 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001968 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001969 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1970 // Not masking anything out for the RHS, move to LHS.
1971 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
1972 Op0LHS->getName()+".masked");
1973 InsertNewInstBefore(NewLHS, I);
1974 return BinaryOperator::create(
1975 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
1976 }
1977 }
1978
Chris Lattner86102b82005-01-01 16:22:27 +00001979 break;
1980 case Instruction::And:
1981 // (X & V) & C2 --> 0 iff (V & C2) == 0
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001982 if (MaskedValueIsZero(Op0LHS, AndRHS->getZExtValue()) ||
1983 MaskedValueIsZero(Op0RHS, AndRHS->getZExtValue()))
Chris Lattner86102b82005-01-01 16:22:27 +00001984 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1985 break;
Chris Lattneraf517572005-09-18 04:24:45 +00001986 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00001987 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1988 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1989 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1990 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1991 return BinaryOperator::createAnd(V, AndRHS);
1992 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1993 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00001994 break;
1995
1996 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00001997 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1998 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1999 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2000 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2001 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00002002 break;
Chris Lattner86102b82005-01-01 16:22:27 +00002003 }
2004
Chris Lattner16464b32003-07-23 19:25:52 +00002005 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00002006 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00002007 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00002008 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2009 const Type *SrcTy = CI->getOperand(0)->getType();
2010
Chris Lattner2c14cf72005-08-07 07:03:10 +00002011 // If this is an integer truncation or change from signed-to-unsigned, and
2012 // if the source is an and/or with immediate, transform it. This
2013 // frequently occurs for bitfield accesses.
2014 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2015 if (SrcTy->getPrimitiveSizeInBits() >=
2016 I.getType()->getPrimitiveSizeInBits() &&
2017 CastOp->getNumOperands() == 2)
2018 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1)))
2019 if (CastOp->getOpcode() == Instruction::And) {
2020 // Change: and (cast (and X, C1) to T), C2
2021 // into : and (cast X to T), trunc(C1)&C2
2022 // This will folds the two ands together, which may allow other
2023 // simplifications.
2024 Instruction *NewCast =
2025 new CastInst(CastOp->getOperand(0), I.getType(),
2026 CastOp->getName()+".shrunk");
2027 NewCast = InsertNewInstBefore(NewCast, I);
2028
2029 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2030 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2031 return BinaryOperator::createAnd(NewCast, C3);
2032 } else if (CastOp->getOpcode() == Instruction::Or) {
2033 // Change: and (cast (or X, C1) to T), C2
2034 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2035 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2036 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2037 return ReplaceInstUsesWith(I, AndRHS);
2038 }
2039 }
2040
2041
Chris Lattner86102b82005-01-01 16:22:27 +00002042 // If this is an integer sign or zero extension instruction.
2043 if (SrcTy->isIntegral() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002044 SrcTy->getPrimitiveSizeInBits() <
2045 CI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner86102b82005-01-01 16:22:27 +00002046
2047 if (SrcTy->isUnsigned()) {
2048 // See if this and is clearing out bits that are known to be zero
2049 // anyway (due to the zero extension).
2050 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
2051 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
2052 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
2053 if (Result == Mask) // The "and" isn't doing anything, remove it.
2054 return ReplaceInstUsesWith(I, CI);
2055 if (Result != AndRHS) { // Reduce the and RHS constant.
2056 I.setOperand(1, Result);
2057 return &I;
2058 }
2059
2060 } else {
2061 if (CI->hasOneUse() && SrcTy->isInteger()) {
2062 // We can only do this if all of the sign bits brought in are masked
2063 // out. Compute this by first getting 0000011111, then inverting
2064 // it.
2065 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
2066 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
2067 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
2068 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
2069 // If the and is clearing all of the sign bits, change this to a
2070 // zero extension cast. To do this, cast the cast input to
2071 // unsigned, then to the requested size.
2072 Value *CastOp = CI->getOperand(0);
2073 Instruction *NC =
2074 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
2075 CI->getName()+".uns");
2076 NC = InsertNewInstBefore(NC, I);
2077 // Finally, insert a replacement for CI.
2078 NC = new CastInst(NC, CI->getType(), CI->getName());
2079 CI->setName("");
2080 NC = InsertNewInstBefore(NC, I);
2081 WorkList.push_back(CI); // Delete CI later.
2082 I.setOperand(0, NC);
2083 return &I; // The AND operand was modified.
2084 }
2085 }
2086 }
2087 }
Chris Lattner33217db2003-07-23 19:36:21 +00002088 }
Chris Lattner183b3362004-04-09 19:05:30 +00002089
2090 // Try to fold constant and into select arguments.
2091 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002092 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002093 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002094 if (isa<PHINode>(Op0))
2095 if (Instruction *NV = FoldOpIntoPhi(I))
2096 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00002097 }
2098
Chris Lattnerbb74e222003-03-10 23:06:50 +00002099 Value *Op0NotVal = dyn_castNotVal(Op0);
2100 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002101
Chris Lattner023a4832004-06-18 06:07:51 +00002102 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2103 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2104
Misha Brukman9c003d82004-07-30 12:50:08 +00002105 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00002106 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002107 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2108 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00002109 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002110 return BinaryOperator::createNot(Or);
2111 }
2112
Chris Lattner623826c2004-09-28 21:48:02 +00002113 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2114 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002115 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2116 return R;
2117
Chris Lattner623826c2004-09-28 21:48:02 +00002118 Value *LHSVal, *RHSVal;
2119 ConstantInt *LHSCst, *RHSCst;
2120 Instruction::BinaryOps LHSCC, RHSCC;
2121 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2122 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2123 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
2124 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002125 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00002126 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2127 // Ensure that the larger constant is on the RHS.
2128 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2129 SetCondInst *LHS = cast<SetCondInst>(Op0);
2130 if (cast<ConstantBool>(Cmp)->getValue()) {
2131 std::swap(LHS, RHS);
2132 std::swap(LHSCst, RHSCst);
2133 std::swap(LHSCC, RHSCC);
2134 }
2135
2136 // At this point, we know we have have two setcc instructions
2137 // comparing a value against two constants and and'ing the result
2138 // together. Because of the above check, we know that we only have
2139 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2140 // FoldSetCCLogical check above), that the two constants are not
2141 // equal.
2142 assert(LHSCst != RHSCst && "Compares not folded above?");
2143
2144 switch (LHSCC) {
2145 default: assert(0 && "Unknown integer condition code!");
2146 case Instruction::SetEQ:
2147 switch (RHSCC) {
2148 default: assert(0 && "Unknown integer condition code!");
2149 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
2150 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2151 return ReplaceInstUsesWith(I, ConstantBool::False);
2152 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2153 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2154 return ReplaceInstUsesWith(I, LHS);
2155 }
2156 case Instruction::SetNE:
2157 switch (RHSCC) {
2158 default: assert(0 && "Unknown integer condition code!");
2159 case Instruction::SetLT:
2160 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2161 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2162 break; // (X != 13 & X < 15) -> no change
2163 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2164 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2165 return ReplaceInstUsesWith(I, RHS);
2166 case Instruction::SetNE:
2167 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2168 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2169 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2170 LHSVal->getName()+".off");
2171 InsertNewInstBefore(Add, I);
2172 const Type *UnsType = Add->getType()->getUnsignedVersion();
2173 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2174 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2175 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2176 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2177 }
2178 break; // (X != 13 & X != 15) -> no change
2179 }
2180 break;
2181 case Instruction::SetLT:
2182 switch (RHSCC) {
2183 default: assert(0 && "Unknown integer condition code!");
2184 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2185 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2186 return ReplaceInstUsesWith(I, ConstantBool::False);
2187 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2188 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2189 return ReplaceInstUsesWith(I, LHS);
2190 }
2191 case Instruction::SetGT:
2192 switch (RHSCC) {
2193 default: assert(0 && "Unknown integer condition code!");
2194 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2195 return ReplaceInstUsesWith(I, LHS);
2196 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2197 return ReplaceInstUsesWith(I, RHS);
2198 case Instruction::SetNE:
2199 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2200 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2201 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00002202 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2203 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00002204 }
2205 }
2206 }
2207 }
2208
Chris Lattner113f4f42002-06-25 16:13:24 +00002209 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002210}
2211
Chris Lattner113f4f42002-06-25 16:13:24 +00002212Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002213 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002214 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002215
Chris Lattner81a7a232004-10-16 18:11:37 +00002216 if (isa<UndefValue>(Op1))
2217 return ReplaceInstUsesWith(I, // X | undef -> -1
2218 ConstantIntegral::getAllOnesValue(I.getType()));
2219
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002220 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00002221 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
2222 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002223
2224 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00002225 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner86102b82005-01-01 16:22:27 +00002226 // If X is known to only contain bits that already exist in RHS, just
2227 // replace this instruction with RHS directly.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002228 if (MaskedValueIsZero(Op0,
2229 RHS->getZExtValue()^RHS->getType()->getIntegralTypeMask()))
Chris Lattner86102b82005-01-01 16:22:27 +00002230 return ReplaceInstUsesWith(I, RHS);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002231
Chris Lattner330628a2006-01-06 17:59:59 +00002232 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002233 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2234 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002235 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2236 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00002237 InsertNewInstBefore(Or, I);
2238 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2239 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00002240
Chris Lattnerd4252a72004-07-30 07:50:03 +00002241 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2242 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2243 std::string Op0Name = Op0->getName(); Op0->setName("");
2244 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2245 InsertNewInstBefore(Or, I);
2246 return BinaryOperator::createXor(Or,
2247 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00002248 }
Chris Lattner183b3362004-04-09 19:05:30 +00002249
2250 // Try to fold constant and into select arguments.
2251 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002252 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002253 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002254 if (isa<PHINode>(Op0))
2255 if (Instruction *NV = FoldOpIntoPhi(I))
2256 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00002257 }
2258
Chris Lattner330628a2006-01-06 17:59:59 +00002259 Value *A = 0, *B = 0;
2260 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00002261
2262 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2263 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2264 return ReplaceInstUsesWith(I, Op1);
2265 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2266 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2267 return ReplaceInstUsesWith(I, Op0);
2268
Chris Lattnerb62f5082005-05-09 04:58:36 +00002269 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2270 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002271 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002272 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2273 Op0->setName("");
2274 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2275 }
2276
2277 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2278 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002279 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002280 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2281 Op0->setName("");
2282 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2283 }
2284
Chris Lattner15212982005-09-18 03:42:07 +00002285 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00002286 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00002287 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2288
2289 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2290 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2291
2292
Chris Lattner01f56c62005-09-18 06:02:59 +00002293 // If we have: ((V + N) & C1) | (V & C2)
2294 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2295 // replace with V+N.
2296 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002297 Value *V1 = 0, *V2 = 0;
Chris Lattner01f56c62005-09-18 06:02:59 +00002298 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2299 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2300 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002301 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002302 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002303 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002304 return ReplaceInstUsesWith(I, A);
2305 }
2306 // Or commutes, try both ways.
2307 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2308 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2309 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002310 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002311 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002312 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002313 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00002314 }
2315 }
2316 }
Chris Lattner812aab72003-08-12 19:11:07 +00002317
Chris Lattnerd4252a72004-07-30 07:50:03 +00002318 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2319 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00002320 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002321 ConstantIntegral::getAllOnesValue(I.getType()));
2322 } else {
2323 A = 0;
2324 }
Chris Lattner4294cec2005-05-07 23:49:08 +00002325 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00002326 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2327 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00002328 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002329 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00002330
Misha Brukman9c003d82004-07-30 12:50:08 +00002331 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00002332 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2333 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2334 I.getName()+".demorgan"), I);
2335 return BinaryOperator::createNot(And);
2336 }
Chris Lattner3e327a42003-03-10 23:13:59 +00002337 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002338
Chris Lattner3ac7c262003-08-13 20:16:26 +00002339 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002340 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002341 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2342 return R;
2343
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002344 Value *LHSVal, *RHSVal;
2345 ConstantInt *LHSCst, *RHSCst;
2346 Instruction::BinaryOps LHSCC, RHSCC;
2347 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2348 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2349 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2350 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002351 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002352 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2353 // Ensure that the larger constant is on the RHS.
2354 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2355 SetCondInst *LHS = cast<SetCondInst>(Op0);
2356 if (cast<ConstantBool>(Cmp)->getValue()) {
2357 std::swap(LHS, RHS);
2358 std::swap(LHSCst, RHSCst);
2359 std::swap(LHSCC, RHSCC);
2360 }
2361
2362 // At this point, we know we have have two setcc instructions
2363 // comparing a value against two constants and or'ing the result
2364 // together. Because of the above check, we know that we only have
2365 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2366 // FoldSetCCLogical check above), that the two constants are not
2367 // equal.
2368 assert(LHSCst != RHSCst && "Compares not folded above?");
2369
2370 switch (LHSCC) {
2371 default: assert(0 && "Unknown integer condition code!");
2372 case Instruction::SetEQ:
2373 switch (RHSCC) {
2374 default: assert(0 && "Unknown integer condition code!");
2375 case Instruction::SetEQ:
2376 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2377 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2378 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2379 LHSVal->getName()+".off");
2380 InsertNewInstBefore(Add, I);
2381 const Type *UnsType = Add->getType()->getUnsignedVersion();
2382 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2383 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2384 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2385 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2386 }
2387 break; // (X == 13 | X == 15) -> no change
2388
Chris Lattner5c219462005-04-19 06:04:18 +00002389 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2390 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002391 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2392 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2393 return ReplaceInstUsesWith(I, RHS);
2394 }
2395 break;
2396 case Instruction::SetNE:
2397 switch (RHSCC) {
2398 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002399 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2400 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2401 return ReplaceInstUsesWith(I, LHS);
2402 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00002403 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002404 return ReplaceInstUsesWith(I, ConstantBool::True);
2405 }
2406 break;
2407 case Instruction::SetLT:
2408 switch (RHSCC) {
2409 default: assert(0 && "Unknown integer condition code!");
2410 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2411 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00002412 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2413 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002414 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2415 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2416 return ReplaceInstUsesWith(I, RHS);
2417 }
2418 break;
2419 case Instruction::SetGT:
2420 switch (RHSCC) {
2421 default: assert(0 && "Unknown integer condition code!");
2422 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
2423 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
2424 return ReplaceInstUsesWith(I, LHS);
2425 case Instruction::SetNE: // (X > 13 | X != 15) -> true
2426 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2427 return ReplaceInstUsesWith(I, ConstantBool::True);
2428 }
2429 }
2430 }
2431 }
Chris Lattner15212982005-09-18 03:42:07 +00002432
Chris Lattner113f4f42002-06-25 16:13:24 +00002433 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002434}
2435
Chris Lattnerc2076352004-02-16 01:20:27 +00002436// XorSelf - Implements: X ^ X --> 0
2437struct XorSelf {
2438 Value *RHS;
2439 XorSelf(Value *rhs) : RHS(rhs) {}
2440 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2441 Instruction *apply(BinaryOperator &Xor) const {
2442 return &Xor;
2443 }
2444};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002445
2446
Chris Lattner113f4f42002-06-25 16:13:24 +00002447Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002448 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002449 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002450
Chris Lattner81a7a232004-10-16 18:11:37 +00002451 if (isa<UndefValue>(Op1))
2452 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2453
Chris Lattnerc2076352004-02-16 01:20:27 +00002454 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2455 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2456 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00002457 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00002458 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002459
Chris Lattner97638592003-07-23 21:37:07 +00002460 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002461 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00002462 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00002463 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002464
Chris Lattner97638592003-07-23 21:37:07 +00002465 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002466 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00002467 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002468 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002469 return new SetCondInst(SCI->getInverseCondition(),
2470 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00002471
Chris Lattner8f2f5982003-11-05 01:06:05 +00002472 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002473 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2474 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002475 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2476 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002477 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002478 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002479 }
Chris Lattner023a4832004-06-18 06:07:51 +00002480
2481 // ~(~X & Y) --> (X | ~Y)
2482 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2483 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2484 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2485 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00002486 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00002487 Op0I->getOperand(1)->getName()+".not");
2488 InsertNewInstBefore(NotY, I);
2489 return BinaryOperator::createOr(Op0NotVal, NotY);
2490 }
2491 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002492
Chris Lattner97638592003-07-23 21:37:07 +00002493 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00002494 switch (Op0I->getOpcode()) {
2495 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00002496 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002497 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002498 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2499 return BinaryOperator::createSub(
2500 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002501 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00002502 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002503 }
Chris Lattnere5806662003-11-04 23:50:51 +00002504 break;
2505 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00002506 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002507 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2508 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00002509 break;
2510 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00002511 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002512 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002513 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00002514 break;
2515 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00002516 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002517 }
Chris Lattner183b3362004-04-09 19:05:30 +00002518
2519 // Try to fold constant and into select arguments.
2520 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002521 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002522 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002523 if (isa<PHINode>(Op0))
2524 if (Instruction *NV = FoldOpIntoPhi(I))
2525 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002526 }
2527
Chris Lattnerbb74e222003-03-10 23:06:50 +00002528 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002529 if (X == Op1)
2530 return ReplaceInstUsesWith(I,
2531 ConstantIntegral::getAllOnesValue(I.getType()));
2532
Chris Lattnerbb74e222003-03-10 23:06:50 +00002533 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002534 if (X == Op0)
2535 return ReplaceInstUsesWith(I,
2536 ConstantIntegral::getAllOnesValue(I.getType()));
2537
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002538 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00002539 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002540 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2541 cast<BinaryOperator>(Op1I)->swapOperands();
2542 I.swapOperands();
2543 std::swap(Op0, Op1);
2544 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2545 I.swapOperands();
2546 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002547 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002548 } else if (Op1I->getOpcode() == Instruction::Xor) {
2549 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2550 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2551 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2552 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2553 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002554
2555 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002556 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002557 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2558 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002559 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00002560 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2561 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002562 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002563 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002564 } else if (Op0I->getOpcode() == Instruction::Xor) {
2565 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2566 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2567 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2568 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002569 }
2570
Chris Lattner7aa2d472004-08-01 19:42:59 +00002571 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner330628a2006-01-06 17:59:59 +00002572 ConstantInt *C1 = 0, *C2 = 0;
2573 if (match(Op0, m_And(m_Value(), m_ConstantInt(C1))) &&
2574 match(Op1, m_And(m_Value(), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00002575 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00002576 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00002577
Chris Lattner3ac7c262003-08-13 20:16:26 +00002578 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2579 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2580 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2581 return R;
2582
Chris Lattner113f4f42002-06-25 16:13:24 +00002583 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002584}
2585
Chris Lattner6862fbd2004-09-29 17:40:11 +00002586/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2587/// overflowed for this type.
2588static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2589 ConstantInt *In2) {
2590 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2591 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2592}
2593
2594static bool isPositive(ConstantInt *C) {
2595 return cast<ConstantSInt>(C)->getValue() >= 0;
2596}
2597
2598/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2599/// overflowed for this type.
2600static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2601 ConstantInt *In2) {
2602 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2603
2604 if (In1->getType()->isUnsigned())
2605 return cast<ConstantUInt>(Result)->getValue() <
2606 cast<ConstantUInt>(In1)->getValue();
2607 if (isPositive(In1) != isPositive(In2))
2608 return false;
2609 if (isPositive(In1))
2610 return cast<ConstantSInt>(Result)->getValue() <
2611 cast<ConstantSInt>(In1)->getValue();
2612 return cast<ConstantSInt>(Result)->getValue() >
2613 cast<ConstantSInt>(In1)->getValue();
2614}
2615
Chris Lattner0798af32005-01-13 20:14:25 +00002616/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2617/// code necessary to compute the offset from the base pointer (without adding
2618/// in the base pointer). Return the result as a signed integer of intptr size.
2619static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2620 TargetData &TD = IC.getTargetData();
2621 gep_type_iterator GTI = gep_type_begin(GEP);
2622 const Type *UIntPtrTy = TD.getIntPtrType();
2623 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2624 Value *Result = Constant::getNullValue(SIntPtrTy);
2625
2626 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00002627 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00002628
Chris Lattner0798af32005-01-13 20:14:25 +00002629 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2630 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00002631 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00002632 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2633 SIntPtrTy);
2634 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2635 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002636 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00002637 Scale = ConstantExpr::getMul(OpC, Scale);
2638 if (Constant *RC = dyn_cast<Constant>(Result))
2639 Result = ConstantExpr::getAdd(RC, Scale);
2640 else {
2641 // Emit an add instruction.
2642 Result = IC.InsertNewInstBefore(
2643 BinaryOperator::createAdd(Result, Scale,
2644 GEP->getName()+".offs"), I);
2645 }
2646 }
2647 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00002648 // Convert to correct type.
2649 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2650 Op->getName()+".c"), I);
2651 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002652 // We'll let instcombine(mul) convert this to a shl if possible.
2653 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2654 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00002655
2656 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002657 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00002658 GEP->getName()+".offs"), I);
2659 }
2660 }
2661 return Result;
2662}
2663
2664/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2665/// else. At this point we know that the GEP is on the LHS of the comparison.
2666Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2667 Instruction::BinaryOps Cond,
2668 Instruction &I) {
2669 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00002670
2671 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2672 if (isa<PointerType>(CI->getOperand(0)->getType()))
2673 RHS = CI->getOperand(0);
2674
Chris Lattner0798af32005-01-13 20:14:25 +00002675 Value *PtrBase = GEPLHS->getOperand(0);
2676 if (PtrBase == RHS) {
2677 // As an optimization, we don't actually have to compute the actual value of
2678 // OFFSET if this is a seteq or setne comparison, just return whether each
2679 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00002680 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2681 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002682 gep_type_iterator GTI = gep_type_begin(GEPLHS);
2683 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00002684 bool EmitIt = true;
2685 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2686 if (isa<UndefValue>(C)) // undef index -> undef.
2687 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2688 if (C->isNullValue())
2689 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002690 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2691 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00002692 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00002693 return ReplaceInstUsesWith(I, // No comparison is needed here.
2694 ConstantBool::get(Cond == Instruction::SetNE));
2695 }
2696
2697 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002698 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00002699 new SetCondInst(Cond, GEPLHS->getOperand(i),
2700 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2701 if (InVal == 0)
2702 InVal = Comp;
2703 else {
2704 InVal = InsertNewInstBefore(InVal, I);
2705 InsertNewInstBefore(Comp, I);
2706 if (Cond == Instruction::SetNE) // True if any are unequal
2707 InVal = BinaryOperator::createOr(InVal, Comp);
2708 else // True if all are equal
2709 InVal = BinaryOperator::createAnd(InVal, Comp);
2710 }
2711 }
2712 }
2713
2714 if (InVal)
2715 return InVal;
2716 else
2717 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2718 ConstantBool::get(Cond == Instruction::SetEQ));
2719 }
Chris Lattner0798af32005-01-13 20:14:25 +00002720
2721 // Only lower this if the setcc is the only user of the GEP or if we expect
2722 // the result to fold to a constant!
2723 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2724 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
2725 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2726 return new SetCondInst(Cond, Offset,
2727 Constant::getNullValue(Offset->getType()));
2728 }
2729 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002730 // If the base pointers are different, but the indices are the same, just
2731 // compare the base pointer.
2732 if (PtrBase != GEPRHS->getOperand(0)) {
2733 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002734 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00002735 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002736 if (IndicesTheSame)
2737 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2738 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2739 IndicesTheSame = false;
2740 break;
2741 }
2742
2743 // If all indices are the same, just compare the base pointers.
2744 if (IndicesTheSame)
2745 return new SetCondInst(Cond, GEPLHS->getOperand(0),
2746 GEPRHS->getOperand(0));
2747
2748 // Otherwise, the base pointers are different and the indices are
2749 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00002750 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002751 }
Chris Lattner0798af32005-01-13 20:14:25 +00002752
Chris Lattner81e84172005-01-13 22:25:21 +00002753 // If one of the GEPs has all zero indices, recurse.
2754 bool AllZeros = true;
2755 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2756 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2757 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2758 AllZeros = false;
2759 break;
2760 }
2761 if (AllZeros)
2762 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2763 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00002764
2765 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00002766 AllZeros = true;
2767 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2768 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2769 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2770 AllZeros = false;
2771 break;
2772 }
2773 if (AllZeros)
2774 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2775
Chris Lattner4fa89822005-01-14 00:20:05 +00002776 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2777 // If the GEPs only differ by one index, compare it.
2778 unsigned NumDifferences = 0; // Keep track of # differences.
2779 unsigned DiffOperand = 0; // The operand that differs.
2780 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2781 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002782 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
2783 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002784 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00002785 NumDifferences = 2;
2786 break;
2787 } else {
2788 if (NumDifferences++) break;
2789 DiffOperand = i;
2790 }
2791 }
2792
2793 if (NumDifferences == 0) // SAME GEP?
2794 return ReplaceInstUsesWith(I, // No comparison is needed here.
2795 ConstantBool::get(Cond == Instruction::SetEQ));
2796 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002797 Value *LHSV = GEPLHS->getOperand(DiffOperand);
2798 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00002799
2800 // Convert the operands to signed values to make sure to perform a
2801 // signed comparison.
2802 const Type *NewTy = LHSV->getType()->getSignedVersion();
2803 if (LHSV->getType() != NewTy)
2804 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
2805 LHSV->getName()), I);
2806 if (RHSV->getType() != NewTy)
2807 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
2808 RHSV->getName()), I);
2809 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00002810 }
2811 }
2812
Chris Lattner0798af32005-01-13 20:14:25 +00002813 // Only lower this if the setcc is the only user of the GEP or if we expect
2814 // the result to fold to a constant!
2815 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2816 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2817 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
2818 Value *L = EmitGEPOffset(GEPLHS, I, *this);
2819 Value *R = EmitGEPOffset(GEPRHS, I, *this);
2820 return new SetCondInst(Cond, L, R);
2821 }
2822 }
2823 return 0;
2824}
2825
2826
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002827Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002828 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002829 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2830 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002831
2832 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002833 if (Op0 == Op1)
2834 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00002835
Chris Lattner81a7a232004-10-16 18:11:37 +00002836 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2837 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2838
Chris Lattner15ff1e12004-11-14 07:33:16 +00002839 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2840 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002841 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2842 isa<ConstantPointerNull>(Op0)) &&
2843 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00002844 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002845 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2846
2847 // setcc's with boolean values can always be turned into bitwise operations
2848 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00002849 switch (I.getOpcode()) {
2850 default: assert(0 && "Invalid setcc instruction!");
2851 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002852 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002853 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00002854 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002855 }
Chris Lattner4456da62004-08-11 00:50:51 +00002856 case Instruction::SetNE:
2857 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002858
Chris Lattner4456da62004-08-11 00:50:51 +00002859 case Instruction::SetGT:
2860 std::swap(Op0, Op1); // Change setgt -> setlt
2861 // FALL THROUGH
2862 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2863 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2864 InsertNewInstBefore(Not, I);
2865 return BinaryOperator::createAnd(Not, Op1);
2866 }
2867 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002868 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00002869 // FALL THROUGH
2870 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
2871 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2872 InsertNewInstBefore(Not, I);
2873 return BinaryOperator::createOr(Not, Op1);
2874 }
2875 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002876 }
2877
Chris Lattner2dd01742004-06-09 04:24:29 +00002878 // See if we are doing a comparison between a constant and an instruction that
2879 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002880 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002881 // Check to see if we are comparing against the minimum or maximum value...
2882 if (CI->isMinValue()) {
2883 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2884 return ReplaceInstUsesWith(I, ConstantBool::False);
2885 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2886 return ReplaceInstUsesWith(I, ConstantBool::True);
2887 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2888 return BinaryOperator::createSetEQ(Op0, Op1);
2889 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2890 return BinaryOperator::createSetNE(Op0, Op1);
2891
2892 } else if (CI->isMaxValue()) {
2893 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2894 return ReplaceInstUsesWith(I, ConstantBool::False);
2895 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2896 return ReplaceInstUsesWith(I, ConstantBool::True);
2897 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2898 return BinaryOperator::createSetEQ(Op0, Op1);
2899 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2900 return BinaryOperator::createSetNE(Op0, Op1);
2901
2902 // Comparing against a value really close to min or max?
2903 } else if (isMinValuePlusOne(CI)) {
2904 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2905 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2906 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2907 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2908
2909 } else if (isMaxValueMinusOne(CI)) {
2910 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2911 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2912 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2913 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2914 }
2915
2916 // If we still have a setle or setge instruction, turn it into the
2917 // appropriate setlt or setgt instruction. Since the border cases have
2918 // already been handled above, this requires little checking.
2919 //
2920 if (I.getOpcode() == Instruction::SetLE)
2921 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2922 if (I.getOpcode() == Instruction::SetGE)
2923 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2924
Chris Lattnere1e10e12004-05-25 06:32:08 +00002925 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002926 switch (LHSI->getOpcode()) {
2927 case Instruction::And:
2928 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2929 LHSI->getOperand(0)->hasOneUse()) {
2930 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2931 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2932 // happens a LOT in code produced by the C front-end, for bitfield
2933 // access.
2934 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2935 ConstantUInt *ShAmt;
2936 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2937 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2938 const Type *Ty = LHSI->getType();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002939
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002940 // We can fold this as long as we can't shift unknown bits
2941 // into the mask. This can only happen with signed shift
2942 // rights, as they sign-extend.
2943 if (ShAmt) {
2944 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00002945 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002946 if (!CanFold) {
2947 // To test for the bad case of the signed shr, see if any
2948 // of the bits shifted in could be tested after the mask.
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00002949 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
2950 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
2951
2952 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002953 Constant *ShVal =
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002954 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2955 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2956 CanFold = true;
2957 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002958
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002959 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00002960 Constant *NewCst;
2961 if (Shift->getOpcode() == Instruction::Shl)
2962 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2963 else
2964 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002965
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002966 // Check to see if we are shifting out any of the bits being
2967 // compared.
2968 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2969 // If we shifted bits out, the fold is not going to work out.
2970 // As a special case, check to see if this means that the
2971 // result is always true or false now.
2972 if (I.getOpcode() == Instruction::SetEQ)
2973 return ReplaceInstUsesWith(I, ConstantBool::False);
2974 if (I.getOpcode() == Instruction::SetNE)
2975 return ReplaceInstUsesWith(I, ConstantBool::True);
2976 } else {
2977 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00002978 Constant *NewAndCST;
2979 if (Shift->getOpcode() == Instruction::Shl)
2980 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2981 else
2982 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2983 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002984 LHSI->setOperand(0, Shift->getOperand(0));
2985 WorkList.push_back(Shift); // Shift is dead.
2986 AddUsesToWorkList(I);
2987 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00002988 }
2989 }
Chris Lattner35167c32004-06-09 07:59:58 +00002990 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002991 }
2992 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002993
Chris Lattner272d5ca2004-09-28 18:22:15 +00002994 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2995 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2996 switch (I.getOpcode()) {
2997 default: break;
2998 case Instruction::SetEQ:
2999 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00003000 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3001
3002 // Check that the shift amount is in range. If not, don't perform
3003 // undefined shifts. When the shift is visited it will be
3004 // simplified.
3005 if (ShAmt->getValue() >= TypeBits)
3006 break;
3007
Chris Lattner272d5ca2004-09-28 18:22:15 +00003008 // If we are comparing against bits always shifted out, the
3009 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003010 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00003011 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
3012 if (Comp != CI) {// Comparing against a bit that we know is zero.
3013 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3014 Constant *Cst = ConstantBool::get(IsSetNE);
3015 return ReplaceInstUsesWith(I, Cst);
3016 }
3017
3018 if (LHSI->hasOneUse()) {
3019 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003020 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00003021 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
3022
3023 Constant *Mask;
3024 if (CI->getType()->isUnsigned()) {
3025 Mask = ConstantUInt::get(CI->getType(), Val);
3026 } else if (ShAmtVal != 0) {
3027 Mask = ConstantSInt::get(CI->getType(), Val);
3028 } else {
3029 Mask = ConstantInt::getAllOnesValue(CI->getType());
3030 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003031
Chris Lattner272d5ca2004-09-28 18:22:15 +00003032 Instruction *AndI =
3033 BinaryOperator::createAnd(LHSI->getOperand(0),
3034 Mask, LHSI->getName()+".mask");
3035 Value *And = InsertNewInstBefore(AndI, I);
3036 return new SetCondInst(I.getOpcode(), And,
3037 ConstantExpr::getUShr(CI, ShAmt));
3038 }
3039 }
3040 }
3041 }
3042 break;
3043
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003044 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00003045 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00003046 switch (I.getOpcode()) {
3047 default: break;
3048 case Instruction::SetEQ:
3049 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00003050
3051 // Check that the shift amount is in range. If not, don't perform
3052 // undefined shifts. When the shift is visited it will be
3053 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00003054 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner19b57f52005-06-15 20:53:31 +00003055 if (ShAmt->getValue() >= TypeBits)
3056 break;
3057
Chris Lattner1023b872004-09-27 16:18:50 +00003058 // If we are comparing against bits always shifted out, the
3059 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003060 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00003061 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003062
Chris Lattner1023b872004-09-27 16:18:50 +00003063 if (Comp != CI) {// Comparing against a bit that we know is zero.
3064 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3065 Constant *Cst = ConstantBool::get(IsSetNE);
3066 return ReplaceInstUsesWith(I, Cst);
3067 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003068
Chris Lattner1023b872004-09-27 16:18:50 +00003069 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003070 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00003071
Chris Lattner1023b872004-09-27 16:18:50 +00003072 // Otherwise strength reduce the shift into an and.
3073 uint64_t Val = ~0ULL; // All ones.
3074 Val <<= ShAmtVal; // Shift over to the right spot.
3075
3076 Constant *Mask;
3077 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00003078 Val &= ~0ULL >> (64-TypeBits);
Chris Lattner1023b872004-09-27 16:18:50 +00003079 Mask = ConstantUInt::get(CI->getType(), Val);
3080 } else {
3081 Mask = ConstantSInt::get(CI->getType(), Val);
3082 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003083
Chris Lattner1023b872004-09-27 16:18:50 +00003084 Instruction *AndI =
3085 BinaryOperator::createAnd(LHSI->getOperand(0),
3086 Mask, LHSI->getName()+".mask");
3087 Value *And = InsertNewInstBefore(AndI, I);
3088 return new SetCondInst(I.getOpcode(), And,
3089 ConstantExpr::getShl(CI, ShAmt));
3090 }
3091 break;
3092 }
3093 }
3094 }
3095 break;
Chris Lattner7e794272004-09-24 15:21:34 +00003096
Chris Lattner6862fbd2004-09-29 17:40:11 +00003097 case Instruction::Div:
3098 // Fold: (div X, C1) op C2 -> range check
3099 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
3100 // Fold this div into the comparison, producing a range check.
3101 // Determine, based on the divide type, what the range is being
3102 // checked. If there is an overflow on the low or high side, remember
3103 // it, otherwise compute the range [low, hi) bounding the new value.
3104 bool LoOverflow = false, HiOverflow = 0;
3105 ConstantInt *LoBound = 0, *HiBound = 0;
3106
3107 ConstantInt *Prod;
3108 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
3109
Chris Lattnera92af962004-10-11 19:40:04 +00003110 Instruction::BinaryOps Opcode = I.getOpcode();
3111
Chris Lattner6862fbd2004-09-29 17:40:11 +00003112 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
3113 } else if (LHSI->getType()->isUnsigned()) { // udiv
3114 LoBound = Prod;
3115 LoOverflow = ProdOV;
3116 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
3117 } else if (isPositive(DivRHS)) { // Divisor is > 0.
3118 if (CI->isNullValue()) { // (X / pos) op 0
3119 // Can't overflow.
3120 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
3121 HiBound = DivRHS;
3122 } else if (isPositive(CI)) { // (X / pos) op pos
3123 LoBound = Prod;
3124 LoOverflow = ProdOV;
3125 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
3126 } else { // (X / pos) op neg
3127 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
3128 LoOverflow = AddWithOverflow(LoBound, Prod,
3129 cast<ConstantInt>(DivRHSH));
3130 HiBound = Prod;
3131 HiOverflow = ProdOV;
3132 }
3133 } else { // Divisor is < 0.
3134 if (CI->isNullValue()) { // (X / neg) op 0
3135 LoBound = AddOne(DivRHS);
3136 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00003137 if (HiBound == DivRHS)
3138 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00003139 } else if (isPositive(CI)) { // (X / neg) op pos
3140 HiOverflow = LoOverflow = ProdOV;
3141 if (!LoOverflow)
3142 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
3143 HiBound = AddOne(Prod);
3144 } else { // (X / neg) op neg
3145 LoBound = Prod;
3146 LoOverflow = HiOverflow = ProdOV;
3147 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
3148 }
Chris Lattner0b41e862004-10-08 19:15:44 +00003149
Chris Lattnera92af962004-10-11 19:40:04 +00003150 // Dividing by a negate swaps the condition.
3151 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003152 }
3153
3154 if (LoBound) {
3155 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00003156 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00003157 default: assert(0 && "Unhandled setcc opcode!");
3158 case Instruction::SetEQ:
3159 if (LoOverflow && HiOverflow)
3160 return ReplaceInstUsesWith(I, ConstantBool::False);
3161 else if (HiOverflow)
3162 return new SetCondInst(Instruction::SetGE, X, LoBound);
3163 else if (LoOverflow)
3164 return new SetCondInst(Instruction::SetLT, X, HiBound);
3165 else
3166 return InsertRangeTest(X, LoBound, HiBound, true, I);
3167 case Instruction::SetNE:
3168 if (LoOverflow && HiOverflow)
3169 return ReplaceInstUsesWith(I, ConstantBool::True);
3170 else if (HiOverflow)
3171 return new SetCondInst(Instruction::SetLT, X, LoBound);
3172 else if (LoOverflow)
3173 return new SetCondInst(Instruction::SetGE, X, HiBound);
3174 else
3175 return InsertRangeTest(X, LoBound, HiBound, false, I);
3176 case Instruction::SetLT:
3177 if (LoOverflow)
3178 return ReplaceInstUsesWith(I, ConstantBool::False);
3179 return new SetCondInst(Instruction::SetLT, X, LoBound);
3180 case Instruction::SetGT:
3181 if (HiOverflow)
3182 return ReplaceInstUsesWith(I, ConstantBool::False);
3183 return new SetCondInst(Instruction::SetGE, X, HiBound);
3184 }
3185 }
3186 }
3187 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003188 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003189
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003190 // Simplify seteq and setne instructions...
3191 if (I.getOpcode() == Instruction::SetEQ ||
3192 I.getOpcode() == Instruction::SetNE) {
3193 bool isSetNE = I.getOpcode() == Instruction::SetNE;
3194
Chris Lattnercfbce7c2003-07-23 17:26:36 +00003195 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003196 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00003197 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3198 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00003199 case Instruction::Rem:
3200 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3201 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3202 BO->hasOneUse() &&
Chris Lattner22d00a82005-08-02 19:16:58 +00003203 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3204 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3205 if (isPowerOf2_64(V)) {
3206 unsigned L2 = Log2_64(V);
Chris Lattner23b47b62004-07-06 07:38:18 +00003207 const Type *UTy = BO->getType()->getUnsignedVersion();
3208 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3209 UTy, "tmp"), I);
3210 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3211 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3212 RHSCst, BO->getName()), I);
3213 return BinaryOperator::create(I.getOpcode(), NewRem,
3214 Constant::getNullValue(UTy));
3215 }
Chris Lattner22d00a82005-08-02 19:16:58 +00003216 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003217 break;
Chris Lattner23b47b62004-07-06 07:38:18 +00003218
Chris Lattnerc992add2003-08-13 05:33:12 +00003219 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00003220 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3221 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00003222 if (BO->hasOneUse())
3223 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3224 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00003225 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003226 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3227 // efficiently invertible, or if the add has just this one use.
3228 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003229
Chris Lattnerc992add2003-08-13 05:33:12 +00003230 if (Value *NegVal = dyn_castNegVal(BOp1))
3231 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3232 else if (Value *NegVal = dyn_castNegVal(BOp0))
3233 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003234 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003235 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3236 BO->setName("");
3237 InsertNewInstBefore(Neg, I);
3238 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3239 }
3240 }
3241 break;
3242 case Instruction::Xor:
3243 // For the xor case, we can xor two constants together, eliminating
3244 // the explicit xor.
3245 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3246 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003247 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00003248
3249 // FALLTHROUGH
3250 case Instruction::Sub:
3251 // Replace (([sub|xor] A, B) != 0) with (A != B)
3252 if (CI->isNullValue())
3253 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3254 BO->getOperand(1));
3255 break;
3256
3257 case Instruction::Or:
3258 // If bits are being or'd in that are not present in the constant we
3259 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003260 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003261 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003262 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003263 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003264 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003265 break;
3266
3267 case Instruction::And:
3268 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003269 // If bits are being compared against that are and'd out, then the
3270 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003271 if (!ConstantExpr::getAnd(CI,
3272 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003273 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00003274
Chris Lattner35167c32004-06-09 07:59:58 +00003275 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00003276 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00003277 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3278 Instruction::SetNE, Op0,
3279 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00003280
Chris Lattnerc992add2003-08-13 05:33:12 +00003281 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3282 // to be a signed value as appropriate.
3283 if (isSignBit(BOC)) {
3284 Value *X = BO->getOperand(0);
3285 // If 'X' is not signed, insert a cast now...
3286 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00003287 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003288 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00003289 }
3290 return new SetCondInst(isSetNE ? Instruction::SetLT :
3291 Instruction::SetGE, X,
3292 Constant::getNullValue(X->getType()));
3293 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003294
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003295 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00003296 if (CI->isNullValue() && isHighOnes(BOC)) {
3297 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003298 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003299
3300 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003301 if (NegX->getType()->isSigned()) {
3302 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3303 X = InsertCastBefore(X, DestTy, I);
3304 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003305 }
3306
3307 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003308 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003309 }
3310
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003311 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003312 default: break;
3313 }
3314 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00003315 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00003316 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00003317 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3318 Value *CastOp = Cast->getOperand(0);
3319 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003320 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00003321 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003322 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003323 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00003324 "Source and destination signednesses should differ!");
3325 if (Cast->getType()->isSigned()) {
3326 // If this is a signed comparison, check for comparisons in the
3327 // vicinity of zero.
3328 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3329 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003330 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003331 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003332 else if (I.getOpcode() == Instruction::SetGT &&
3333 cast<ConstantSInt>(CI)->getValue() == -1)
3334 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003335 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003336 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003337 } else {
3338 ConstantUInt *CUI = cast<ConstantUInt>(CI);
3339 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003340 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00003341 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003342 return BinaryOperator::createSetGT(CastOp,
3343 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003344 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003345 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00003346 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003347 return BinaryOperator::createSetLT(CastOp,
3348 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003349 }
3350 }
3351 }
Chris Lattnere967b342003-06-04 05:10:11 +00003352 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003353 }
3354
Chris Lattner77c32c32005-04-23 15:31:55 +00003355 // Handle setcc with constant RHS's that can be integer, FP or pointer.
3356 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3357 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3358 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00003359 case Instruction::GetElementPtr:
3360 if (RHSC->isNullValue()) {
3361 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3362 bool isAllZeros = true;
3363 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3364 if (!isa<Constant>(LHSI->getOperand(i)) ||
3365 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3366 isAllZeros = false;
3367 break;
3368 }
3369 if (isAllZeros)
3370 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3371 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3372 }
3373 break;
3374
Chris Lattner77c32c32005-04-23 15:31:55 +00003375 case Instruction::PHI:
3376 if (Instruction *NV = FoldOpIntoPhi(I))
3377 return NV;
3378 break;
3379 case Instruction::Select:
3380 // If either operand of the select is a constant, we can fold the
3381 // comparison into the select arms, which will cause one to be
3382 // constant folded and the select turned into a bitwise or.
3383 Value *Op1 = 0, *Op2 = 0;
3384 if (LHSI->hasOneUse()) {
3385 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3386 // Fold the known value into the constant operand.
3387 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3388 // Insert a new SetCC of the other select operand.
3389 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3390 LHSI->getOperand(2), RHSC,
3391 I.getName()), I);
3392 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3393 // Fold the known value into the constant operand.
3394 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3395 // Insert a new SetCC of the other select operand.
3396 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3397 LHSI->getOperand(1), RHSC,
3398 I.getName()), I);
3399 }
3400 }
Jeff Cohen82639852005-04-23 21:38:35 +00003401
Chris Lattner77c32c32005-04-23 15:31:55 +00003402 if (Op1)
3403 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3404 break;
3405 }
3406 }
3407
Chris Lattner0798af32005-01-13 20:14:25 +00003408 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3409 if (User *GEP = dyn_castGetElementPtr(Op0))
3410 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3411 return NI;
3412 if (User *GEP = dyn_castGetElementPtr(Op1))
3413 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3414 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3415 return NI;
3416
Chris Lattner16930792003-11-03 04:25:02 +00003417 // Test to see if the operands of the setcc are casted versions of other
3418 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00003419 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3420 Value *CastOp0 = CI->getOperand(0);
3421 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00003422 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00003423 (I.getOpcode() == Instruction::SetEQ ||
3424 I.getOpcode() == Instruction::SetNE)) {
3425 // We keep moving the cast from the left operand over to the right
3426 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00003427 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003428
Chris Lattner16930792003-11-03 04:25:02 +00003429 // If operand #1 is a cast instruction, see if we can eliminate it as
3430 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00003431 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3432 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00003433 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00003434 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003435
Chris Lattner16930792003-11-03 04:25:02 +00003436 // If Op1 is a constant, we can fold the cast into the constant.
3437 if (Op1->getType() != Op0->getType())
3438 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3439 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3440 } else {
3441 // Otherwise, cast the RHS right before the setcc
3442 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3443 InsertNewInstBefore(cast<Instruction>(Op1), I);
3444 }
3445 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3446 }
3447
Chris Lattner6444c372003-11-03 05:17:03 +00003448 // Handle the special case of: setcc (cast bool to X), <cst>
3449 // This comes up when you have code like
3450 // int X = A < B;
3451 // if (X) ...
3452 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003453 // with a constant or another cast from the same type.
3454 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3455 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3456 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00003457 }
Chris Lattner113f4f42002-06-25 16:13:24 +00003458 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003459}
3460
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003461// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
3462// We only handle extending casts so far.
3463//
3464Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
3465 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
3466 const Type *SrcTy = LHSCIOp->getType();
3467 const Type *DestTy = SCI.getOperand(0)->getType();
3468 Value *RHSCIOp;
3469
3470 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00003471 return 0;
3472
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003473 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
3474 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3475 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
3476
3477 // Is this a sign or zero extension?
3478 bool isSignSrc = SrcTy->isSigned();
3479 bool isSignDest = DestTy->isSigned();
3480
3481 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3482 // Not an extension from the same type?
3483 RHSCIOp = CI->getOperand(0);
3484 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3485 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3486 // Compute the constant that would happen if we truncated to SrcTy then
3487 // reextended to DestTy.
3488 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3489
3490 if (ConstantExpr::getCast(Res, DestTy) == CI) {
3491 RHSCIOp = Res;
3492 } else {
3493 // If the value cannot be represented in the shorter type, we cannot emit
3494 // a simple comparison.
3495 if (SCI.getOpcode() == Instruction::SetEQ)
3496 return ReplaceInstUsesWith(SCI, ConstantBool::False);
3497 if (SCI.getOpcode() == Instruction::SetNE)
3498 return ReplaceInstUsesWith(SCI, ConstantBool::True);
3499
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003500 // Evaluate the comparison for LT.
3501 Value *Result;
3502 if (DestTy->isSigned()) {
3503 // We're performing a signed comparison.
3504 if (isSignSrc) {
3505 // Signed extend and signed comparison.
3506 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
3507 Result = ConstantBool::False;
3508 else
3509 Result = ConstantBool::True; // X < (large) --> true
3510 } else {
3511 // Unsigned extend and signed comparison.
3512 if (cast<ConstantSInt>(CI)->getValue() < 0)
3513 Result = ConstantBool::False;
3514 else
3515 Result = ConstantBool::True;
3516 }
3517 } else {
3518 // We're performing an unsigned comparison.
3519 if (!isSignSrc) {
3520 // Unsigned extend & compare -> always true.
3521 Result = ConstantBool::True;
3522 } else {
3523 // We're performing an unsigned comp with a sign extended value.
3524 // This is true if the input is >= 0. [aka >s -1]
3525 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
3526 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
3527 NegOne, SCI.getName()), SCI);
3528 }
Reid Spencer279fa252004-11-28 21:31:15 +00003529 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003530
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003531 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003532 if (SCI.getOpcode() == Instruction::SetLT) {
3533 return ReplaceInstUsesWith(SCI, Result);
3534 } else {
3535 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
3536 if (Constant *CI = dyn_cast<Constant>(Result))
3537 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
3538 else
3539 return BinaryOperator::createNot(Result);
3540 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003541 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003542 } else {
3543 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00003544 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003545
Chris Lattner252a8452005-06-16 03:00:08 +00003546 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003547 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
3548}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003549
Chris Lattnere8d6c602003-03-10 19:16:08 +00003550Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00003551 assert(I.getOperand(1)->getType() == Type::UByteTy);
3552 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003553 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003554
3555 // shl X, 0 == X and shr X, 0 == X
3556 // shl 0, X == 0 and shr 0, X == 0
3557 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00003558 Op0 == Constant::getNullValue(Op0->getType()))
3559 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003560
Chris Lattner81a7a232004-10-16 18:11:37 +00003561 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3562 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00003563 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00003564 else // undef << X -> 0 AND undef >>u X -> 0
3565 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3566 }
3567 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00003568 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00003569 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3570 else
3571 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3572 }
3573
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003574 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3575 if (!isLeftShift)
3576 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3577 if (CSI->isAllOnesValue())
3578 return ReplaceInstUsesWith(I, CSI);
3579
Chris Lattner183b3362004-04-09 19:05:30 +00003580 // Try to fold constant and into select arguments.
3581 if (isa<Constant>(Op0))
3582 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00003583 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003584 return R;
3585
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00003586 // See if we can turn a signed shr into an unsigned shr.
3587 if (!isLeftShift && I.getType()->isSigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003588 if (MaskedValueIsZero(Op0,
3589 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00003590 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
3591 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
3592 I.getName()), I);
3593 return new CastInst(V, I.getType());
3594 }
3595 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003596
Chris Lattner14553932006-01-06 07:12:35 +00003597 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
3598 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
3599 return Res;
3600 return 0;
3601}
3602
3603Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
3604 ShiftInst &I) {
3605 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerb3309392006-01-06 07:22:22 +00003606 bool isSignedShift = Op0->getType()->isSigned();
3607 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00003608
3609 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3610 // of a signed value.
3611 //
3612 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
3613 if (Op1->getValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00003614 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00003615 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3616 else {
3617 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3618 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00003619 }
Chris Lattner14553932006-01-06 07:12:35 +00003620 }
3621
3622 // ((X*C1) << C2) == (X * (C1 << C2))
3623 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3624 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3625 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
3626 return BinaryOperator::createMul(BO->getOperand(0),
3627 ConstantExpr::getShl(BOOp, Op1));
3628
3629 // Try to fold constant and into select arguments.
3630 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3631 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3632 return R;
3633 if (isa<PHINode>(Op0))
3634 if (Instruction *NV = FoldOpIntoPhi(I))
3635 return NV;
3636
3637 if (Op0->hasOneUse()) {
3638 // If this is a SHL of a sign-extending cast, see if we can turn the input
3639 // into a zero extending cast (a simple strength reduction).
3640 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3641 const Type *SrcTy = CI->getOperand(0)->getType();
3642 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
3643 SrcTy->getPrimitiveSizeInBits() <
3644 CI->getType()->getPrimitiveSizeInBits()) {
3645 // We can change it to a zero extension if we are shifting out all of
3646 // the sign extended bits. To check this, form a mask of all of the
3647 // sign extend bits, then shift them left and see if we have anything
3648 // left.
3649 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3650 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3651 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3652 if (ConstantExpr::getShl(Mask, Op1)->isNullValue()) {
3653 // If the shift is nuking all of the sign bits, change this to a
3654 // zero extension cast. To do this, cast the cast input to
3655 // unsigned, then to the requested size.
3656 Value *CastOp = CI->getOperand(0);
3657 Instruction *NC =
3658 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3659 CI->getName()+".uns");
3660 NC = InsertNewInstBefore(NC, I);
3661 // Finally, insert a replacement for CI.
3662 NC = new CastInst(NC, CI->getType(), CI->getName());
3663 CI->setName("");
3664 NC = InsertNewInstBefore(NC, I);
3665 WorkList.push_back(CI); // Delete CI later.
3666 I.setOperand(0, NC);
3667 return &I; // The SHL operand was modified.
Chris Lattner86102b82005-01-01 16:22:27 +00003668 }
3669 }
Chris Lattner14553932006-01-06 07:12:35 +00003670 }
3671
3672 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
3673 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
3674 Value *V1, *V2;
3675 ConstantInt *CC;
3676 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00003677 default: break;
3678 case Instruction::Add:
3679 case Instruction::And:
3680 case Instruction::Or:
3681 case Instruction::Xor:
3682 // These operators commute.
3683 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00003684 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3685 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00003686 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00003687 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00003688 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00003689 Op0BO->getName());
3690 InsertNewInstBefore(YS, I); // (Y << C)
3691 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3692 V1,
Chris Lattner14553932006-01-06 07:12:35 +00003693 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00003694 InsertNewInstBefore(X, I); // (X + (Y << C))
3695 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00003696 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00003697 return BinaryOperator::createAnd(X, C2);
3698 }
Chris Lattner14553932006-01-06 07:12:35 +00003699
Chris Lattner797dee72005-09-18 06:30:59 +00003700 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
3701 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3702 match(Op0BO->getOperand(1),
3703 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00003704 m_ConstantInt(CC))) && V2 == Op1 &&
3705 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00003706 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00003707 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00003708 Op0BO->getName());
3709 InsertNewInstBefore(YS, I); // (Y << C)
3710 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00003711 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00003712 V1->getName()+".mask");
3713 InsertNewInstBefore(XM, I); // X & (CC << C)
3714
3715 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3716 }
Chris Lattner14553932006-01-06 07:12:35 +00003717
Chris Lattner797dee72005-09-18 06:30:59 +00003718 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00003719 case Instruction::Sub:
3720 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00003721 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3722 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00003723 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00003724 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00003725 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00003726 Op0BO->getName());
3727 InsertNewInstBefore(YS, I); // (Y << C)
3728 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3729 V1,
Chris Lattner14553932006-01-06 07:12:35 +00003730 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00003731 InsertNewInstBefore(X, I); // (X + (Y << C))
3732 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00003733 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00003734 return BinaryOperator::createAnd(X, C2);
3735 }
Chris Lattner14553932006-01-06 07:12:35 +00003736
Chris Lattner797dee72005-09-18 06:30:59 +00003737 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3738 match(Op0BO->getOperand(0),
3739 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00003740 m_ConstantInt(CC))) && V2 == Op1 &&
3741 cast<BinaryOperator>(Op0BO->getOperand(0))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00003742 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00003743 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00003744 Op0BO->getName());
3745 InsertNewInstBefore(YS, I); // (Y << C)
3746 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00003747 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00003748 V1->getName()+".mask");
3749 InsertNewInstBefore(XM, I); // X & (CC << C)
3750
3751 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3752 }
Chris Lattner14553932006-01-06 07:12:35 +00003753
Chris Lattner27cb9db2005-09-18 05:12:10 +00003754 break;
Chris Lattner14553932006-01-06 07:12:35 +00003755 }
3756
3757
3758 // If the operand is an bitwise operator with a constant RHS, and the
3759 // shift is the only use, we can pull it out of the shift.
3760 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3761 bool isValid = true; // Valid only for And, Or, Xor
3762 bool highBitSet = false; // Transform if high bit of constant set?
3763
3764 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003765 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00003766 case Instruction::Add:
3767 isValid = isLeftShift;
3768 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003769 case Instruction::Or:
3770 case Instruction::Xor:
3771 highBitSet = false;
3772 break;
3773 case Instruction::And:
3774 highBitSet = true;
3775 break;
Chris Lattner14553932006-01-06 07:12:35 +00003776 }
3777
3778 // If this is a signed shift right, and the high bit is modified
3779 // by the logical operation, do not perform the transformation.
3780 // The highBitSet boolean indicates the value of the high bit of
3781 // the constant which would cause it to be modified for this
3782 // operation.
3783 //
Chris Lattnerb3309392006-01-06 07:22:22 +00003784 if (isValid && !isLeftShift && isSignedShift) {
Chris Lattner14553932006-01-06 07:12:35 +00003785 uint64_t Val = Op0C->getRawValue();
3786 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3787 }
3788
3789 if (isValid) {
3790 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
3791
3792 Instruction *NewShift =
3793 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
3794 Op0BO->getName());
3795 Op0BO->setName("");
3796 InsertNewInstBefore(NewShift, I);
3797
3798 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3799 NewRHS);
3800 }
3801 }
3802 }
3803 }
3804
Chris Lattnereb372a02006-01-06 07:52:12 +00003805 // Find out if this is a shift of a shift by a constant.
3806 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00003807 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00003808 ShiftOp = Op0SI;
3809 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3810 // If this is a noop-integer case of a shift instruction, use the shift.
3811 if (CI->getOperand(0)->getType()->isInteger() &&
3812 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3813 CI->getType()->getPrimitiveSizeInBits() &&
3814 isa<ShiftInst>(CI->getOperand(0))) {
3815 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
3816 }
3817 }
3818
3819 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
3820 // Find the operands and properties of the input shift. Note that the
3821 // signedness of the input shift may differ from the current shift if there
3822 // is a noop cast between the two.
3823 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
3824 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattner9cbfbc22006-01-07 01:32:28 +00003825 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00003826
3827 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
3828
3829 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3830 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
3831
3832 // Check for (A << c1) << c2 and (A >> c1) >> c2.
3833 if (isLeftShift == isShiftOfLeftShift) {
3834 // Do not fold these shifts if the first one is signed and the second one
3835 // is unsigned and this is a right shift. Further, don't do any folding
3836 // on them.
3837 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
3838 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00003839
Chris Lattnereb372a02006-01-06 07:52:12 +00003840 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
3841 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
3842 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00003843
Chris Lattnereb372a02006-01-06 07:52:12 +00003844 Value *Op = ShiftOp->getOperand(0);
3845 if (isShiftOfSignedShift != isSignedShift)
3846 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
3847 return new ShiftInst(I.getOpcode(), Op,
3848 ConstantUInt::get(Type::UByteTy, Amt));
3849 }
3850
3851 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
3852 // signed types, we can only support the (A >> c1) << c2 configuration,
3853 // because it can not turn an arbitrary bit of A into a sign bit.
3854 if (isUnsignedShift || isLeftShift) {
3855 // Calculate bitmask for what gets shifted off the edge.
3856 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
3857 if (isLeftShift)
3858 C = ConstantExpr::getShl(C, ShiftAmt1C);
3859 else
Chris Lattner9cbfbc22006-01-07 01:32:28 +00003860 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00003861
3862 Value *Op = ShiftOp->getOperand(0);
3863 if (isShiftOfSignedShift != isSignedShift)
3864 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
3865
3866 Instruction *Mask =
3867 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
3868 InsertNewInstBefore(Mask, I);
3869
3870 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00003871 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00003872 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00003873 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00003874 return new ShiftInst(I.getOpcode(), Mask,
3875 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00003876 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
3877 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
3878 // Make sure to emit an unsigned shift right, not a signed one.
3879 Mask = InsertNewInstBefore(new CastInst(Mask,
3880 Mask->getType()->getUnsignedVersion(),
3881 Op->getName()), I);
3882 Mask = new ShiftInst(Instruction::Shr, Mask,
Chris Lattnereb372a02006-01-06 07:52:12 +00003883 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00003884 InsertNewInstBefore(Mask, I);
3885 return new CastInst(Mask, I.getType());
3886 } else {
3887 return new ShiftInst(ShiftOp->getOpcode(), Mask,
3888 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3889 }
3890 } else {
3891 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
3892 Op = InsertNewInstBefore(new CastInst(Mask,
3893 I.getType()->getSignedVersion(),
3894 Mask->getName()), I);
3895 Instruction *Shift =
3896 new ShiftInst(ShiftOp->getOpcode(), Op,
3897 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3898 InsertNewInstBefore(Shift, I);
3899
3900 C = ConstantIntegral::getAllOnesValue(Shift->getType());
3901 C = ConstantExpr::getShl(C, Op1);
3902 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
3903 InsertNewInstBefore(Mask, I);
3904 return new CastInst(Mask, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00003905 }
3906 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00003907 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00003908 // this case, C1 == C2 and C1 is 8, 16, or 32.
3909 if (ShiftAmt1 == ShiftAmt2) {
3910 const Type *SExtType = 0;
3911 switch (ShiftAmt1) {
3912 case 8 : SExtType = Type::SByteTy; break;
3913 case 16: SExtType = Type::ShortTy; break;
3914 case 32: SExtType = Type::IntTy; break;
3915 }
3916
3917 if (SExtType) {
3918 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
3919 SExtType, "sext");
3920 InsertNewInstBefore(NewTrunc, I);
3921 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003922 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00003923 }
Chris Lattner86102b82005-01-01 16:22:27 +00003924 }
Chris Lattnereb372a02006-01-06 07:52:12 +00003925 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003926 return 0;
3927}
3928
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003929enum CastType {
3930 Noop = 0,
3931 Truncate = 1,
3932 Signext = 2,
3933 Zeroext = 3
3934};
3935
3936/// getCastType - In the future, we will split the cast instruction into these
3937/// various types. Until then, we have to do the analysis here.
3938static CastType getCastType(const Type *Src, const Type *Dest) {
3939 assert(Src->isIntegral() && Dest->isIntegral() &&
3940 "Only works on integral types!");
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003941 unsigned SrcSize = Src->getPrimitiveSizeInBits();
3942 unsigned DestSize = Dest->getPrimitiveSizeInBits();
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003943
3944 if (SrcSize == DestSize) return Noop;
3945 if (SrcSize > DestSize) return Truncate;
3946 if (Src->isSigned()) return Signext;
3947 return Zeroext;
3948}
3949
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003950
Chris Lattner48a44f72002-05-02 17:06:02 +00003951// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3952// instruction.
3953//
Chris Lattnere154abf2006-01-19 07:40:22 +00003954static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
3955 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003956
Chris Lattner650b6da2002-08-02 20:00:25 +00003957 // It is legal to eliminate the instruction if casting A->B->A if the sizes
Misha Brukmanb1c93172005-04-21 23:48:37 +00003958 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00003959 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00003960 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00003961 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00003962
Chris Lattner4fbad962004-07-21 04:27:24 +00003963 // If we are casting between pointer and integer types, treat pointers as
3964 // integers of the appropriate size for the code below.
3965 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3966 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3967 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00003968
Chris Lattner48a44f72002-05-02 17:06:02 +00003969 // Allow free casting and conversion of sizes as long as the sign doesn't
3970 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003971 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003972 CastType FirstCast = getCastType(SrcTy, MidTy);
3973 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00003974
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003975 // Capture the effect of these two casts. If the result is a legal cast,
3976 // the CastType is stored here, otherwise a special code is used.
3977 static const unsigned CastResult[] = {
3978 // First cast is noop
3979 0, 1, 2, 3,
3980 // First cast is a truncate
3981 1, 1, 4, 4, // trunc->extend is not safe to eliminate
3982 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00003983 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003984 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00003985 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003986 };
3987
3988 unsigned Result = CastResult[FirstCast*4+SecondCast];
3989 switch (Result) {
3990 default: assert(0 && "Illegal table value!");
3991 case 0:
3992 case 1:
3993 case 2:
3994 case 3:
3995 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
3996 // truncates, we could eliminate more casts.
3997 return (unsigned)getCastType(SrcTy, DstTy) == Result;
3998 case 4:
3999 return false; // Not possible to eliminate this here.
4000 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00004001 // Sign or zero extend followed by truncate is always ok if the result
4002 // is a truncate or noop.
4003 CastType ResultCast = getCastType(SrcTy, DstTy);
4004 if (ResultCast == Noop || ResultCast == Truncate)
4005 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004006 // Otherwise we are still growing the value, we are only safe if the
Chris Lattner1638de42004-07-21 19:50:44 +00004007 // result will match the sign/zeroextendness of the result.
4008 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00004009 }
Chris Lattner650b6da2002-08-02 20:00:25 +00004010 }
Chris Lattnere154abf2006-01-19 07:40:22 +00004011
4012 // If this is a cast from 'float -> double -> integer', cast from
4013 // 'float -> integer' directly, as the value isn't changed by the
4014 // float->double conversion.
4015 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
4016 DstTy->isIntegral() &&
4017 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
4018 return true;
4019
Chris Lattner48a44f72002-05-02 17:06:02 +00004020 return false;
4021}
4022
Chris Lattner11ffd592004-07-20 05:21:00 +00004023static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004024 if (V->getType() == Ty || isa<Constant>(V)) return false;
4025 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00004026 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
4027 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004028 return false;
4029 return true;
4030}
4031
4032/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
4033/// InsertBefore instruction. This is specialized a bit to avoid inserting
4034/// casts that are known to not do anything...
4035///
4036Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
4037 Instruction *InsertBefore) {
4038 if (V->getType() == DestTy) return V;
4039 if (Constant *C = dyn_cast<Constant>(V))
4040 return ConstantExpr::getCast(C, DestTy);
4041
4042 CastInst *CI = new CastInst(V, DestTy, V->getName());
4043 InsertNewInstBefore(CI, *InsertBefore);
4044 return CI;
4045}
Chris Lattner48a44f72002-05-02 17:06:02 +00004046
Chris Lattner8f663e82005-10-29 04:36:15 +00004047/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4048/// expression. If so, decompose it, returning some value X, such that Val is
4049/// X*Scale+Offset.
4050///
4051static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4052 unsigned &Offset) {
4053 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4054 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4055 Offset = CI->getValue();
4056 Scale = 1;
4057 return ConstantUInt::get(Type::UIntTy, 0);
4058 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4059 if (I->getNumOperands() == 2) {
4060 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4061 if (I->getOpcode() == Instruction::Shl) {
4062 // This is a value scaled by '1 << the shift amt'.
4063 Scale = 1U << CUI->getValue();
4064 Offset = 0;
4065 return I->getOperand(0);
4066 } else if (I->getOpcode() == Instruction::Mul) {
4067 // This value is scaled by 'CUI'.
4068 Scale = CUI->getValue();
4069 Offset = 0;
4070 return I->getOperand(0);
4071 } else if (I->getOpcode() == Instruction::Add) {
4072 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
4073 // divisible by C2.
4074 unsigned SubScale;
4075 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
4076 Offset);
4077 Offset += CUI->getValue();
4078 if (SubScale > 1 && (Offset % SubScale == 0)) {
4079 Scale = SubScale;
4080 return SubVal;
4081 }
4082 }
4083 }
4084 }
4085 }
4086
4087 // Otherwise, we can't look past this.
4088 Scale = 1;
4089 Offset = 0;
4090 return Val;
4091}
4092
4093
Chris Lattner216be912005-10-24 06:03:58 +00004094/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4095/// try to eliminate the cast by moving the type information into the alloc.
4096Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
4097 AllocationInst &AI) {
4098 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00004099 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00004100
Chris Lattnerac87beb2005-10-24 06:22:12 +00004101 // Remove any uses of AI that are dead.
4102 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
4103 std::vector<Instruction*> DeadUsers;
4104 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4105 Instruction *User = cast<Instruction>(*UI++);
4106 if (isInstructionTriviallyDead(User)) {
4107 while (UI != E && *UI == User)
4108 ++UI; // If this instruction uses AI more than once, don't break UI.
4109
4110 // Add operands to the worklist.
4111 AddUsesToWorkList(*User);
4112 ++NumDeadInst;
4113 DEBUG(std::cerr << "IC: DCE: " << *User);
4114
4115 User->eraseFromParent();
4116 removeFromWorkList(User);
4117 }
4118 }
4119
Chris Lattner216be912005-10-24 06:03:58 +00004120 // Get the type really allocated and the type casted to.
4121 const Type *AllocElTy = AI.getAllocatedType();
4122 const Type *CastElTy = PTy->getElementType();
4123 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00004124
4125 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
4126 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
4127 if (CastElTyAlign < AllocElTyAlign) return 0;
4128
Chris Lattner46705b22005-10-24 06:35:18 +00004129 // If the allocation has multiple uses, only promote it if we are strictly
4130 // increasing the alignment of the resultant allocation. If we keep it the
4131 // same, we open the door to infinite loops of various kinds.
4132 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
4133
Chris Lattner216be912005-10-24 06:03:58 +00004134 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
4135 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00004136 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00004137
Chris Lattner8270c332005-10-29 03:19:53 +00004138 // See if we can satisfy the modulus by pulling a scale out of the array
4139 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00004140 unsigned ArraySizeScale, ArrayOffset;
4141 Value *NumElements = // See if the array size is a decomposable linear expr.
4142 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
4143
Chris Lattner8270c332005-10-29 03:19:53 +00004144 // If we can now satisfy the modulus, by using a non-1 scale, we really can
4145 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00004146 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4147 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00004148
Chris Lattner8270c332005-10-29 03:19:53 +00004149 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4150 Value *Amt = 0;
4151 if (Scale == 1) {
4152 Amt = NumElements;
4153 } else {
4154 Amt = ConstantUInt::get(Type::UIntTy, Scale);
4155 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4156 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4157 else if (Scale != 1) {
4158 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4159 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00004160 }
Chris Lattnerbb171802005-10-27 05:53:56 +00004161 }
4162
Chris Lattner8f663e82005-10-29 04:36:15 +00004163 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4164 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4165 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4166 Amt = InsertNewInstBefore(Tmp, AI);
4167 }
4168
Chris Lattner216be912005-10-24 06:03:58 +00004169 std::string Name = AI.getName(); AI.setName("");
4170 AllocationInst *New;
4171 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00004172 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00004173 else
Nate Begeman848622f2005-11-05 09:21:28 +00004174 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00004175 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00004176
4177 // If the allocation has multiple uses, insert a cast and change all things
4178 // that used it to use the new cast. This will also hack on CI, but it will
4179 // die soon.
4180 if (!AI.hasOneUse()) {
4181 AddUsesToWorkList(AI);
4182 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4183 InsertNewInstBefore(NewCast, AI);
4184 AI.replaceAllUsesWith(NewCast);
4185 }
Chris Lattner216be912005-10-24 06:03:58 +00004186 return ReplaceInstUsesWith(CI, New);
4187}
4188
4189
Chris Lattner48a44f72002-05-02 17:06:02 +00004190// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00004191//
Chris Lattner113f4f42002-06-25 16:13:24 +00004192Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00004193 Value *Src = CI.getOperand(0);
4194
Chris Lattner48a44f72002-05-02 17:06:02 +00004195 // If the user is casting a value to the same type, eliminate this cast
4196 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00004197 if (CI.getType() == Src->getType())
4198 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00004199
Chris Lattner81a7a232004-10-16 18:11:37 +00004200 if (isa<UndefValue>(Src)) // cast undef -> undef
4201 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
4202
Chris Lattner48a44f72002-05-02 17:06:02 +00004203 // If casting the result of another cast instruction, try to eliminate this
4204 // one!
4205 //
Chris Lattner86102b82005-01-01 16:22:27 +00004206 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
4207 Value *A = CSrc->getOperand(0);
4208 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
4209 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00004210 // This instruction now refers directly to the cast's src operand. This
4211 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00004212 CI.setOperand(0, CSrc->getOperand(0));
4213 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00004214 }
4215
Chris Lattner650b6da2002-08-02 20:00:25 +00004216 // If this is an A->B->A cast, and we are dealing with integral types, try
4217 // to convert this into a logical 'and' instruction.
4218 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00004219 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00004220 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00004221 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004222 CSrc->getType()->getPrimitiveSizeInBits() <
4223 CI.getType()->getPrimitiveSizeInBits()&&
4224 A->getType()->getPrimitiveSizeInBits() ==
4225 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00004226 assert(CSrc->getType() != Type::ULongTy &&
4227 "Cannot have type bigger than ulong!");
Chris Lattner77defba2006-02-07 07:00:41 +00004228 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Chris Lattner86102b82005-01-01 16:22:27 +00004229 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
4230 AndValue);
4231 AndOp = ConstantExpr::getCast(AndOp, A->getType());
4232 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
4233 if (And->getType() != CI.getType()) {
4234 And->setName(CSrc->getName()+".mask");
4235 InsertNewInstBefore(And, CI);
4236 And = new CastInst(And, CI.getType());
4237 }
4238 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00004239 }
4240 }
Chris Lattner2590e512006-02-07 06:56:34 +00004241
Chris Lattner03841652004-05-25 04:29:21 +00004242 // If this is a cast to bool, turn it into the appropriate setne instruction.
4243 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004244 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00004245 Constant::getNullValue(CI.getOperand(0)->getType()));
4246
Chris Lattner2590e512006-02-07 06:56:34 +00004247 // See if we can simplify any instructions used by the LHS whose sole
4248 // purpose is to compute bits we don't care about.
4249 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral() &&
4250 SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask()))
4251 return &CI;
4252
Chris Lattnerd0d51602003-06-21 23:12:02 +00004253 // If casting the result of a getelementptr instruction with no offset, turn
4254 // this into a cast of the original pointer!
4255 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00004256 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00004257 bool AllZeroOperands = true;
4258 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
4259 if (!isa<Constant>(GEP->getOperand(i)) ||
4260 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
4261 AllZeroOperands = false;
4262 break;
4263 }
4264 if (AllZeroOperands) {
4265 CI.setOperand(0, GEP->getOperand(0));
4266 return &CI;
4267 }
4268 }
4269
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004270 // If we are casting a malloc or alloca to a pointer to a type of the same
4271 // size, rewrite the allocation instruction to allocate the "right" type.
4272 //
4273 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00004274 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4275 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004276
Chris Lattner86102b82005-01-01 16:22:27 +00004277 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4278 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4279 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004280 if (isa<PHINode>(Src))
4281 if (Instruction *NV = FoldOpIntoPhi(CI))
4282 return NV;
4283
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004284 // If the source value is an instruction with only this use, we can attempt to
4285 // propagate the cast into the instruction. Also, only handle integral types
4286 // for now.
4287 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004288 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004289 CI.getType()->isInteger()) { // Don't mess with casts to bool here
4290 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004291 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
4292 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004293
4294 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
4295 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
4296
4297 switch (SrcI->getOpcode()) {
4298 case Instruction::Add:
4299 case Instruction::Mul:
4300 case Instruction::And:
4301 case Instruction::Or:
4302 case Instruction::Xor:
4303 // If we are discarding information, or just changing the sign, rewrite.
4304 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
4305 // Don't insert two casts if they cannot be eliminated. We allow two
4306 // casts to be inserted if the sizes are the same. This could only be
4307 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00004308 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
4309 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004310 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4311 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
4312 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
4313 ->getOpcode(), Op0c, Op1c);
4314 }
4315 }
Chris Lattner72086162005-05-06 02:07:39 +00004316
4317 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
4318 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
4319 Op1 == ConstantBool::True &&
4320 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
4321 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
4322 return BinaryOperator::createXor(New,
4323 ConstantInt::get(CI.getType(), 1));
4324 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004325 break;
4326 case Instruction::Shl:
4327 // Allow changing the sign of the source operand. Do not allow changing
4328 // the size of the shift, UNLESS the shift amount is a constant. We
4329 // mush not change variable sized shifts to a smaller size, because it
4330 // is undefined to shift more bits out than exist in the value.
4331 if (DestBitSize == SrcBitSize ||
4332 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
4333 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4334 return new ShiftInst(Instruction::Shl, Op0c, Op1);
4335 }
4336 break;
Chris Lattner87380412005-05-06 04:18:52 +00004337 case Instruction::Shr:
4338 // If this is a signed shr, and if all bits shifted in are about to be
4339 // truncated off, turn it into an unsigned shr to allow greater
4340 // simplifications.
4341 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
4342 isa<ConstantInt>(Op1)) {
4343 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
4344 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
4345 // Convert to unsigned.
4346 Value *N1 = InsertOperandCastBefore(Op0,
4347 Op0->getType()->getUnsignedVersion(), &CI);
4348 // Insert the new shift, which is now unsigned.
4349 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
4350 Op1, Src->getName()), CI);
4351 return new CastInst(N1, CI.getType());
4352 }
4353 }
4354 break;
4355
Chris Lattner809dfac2005-05-04 19:10:26 +00004356 case Instruction::SetNE:
Chris Lattner809dfac2005-05-04 19:10:26 +00004357 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00004358 if (Op1C->getRawValue() == 0) {
4359 // If the input only has the low bit set, simplify directly.
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004360 Constant *Not1 =
Chris Lattner809dfac2005-05-04 19:10:26 +00004361 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
Chris Lattner4c2d3782005-05-06 01:53:19 +00004362 // cast (X != 0) to int --> X if X&~1 == 0
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004363 if (MaskedValueIsZero(Op0,
4364 cast<ConstantIntegral>(Not1)->getZExtValue())) {
Chris Lattner809dfac2005-05-04 19:10:26 +00004365 if (CI.getType() == Op0->getType())
4366 return ReplaceInstUsesWith(CI, Op0);
4367 else
4368 return new CastInst(Op0, CI.getType());
4369 }
Chris Lattner4c2d3782005-05-06 01:53:19 +00004370
4371 // If the input is an and with a single bit, shift then simplify.
4372 ConstantInt *AndRHS;
4373 if (match(Op0, m_And(m_Value(), m_ConstantInt(AndRHS))))
4374 if (AndRHS->getRawValue() &&
4375 (AndRHS->getRawValue() & (AndRHS->getRawValue()-1)) == 0) {
Chris Lattner22d00a82005-08-02 19:16:58 +00004376 unsigned ShiftAmt = Log2_64(AndRHS->getRawValue());
Chris Lattner4c2d3782005-05-06 01:53:19 +00004377 // Perform an unsigned shr by shiftamt. Convert input to
4378 // unsigned if it is signed.
4379 Value *In = Op0;
4380 if (In->getType()->isSigned())
4381 In = InsertNewInstBefore(new CastInst(In,
4382 In->getType()->getUnsignedVersion(), In->getName()),CI);
4383 // Insert the shift to put the result in the low bit.
4384 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
4385 ConstantInt::get(Type::UByteTy, ShiftAmt),
4386 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00004387 if (CI.getType() == In->getType())
4388 return ReplaceInstUsesWith(CI, In);
4389 else
4390 return new CastInst(In, CI.getType());
4391 }
4392 }
4393 }
4394 break;
4395 case Instruction::SetEQ:
4396 // We if we are just checking for a seteq of a single bit and casting it
4397 // to an integer. If so, shift the bit to the appropriate place then
4398 // cast to integer to avoid the comparison.
4399 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
4400 // Is Op1C a power of two or zero?
4401 if ((Op1C->getRawValue() & Op1C->getRawValue()-1) == 0) {
4402 // cast (X == 1) to int -> X iff X has only the low bit set.
4403 if (Op1C->getRawValue() == 1) {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004404 Constant *Not1 =
Chris Lattner4c2d3782005-05-06 01:53:19 +00004405 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004406 if (MaskedValueIsZero(Op0,
4407 cast<ConstantIntegral>(Not1)->getZExtValue())) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00004408 if (CI.getType() == Op0->getType())
4409 return ReplaceInstUsesWith(CI, Op0);
4410 else
4411 return new CastInst(Op0, CI.getType());
4412 }
4413 }
Chris Lattner809dfac2005-05-04 19:10:26 +00004414 }
4415 }
4416 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004417 }
4418 }
Chris Lattnerbb171802005-10-27 05:53:56 +00004419
Chris Lattner260ab202002-04-18 17:39:14 +00004420 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00004421}
4422
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004423/// GetSelectFoldableOperands - We want to turn code that looks like this:
4424/// %C = or %A, %B
4425/// %D = select %cond, %C, %A
4426/// into:
4427/// %C = select %cond, %B, 0
4428/// %D = or %A, %C
4429///
4430/// Assuming that the specified instruction is an operand to the select, return
4431/// a bitmask indicating which operands of this instruction are foldable if they
4432/// equal the other incoming value of the select.
4433///
4434static unsigned GetSelectFoldableOperands(Instruction *I) {
4435 switch (I->getOpcode()) {
4436 case Instruction::Add:
4437 case Instruction::Mul:
4438 case Instruction::And:
4439 case Instruction::Or:
4440 case Instruction::Xor:
4441 return 3; // Can fold through either operand.
4442 case Instruction::Sub: // Can only fold on the amount subtracted.
4443 case Instruction::Shl: // Can only fold on the shift amount.
4444 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00004445 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004446 default:
4447 return 0; // Cannot fold
4448 }
4449}
4450
4451/// GetSelectFoldableConstant - For the same transformation as the previous
4452/// function, return the identity constant that goes into the select.
4453static Constant *GetSelectFoldableConstant(Instruction *I) {
4454 switch (I->getOpcode()) {
4455 default: assert(0 && "This cannot happen!"); abort();
4456 case Instruction::Add:
4457 case Instruction::Sub:
4458 case Instruction::Or:
4459 case Instruction::Xor:
4460 return Constant::getNullValue(I->getType());
4461 case Instruction::Shl:
4462 case Instruction::Shr:
4463 return Constant::getNullValue(Type::UByteTy);
4464 case Instruction::And:
4465 return ConstantInt::getAllOnesValue(I->getType());
4466 case Instruction::Mul:
4467 return ConstantInt::get(I->getType(), 1);
4468 }
4469}
4470
Chris Lattner411336f2005-01-19 21:50:18 +00004471/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
4472/// have the same opcode and only one use each. Try to simplify this.
4473Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
4474 Instruction *FI) {
4475 if (TI->getNumOperands() == 1) {
4476 // If this is a non-volatile load or a cast from the same type,
4477 // merge.
4478 if (TI->getOpcode() == Instruction::Cast) {
4479 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
4480 return 0;
4481 } else {
4482 return 0; // unknown unary op.
4483 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004484
Chris Lattner411336f2005-01-19 21:50:18 +00004485 // Fold this by inserting a select from the input values.
4486 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
4487 FI->getOperand(0), SI.getName()+".v");
4488 InsertNewInstBefore(NewSI, SI);
4489 return new CastInst(NewSI, TI->getType());
4490 }
4491
4492 // Only handle binary operators here.
4493 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
4494 return 0;
4495
4496 // Figure out if the operations have any operands in common.
4497 Value *MatchOp, *OtherOpT, *OtherOpF;
4498 bool MatchIsOpZero;
4499 if (TI->getOperand(0) == FI->getOperand(0)) {
4500 MatchOp = TI->getOperand(0);
4501 OtherOpT = TI->getOperand(1);
4502 OtherOpF = FI->getOperand(1);
4503 MatchIsOpZero = true;
4504 } else if (TI->getOperand(1) == FI->getOperand(1)) {
4505 MatchOp = TI->getOperand(1);
4506 OtherOpT = TI->getOperand(0);
4507 OtherOpF = FI->getOperand(0);
4508 MatchIsOpZero = false;
4509 } else if (!TI->isCommutative()) {
4510 return 0;
4511 } else if (TI->getOperand(0) == FI->getOperand(1)) {
4512 MatchOp = TI->getOperand(0);
4513 OtherOpT = TI->getOperand(1);
4514 OtherOpF = FI->getOperand(0);
4515 MatchIsOpZero = true;
4516 } else if (TI->getOperand(1) == FI->getOperand(0)) {
4517 MatchOp = TI->getOperand(1);
4518 OtherOpT = TI->getOperand(0);
4519 OtherOpF = FI->getOperand(1);
4520 MatchIsOpZero = true;
4521 } else {
4522 return 0;
4523 }
4524
4525 // If we reach here, they do have operations in common.
4526 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
4527 OtherOpF, SI.getName()+".v");
4528 InsertNewInstBefore(NewSI, SI);
4529
4530 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
4531 if (MatchIsOpZero)
4532 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
4533 else
4534 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
4535 } else {
4536 if (MatchIsOpZero)
4537 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
4538 else
4539 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
4540 }
4541}
4542
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004543Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00004544 Value *CondVal = SI.getCondition();
4545 Value *TrueVal = SI.getTrueValue();
4546 Value *FalseVal = SI.getFalseValue();
4547
4548 // select true, X, Y -> X
4549 // select false, X, Y -> Y
4550 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004551 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00004552 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004553 else {
4554 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00004555 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004556 }
Chris Lattner533bc492004-03-30 19:37:13 +00004557
4558 // select C, X, X -> X
4559 if (TrueVal == FalseVal)
4560 return ReplaceInstUsesWith(SI, TrueVal);
4561
Chris Lattner81a7a232004-10-16 18:11:37 +00004562 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
4563 return ReplaceInstUsesWith(SI, FalseVal);
4564 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
4565 return ReplaceInstUsesWith(SI, TrueVal);
4566 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
4567 if (isa<Constant>(TrueVal))
4568 return ReplaceInstUsesWith(SI, TrueVal);
4569 else
4570 return ReplaceInstUsesWith(SI, FalseVal);
4571 }
4572
Chris Lattner1c631e82004-04-08 04:43:23 +00004573 if (SI.getType() == Type::BoolTy)
4574 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
4575 if (C == ConstantBool::True) {
4576 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004577 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004578 } else {
4579 // Change: A = select B, false, C --> A = and !B, C
4580 Value *NotCond =
4581 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4582 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004583 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004584 }
4585 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
4586 if (C == ConstantBool::False) {
4587 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004588 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004589 } else {
4590 // Change: A = select B, C, true --> A = or !B, C
4591 Value *NotCond =
4592 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4593 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004594 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004595 }
4596 }
4597
Chris Lattner183b3362004-04-09 19:05:30 +00004598 // Selecting between two integer constants?
4599 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
4600 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
4601 // select C, 1, 0 -> cast C to int
4602 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
4603 return new CastInst(CondVal, SI.getType());
4604 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
4605 // select C, 0, 1 -> cast !C to int
4606 Value *NotCond =
4607 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00004608 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00004609 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00004610 }
Chris Lattner35167c32004-06-09 07:59:58 +00004611
4612 // If one of the constants is zero (we know they can't both be) and we
4613 // have a setcc instruction with zero, and we have an 'and' with the
4614 // non-constant value, eliminate this whole mess. This corresponds to
4615 // cases like this: ((X & 27) ? 27 : 0)
4616 if (TrueValC->isNullValue() || FalseValC->isNullValue())
4617 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
4618 if ((IC->getOpcode() == Instruction::SetEQ ||
4619 IC->getOpcode() == Instruction::SetNE) &&
4620 isa<ConstantInt>(IC->getOperand(1)) &&
4621 cast<Constant>(IC->getOperand(1))->isNullValue())
4622 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
4623 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00004624 isa<ConstantInt>(ICA->getOperand(1)) &&
4625 (ICA->getOperand(1) == TrueValC ||
4626 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00004627 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
4628 // Okay, now we know that everything is set up, we just don't
4629 // know whether we have a setne or seteq and whether the true or
4630 // false val is the zero.
4631 bool ShouldNotVal = !TrueValC->isNullValue();
4632 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
4633 Value *V = ICA;
4634 if (ShouldNotVal)
4635 V = InsertNewInstBefore(BinaryOperator::create(
4636 Instruction::Xor, V, ICA->getOperand(1)), SI);
4637 return ReplaceInstUsesWith(SI, V);
4638 }
Chris Lattner533bc492004-03-30 19:37:13 +00004639 }
Chris Lattner623fba12004-04-10 22:21:27 +00004640
4641 // See if we are selecting two values based on a comparison of the two values.
4642 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
4643 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
4644 // Transform (X == Y) ? X : Y -> Y
4645 if (SCI->getOpcode() == Instruction::SetEQ)
4646 return ReplaceInstUsesWith(SI, FalseVal);
4647 // Transform (X != Y) ? X : Y -> X
4648 if (SCI->getOpcode() == Instruction::SetNE)
4649 return ReplaceInstUsesWith(SI, TrueVal);
4650 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4651
4652 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
4653 // Transform (X == Y) ? Y : X -> X
4654 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00004655 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00004656 // Transform (X != Y) ? Y : X -> Y
4657 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00004658 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00004659 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4660 }
4661 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004662
Chris Lattnera04c9042005-01-13 22:52:24 +00004663 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
4664 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
4665 if (TI->hasOneUse() && FI->hasOneUse()) {
4666 bool isInverse = false;
4667 Instruction *AddOp = 0, *SubOp = 0;
4668
Chris Lattner411336f2005-01-19 21:50:18 +00004669 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
4670 if (TI->getOpcode() == FI->getOpcode())
4671 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
4672 return IV;
4673
4674 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
4675 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00004676 if (TI->getOpcode() == Instruction::Sub &&
4677 FI->getOpcode() == Instruction::Add) {
4678 AddOp = FI; SubOp = TI;
4679 } else if (FI->getOpcode() == Instruction::Sub &&
4680 TI->getOpcode() == Instruction::Add) {
4681 AddOp = TI; SubOp = FI;
4682 }
4683
4684 if (AddOp) {
4685 Value *OtherAddOp = 0;
4686 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
4687 OtherAddOp = AddOp->getOperand(1);
4688 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
4689 OtherAddOp = AddOp->getOperand(0);
4690 }
4691
4692 if (OtherAddOp) {
4693 // So at this point we know we have:
4694 // select C, (add X, Y), (sub X, ?)
4695 // We can do the transform profitably if either 'Y' = '?' or '?' is
4696 // a constant.
4697 if (SubOp->getOperand(1) == AddOp ||
4698 isa<Constant>(SubOp->getOperand(1))) {
4699 Value *NegVal;
4700 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
4701 NegVal = ConstantExpr::getNeg(C);
4702 } else {
4703 NegVal = InsertNewInstBefore(
4704 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
4705 }
4706
Chris Lattner51726c42005-01-14 17:35:12 +00004707 Value *NewTrueOp = OtherAddOp;
Chris Lattnera04c9042005-01-13 22:52:24 +00004708 Value *NewFalseOp = NegVal;
4709 if (AddOp != TI)
4710 std::swap(NewTrueOp, NewFalseOp);
4711 Instruction *NewSel =
4712 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
Misha Brukmanb1c93172005-04-21 23:48:37 +00004713
Chris Lattnera04c9042005-01-13 22:52:24 +00004714 NewSel = InsertNewInstBefore(NewSel, SI);
Chris Lattner51726c42005-01-14 17:35:12 +00004715 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00004716 }
4717 }
4718 }
4719 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004720
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004721 // See if we can fold the select into one of our operands.
4722 if (SI.getType()->isInteger()) {
4723 // See the comment above GetSelectFoldableOperands for a description of the
4724 // transformation we are doing here.
4725 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
4726 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
4727 !isa<Constant>(FalseVal))
4728 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
4729 unsigned OpToFold = 0;
4730 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
4731 OpToFold = 1;
4732 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
4733 OpToFold = 2;
4734 }
4735
4736 if (OpToFold) {
4737 Constant *C = GetSelectFoldableConstant(TVI);
4738 std::string Name = TVI->getName(); TVI->setName("");
4739 Instruction *NewSel =
4740 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
4741 Name);
4742 InsertNewInstBefore(NewSel, SI);
4743 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
4744 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
4745 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
4746 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
4747 else {
4748 assert(0 && "Unknown instruction!!");
4749 }
4750 }
4751 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00004752
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004753 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
4754 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
4755 !isa<Constant>(TrueVal))
4756 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
4757 unsigned OpToFold = 0;
4758 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
4759 OpToFold = 1;
4760 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
4761 OpToFold = 2;
4762 }
4763
4764 if (OpToFold) {
4765 Constant *C = GetSelectFoldableConstant(FVI);
4766 std::string Name = FVI->getName(); FVI->setName("");
4767 Instruction *NewSel =
4768 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
4769 Name);
4770 InsertNewInstBefore(NewSel, SI);
4771 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
4772 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
4773 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
4774 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
4775 else {
4776 assert(0 && "Unknown instruction!!");
4777 }
4778 }
4779 }
4780 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00004781
4782 if (BinaryOperator::isNot(CondVal)) {
4783 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
4784 SI.setOperand(1, FalseVal);
4785 SI.setOperand(2, TrueVal);
4786 return &SI;
4787 }
4788
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004789 return 0;
4790}
4791
4792
Chris Lattnerc66b2232006-01-13 20:11:04 +00004793/// visitCallInst - CallInst simplification. This mostly only handles folding
4794/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
4795/// the heavy lifting.
4796///
Chris Lattner970c33a2003-06-19 17:00:31 +00004797Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00004798 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
4799 if (!II) return visitCallSite(&CI);
4800
Chris Lattner51ea1272004-02-28 05:22:00 +00004801 // Intrinsics cannot occur in an invoke, so handle them here instead of in
4802 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00004803 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00004804 bool Changed = false;
4805
4806 // memmove/cpy/set of zero bytes is a noop.
4807 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
4808 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
4809
4810 // FIXME: Increase alignment here.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004811
Chris Lattner00648e12004-10-12 04:52:52 +00004812 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
4813 if (CI->getRawValue() == 1) {
4814 // Replace the instruction with just byte operations. We would
4815 // transform other cases to loads/stores, but we don't know if
4816 // alignment is sufficient.
4817 }
Chris Lattner51ea1272004-02-28 05:22:00 +00004818 }
4819
Chris Lattner00648e12004-10-12 04:52:52 +00004820 // If we have a memmove and the source operation is a constant global,
4821 // then the source and dest pointers can't alias, so we can change this
4822 // into a call to memcpy.
Chris Lattnerc66b2232006-01-13 20:11:04 +00004823 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II))
Chris Lattner00648e12004-10-12 04:52:52 +00004824 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
4825 if (GVSrc->isConstant()) {
4826 Module *M = CI.getParent()->getParent()->getParent();
4827 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
4828 CI.getCalledFunction()->getFunctionType());
4829 CI.setOperand(0, MemCpy);
4830 Changed = true;
4831 }
4832
Chris Lattnerc66b2232006-01-13 20:11:04 +00004833 if (Changed) return II;
4834 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(II)) {
Chris Lattner95307542004-11-18 21:41:39 +00004835 // If this stoppoint is at the same source location as the previous
4836 // stoppoint in the chain, it is not needed.
4837 if (DbgStopPointInst *PrevSPI =
4838 dyn_cast<DbgStopPointInst>(SPI->getChain()))
4839 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
4840 SPI->getColNo() == PrevSPI->getColNo()) {
4841 SPI->replaceAllUsesWith(PrevSPI);
4842 return EraseInstFromFunction(CI);
4843 }
Chris Lattner503221f2006-01-13 21:28:09 +00004844 } else {
4845 switch (II->getIntrinsicID()) {
4846 default: break;
4847 case Intrinsic::stackrestore: {
4848 // If the save is right next to the restore, remove the restore. This can
4849 // happen when variable allocas are DCE'd.
4850 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
4851 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
4852 BasicBlock::iterator BI = SS;
4853 if (&*++BI == II)
4854 return EraseInstFromFunction(CI);
4855 }
4856 }
4857
4858 // If the stack restore is in a return/unwind block and if there are no
4859 // allocas or calls between the restore and the return, nuke the restore.
4860 TerminatorInst *TI = II->getParent()->getTerminator();
4861 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
4862 BasicBlock::iterator BI = II;
4863 bool CannotRemove = false;
4864 for (++BI; &*BI != TI; ++BI) {
4865 if (isa<AllocaInst>(BI) ||
4866 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
4867 CannotRemove = true;
4868 break;
4869 }
4870 }
4871 if (!CannotRemove)
4872 return EraseInstFromFunction(CI);
4873 }
4874 break;
4875 }
4876 }
Chris Lattner00648e12004-10-12 04:52:52 +00004877 }
4878
Chris Lattnerc66b2232006-01-13 20:11:04 +00004879 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00004880}
4881
4882// InvokeInst simplification
4883//
4884Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00004885 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00004886}
4887
Chris Lattneraec3d942003-10-07 22:32:43 +00004888// visitCallSite - Improvements for call and invoke instructions.
4889//
4890Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004891 bool Changed = false;
4892
4893 // If the callee is a constexpr cast of a function, attempt to move the cast
4894 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00004895 if (transformConstExprCastCall(CS)) return 0;
4896
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004897 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00004898
Chris Lattner61d9d812005-05-13 07:09:09 +00004899 if (Function *CalleeF = dyn_cast<Function>(Callee))
4900 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
4901 Instruction *OldCall = CS.getInstruction();
4902 // If the call and callee calling conventions don't match, this call must
4903 // be unreachable, as the call is undefined.
4904 new StoreInst(ConstantBool::True,
4905 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
4906 if (!OldCall->use_empty())
4907 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
4908 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
4909 return EraseInstFromFunction(*OldCall);
4910 return 0;
4911 }
4912
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004913 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
4914 // This instruction is not reachable, just remove it. We insert a store to
4915 // undef so that we know that this code is not reachable, despite the fact
4916 // that we can't modify the CFG here.
4917 new StoreInst(ConstantBool::True,
4918 UndefValue::get(PointerType::get(Type::BoolTy)),
4919 CS.getInstruction());
4920
4921 if (!CS.getInstruction()->use_empty())
4922 CS.getInstruction()->
4923 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
4924
4925 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
4926 // Don't break the CFG, insert a dummy cond branch.
4927 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
4928 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00004929 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004930 return EraseInstFromFunction(*CS.getInstruction());
4931 }
Chris Lattner81a7a232004-10-16 18:11:37 +00004932
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004933 const PointerType *PTy = cast<PointerType>(Callee->getType());
4934 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4935 if (FTy->isVarArg()) {
4936 // See if we can optimize any arguments passed through the varargs area of
4937 // the call.
4938 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
4939 E = CS.arg_end(); I != E; ++I)
4940 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
4941 // If this cast does not effect the value passed through the varargs
4942 // area, we can eliminate the use of the cast.
4943 Value *Op = CI->getOperand(0);
4944 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
4945 *I = Op;
4946 Changed = true;
4947 }
4948 }
4949 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004950
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004951 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00004952}
4953
Chris Lattner970c33a2003-06-19 17:00:31 +00004954// transformConstExprCastCall - If the callee is a constexpr cast of a function,
4955// attempt to move the cast to the arguments of the call/invoke.
4956//
4957bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4958 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
4959 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00004960 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00004961 return false;
Reid Spencer87436872004-07-18 00:38:32 +00004962 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00004963 Instruction *Caller = CS.getInstruction();
4964
4965 // Okay, this is a cast from a function to a different type. Unless doing so
4966 // would cause a type conversion of one of our arguments, change this call to
4967 // be a direct call with arguments casted to the appropriate types.
4968 //
4969 const FunctionType *FT = Callee->getFunctionType();
4970 const Type *OldRetTy = Caller->getType();
4971
Chris Lattner1f7942f2004-01-14 06:06:08 +00004972 // Check to see if we are changing the return type...
4973 if (OldRetTy != FT->getReturnType()) {
4974 if (Callee->isExternal() &&
4975 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
4976 !Caller->use_empty())
4977 return false; // Cannot transform this return value...
4978
4979 // If the callsite is an invoke instruction, and the return value is used by
4980 // a PHI node in a successor, we cannot change the return type of the call
4981 // because there is no place to put the cast instruction (without breaking
4982 // the critical edge). Bail out in this case.
4983 if (!Caller->use_empty())
4984 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4985 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4986 UI != E; ++UI)
4987 if (PHINode *PN = dyn_cast<PHINode>(*UI))
4988 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004989 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00004990 return false;
4991 }
Chris Lattner970c33a2003-06-19 17:00:31 +00004992
4993 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
4994 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004995
Chris Lattner970c33a2003-06-19 17:00:31 +00004996 CallSite::arg_iterator AI = CS.arg_begin();
4997 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4998 const Type *ParamTy = FT->getParamType(i);
4999 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005000 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00005001 }
5002
5003 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
5004 Callee->isExternal())
5005 return false; // Do not delete arguments unless we have a function body...
5006
5007 // Okay, we decided that this is a safe thing to do: go ahead and start
5008 // inserting cast instructions as necessary...
5009 std::vector<Value*> Args;
5010 Args.reserve(NumActualArgs);
5011
5012 AI = CS.arg_begin();
5013 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
5014 const Type *ParamTy = FT->getParamType(i);
5015 if ((*AI)->getType() == ParamTy) {
5016 Args.push_back(*AI);
5017 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00005018 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
5019 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00005020 }
5021 }
5022
5023 // If the function takes more arguments than the call was taking, add them
5024 // now...
5025 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
5026 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
5027
5028 // If we are removing arguments to the function, emit an obnoxious warning...
5029 if (FT->getNumParams() < NumActualArgs)
5030 if (!FT->isVarArg()) {
5031 std::cerr << "WARNING: While resolving call to function '"
5032 << Callee->getName() << "' arguments were dropped!\n";
5033 } else {
5034 // Add all of the arguments in their promoted form to the arg list...
5035 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
5036 const Type *PTy = getPromotedType((*AI)->getType());
5037 if (PTy != (*AI)->getType()) {
5038 // Must promote to pass through va_arg area!
5039 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
5040 InsertNewInstBefore(Cast, *Caller);
5041 Args.push_back(Cast);
5042 } else {
5043 Args.push_back(*AI);
5044 }
5045 }
5046 }
5047
5048 if (FT->getReturnType() == Type::VoidTy)
5049 Caller->setName(""); // Void type should not have a name...
5050
5051 Instruction *NC;
5052 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00005053 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00005054 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00005055 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00005056 } else {
5057 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00005058 if (cast<CallInst>(Caller)->isTailCall())
5059 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00005060 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00005061 }
5062
5063 // Insert a cast of the return type as necessary...
5064 Value *NV = NC;
5065 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
5066 if (NV->getType() != Type::VoidTy) {
5067 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00005068
5069 // If this is an invoke instruction, we should insert it after the first
5070 // non-phi, instruction in the normal successor block.
5071 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5072 BasicBlock::iterator I = II->getNormalDest()->begin();
5073 while (isa<PHINode>(I)) ++I;
5074 InsertNewInstBefore(NC, *I);
5075 } else {
5076 // Otherwise, it's a call, just insert cast right after the call instr
5077 InsertNewInstBefore(NC, *Caller);
5078 }
Chris Lattner51ea1272004-02-28 05:22:00 +00005079 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00005080 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00005081 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00005082 }
5083 }
5084
5085 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
5086 Caller->replaceAllUsesWith(NV);
5087 Caller->getParent()->getInstList().erase(Caller);
5088 removeFromWorkList(Caller);
5089 return true;
5090}
5091
5092
Chris Lattner7515cab2004-11-14 19:13:23 +00005093// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
5094// operator and they all are only used by the PHI, PHI together their
5095// inputs, and do the operation once, to the result of the PHI.
5096Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
5097 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
5098
5099 // Scan the instruction, looking for input operations that can be folded away.
5100 // If all input operands to the phi are the same instruction (e.g. a cast from
5101 // the same type or "+42") we can pull the operation through the PHI, reducing
5102 // code size and simplifying code.
5103 Constant *ConstantOp = 0;
5104 const Type *CastSrcTy = 0;
5105 if (isa<CastInst>(FirstInst)) {
5106 CastSrcTy = FirstInst->getOperand(0)->getType();
5107 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
5108 // Can fold binop or shift if the RHS is a constant.
5109 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
5110 if (ConstantOp == 0) return 0;
5111 } else {
5112 return 0; // Cannot fold this operation.
5113 }
5114
5115 // Check to see if all arguments are the same operation.
5116 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5117 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
5118 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
5119 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
5120 return 0;
5121 if (CastSrcTy) {
5122 if (I->getOperand(0)->getType() != CastSrcTy)
5123 return 0; // Cast operation must match.
5124 } else if (I->getOperand(1) != ConstantOp) {
5125 return 0;
5126 }
5127 }
5128
5129 // Okay, they are all the same operation. Create a new PHI node of the
5130 // correct type, and PHI together all of the LHS's of the instructions.
5131 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
5132 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00005133 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00005134
5135 Value *InVal = FirstInst->getOperand(0);
5136 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00005137
5138 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00005139 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5140 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
5141 if (NewInVal != InVal)
5142 InVal = 0;
5143 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
5144 }
5145
5146 Value *PhiVal;
5147 if (InVal) {
5148 // The new PHI unions all of the same values together. This is really
5149 // common, so we handle it intelligently here for compile-time speed.
5150 PhiVal = InVal;
5151 delete NewPN;
5152 } else {
5153 InsertNewInstBefore(NewPN, PN);
5154 PhiVal = NewPN;
5155 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005156
Chris Lattner7515cab2004-11-14 19:13:23 +00005157 // Insert and return the new operation.
5158 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00005159 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00005160 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00005161 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00005162 else
5163 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00005164 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00005165}
Chris Lattner48a44f72002-05-02 17:06:02 +00005166
Chris Lattner71536432005-01-17 05:10:15 +00005167/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
5168/// that is dead.
5169static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
5170 if (PN->use_empty()) return true;
5171 if (!PN->hasOneUse()) return false;
5172
5173 // Remember this node, and if we find the cycle, return.
5174 if (!PotentiallyDeadPHIs.insert(PN).second)
5175 return true;
5176
5177 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
5178 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005179
Chris Lattner71536432005-01-17 05:10:15 +00005180 return false;
5181}
5182
Chris Lattnerbbbdd852002-05-06 18:06:38 +00005183// PHINode simplification
5184//
Chris Lattner113f4f42002-06-25 16:13:24 +00005185Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner9f9c2602005-08-05 01:04:30 +00005186 if (Value *V = PN.hasConstantValue())
5187 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00005188
5189 // If the only user of this instruction is a cast instruction, and all of the
5190 // incoming values are constants, change this PHI to merge together the casted
5191 // constants.
5192 if (PN.hasOneUse())
5193 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
5194 if (CI->getType() != PN.getType()) { // noop casts will be folded
5195 bool AllConstant = true;
5196 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
5197 if (!isa<Constant>(PN.getIncomingValue(i))) {
5198 AllConstant = false;
5199 break;
5200 }
5201 if (AllConstant) {
5202 // Make a new PHI with all casted values.
5203 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
5204 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
5205 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
5206 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
5207 PN.getIncomingBlock(i));
5208 }
5209
5210 // Update the cast instruction.
5211 CI->setOperand(0, New);
5212 WorkList.push_back(CI); // revisit the cast instruction to fold.
5213 WorkList.push_back(New); // Make sure to revisit the new Phi
5214 return &PN; // PN is now dead!
5215 }
5216 }
Chris Lattner7515cab2004-11-14 19:13:23 +00005217
5218 // If all PHI operands are the same operation, pull them through the PHI,
5219 // reducing code size.
5220 if (isa<Instruction>(PN.getIncomingValue(0)) &&
5221 PN.getIncomingValue(0)->hasOneUse())
5222 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
5223 return Result;
5224
Chris Lattner71536432005-01-17 05:10:15 +00005225 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
5226 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
5227 // PHI)... break the cycle.
5228 if (PN.hasOneUse())
5229 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
5230 std::set<PHINode*> PotentiallyDeadPHIs;
5231 PotentiallyDeadPHIs.insert(&PN);
5232 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
5233 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
5234 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005235
Chris Lattner91daeb52003-12-19 05:58:40 +00005236 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00005237}
5238
Chris Lattner69193f92004-04-05 01:30:19 +00005239static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
5240 Instruction *InsertPoint,
5241 InstCombiner *IC) {
5242 unsigned PS = IC->getTargetData().getPointerSize();
5243 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00005244 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
5245 // We must insert a cast to ensure we sign-extend.
5246 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
5247 V->getName()), *InsertPoint);
5248 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
5249 *InsertPoint);
5250}
5251
Chris Lattner48a44f72002-05-02 17:06:02 +00005252
Chris Lattner113f4f42002-06-25 16:13:24 +00005253Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00005254 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00005255 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00005256 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005257 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00005258 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005259
Chris Lattner81a7a232004-10-16 18:11:37 +00005260 if (isa<UndefValue>(GEP.getOperand(0)))
5261 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
5262
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005263 bool HasZeroPointerIndex = false;
5264 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
5265 HasZeroPointerIndex = C->isNullValue();
5266
5267 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00005268 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00005269
Chris Lattner69193f92004-04-05 01:30:19 +00005270 // Eliminate unneeded casts for indices.
5271 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00005272 gep_type_iterator GTI = gep_type_begin(GEP);
5273 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
5274 if (isa<SequentialType>(*GTI)) {
5275 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
5276 Value *Src = CI->getOperand(0);
5277 const Type *SrcTy = Src->getType();
5278 const Type *DestTy = CI->getType();
5279 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005280 if (SrcTy->getPrimitiveSizeInBits() ==
5281 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00005282 // We can always eliminate a cast from ulong or long to the other.
5283 // We can always eliminate a cast from uint to int or the other on
5284 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005285 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00005286 MadeChange = true;
5287 GEP.setOperand(i, Src);
5288 }
5289 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
5290 SrcTy->getPrimitiveSize() == 4) {
5291 // We can always eliminate a cast from int to [u]long. We can
5292 // eliminate a cast from uint to [u]long iff the target is a 32-bit
5293 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005294 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005295 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00005296 MadeChange = true;
5297 GEP.setOperand(i, Src);
5298 }
Chris Lattner69193f92004-04-05 01:30:19 +00005299 }
5300 }
5301 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00005302 // If we are using a wider index than needed for this platform, shrink it
5303 // to what we need. If the incoming value needs a cast instruction,
5304 // insert it. This explicit cast can make subsequent optimizations more
5305 // obvious.
5306 Value *Op = GEP.getOperand(i);
5307 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00005308 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00005309 GEP.setOperand(i, ConstantExpr::getCast(C,
5310 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00005311 MadeChange = true;
5312 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00005313 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
5314 Op->getName()), GEP);
5315 GEP.setOperand(i, Op);
5316 MadeChange = true;
5317 }
Chris Lattner44d0b952004-07-20 01:48:15 +00005318
5319 // If this is a constant idx, make sure to canonicalize it to be a signed
5320 // operand, otherwise CSE and other optimizations are pessimized.
5321 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
5322 GEP.setOperand(i, ConstantExpr::getCast(CUI,
5323 CUI->getType()->getSignedVersion()));
5324 MadeChange = true;
5325 }
Chris Lattner69193f92004-04-05 01:30:19 +00005326 }
5327 if (MadeChange) return &GEP;
5328
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005329 // Combine Indices - If the source pointer to this getelementptr instruction
5330 // is a getelementptr instruction, combine the indices of the two
5331 // getelementptr instructions into a single instruction.
5332 //
Chris Lattner57c67b02004-03-25 22:59:29 +00005333 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00005334 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00005335 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00005336
5337 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00005338 // Note that if our source is a gep chain itself that we wait for that
5339 // chain to be resolved before we perform this transformation. This
5340 // avoids us creating a TON of code in some cases.
5341 //
5342 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
5343 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
5344 return 0; // Wait until our source is folded to completion.
5345
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005346 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00005347
5348 // Find out whether the last index in the source GEP is a sequential idx.
5349 bool EndsWithSequential = false;
5350 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
5351 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00005352 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005353
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005354 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00005355 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00005356 // Replace: gep (gep %P, long B), long A, ...
5357 // With: T = long A+B; gep %P, T, ...
5358 //
Chris Lattner5f667a62004-05-07 22:09:22 +00005359 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00005360 if (SO1 == Constant::getNullValue(SO1->getType())) {
5361 Sum = GO1;
5362 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
5363 Sum = SO1;
5364 } else {
5365 // If they aren't the same type, convert both to an integer of the
5366 // target's pointer size.
5367 if (SO1->getType() != GO1->getType()) {
5368 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
5369 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
5370 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
5371 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
5372 } else {
5373 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00005374 if (SO1->getType()->getPrimitiveSize() == PS) {
5375 // Convert GO1 to SO1's type.
5376 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
5377
5378 } else if (GO1->getType()->getPrimitiveSize() == PS) {
5379 // Convert SO1 to GO1's type.
5380 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
5381 } else {
5382 const Type *PT = TD->getIntPtrType();
5383 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
5384 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
5385 }
5386 }
5387 }
Chris Lattner5f667a62004-05-07 22:09:22 +00005388 if (isa<Constant>(SO1) && isa<Constant>(GO1))
5389 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
5390 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005391 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
5392 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00005393 }
Chris Lattner69193f92004-04-05 01:30:19 +00005394 }
Chris Lattner5f667a62004-05-07 22:09:22 +00005395
5396 // Recycle the GEP we already have if possible.
5397 if (SrcGEPOperands.size() == 2) {
5398 GEP.setOperand(0, SrcGEPOperands[0]);
5399 GEP.setOperand(1, Sum);
5400 return &GEP;
5401 } else {
5402 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5403 SrcGEPOperands.end()-1);
5404 Indices.push_back(Sum);
5405 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
5406 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005407 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00005408 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005409 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005410 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00005411 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5412 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005413 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
5414 }
5415
5416 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00005417 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005418
Chris Lattner5f667a62004-05-07 22:09:22 +00005419 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005420 // GEP of global variable. If all of the indices for this GEP are
5421 // constants, we can promote this to a constexpr instead of an instruction.
5422
5423 // Scan for nonconstants...
5424 std::vector<Constant*> Indices;
5425 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
5426 for (; I != E && isa<Constant>(*I); ++I)
5427 Indices.push_back(cast<Constant>(*I));
5428
5429 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00005430 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005431
5432 // Replace all uses of the GEP with the new constexpr...
5433 return ReplaceInstUsesWith(GEP, CE);
5434 }
Chris Lattner567b81f2005-09-13 00:40:14 +00005435 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
5436 if (!isa<PointerType>(X->getType())) {
5437 // Not interesting. Source pointer must be a cast from pointer.
5438 } else if (HasZeroPointerIndex) {
5439 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
5440 // into : GEP [10 x ubyte]* X, long 0, ...
5441 //
5442 // This occurs when the program declares an array extern like "int X[];"
5443 //
5444 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
5445 const PointerType *XTy = cast<PointerType>(X->getType());
5446 if (const ArrayType *XATy =
5447 dyn_cast<ArrayType>(XTy->getElementType()))
5448 if (const ArrayType *CATy =
5449 dyn_cast<ArrayType>(CPTy->getElementType()))
5450 if (CATy->getElementType() == XATy->getElementType()) {
5451 // At this point, we know that the cast source type is a pointer
5452 // to an array of the same type as the destination pointer
5453 // array. Because the array type is never stepped over (there
5454 // is a leading zero) we can fold the cast into this GEP.
5455 GEP.setOperand(0, X);
5456 return &GEP;
5457 }
5458 } else if (GEP.getNumOperands() == 2) {
5459 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00005460 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
5461 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00005462 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
5463 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
5464 if (isa<ArrayType>(SrcElTy) &&
5465 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
5466 TD->getTypeSize(ResElTy)) {
5467 Value *V = InsertNewInstBefore(
5468 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5469 GEP.getOperand(1), GEP.getName()), GEP);
5470 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005471 }
Chris Lattner2a893292005-09-13 18:36:04 +00005472
5473 // Transform things like:
5474 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
5475 // (where tmp = 8*tmp2) into:
5476 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
5477
5478 if (isa<ArrayType>(SrcElTy) &&
5479 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
5480 uint64_t ArrayEltSize =
5481 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
5482
5483 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
5484 // allow either a mul, shift, or constant here.
5485 Value *NewIdx = 0;
5486 ConstantInt *Scale = 0;
5487 if (ArrayEltSize == 1) {
5488 NewIdx = GEP.getOperand(1);
5489 Scale = ConstantInt::get(NewIdx->getType(), 1);
5490 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00005491 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00005492 Scale = CI;
5493 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
5494 if (Inst->getOpcode() == Instruction::Shl &&
5495 isa<ConstantInt>(Inst->getOperand(1))) {
5496 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
5497 if (Inst->getType()->isSigned())
5498 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
5499 else
5500 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
5501 NewIdx = Inst->getOperand(0);
5502 } else if (Inst->getOpcode() == Instruction::Mul &&
5503 isa<ConstantInt>(Inst->getOperand(1))) {
5504 Scale = cast<ConstantInt>(Inst->getOperand(1));
5505 NewIdx = Inst->getOperand(0);
5506 }
5507 }
5508
5509 // If the index will be to exactly the right offset with the scale taken
5510 // out, perform the transformation.
5511 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
5512 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
5513 Scale = ConstantSInt::get(C->getType(),
Chris Lattnera393e4d2005-09-14 17:32:56 +00005514 (int64_t)C->getRawValue() /
5515 (int64_t)ArrayEltSize);
Chris Lattner2a893292005-09-13 18:36:04 +00005516 else
5517 Scale = ConstantUInt::get(Scale->getType(),
5518 Scale->getRawValue() / ArrayEltSize);
5519 if (Scale->getRawValue() != 1) {
5520 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
5521 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
5522 NewIdx = InsertNewInstBefore(Sc, GEP);
5523 }
5524
5525 // Insert the new GEP instruction.
5526 Instruction *Idx =
5527 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5528 NewIdx, GEP.getName());
5529 Idx = InsertNewInstBefore(Idx, GEP);
5530 return new CastInst(Idx, GEP.getType());
5531 }
5532 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005533 }
Chris Lattnerca081252001-12-14 16:52:21 +00005534 }
5535
Chris Lattnerca081252001-12-14 16:52:21 +00005536 return 0;
5537}
5538
Chris Lattner1085bdf2002-11-04 16:18:53 +00005539Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
5540 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
5541 if (AI.isArrayAllocation()) // Check C != 1
5542 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
5543 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005544 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00005545
5546 // Create and insert the replacement instruction...
5547 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005548 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005549 else {
5550 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00005551 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005552 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00005553
5554 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005555
Chris Lattner1085bdf2002-11-04 16:18:53 +00005556 // Scan to the end of the allocation instructions, to skip over a block of
5557 // allocas if possible...
5558 //
5559 BasicBlock::iterator It = New;
5560 while (isa<AllocationInst>(*It)) ++It;
5561
5562 // Now that I is pointing to the first non-allocation-inst in the block,
5563 // insert our getelementptr instruction...
5564 //
Chris Lattner809dfac2005-05-04 19:10:26 +00005565 Value *NullIdx = Constant::getNullValue(Type::IntTy);
5566 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
5567 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00005568
5569 // Now make everything use the getelementptr instead of the original
5570 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00005571 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00005572 } else if (isa<UndefValue>(AI.getArraySize())) {
5573 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00005574 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00005575
5576 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
5577 // Note that we only do this for alloca's, because malloc should allocate and
5578 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005579 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00005580 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00005581 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5582
Chris Lattner1085bdf2002-11-04 16:18:53 +00005583 return 0;
5584}
5585
Chris Lattner8427bff2003-12-07 01:24:23 +00005586Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
5587 Value *Op = FI.getOperand(0);
5588
5589 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
5590 if (CastInst *CI = dyn_cast<CastInst>(Op))
5591 if (isa<PointerType>(CI->getOperand(0)->getType())) {
5592 FI.setOperand(0, CI->getOperand(0));
5593 return &FI;
5594 }
5595
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005596 // free undef -> unreachable.
5597 if (isa<UndefValue>(Op)) {
5598 // Insert a new store to null because we cannot modify the CFG here.
5599 new StoreInst(ConstantBool::True,
5600 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
5601 return EraseInstFromFunction(FI);
5602 }
5603
Chris Lattnerf3a36602004-02-28 04:57:37 +00005604 // If we have 'free null' delete the instruction. This can happen in stl code
5605 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005606 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00005607 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00005608
Chris Lattner8427bff2003-12-07 01:24:23 +00005609 return 0;
5610}
5611
5612
Chris Lattner72684fe2005-01-31 05:51:45 +00005613/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00005614static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
5615 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005616 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00005617
5618 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005619 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00005620 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005621
5622 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5623 // If the source is an array, the code below will not succeed. Check to
5624 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5625 // constants.
5626 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5627 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5628 if (ASrcTy->getNumElements() != 0) {
5629 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5630 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5631 SrcTy = cast<PointerType>(CastOp->getType());
5632 SrcPTy = SrcTy->getElementType();
5633 }
5634
5635 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00005636 // Do not allow turning this into a load of an integer, which is then
5637 // casted to a pointer, this pessimizes pointer analysis a lot.
5638 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005639 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005640 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00005641
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005642 // Okay, we are casting from one integer or pointer type to another of
5643 // the same size. Instead of casting the pointer before the load, cast
5644 // the result of the loaded value.
5645 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
5646 CI->getName(),
5647 LI.isVolatile()),LI);
5648 // Now cast the result of the load.
5649 return new CastInst(NewLoad, LI.getType());
5650 }
Chris Lattner35e24772004-07-13 01:49:43 +00005651 }
5652 }
5653 return 0;
5654}
5655
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005656/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00005657/// from this value cannot trap. If it is not obviously safe to load from the
5658/// specified pointer, we do a quick local scan of the basic block containing
5659/// ScanFrom, to determine if the address is already accessed.
5660static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
5661 // If it is an alloca or global variable, it is always safe to load from.
5662 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
5663
5664 // Otherwise, be a little bit agressive by scanning the local block where we
5665 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00005666 // from/to. If so, the previous load or store would have already trapped,
5667 // so there is no harm doing an extra load (also, CSE will later eliminate
5668 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00005669 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
5670
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00005671 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00005672 --BBI;
5673
5674 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
5675 if (LI->getOperand(0) == V) return true;
5676 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5677 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00005678
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00005679 }
Chris Lattnere6f13092004-09-19 19:18:10 +00005680 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005681}
5682
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005683Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
5684 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00005685
Chris Lattnera9d84e32005-05-01 04:24:53 +00005686 // load (cast X) --> cast (load X) iff safe
5687 if (CastInst *CI = dyn_cast<CastInst>(Op))
5688 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5689 return Res;
5690
5691 // None of the following transforms are legal for volatile loads.
5692 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005693
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005694 if (&LI.getParent()->front() != &LI) {
5695 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00005696 // If the instruction immediately before this is a store to the same
5697 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005698 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5699 if (SI->getOperand(1) == LI.getOperand(0))
5700 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00005701 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
5702 if (LIB->getOperand(0) == LI.getOperand(0))
5703 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005704 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00005705
5706 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
5707 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
5708 isa<UndefValue>(GEPI->getOperand(0))) {
5709 // Insert a new store to null instruction before the load to indicate
5710 // that this code is not reachable. We do this instead of inserting
5711 // an unreachable instruction directly because we cannot modify the
5712 // CFG.
5713 new StoreInst(UndefValue::get(LI.getType()),
5714 Constant::getNullValue(Op->getType()), &LI);
5715 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5716 }
5717
Chris Lattner81a7a232004-10-16 18:11:37 +00005718 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00005719 // load null/undef -> undef
5720 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005721 // Insert a new store to null instruction before the load to indicate that
5722 // this code is not reachable. We do this instead of inserting an
5723 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00005724 new StoreInst(UndefValue::get(LI.getType()),
5725 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00005726 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005727 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005728
Chris Lattner81a7a232004-10-16 18:11:37 +00005729 // Instcombine load (constant global) into the value loaded.
5730 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
5731 if (GV->isConstant() && !GV->isExternal())
5732 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00005733
Chris Lattner81a7a232004-10-16 18:11:37 +00005734 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
5735 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
5736 if (CE->getOpcode() == Instruction::GetElementPtr) {
5737 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
5738 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00005739 if (Constant *V =
5740 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00005741 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00005742 if (CE->getOperand(0)->isNullValue()) {
5743 // Insert a new store to null instruction before the load to indicate
5744 // that this code is not reachable. We do this instead of inserting
5745 // an unreachable instruction directly because we cannot modify the
5746 // CFG.
5747 new StoreInst(UndefValue::get(LI.getType()),
5748 Constant::getNullValue(Op->getType()), &LI);
5749 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5750 }
5751
Chris Lattner81a7a232004-10-16 18:11:37 +00005752 } else if (CE->getOpcode() == Instruction::Cast) {
5753 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5754 return Res;
5755 }
5756 }
Chris Lattnere228ee52004-04-08 20:39:49 +00005757
Chris Lattnera9d84e32005-05-01 04:24:53 +00005758 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005759 // Change select and PHI nodes to select values instead of addresses: this
5760 // helps alias analysis out a lot, allows many others simplifications, and
5761 // exposes redundancy in the code.
5762 //
5763 // Note that we cannot do the transformation unless we know that the
5764 // introduced loads cannot trap! Something like this is valid as long as
5765 // the condition is always false: load (select bool %C, int* null, int* %G),
5766 // but it would not be valid if we transformed it to load from null
5767 // unconditionally.
5768 //
5769 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
5770 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00005771 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
5772 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005773 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00005774 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005775 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00005776 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005777 return new SelectInst(SI->getCondition(), V1, V2);
5778 }
5779
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00005780 // load (select (cond, null, P)) -> load P
5781 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
5782 if (C->isNullValue()) {
5783 LI.setOperand(0, SI->getOperand(2));
5784 return &LI;
5785 }
5786
5787 // load (select (cond, P, null)) -> load P
5788 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
5789 if (C->isNullValue()) {
5790 LI.setOperand(0, SI->getOperand(1));
5791 return &LI;
5792 }
5793
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005794 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
5795 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00005796 bool Safe = PN->getParent() == LI.getParent();
5797
5798 // Scan all of the instructions between the PHI and the load to make
5799 // sure there are no instructions that might possibly alter the value
5800 // loaded from the PHI.
5801 if (Safe) {
5802 BasicBlock::iterator I = &LI;
5803 for (--I; !isa<PHINode>(I); --I)
5804 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
5805 Safe = false;
5806 break;
5807 }
5808 }
5809
5810 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00005811 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00005812 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005813 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00005814
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005815 if (Safe) {
5816 // Create the PHI.
5817 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
5818 InsertNewInstBefore(NewPN, *PN);
5819 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
5820
5821 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5822 BasicBlock *BB = PN->getIncomingBlock(i);
5823 Value *&TheLoad = LoadMap[BB];
5824 if (TheLoad == 0) {
5825 Value *InVal = PN->getIncomingValue(i);
5826 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
5827 InVal->getName()+".val"),
5828 *BB->getTerminator());
5829 }
5830 NewPN->addIncoming(TheLoad, BB);
5831 }
5832 return ReplaceInstUsesWith(LI, NewPN);
5833 }
5834 }
5835 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005836 return 0;
5837}
5838
Chris Lattner72684fe2005-01-31 05:51:45 +00005839/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
5840/// when possible.
5841static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
5842 User *CI = cast<User>(SI.getOperand(1));
5843 Value *CastOp = CI->getOperand(0);
5844
5845 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
5846 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
5847 const Type *SrcPTy = SrcTy->getElementType();
5848
5849 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5850 // If the source is an array, the code below will not succeed. Check to
5851 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5852 // constants.
5853 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5854 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5855 if (ASrcTy->getNumElements() != 0) {
5856 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5857 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5858 SrcTy = cast<PointerType>(CastOp->getType());
5859 SrcPTy = SrcTy->getElementType();
5860 }
5861
5862 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005863 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00005864 IC.getTargetData().getTypeSize(DestPTy)) {
5865
5866 // Okay, we are casting from one integer or pointer type to another of
5867 // the same size. Instead of casting the pointer before the store, cast
5868 // the value to be stored.
5869 Value *NewCast;
5870 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
5871 NewCast = ConstantExpr::getCast(C, SrcPTy);
5872 else
5873 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
5874 SrcPTy,
5875 SI.getOperand(0)->getName()+".c"), SI);
5876
5877 return new StoreInst(NewCast, CastOp);
5878 }
5879 }
5880 }
5881 return 0;
5882}
5883
Chris Lattner31f486c2005-01-31 05:36:43 +00005884Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
5885 Value *Val = SI.getOperand(0);
5886 Value *Ptr = SI.getOperand(1);
5887
5888 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
5889 removeFromWorkList(&SI);
5890 SI.eraseFromParent();
5891 ++NumCombined;
5892 return 0;
5893 }
5894
5895 if (SI.isVolatile()) return 0; // Don't hack volatile loads.
5896
5897 // store X, null -> turns into 'unreachable' in SimplifyCFG
5898 if (isa<ConstantPointerNull>(Ptr)) {
5899 if (!isa<UndefValue>(Val)) {
5900 SI.setOperand(0, UndefValue::get(Val->getType()));
5901 if (Instruction *U = dyn_cast<Instruction>(Val))
5902 WorkList.push_back(U); // Dropped a use.
5903 ++NumCombined;
5904 }
5905 return 0; // Do not modify these!
5906 }
5907
5908 // store undef, Ptr -> noop
5909 if (isa<UndefValue>(Val)) {
5910 removeFromWorkList(&SI);
5911 SI.eraseFromParent();
5912 ++NumCombined;
5913 return 0;
5914 }
5915
Chris Lattner72684fe2005-01-31 05:51:45 +00005916 // If the pointer destination is a cast, see if we can fold the cast into the
5917 // source instead.
5918 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
5919 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5920 return Res;
5921 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
5922 if (CE->getOpcode() == Instruction::Cast)
5923 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5924 return Res;
5925
Chris Lattner219175c2005-09-12 23:23:25 +00005926
5927 // If this store is the last instruction in the basic block, and if the block
5928 // ends with an unconditional branch, try to move it to the successor block.
5929 BasicBlock::iterator BBI = &SI; ++BBI;
5930 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
5931 if (BI->isUnconditional()) {
5932 // Check to see if the successor block has exactly two incoming edges. If
5933 // so, see if the other predecessor contains a store to the same location.
5934 // if so, insert a PHI node (if needed) and move the stores down.
5935 BasicBlock *Dest = BI->getSuccessor(0);
5936
5937 pred_iterator PI = pred_begin(Dest);
5938 BasicBlock *Other = 0;
5939 if (*PI != BI->getParent())
5940 Other = *PI;
5941 ++PI;
5942 if (PI != pred_end(Dest)) {
5943 if (*PI != BI->getParent())
5944 if (Other)
5945 Other = 0;
5946 else
5947 Other = *PI;
5948 if (++PI != pred_end(Dest))
5949 Other = 0;
5950 }
5951 if (Other) { // If only one other pred...
5952 BBI = Other->getTerminator();
5953 // Make sure this other block ends in an unconditional branch and that
5954 // there is an instruction before the branch.
5955 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
5956 BBI != Other->begin()) {
5957 --BBI;
5958 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
5959
5960 // If this instruction is a store to the same location.
5961 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
5962 // Okay, we know we can perform this transformation. Insert a PHI
5963 // node now if we need it.
5964 Value *MergedVal = OtherStore->getOperand(0);
5965 if (MergedVal != SI.getOperand(0)) {
5966 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
5967 PN->reserveOperandSpace(2);
5968 PN->addIncoming(SI.getOperand(0), SI.getParent());
5969 PN->addIncoming(OtherStore->getOperand(0), Other);
5970 MergedVal = InsertNewInstBefore(PN, Dest->front());
5971 }
5972
5973 // Advance to a place where it is safe to insert the new store and
5974 // insert it.
5975 BBI = Dest->begin();
5976 while (isa<PHINode>(BBI)) ++BBI;
5977 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
5978 OtherStore->isVolatile()), *BBI);
5979
5980 // Nuke the old stores.
5981 removeFromWorkList(&SI);
5982 removeFromWorkList(OtherStore);
5983 SI.eraseFromParent();
5984 OtherStore->eraseFromParent();
5985 ++NumCombined;
5986 return 0;
5987 }
5988 }
5989 }
5990 }
5991
Chris Lattner31f486c2005-01-31 05:36:43 +00005992 return 0;
5993}
5994
5995
Chris Lattner9eef8a72003-06-04 04:46:00 +00005996Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
5997 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00005998 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00005999 BasicBlock *TrueDest;
6000 BasicBlock *FalseDest;
6001 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
6002 !isa<Constant>(X)) {
6003 // Swap Destinations and condition...
6004 BI.setCondition(X);
6005 BI.setSuccessor(0, FalseDest);
6006 BI.setSuccessor(1, TrueDest);
6007 return &BI;
6008 }
6009
6010 // Cannonicalize setne -> seteq
6011 Instruction::BinaryOps Op; Value *Y;
6012 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
6013 TrueDest, FalseDest)))
6014 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
6015 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
6016 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
6017 std::string Name = I->getName(); I->setName("");
6018 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
6019 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00006020 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00006021 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00006022 BI.setSuccessor(0, FalseDest);
6023 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00006024 removeFromWorkList(I);
6025 I->getParent()->getInstList().erase(I);
6026 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00006027 return &BI;
6028 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006029
Chris Lattner9eef8a72003-06-04 04:46:00 +00006030 return 0;
6031}
Chris Lattner1085bdf2002-11-04 16:18:53 +00006032
Chris Lattner4c9c20a2004-07-03 00:26:11 +00006033Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
6034 Value *Cond = SI.getCondition();
6035 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
6036 if (I->getOpcode() == Instruction::Add)
6037 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6038 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
6039 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00006040 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00006041 AddRHS));
6042 SI.setOperand(0, I->getOperand(0));
6043 WorkList.push_back(I);
6044 return &SI;
6045 }
6046 }
6047 return 0;
6048}
6049
Robert Bocchinoa8352962006-01-13 22:48:06 +00006050Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
6051 if (ConstantAggregateZero *C =
6052 dyn_cast<ConstantAggregateZero>(EI.getOperand(0))) {
6053 // If packed val is constant 0, replace extract with scalar 0
6054 const Type *Ty = cast<PackedType>(C->getType())->getElementType();
6055 EI.replaceAllUsesWith(Constant::getNullValue(Ty));
6056 return ReplaceInstUsesWith(EI, Constant::getNullValue(Ty));
6057 }
6058 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
6059 // If packed val is constant with uniform operands, replace EI
6060 // with that operand
6061 Constant *op0 = cast<Constant>(C->getOperand(0));
6062 for (unsigned i = 1; i < C->getNumOperands(); ++i)
6063 if (C->getOperand(i) != op0) return 0;
6064 return ReplaceInstUsesWith(EI, op0);
6065 }
6066 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0)))
6067 if (I->hasOneUse()) {
6068 // Push extractelement into predecessor operation if legal and
6069 // profitable to do so
6070 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
6071 if (!isa<Constant>(BO->getOperand(0)) &&
6072 !isa<Constant>(BO->getOperand(1)))
6073 return 0;
6074 ExtractElementInst *newEI0 =
6075 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
6076 EI.getName());
6077 ExtractElementInst *newEI1 =
6078 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
6079 EI.getName());
6080 InsertNewInstBefore(newEI0, EI);
6081 InsertNewInstBefore(newEI1, EI);
6082 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
6083 }
6084 switch(I->getOpcode()) {
6085 case Instruction::Load: {
6086 Value *Ptr = InsertCastBefore(I->getOperand(0),
6087 PointerType::get(EI.getType()), EI);
6088 GetElementPtrInst *GEP =
6089 new GetElementPtrInst(Ptr, EI.getOperand(1),
6090 I->getName() + ".gep");
6091 InsertNewInstBefore(GEP, EI);
6092 return new LoadInst(GEP);
6093 }
6094 default:
6095 return 0;
6096 }
6097 }
6098 return 0;
6099}
6100
6101
Chris Lattner99f48c62002-09-02 04:59:56 +00006102void InstCombiner::removeFromWorkList(Instruction *I) {
6103 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
6104 WorkList.end());
6105}
6106
Chris Lattner39c98bb2004-12-08 23:43:58 +00006107
6108/// TryToSinkInstruction - Try to move the specified instruction from its
6109/// current block into the beginning of DestBlock, which can only happen if it's
6110/// safe to move the instruction past all of the instructions between it and the
6111/// end of its block.
6112static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
6113 assert(I->hasOneUse() && "Invariants didn't hold!");
6114
Chris Lattnerc4f67e62005-10-27 17:13:11 +00006115 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
6116 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00006117
Chris Lattner39c98bb2004-12-08 23:43:58 +00006118 // Do not sink alloca instructions out of the entry block.
6119 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
6120 return false;
6121
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00006122 // We can only sink load instructions if there is nothing between the load and
6123 // the end of block that could change the value.
6124 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00006125 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
6126 Scan != E; ++Scan)
6127 if (Scan->mayWriteToMemory())
6128 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00006129 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00006130
6131 BasicBlock::iterator InsertPos = DestBlock->begin();
6132 while (isa<PHINode>(InsertPos)) ++InsertPos;
6133
Chris Lattner9f269e42005-08-08 19:11:57 +00006134 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00006135 ++NumSunkInst;
6136 return true;
6137}
6138
Chris Lattner113f4f42002-06-25 16:13:24 +00006139bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00006140 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006141 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00006142
Chris Lattner4ed40f72005-07-07 20:40:38 +00006143 {
6144 // Populate the worklist with the reachable instructions.
6145 std::set<BasicBlock*> Visited;
6146 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
6147 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
6148 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
6149 WorkList.push_back(I);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00006150
Chris Lattner4ed40f72005-07-07 20:40:38 +00006151 // Do a quick scan over the function. If we find any blocks that are
6152 // unreachable, remove any instructions inside of them. This prevents
6153 // the instcombine code from having to deal with some bad special cases.
6154 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
6155 if (!Visited.count(BB)) {
6156 Instruction *Term = BB->getTerminator();
6157 while (Term != BB->begin()) { // Remove instrs bottom-up
6158 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00006159
Chris Lattner4ed40f72005-07-07 20:40:38 +00006160 DEBUG(std::cerr << "IC: DCE: " << *I);
6161 ++NumDeadInst;
6162
6163 if (!I->use_empty())
6164 I->replaceAllUsesWith(UndefValue::get(I->getType()));
6165 I->eraseFromParent();
6166 }
6167 }
6168 }
Chris Lattnerca081252001-12-14 16:52:21 +00006169
6170 while (!WorkList.empty()) {
6171 Instruction *I = WorkList.back(); // Get an instruction from the worklist
6172 WorkList.pop_back();
6173
Misha Brukman632df282002-10-29 23:06:16 +00006174 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00006175 // Check to see if we can DIE the instruction...
6176 if (isInstructionTriviallyDead(I)) {
6177 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006178 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00006179 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00006180 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006181
Chris Lattnercd517ff2005-01-28 19:32:01 +00006182 DEBUG(std::cerr << "IC: DCE: " << *I);
6183
6184 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006185 removeFromWorkList(I);
6186 continue;
6187 }
Chris Lattner99f48c62002-09-02 04:59:56 +00006188
Misha Brukman632df282002-10-29 23:06:16 +00006189 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00006190 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00006191 Value* Ptr = I->getOperand(0);
Chris Lattner6580e092004-10-16 19:44:59 +00006192 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00006193 cast<Constant>(Ptr)->isNullValue() &&
6194 !isa<ConstantPointerNull>(C) &&
6195 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner6580e092004-10-16 19:44:59 +00006196 // If this is a constant expr gep that is effectively computing an
6197 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
6198 bool isFoldableGEP = true;
6199 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
6200 if (!isa<ConstantInt>(I->getOperand(i)))
6201 isFoldableGEP = false;
6202 if (isFoldableGEP) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00006203 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner6580e092004-10-16 19:44:59 +00006204 std::vector<Value*>(I->op_begin()+1, I->op_end()));
6205 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00006206 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00006207 C = ConstantExpr::getCast(C, I->getType());
6208 }
6209 }
6210
Chris Lattnercd517ff2005-01-28 19:32:01 +00006211 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
6212
Chris Lattner99f48c62002-09-02 04:59:56 +00006213 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00006214 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00006215 ReplaceInstUsesWith(*I, C);
6216
Chris Lattner99f48c62002-09-02 04:59:56 +00006217 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006218 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00006219 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006220 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00006221 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006222
Chris Lattner39c98bb2004-12-08 23:43:58 +00006223 // See if we can trivially sink this instruction to a successor basic block.
6224 if (I->hasOneUse()) {
6225 BasicBlock *BB = I->getParent();
6226 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
6227 if (UserParent != BB) {
6228 bool UserIsSuccessor = false;
6229 // See if the user is one of our successors.
6230 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
6231 if (*SI == UserParent) {
6232 UserIsSuccessor = true;
6233 break;
6234 }
6235
6236 // If the user is one of our immediate successors, and if that successor
6237 // only has us as a predecessors (we'd have to split the critical edge
6238 // otherwise), we can keep going.
6239 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
6240 next(pred_begin(UserParent)) == pred_end(UserParent))
6241 // Okay, the CFG is simple enough, try to sink this instruction.
6242 Changed |= TryToSinkInstruction(I, UserParent);
6243 }
6244 }
6245
Chris Lattnerca081252001-12-14 16:52:21 +00006246 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006247 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00006248 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00006249 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00006250 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00006251 DEBUG(std::cerr << "IC: Old = " << *I
6252 << " New = " << *Result);
6253
Chris Lattner396dbfe2004-06-09 05:08:07 +00006254 // Everything uses the new instruction now.
6255 I->replaceAllUsesWith(Result);
6256
6257 // Push the new instruction and any users onto the worklist.
6258 WorkList.push_back(Result);
6259 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006260
6261 // Move the name to the new instruction first...
6262 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00006263 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006264
6265 // Insert the new instruction into the basic block...
6266 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00006267 BasicBlock::iterator InsertPos = I;
6268
6269 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
6270 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
6271 ++InsertPos;
6272
6273 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006274
Chris Lattner63d75af2004-05-01 23:27:23 +00006275 // Make sure that we reprocess all operands now that we reduced their
6276 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00006277 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6278 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6279 WorkList.push_back(OpI);
6280
Chris Lattner396dbfe2004-06-09 05:08:07 +00006281 // Instructions can end up on the worklist more than once. Make sure
6282 // we do not process an instruction that has been deleted.
6283 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006284
6285 // Erase the old instruction.
6286 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00006287 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00006288 DEBUG(std::cerr << "IC: MOD = " << *I);
6289
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006290 // If the instruction was modified, it's possible that it is now dead.
6291 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00006292 if (isInstructionTriviallyDead(I)) {
6293 // Make sure we process all operands now that we are reducing their
6294 // use counts.
6295 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6296 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6297 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006298
Chris Lattner63d75af2004-05-01 23:27:23 +00006299 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00006300 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00006301 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00006302 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00006303 } else {
6304 WorkList.push_back(Result);
6305 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006306 }
Chris Lattner053c0932002-05-14 15:24:07 +00006307 }
Chris Lattner260ab202002-04-18 17:39:14 +00006308 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00006309 }
6310 }
6311
Chris Lattner260ab202002-04-18 17:39:14 +00006312 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00006313}
6314
Brian Gaeke38b79e82004-07-27 17:43:21 +00006315FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00006316 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00006317}
Brian Gaeke960707c2003-11-11 22:41:34 +00006318